text
stringlengths 54
60.6k
|
---|
<commit_before>// Copyright 2018 Google Inc. 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 "bloaty.h"
#include "util.h"
#include "absl/strings/substitute.h"
using absl::string_view;
namespace bloaty {
namespace wasm {
uint64_t ReadLEB128Internal(bool is_signed, size_t size, string_view* data) {
uint64_t ret = 0;
int shift = 0;
int maxshift = 70;
const char* ptr = data->data();
const char* limit = ptr + data->size();
while (ptr < limit && shift < maxshift) {
char byte = *(ptr++);
ret |= static_cast<uint64_t>(byte & 0x7f) << shift;
shift += 7;
if ((byte & 0x80) == 0) {
data->remove_prefix(ptr - data->data());
if (is_signed && shift < size && (byte & 0x40)) {
ret |= -(1ULL << shift);
}
return ret;
}
}
THROW("corrupt wasm data, unterminated LEB128");
}
bool ReadVarUInt1(string_view* data) {
return static_cast<bool>(ReadLEB128Internal(false, 1, data));
}
uint8_t ReadVarUInt7(string_view* data) {
return static_cast<char>(ReadLEB128Internal(false, 7, data));
}
uint32_t ReadVarUInt32(string_view* data) {
return static_cast<uint32_t>(ReadLEB128Internal(false, 32, data));
}
int8_t ReadVarint7(string_view* data) {
return static_cast<int8_t>(ReadLEB128Internal(true, 7, data));
}
string_view ReadPiece(size_t bytes, string_view* data) {
if(data->size() < bytes) {
THROW("premature EOF reading variable-length DWARF data");
}
string_view ret = data->substr(0, bytes);
data->remove_prefix(bytes);
return ret;
}
bool ReadMagic(string_view* data) {
const uint32_t wasm_magic = 0x6d736100;
auto magic = ReadFixed<uint32_t>(data);
if (magic != wasm_magic) {
return false;
}
// TODO(haberman): do we need to fail if this is >1?
auto version = ReadFixed<uint32_t>(data);
(void)version;
return true;
}
class Section {
public:
uint32_t id;
std::string name;
string_view data;
string_view contents;
static Section Read(string_view* data_param) {
Section ret;
string_view data = *data_param;
string_view section_data = data;
ret.id = ReadVarUInt7(&data);
uint32_t size = ReadVarUInt32(&data);
ret.contents = ReadPiece(size, &data);
size_t header_size = ret.contents.data() - section_data.data();
ret.data = section_data.substr(0, size + header_size);
if (ret.id == 0) {
uint32_t name_len = ReadVarUInt32(&ret.contents);
ret.name = std::string(ReadPiece(name_len, &ret.contents));
} else if (ret.id <= 13) {
ret.name = names[ret.id];
} else {
THROWF("Unknown section id: $0", ret.id);
}
*data_param = data;
return ret;
}
enum Name {
kType = 1,
kImport = 2,
kFunction = 3,
kTable = 4,
kMemory = 5,
kGlobal = 6,
kExport = 7,
kStart = 8,
kElement = 9,
kCode = 10,
kData = 11,
kDataCount = 12,
kEvent = 13,
};
static const char* names[];
};
const char* Section::names[] = {
"<none>", // 0
"Type", // 1
"Import", // 2
"Function", // 3
"Table", // 4
"Memory", // 5
"Global", // 6
"Export", // 7
"Start", // 8
"Element", // 9
"Code", // 10
"Data", // 11
"DataCount", // 12
"Event", // 13
};
struct ExternalKind {
enum Kind {
kFunction = 0,
kTable = 1,
kMemory = 2,
kGlobal = 3,
};
};
template <class Func>
void ForEachSection(string_view file, Func&& section_func) {
string_view data = file;
ReadMagic(&data);
while (!data.empty()) {
Section section = Section::Read(&data);
section_func(section);
}
}
void ParseSections(RangeSink* sink) {
ForEachSection(sink->input_file().data(), [sink](const Section& section) {
sink->AddFileRange("wasm_sections", section.name, section.data);
});
}
typedef std::unordered_map<int, std::string> FuncNames;
void ReadFunctionNames(const Section& section, FuncNames* names,
RangeSink* sink) {
enum class NameType {
kModule = 0,
kFunction = 1,
kLocal = 2,
};
string_view data = section.contents;
while (!data.empty()) {
char type = ReadVarUInt7(&data);
uint32_t size = ReadVarUInt32(&data);
string_view section = data.substr(0, size);
data = data.substr(size);
if (static_cast<NameType>(type) == NameType::kFunction) {
uint32_t count = ReadVarUInt32(§ion);
for (uint32_t i = 0; i < count; i++) {
string_view entry = section;
uint32_t index = ReadVarUInt32(§ion);
uint32_t name_len = ReadVarUInt32(§ion);
string_view name = ReadPiece(name_len, §ion);
entry = entry.substr(0, name.data() - entry.data() + name.size());
sink->AddFileRange("wasm_funcname", name, entry);
(*names)[index] = std::string(name);
}
}
}
}
int ReadValueType(string_view* data) {
return ReadVarint7(data);
}
int ReadElemType(string_view* data) {
return ReadVarint7(data);
}
void ReadResizableLimits(string_view* data) {
auto flags = ReadVarUInt1(data);
ReadVarUInt32(data);
if (flags) {
ReadVarUInt32(data);
}
}
void ReadGlobalType(string_view* data) {
ReadValueType(data);
ReadVarUInt1(data);
}
void ReadTableType(string_view* data) {
ReadElemType(data);
ReadResizableLimits(data);
}
void ReadMemoryType(string_view* data) {
ReadResizableLimits(data);
}
uint32_t GetNumFunctionImports(const Section& section) {
assert(section.id == Section::kImport);
string_view data = section.contents;
uint32_t count = ReadVarUInt32(&data);
uint32_t func_count = 0;
for (uint32_t i = 0; i < count; i++) {
uint32_t module_len = ReadVarUInt32(&data);
ReadPiece(module_len, &data);
uint32_t field_len = ReadVarUInt32(&data);
ReadPiece(field_len, &data);
auto kind = ReadFixed<uint8_t>(&data);
switch (kind) {
case ExternalKind::kFunction:
func_count++;
ReadVarUInt32(&data);
break;
case ExternalKind::kTable:
ReadTableType(&data);
break;
case ExternalKind::kMemory:
ReadMemoryType(&data);
break;
case ExternalKind::kGlobal:
ReadGlobalType(&data);
break;
default:
THROWF("Unrecognized import kind: $0", kind);
}
}
return func_count;
}
void ReadCodeSection(const Section& section, const FuncNames& names,
uint32_t num_imports, RangeSink* sink) {
string_view data = section.contents;
uint32_t count = ReadVarUInt32(&data);
for (uint32_t i = 0; i < count; i++) {
string_view func = data;
uint32_t size = ReadVarUInt32(&data);
uint32_t total_size = size + (data.data() - func.data());
func = func.substr(0, total_size);
data = data.substr(size);
auto iter = names.find(num_imports + i);
if (iter == names.end()) {
std::string name = "func[" + std::to_string(i) + "]";
sink->AddFileRange("wasm_function", name, func);
} else {
sink->AddFileRange("wasm_function", ItaniumDemangle(iter->second, sink->data_source()), func);
}
}
}
void ParseSymbols(RangeSink* sink) {
// First pass: read the custom naming section to get function names.
std::unordered_map<int, std::string> func_names;
uint32_t num_imports = 0;
ForEachSection(sink->input_file().data(),
[&func_names, sink](const Section& section) {
if (section.name == "name") {
ReadFunctionNames(section, &func_names, sink);
}
});
// Second pass: read the function/code sections.
ForEachSection(sink->input_file().data(),
[&func_names, &num_imports, sink](const Section& section) {
if (section.id == Section::kImport) {
num_imports = GetNumFunctionImports(section);
} else if (section.id == Section::kCode) {
ReadCodeSection(section, func_names, num_imports, sink);
}
});
}
void AddWebAssemblyFallback(RangeSink* sink) {
ForEachSection(sink->input_file().data(), [sink](const Section& section) {
std::string name2 =
std::string("[section ") + std::string(section.name) + std::string("]");
sink->AddFileRange("wasm_overhead", name2, section.data);
});
sink->AddFileRange("wasm_overhead", "[WASM Header]",
sink->input_file().data().substr(0, 8));
}
class WebAssemblyObjectFile : public ObjectFile {
public:
WebAssemblyObjectFile(std::unique_ptr<InputFile> file_data)
: ObjectFile(std::move(file_data)) {}
std::string GetBuildId() const override {
// TODO(haberman): does WebAssembly support this?
return std::string();
}
void ProcessFile(const std::vector<RangeSink*>& sinks) const override {
for (auto sink : sinks) {
switch (sink->data_source()) {
case DataSource::kSegments:
case DataSource::kSections:
ParseSections(sink);
break;
case DataSource::kSymbols:
case DataSource::kRawSymbols:
case DataSource::kShortSymbols:
case DataSource::kFullSymbols:
ParseSymbols(sink);
break;
case DataSource::kArchiveMembers:
case DataSource::kCompileUnits:
case DataSource::kInlines:
default:
THROW("WebAssembly doesn't support this data source");
}
AddWebAssemblyFallback(sink);
}
}
bool GetDisassemblyInfo(absl::string_view /*symbol*/,
DataSource /*symbol_source*/,
DisassemblyInfo* /*info*/) const override {
WARN("WebAssembly files do not support disassembly yet");
return false;
}
};
} // namespace wasm
std::unique_ptr<ObjectFile> TryOpenWebAssemblyFile(
std::unique_ptr<InputFile>& file) {
string_view data = file->data();
if (wasm::ReadMagic(&data)) {
return std::unique_ptr<ObjectFile>(
new wasm::WebAssemblyObjectFile(std::move(file)));
}
return nullptr;
}
} // namespace bloaty
<commit_msg>Removed use of pure substr() in wasm, which can throw for badly formed files.<commit_after>// Copyright 2018 Google Inc. 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 "bloaty.h"
#include "util.h"
#include "absl/strings/substitute.h"
using absl::string_view;
namespace bloaty {
namespace wasm {
uint64_t ReadLEB128Internal(bool is_signed, size_t size, string_view* data) {
uint64_t ret = 0;
int shift = 0;
int maxshift = 70;
const char* ptr = data->data();
const char* limit = ptr + data->size();
while (ptr < limit && shift < maxshift) {
char byte = *(ptr++);
ret |= static_cast<uint64_t>(byte & 0x7f) << shift;
shift += 7;
if ((byte & 0x80) == 0) {
data->remove_prefix(ptr - data->data());
if (is_signed && shift < size && (byte & 0x40)) {
ret |= -(1ULL << shift);
}
return ret;
}
}
THROW("corrupt wasm data, unterminated LEB128");
}
bool ReadVarUInt1(string_view* data) {
return static_cast<bool>(ReadLEB128Internal(false, 1, data));
}
uint8_t ReadVarUInt7(string_view* data) {
return static_cast<char>(ReadLEB128Internal(false, 7, data));
}
uint32_t ReadVarUInt32(string_view* data) {
return static_cast<uint32_t>(ReadLEB128Internal(false, 32, data));
}
int8_t ReadVarint7(string_view* data) {
return static_cast<int8_t>(ReadLEB128Internal(true, 7, data));
}
string_view ReadPiece(size_t bytes, string_view* data) {
if(data->size() < bytes) {
THROW("premature EOF reading variable-length DWARF data");
}
string_view ret = data->substr(0, bytes);
data->remove_prefix(bytes);
return ret;
}
bool ReadMagic(string_view* data) {
const uint32_t wasm_magic = 0x6d736100;
auto magic = ReadFixed<uint32_t>(data);
if (magic != wasm_magic) {
return false;
}
// TODO(haberman): do we need to fail if this is >1?
auto version = ReadFixed<uint32_t>(data);
(void)version;
return true;
}
class Section {
public:
uint32_t id;
std::string name;
string_view data;
string_view contents;
static Section Read(string_view* data_param) {
Section ret;
string_view data = *data_param;
string_view section_data = data;
ret.id = ReadVarUInt7(&data);
uint32_t size = ReadVarUInt32(&data);
ret.contents = ReadPiece(size, &data);
size_t header_size = ret.contents.data() - section_data.data();
ret.data = ReadPiece(size + header_size, §ion_data);
if (ret.id == 0) {
uint32_t name_len = ReadVarUInt32(&ret.contents);
ret.name = std::string(ReadPiece(name_len, &ret.contents));
} else if (ret.id <= 13) {
ret.name = names[ret.id];
} else {
THROWF("Unknown section id: $0", ret.id);
}
*data_param = data;
return ret;
}
enum Name {
kType = 1,
kImport = 2,
kFunction = 3,
kTable = 4,
kMemory = 5,
kGlobal = 6,
kExport = 7,
kStart = 8,
kElement = 9,
kCode = 10,
kData = 11,
kDataCount = 12,
kEvent = 13,
};
static const char* names[];
};
const char* Section::names[] = {
"<none>", // 0
"Type", // 1
"Import", // 2
"Function", // 3
"Table", // 4
"Memory", // 5
"Global", // 6
"Export", // 7
"Start", // 8
"Element", // 9
"Code", // 10
"Data", // 11
"DataCount", // 12
"Event", // 13
};
struct ExternalKind {
enum Kind {
kFunction = 0,
kTable = 1,
kMemory = 2,
kGlobal = 3,
};
};
template <class Func>
void ForEachSection(string_view file, Func&& section_func) {
string_view data = file;
ReadMagic(&data);
while (!data.empty()) {
Section section = Section::Read(&data);
section_func(section);
}
}
void ParseSections(RangeSink* sink) {
ForEachSection(sink->input_file().data(), [sink](const Section& section) {
sink->AddFileRange("wasm_sections", section.name, section.data);
});
}
typedef std::unordered_map<int, std::string> FuncNames;
void ReadFunctionNames(const Section& section, FuncNames* names,
RangeSink* sink) {
enum class NameType {
kModule = 0,
kFunction = 1,
kLocal = 2,
};
string_view data = section.contents;
while (!data.empty()) {
char type = ReadVarUInt7(&data);
uint32_t size = ReadVarUInt32(&data);
string_view section = ReadPiece(size, &data);
if (static_cast<NameType>(type) == NameType::kFunction) {
uint32_t count = ReadVarUInt32(§ion);
for (uint32_t i = 0; i < count; i++) {
string_view entry = section;
uint32_t index = ReadVarUInt32(§ion);
uint32_t name_len = ReadVarUInt32(§ion);
string_view name = ReadPiece(name_len, §ion);
entry = StrictSubstr(entry, 0, name.data() - entry.data() + name.size());
sink->AddFileRange("wasm_funcname", name, entry);
(*names)[index] = std::string(name);
}
}
}
}
int ReadValueType(string_view* data) {
return ReadVarint7(data);
}
int ReadElemType(string_view* data) {
return ReadVarint7(data);
}
void ReadResizableLimits(string_view* data) {
auto flags = ReadVarUInt1(data);
ReadVarUInt32(data);
if (flags) {
ReadVarUInt32(data);
}
}
void ReadGlobalType(string_view* data) {
ReadValueType(data);
ReadVarUInt1(data);
}
void ReadTableType(string_view* data) {
ReadElemType(data);
ReadResizableLimits(data);
}
void ReadMemoryType(string_view* data) {
ReadResizableLimits(data);
}
uint32_t GetNumFunctionImports(const Section& section) {
assert(section.id == Section::kImport);
string_view data = section.contents;
uint32_t count = ReadVarUInt32(&data);
uint32_t func_count = 0;
for (uint32_t i = 0; i < count; i++) {
uint32_t module_len = ReadVarUInt32(&data);
ReadPiece(module_len, &data);
uint32_t field_len = ReadVarUInt32(&data);
ReadPiece(field_len, &data);
auto kind = ReadFixed<uint8_t>(&data);
switch (kind) {
case ExternalKind::kFunction:
func_count++;
ReadVarUInt32(&data);
break;
case ExternalKind::kTable:
ReadTableType(&data);
break;
case ExternalKind::kMemory:
ReadMemoryType(&data);
break;
case ExternalKind::kGlobal:
ReadGlobalType(&data);
break;
default:
THROWF("Unrecognized import kind: $0", kind);
}
}
return func_count;
}
void ReadCodeSection(const Section& section, const FuncNames& names,
uint32_t num_imports, RangeSink* sink) {
string_view data = section.contents;
uint32_t count = ReadVarUInt32(&data);
for (uint32_t i = 0; i < count; i++) {
string_view func = data;
uint32_t size = ReadVarUInt32(&data);
uint32_t total_size = size + (data.data() - func.data());
func = StrictSubstr(func, 0, total_size);
data = StrictSubstr(data, size);
auto iter = names.find(num_imports + i);
if (iter == names.end()) {
std::string name = "func[" + std::to_string(i) + "]";
sink->AddFileRange("wasm_function", name, func);
} else {
sink->AddFileRange("wasm_function", ItaniumDemangle(iter->second, sink->data_source()), func);
}
}
}
void ParseSymbols(RangeSink* sink) {
// First pass: read the custom naming section to get function names.
std::unordered_map<int, std::string> func_names;
uint32_t num_imports = 0;
ForEachSection(sink->input_file().data(),
[&func_names, sink](const Section& section) {
if (section.name == "name") {
ReadFunctionNames(section, &func_names, sink);
}
});
// Second pass: read the function/code sections.
ForEachSection(sink->input_file().data(),
[&func_names, &num_imports, sink](const Section& section) {
if (section.id == Section::kImport) {
num_imports = GetNumFunctionImports(section);
} else if (section.id == Section::kCode) {
ReadCodeSection(section, func_names, num_imports, sink);
}
});
}
void AddWebAssemblyFallback(RangeSink* sink) {
ForEachSection(sink->input_file().data(), [sink](const Section& section) {
std::string name2 =
std::string("[section ") + std::string(section.name) + std::string("]");
sink->AddFileRange("wasm_overhead", name2, section.data);
});
sink->AddFileRange("wasm_overhead", "[WASM Header]",
StrictSubstr(sink->input_file().data(), 0, 8));
}
class WebAssemblyObjectFile : public ObjectFile {
public:
WebAssemblyObjectFile(std::unique_ptr<InputFile> file_data)
: ObjectFile(std::move(file_data)) {}
std::string GetBuildId() const override {
// TODO(haberman): does WebAssembly support this?
return std::string();
}
void ProcessFile(const std::vector<RangeSink*>& sinks) const override {
for (auto sink : sinks) {
switch (sink->data_source()) {
case DataSource::kSegments:
case DataSource::kSections:
ParseSections(sink);
break;
case DataSource::kSymbols:
case DataSource::kRawSymbols:
case DataSource::kShortSymbols:
case DataSource::kFullSymbols:
ParseSymbols(sink);
break;
case DataSource::kArchiveMembers:
case DataSource::kCompileUnits:
case DataSource::kInlines:
default:
THROW("WebAssembly doesn't support this data source");
}
AddWebAssemblyFallback(sink);
}
}
bool GetDisassemblyInfo(absl::string_view /*symbol*/,
DataSource /*symbol_source*/,
DisassemblyInfo* /*info*/) const override {
WARN("WebAssembly files do not support disassembly yet");
return false;
}
};
} // namespace wasm
std::unique_ptr<ObjectFile> TryOpenWebAssemblyFile(
std::unique_ptr<InputFile>& file) {
string_view data = file->data();
if (wasm::ReadMagic(&data)) {
return std::unique_ptr<ObjectFile>(
new wasm::WebAssemblyObjectFile(std::move(file)));
}
return nullptr;
}
} // namespace bloaty
<|endoftext|> |
<commit_before>/**
* There are two member functions in storage_t class which you need to use to operate with
* prepared statements: storage_t::prepare and storage_t::execute.
* Also if you need to rebind arguments just use get<N>(statement) = ... syntax
* just like you do with std::tuple.
* Once a statement is prepared it holds a connection to a database inside. This connection will be open
* until at least one statement object exists.
*/
#include <sqlite_orm/sqlite_orm.h>
#include <iostream>
using namespace sqlite_orm;
using std::cout;
using std::endl;
struct Doctor {
int doctor_id = 0;
std::string doctor_name;
std::string degree;
};
struct Speciality {
int spl_id = 0;
std::string spl_descrip;
int doctor_id = 0;
};
struct Visit {
int doctor_id = 0;
std::string patient_name;
std::string vdate;
};
int main() {
auto storage = make_storage("prepared.sqlite",
make_table("doctors",
make_column("doctor_id", &Doctor::doctor_id, primary_key()),
make_column("doctor_name", &Doctor::doctor_name),
make_column("degree", &Doctor::degree)),
make_table("speciality",
make_column("spl_id", &Speciality::spl_id, primary_key()),
make_column("spl_descrip", &Speciality::spl_descrip),
make_column("doctor_id", &Speciality::doctor_id)),
make_table("visits",
make_column("doctor_id", &Visit::doctor_id),
make_column("patient_name", &Visit::patient_name),
make_column("vdate", &Visit::vdate)));
storage.sync_schema();
storage.remove_all<Doctor>();
storage.remove_all<Speciality>();
storage.remove_all<Visit>();
{
// first we create a statement object for replace query with a doctor object
auto replaceStatement = storage.prepare(replace(Doctor{210, "Dr. John Linga", "MD"}));
cout << "replaceStatement = " << replaceStatement.sql() << endl;
// next we execute our statement
storage.execute(replaceStatement);
// now 'doctors' table has one row [210, 'Dr. John Linga', 'MD']
// Next we shall reuse the statement to replace another doctor
// replaceStatement contains a doctor inside it which can be obtained
// with get<0>(statement) function
get<0>(replaceStatement) = {211, "Dr. Peter Hall", "MBBS"};
storage.execute(replaceStatement);
// now 'doctors' table has two rows.
// Next we shall reuse the statement again with member assignment
auto &doctor = get<0>(replaceStatement); // doctor is Doctor &
doctor.doctor_id = 212;
doctor.doctor_name = "Dr. Ke Gee";
doctor.degree = "MD";
storage.execute(replaceStatement);
// now 'doctors' table has three rows.
}
{
// also prepared statement can store arguments by reference. To do this you can
// pass a std::reference_wrapper instead of object value.
Doctor doctorToReplace{213, "Dr. Pat Fay", "MD"};
auto replaceStatementByRef = storage.prepare(replace(std::ref(doctorToReplace)));
cout << "replaceStatementByRef = " << replaceStatementByRef.sql() << endl;
storage.execute(replaceStatementByRef);
// now 'doctors' table has four rows.
// next we shall change doctorToReplace object and then execute our statement.
// Statement will be affected cause it stores a reference to the doctor
doctorToReplace.doctor_id = 214;
doctorToReplace.doctor_name = "Mosby";
doctorToReplace.degree = "MBBS";
storage.execute(replaceStatementByRef);
// and now 'doctors' table has five rows
}
cout << "Doctors count = " << storage.count<Doctor>() << endl;
for(auto &doctor : storage.iterate<Doctor>()) {
cout << storage.dump(doctor) << endl;
}
{
auto insertStatement = storage.prepare(insert(Speciality{1, "CARDIO", 211}));
cout << "insertStatement = " << insertStatement.sql() << endl;
storage.execute(insertStatement);
get<0>(insertStatement) = {2, "NEURO", 213};
storage.execute(insertStatement);
get<0>(insertStatement) = {3, "ARTHO", 212};
storage.execute(insertStatement);
get<0>(insertStatement) = {4, "GYNO", 210};
storage.execute(insertStatement);
}
cout << "Specialities count = " << storage.count<Speciality>() << endl;
for(auto &speciality : storage.iterate<Speciality>()) {
cout << storage.dump(speciality) << endl;
}
{
// let's insert (replace) 5 visits. We create two vectors with 2 visits each
std::vector<Visit> visits;
visits.push_back({210, "Julia Nayer", "2013-10-15"});
visits.push_back({214, "TJ Olson", "2013-10-14"});
// let's make a statement
auto replaceRangeStatement = storage.prepare(replace_range(visits.begin(), visits.end()));
cout << "replaceRangeStatement = " << replaceRangeStatement.sql() << endl;
// replace two objects
storage.execute(replaceRangeStatement);
std::vector<Visit> visits2;
visits2.push_back({215, "John Seo", "2013-10-15"});
visits2.push_back({212, "James Marlow", "2013-10-16"});
// reassign iterators to point to other visits. Beware that if end - begin
// will have different distance then you'll get a runtime error cause statement is
// already compiled with a fixed amount of arguments to bind
get<0>(replaceRangeStatement) = visits2.begin();
get<1>(replaceRangeStatement) = visits2.end();
storage.execute(replaceRangeStatement);
storage.replace(Visit{212, "Jason Mallin", "2013-10-12"});
}
cout << "Visits count = " << storage.count<Visit>() << endl;
for(auto &visit : storage.iterate<Visit>()) {
cout << storage.dump(visit) << endl;
}
{
// SELECT doctor_id
// FROM visits
// WHERE LENGTH(patient_name) > 8
auto selectStatement = storage.prepare(select(&Visit::doctor_id, where(length(&Visit::patient_name) > 8)));
cout << "selectStatement = " << selectStatement.sql() << endl;
{
auto rows = storage.execute(selectStatement);
cout << "rows count = " << rows.size() << endl;
for(auto &id : rows) {
cout << id << endl;
}
}
// same statement, other bound values
// SELECT doctor_id
// FROM visits
// WHERE LENGTH(patient_name) > 11
{
get<0>(selectStatement) = 11;
auto rows = storage.execute(selectStatement);
cout << "rows count = " << rows.size() << endl;
for(auto &id : rows) {
cout << id << endl;
}
}
}
{
// SELECT rowid, 'Doctor ' || doctor_name
// FROM doctors
// WHERE degree LIKE '%S'
auto selectStatement = storage.prepare(select(columns(rowid(), "Doctor " || c(&Doctor::doctor_name)), where(like(&Doctor::degree, "%S"))));
cout << "selectStatement = " << selectStatement.sql() << endl;
{
auto rows = storage.execute(selectStatement);
cout << "rows count = " << rows.size() << endl;
for(auto &row : rows) {
cout << get<0>(row) << '\t' << get<1>(row) << endl;
}
}
// SELECT rowid, 'Nice ' || doctor_name
// FROM doctors
// WHERE degree LIKE '%D'
get<0>(selectStatement) = "Nice ";
get<1>(selectStatement) = "%D";
{
auto rows = storage.execute(selectStatement);
cout << "rows count = " << rows.size() << endl;
for(auto &row : rows) {
cout << get<0>(row) << '\t' << get<1>(row) << endl;
}
}
}
return 0;
}
<commit_msg>code format<commit_after>/**
* There are two member functions in storage_t class which you need to use to operate with
* prepared statements: storage_t::prepare and storage_t::execute.
* Also if you need to rebind arguments just use get<N>(statement) = ... syntax
* just like you do with std::tuple.
* Once a statement is prepared it holds a connection to a database inside. This connection will be open
* until at least one statement object exists.
*/
#include <sqlite_orm/sqlite_orm.h>
#include <iostream>
using namespace sqlite_orm;
using std::cout;
using std::endl;
struct Doctor {
int doctor_id = 0;
std::string doctor_name;
std::string degree;
};
struct Speciality {
int spl_id = 0;
std::string spl_descrip;
int doctor_id = 0;
};
struct Visit {
int doctor_id = 0;
std::string patient_name;
std::string vdate;
};
int main() {
auto storage = make_storage("prepared.sqlite",
make_table("doctors",
make_column("doctor_id", &Doctor::doctor_id, primary_key()),
make_column("doctor_name", &Doctor::doctor_name),
make_column("degree", &Doctor::degree)),
make_table("speciality",
make_column("spl_id", &Speciality::spl_id, primary_key()),
make_column("spl_descrip", &Speciality::spl_descrip),
make_column("doctor_id", &Speciality::doctor_id)),
make_table("visits",
make_column("doctor_id", &Visit::doctor_id),
make_column("patient_name", &Visit::patient_name),
make_column("vdate", &Visit::vdate)));
storage.sync_schema();
storage.remove_all<Doctor>();
storage.remove_all<Speciality>();
storage.remove_all<Visit>();
{
// first we create a statement object for replace query with a doctor object
auto replaceStatement = storage.prepare(replace(Doctor{210, "Dr. John Linga", "MD"}));
cout << "replaceStatement = " << replaceStatement.sql() << endl;
// next we execute our statement
storage.execute(replaceStatement);
// now 'doctors' table has one row [210, 'Dr. John Linga', 'MD']
// Next we shall reuse the statement to replace another doctor
// replaceStatement contains a doctor inside it which can be obtained
// with get<0>(statement) function
get<0>(replaceStatement) = {211, "Dr. Peter Hall", "MBBS"};
storage.execute(replaceStatement);
// now 'doctors' table has two rows.
// Next we shall reuse the statement again with member assignment
auto &doctor = get<0>(replaceStatement); // doctor is Doctor &
doctor.doctor_id = 212;
doctor.doctor_name = "Dr. Ke Gee";
doctor.degree = "MD";
storage.execute(replaceStatement);
// now 'doctors' table has three rows.
}
{
// also prepared statement can store arguments by reference. To do this you can
// pass a std::reference_wrapper instead of object value.
Doctor doctorToReplace{213, "Dr. Pat Fay", "MD"};
auto replaceStatementByRef = storage.prepare(replace(std::ref(doctorToReplace)));
cout << "replaceStatementByRef = " << replaceStatementByRef.sql() << endl;
storage.execute(replaceStatementByRef);
// now 'doctors' table has four rows.
// next we shall change doctorToReplace object and then execute our statement.
// Statement will be affected cause it stores a reference to the doctor
doctorToReplace.doctor_id = 214;
doctorToReplace.doctor_name = "Mosby";
doctorToReplace.degree = "MBBS";
storage.execute(replaceStatementByRef);
// and now 'doctors' table has five rows
}
cout << "Doctors count = " << storage.count<Doctor>() << endl;
for(auto &doctor: storage.iterate<Doctor>()) {
cout << storage.dump(doctor) << endl;
}
{
auto insertStatement = storage.prepare(insert(Speciality{1, "CARDIO", 211}));
cout << "insertStatement = " << insertStatement.sql() << endl;
storage.execute(insertStatement);
get<0>(insertStatement) = {2, "NEURO", 213};
storage.execute(insertStatement);
get<0>(insertStatement) = {3, "ARTHO", 212};
storage.execute(insertStatement);
get<0>(insertStatement) = {4, "GYNO", 210};
storage.execute(insertStatement);
}
cout << "Specialities count = " << storage.count<Speciality>() << endl;
for(auto &speciality: storage.iterate<Speciality>()) {
cout << storage.dump(speciality) << endl;
}
{
// let's insert (replace) 5 visits. We create two vectors with 2 visits each
std::vector<Visit> visits;
visits.push_back({210, "Julia Nayer", "2013-10-15"});
visits.push_back({214, "TJ Olson", "2013-10-14"});
// let's make a statement
auto replaceRangeStatement = storage.prepare(replace_range(visits.begin(), visits.end()));
cout << "replaceRangeStatement = " << replaceRangeStatement.sql() << endl;
// replace two objects
storage.execute(replaceRangeStatement);
std::vector<Visit> visits2;
visits2.push_back({215, "John Seo", "2013-10-15"});
visits2.push_back({212, "James Marlow", "2013-10-16"});
// reassign iterators to point to other visits. Beware that if end - begin
// will have different distance then you'll get a runtime error cause statement is
// already compiled with a fixed amount of arguments to bind
get<0>(replaceRangeStatement) = visits2.begin();
get<1>(replaceRangeStatement) = visits2.end();
storage.execute(replaceRangeStatement);
storage.replace(Visit{212, "Jason Mallin", "2013-10-12"});
}
cout << "Visits count = " << storage.count<Visit>() << endl;
for(auto &visit: storage.iterate<Visit>()) {
cout << storage.dump(visit) << endl;
}
{
// SELECT doctor_id
// FROM visits
// WHERE LENGTH(patient_name) > 8
auto selectStatement = storage.prepare(select(&Visit::doctor_id, where(length(&Visit::patient_name) > 8)));
cout << "selectStatement = " << selectStatement.sql() << endl;
{
auto rows = storage.execute(selectStatement);
cout << "rows count = " << rows.size() << endl;
for(auto &id: rows) {
cout << id << endl;
}
}
// same statement, other bound values
// SELECT doctor_id
// FROM visits
// WHERE LENGTH(patient_name) > 11
{
get<0>(selectStatement) = 11;
auto rows = storage.execute(selectStatement);
cout << "rows count = " << rows.size() << endl;
for(auto &id: rows) {
cout << id << endl;
}
}
}
{
// SELECT rowid, 'Doctor ' || doctor_name
// FROM doctors
// WHERE degree LIKE '%S'
auto selectStatement = storage.prepare(
select(columns(rowid(), "Doctor " || c(&Doctor::doctor_name)), where(like(&Doctor::degree, "%S"))));
cout << "selectStatement = " << selectStatement.sql() << endl;
{
auto rows = storage.execute(selectStatement);
cout << "rows count = " << rows.size() << endl;
for(auto &row: rows) {
cout << get<0>(row) << '\t' << get<1>(row) << endl;
}
}
// SELECT rowid, 'Nice ' || doctor_name
// FROM doctors
// WHERE degree LIKE '%D'
get<0>(selectStatement) = "Nice ";
get<1>(selectStatement) = "%D";
{
auto rows = storage.execute(selectStatement);
cout << "rows count = " << rows.size() << endl;
for(auto &row: rows) {
cout << get<0>(row) << '\t' << get<1>(row) << endl;
}
}
}
return 0;
}
<|endoftext|> |
<commit_before>// @(#)root/graf2d:$Id$
// Author: Sergey Linev <[email protected]>, 2019-10-04
#include "gtest/gtest.h"
#include "ROOT/RStyle.hxx"
#include "ROOT/RDrawable.hxx"
#include "ROOT/RAttrText.hxx"
#include "ROOT/RAttrLine.hxx"
#include "ROOT/RAttrBox.hxx"
using namespace ROOT::Experimental;
class CustomDrawable : public RDrawable {
RAttrLine fAttrLine{this, "line_"}; ///<! line attributes
RAttrBox fAttrBox{this, "box_"}; ///<! box attributes
RAttrText fAttrText{this, "text_"}; ///<! text attributes
public:
CustomDrawable() : RDrawable("custom") {}
const RAttrLine &GetAttrLine() const { return fAttrLine; }
CustomDrawable &SetAttrLine(const RAttrLine &attr) { fAttrLine = attr; return *this; }
RAttrLine &AttrLine() { return fAttrLine; }
const RAttrBox &GetAttrBox() const { return fAttrBox; }
CustomDrawable &SetAttrBox(RAttrBox &box) { fAttrBox = box; return *this; }
RAttrBox &AttrBox() { return fAttrBox; }
const RAttrText &GetAttrText() const { return fAttrText; }
CustomDrawable &SetAttrText(const RAttrText &attr) { fAttrText = attr; return *this; }
RAttrText &AttrText() { return fAttrText; }
};
TEST(RStyleTest, CreateStyle)
{
auto style = std::make_shared<RStyle>();
style->AddBlock("custom").AddDouble("line_width", 2.);
style->AddBlock("#customid").AddInt("box_fill_style", 5);
style->AddBlock(".custom_class").AddDouble("text_size", 3.);
CustomDrawable drawable;
drawable.SetId("customid");
drawable.SetCssClass("custom_class");
drawable.UseStyle(style);
EXPECT_DOUBLE_EQ(drawable.GetAttrLine().GetWidth(), 2.);
EXPECT_EQ(drawable.AttrBox().GetAttrFill().GetStyle(), 5);
EXPECT_DOUBLE_EQ(drawable.GetAttrText().GetSize(), 3.);
}
TEST(RStyleTest, LostStyle)
{
CustomDrawable drawable;
{
auto style = std::make_shared<RStyle>();
style->AddBlock("custom").AddDouble("line_width", 2.);
// here weak_ptr will be set, therefore after style is deleted drawable will loose it
drawable.UseStyle(style);
EXPECT_DOUBLE_EQ(drawable.GetAttrLine().GetWidth(), 2.);
}
// here style no longer exists
EXPECT_DOUBLE_EQ(drawable.GetAttrLine().GetWidth(), 1.);
}
<commit_msg>[rstyle] provide testing based on css parsing<commit_after>// @(#)root/graf2d:$Id$
// Author: Sergey Linev <[email protected]>, 2019-10-04
#include "gtest/gtest.h"
#include "ROOT/RStyle.hxx"
#include "ROOT/RDrawable.hxx"
#include "ROOT/RAttrText.hxx"
#include "ROOT/RAttrLine.hxx"
#include "ROOT/RAttrBox.hxx"
using namespace ROOT::Experimental;
class CustomDrawable : public RDrawable {
RAttrLine fAttrLine{this, "line_"}; ///<! line attributes
RAttrBox fAttrBox{this, "box_"}; ///<! box attributes
RAttrText fAttrText{this, "text_"}; ///<! text attributes
public:
CustomDrawable() : RDrawable("custom") {}
const RAttrLine &GetAttrLine() const { return fAttrLine; }
CustomDrawable &SetAttrLine(const RAttrLine &attr) { fAttrLine = attr; return *this; }
RAttrLine &AttrLine() { return fAttrLine; }
const RAttrBox &GetAttrBox() const { return fAttrBox; }
CustomDrawable &SetAttrBox(RAttrBox &box) { fAttrBox = box; return *this; }
RAttrBox &AttrBox() { return fAttrBox; }
const RAttrText &GetAttrText() const { return fAttrText; }
CustomDrawable &SetAttrText(const RAttrText &attr) { fAttrText = attr; return *this; }
RAttrText &AttrText() { return fAttrText; }
};
TEST(RStyleTest, CreateStyle)
{
auto style = std::make_shared<RStyle>();
style->AddBlock("custom").AddDouble("line_width", 2.);
style->AddBlock("#customid").AddInt("box_fill_style", 5);
style->AddBlock(".custom_class").AddDouble("text_size", 3.);
CustomDrawable drawable;
drawable.SetId("customid");
drawable.SetCssClass("custom_class");
drawable.UseStyle(style);
EXPECT_DOUBLE_EQ(drawable.GetAttrLine().GetWidth(), 2.);
EXPECT_EQ(drawable.AttrBox().GetAttrFill().GetStyle(), 5);
EXPECT_DOUBLE_EQ(drawable.GetAttrText().GetSize(), 3.);
}
TEST(RStyleTest, CreateCss)
{
auto style = std::make_shared<RStyle>();
auto res = style->ParseString("custom { line_width: 2; } #customid { box_fill_style: 5; } .custom_class { text_size: 3; }");
ASSERT_EQ(res, true);
CustomDrawable drawable;
drawable.SetId("customid");
drawable.SetCssClass("custom_class");
drawable.UseStyle(style);
EXPECT_DOUBLE_EQ(drawable.GetAttrLine().GetWidth(), 2.);
EXPECT_EQ(drawable.AttrBox().GetAttrFill().GetStyle(), 5);
EXPECT_DOUBLE_EQ(drawable.GetAttrText().GetSize(), 3.);
}
TEST(RStyleTest, LostStyle)
{
CustomDrawable drawable;
{
auto style = std::make_shared<RStyle>();
style->AddBlock("custom").AddDouble("line_width", 2.);
// here weak_ptr will be set, therefore after style is deleted drawable will loose it
drawable.UseStyle(style);
EXPECT_DOUBLE_EQ(drawable.GetAttrLine().GetWidth(), 2.);
}
// here style no longer exists
EXPECT_DOUBLE_EQ(drawable.GetAttrLine().GetWidth(), 1.);
}
<|endoftext|> |
<commit_before>/*=========================================================================
Program: Visualization Toolkit
Module: vtkContourFilter.cxx
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) 1993-2001 Ken Martin, Will Schroeder, Bill Lorensen
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 name of Ken Martin, Will Schroeder, or Bill Lorensen nor the names
of any contributors may be used to endorse or promote products derived
from this software without specific prior written permission.
* Modified source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
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 AUTHORS 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 <math.h>
#include "vtkContourFilter.h"
#include "vtkScalars.h"
#include "vtkCell.h"
#include "vtkMergePoints.h"
#include "vtkContourValues.h"
#include "vtkScalarTree.h"
#include "vtkObjectFactory.h"
#include "vtkTimerLog.h"
#include "vtkUnstructuredGrid.h"
#include "vtkContourGrid.h"
//------------------------------------------------------------------------------
vtkContourFilter* vtkContourFilter::New()
{
// First try to create the object from the vtkObjectFactory
vtkObject* ret = vtkObjectFactory::CreateInstance("vtkContourFilter");
if(ret)
{
return (vtkContourFilter*)ret;
}
// If the factory was unable to create the object, then create it here.
return new vtkContourFilter;
}
// Construct object with initial range (0,1) and single contour value
// of 0.0.
vtkContourFilter::vtkContourFilter()
{
this->ContourValues = vtkContourValues::New();
this->ComputeNormals = 1;
this->ComputeGradients = 0;
this->ComputeScalars = 1;
this->Locator = NULL;
this->UseScalarTree = 0;
this->ScalarTree = NULL;
}
vtkContourFilter::~vtkContourFilter()
{
this->ContourValues->Delete();
if ( this->Locator )
{
this->Locator->UnRegister(this);
this->Locator = NULL;
}
if ( this->ScalarTree )
{
this->ScalarTree->Delete();
}
}
// Overload standard modified time function. If contour values are modified,
// then this object is modified as well.
unsigned long vtkContourFilter::GetMTime()
{
unsigned long mTime=this->vtkDataSetToPolyDataFilter::GetMTime();
unsigned long time;
if (this->ContourValues)
{
time = this->ContourValues->GetMTime();
mTime = ( time > mTime ? time : mTime );
}
if (this->Locator)
{
time = this->Locator->GetMTime();
mTime = ( time > mTime ? time : mTime );
}
return mTime;
}
//
// General contouring filter. Handles arbitrary input.
//
void vtkContourFilter::Execute()
{
int cellId, i, abortExecute=0;
vtkIdList *cellPts;
vtkScalars *inScalars;
vtkCell *cell;
float range[2];
vtkCellArray *newVerts, *newLines, *newPolys;
vtkPoints *newPts;
vtkDataSet *input=this->GetInput();
vtkPolyData *output=this->GetOutput();
int numCells, estimatedSize;
vtkPointData *inPd=input->GetPointData(), *outPd=output->GetPointData();
vtkCellData *inCd=input->GetCellData(), *outCd=output->GetCellData();
int numContours=this->ContourValues->GetNumberOfContours();
float *values=this->ContourValues->GetValues();
vtkScalars *cellScalars;
vtkDebugMacro(<< "Executing contour filter");
if (input->GetDataObjectType() == VTK_UNSTRUCTURED_GRID)
{
vtkDebugMacro(<< "executing contour grid filter");
vtkContourGrid *cgrid;
cgrid = vtkContourGrid::New();
cgrid->SetInput(input);
for (i = 0; i < numContours; i++)
{
cgrid->SetValue(i, values[i]);
}
cgrid->Update();
output->ShallowCopy(cgrid->GetOutput());
cgrid->Delete();
} //if type VTK_UNSTRUCTURED_GRID
else
{
numCells = input->GetNumberOfCells();
inScalars = input->GetPointData()->GetScalars();
if ( ! inScalars || numCells < 1 )
{
vtkErrorMacro(<<"No data to contour");
return;
}
inScalars->GetRange(range);
//
// Create objects to hold output of contour operation. First estimate
// allocation size.
//
estimatedSize = (int) pow ((double) numCells, .75);
estimatedSize *= numContours;
estimatedSize = estimatedSize / 1024 * 1024; //multiple of 1024
if (estimatedSize < 1024)
{
estimatedSize = 1024;
}
newPts = vtkPoints::New();
newPts->Allocate(estimatedSize,estimatedSize);
newVerts = vtkCellArray::New();
newVerts->Allocate(estimatedSize,estimatedSize);
newLines = vtkCellArray::New();
newLines->Allocate(estimatedSize,estimatedSize);
newPolys = vtkCellArray::New();
newPolys->Allocate(estimatedSize,estimatedSize);
cellScalars = vtkScalars::New();
cellScalars->Allocate(VTK_CELL_SIZE);
// locator used to merge potentially duplicate points
if ( this->Locator == NULL )
{
this->CreateDefaultLocator();
}
this->Locator->InitPointInsertion (newPts, input->GetBounds(),estimatedSize);
// interpolate data along edge
// if we did not ask for scalars to be computed, don't copy them
if (!this->ComputeScalars)
{
outPd->CopyScalarsOff();
}
outPd->InterpolateAllocate(inPd,estimatedSize,estimatedSize);
outCd->CopyAllocate(inCd,estimatedSize,estimatedSize);
// If enabled, build a scalar tree to accelerate search
//
if ( !this->UseScalarTree )
{
for (cellId=0; cellId < numCells && !abortExecute; cellId++)
{
cell = input->GetCell(cellId);
cellPts = cell->GetPointIds();
inScalars->GetScalars(cellPts,cellScalars);
if ( ! (cellId % 5000) )
{
vtkDebugMacro(<<"Contouring #" << cellId);
this->UpdateProgress ((float)cellId/numCells);
if (this->GetAbortExecute())
{
abortExecute = 1;
break;
}
}
for (i=0; i < numContours; i++)
{
cell->Contour(values[i], cellScalars, this->Locator,
newVerts, newLines, newPolys, inPd, outPd,
inCd, cellId, outCd);
} // for all contour values
} // for all cells
} //if using scalar tree
else
{
if ( this->ScalarTree == NULL )
{
this->ScalarTree = vtkScalarTree::New();
}
this->ScalarTree->SetDataSet(input);
//
// Loop over all contour values. Then for each contour value,
// loop over all cells.
//
for (i=0; i < numContours; i++)
{
for ( this->ScalarTree->InitTraversal(values[i]);
(cell=this->ScalarTree->GetNextCell(cellId,cellPts,cellScalars)) != NULL; )
{
cell->Contour(values[i], cellScalars, this->Locator,
newVerts, newLines, newPolys, inPd, outPd,
inCd, cellId, outCd);
} //for all cells
} //for all contour values
} //using scalar tree
vtkDebugMacro(<<"Created: "
<< newPts->GetNumberOfPoints() << " points, "
<< newVerts->GetNumberOfCells() << " verts, "
<< newLines->GetNumberOfCells() << " lines, "
<< newPolys->GetNumberOfCells() << " triangles");
//
// Update ourselves. Because we don't know up front how many verts, lines,
// polys we've created, take care to reclaim memory.
//
output->SetPoints(newPts);
newPts->Delete();
cellScalars->Delete();
if (newVerts->GetNumberOfCells())
{
output->SetVerts(newVerts);
}
newVerts->Delete();
if (newLines->GetNumberOfCells())
{
output->SetLines(newLines);
}
newLines->Delete();
if (newPolys->GetNumberOfCells())
{
output->SetPolys(newPolys);
}
newPolys->Delete();
this->Locator->Initialize();//releases leftover memory
output->Squeeze();
} //else (for if vtkUnstructuredGrid)
}
// Specify a spatial locator for merging points. By default,
// an instance of vtkMergePoints is used.
void vtkContourFilter::SetLocator(vtkPointLocator *locator)
{
if ( this->Locator == locator )
{
return;
}
if ( this->Locator )
{
this->Locator->UnRegister(this);
this->Locator = NULL;
}
if ( locator )
{
locator->Register(this);
}
this->Locator = locator;
this->Modified();
}
void vtkContourFilter::CreateDefaultLocator()
{
if ( this->Locator == NULL )
{
this->Locator = vtkMergePoints::New();
}
}
void vtkContourFilter::PrintSelf(ostream& os, vtkIndent indent)
{
vtkDataSetToPolyDataFilter::PrintSelf(os,indent);
os << indent << "Compute Gradients: " << (this->ComputeGradients ? "On\n" : "Off\n");
os << indent << "Compute Normals: " << (this->ComputeNormals ? "On\n" : "Off\n");
os << indent << "Compute Scalars: " << (this->ComputeScalars ? "On\n" : "Off\n");
os << indent << "Use Scalar Tree: " << (this->UseScalarTree ? "On\n" : "Off\n");
this->ContourValues->PrintSelf(os,indent);
if ( this->Locator )
{
os << indent << "Locator: " << this->Locator << "\n";
}
else
{
os << indent << "Locator: (none)\n";
}
}
<commit_msg>Need to copy the requested piece.<commit_after>/*=========================================================================
Program: Visualization Toolkit
Module: vtkContourFilter.cxx
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) 1993-2001 Ken Martin, Will Schroeder, Bill Lorensen
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 name of Ken Martin, Will Schroeder, or Bill Lorensen nor the names
of any contributors may be used to endorse or promote products derived
from this software without specific prior written permission.
* Modified source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
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 AUTHORS 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 <math.h>
#include "vtkContourFilter.h"
#include "vtkScalars.h"
#include "vtkCell.h"
#include "vtkMergePoints.h"
#include "vtkContourValues.h"
#include "vtkScalarTree.h"
#include "vtkObjectFactory.h"
#include "vtkTimerLog.h"
#include "vtkUnstructuredGrid.h"
#include "vtkContourGrid.h"
//------------------------------------------------------------------------------
vtkContourFilter* vtkContourFilter::New()
{
// First try to create the object from the vtkObjectFactory
vtkObject* ret = vtkObjectFactory::CreateInstance("vtkContourFilter");
if(ret)
{
return (vtkContourFilter*)ret;
}
// If the factory was unable to create the object, then create it here.
return new vtkContourFilter;
}
// Construct object with initial range (0,1) and single contour value
// of 0.0.
vtkContourFilter::vtkContourFilter()
{
this->ContourValues = vtkContourValues::New();
this->ComputeNormals = 1;
this->ComputeGradients = 0;
this->ComputeScalars = 1;
this->Locator = NULL;
this->UseScalarTree = 0;
this->ScalarTree = NULL;
}
vtkContourFilter::~vtkContourFilter()
{
this->ContourValues->Delete();
if ( this->Locator )
{
this->Locator->UnRegister(this);
this->Locator = NULL;
}
if ( this->ScalarTree )
{
this->ScalarTree->Delete();
}
}
// Overload standard modified time function. If contour values are modified,
// then this object is modified as well.
unsigned long vtkContourFilter::GetMTime()
{
unsigned long mTime=this->vtkDataSetToPolyDataFilter::GetMTime();
unsigned long time;
if (this->ContourValues)
{
time = this->ContourValues->GetMTime();
mTime = ( time > mTime ? time : mTime );
}
if (this->Locator)
{
time = this->Locator->GetMTime();
mTime = ( time > mTime ? time : mTime );
}
return mTime;
}
//
// General contouring filter. Handles arbitrary input.
//
void vtkContourFilter::Execute()
{
int cellId, i, abortExecute=0;
vtkIdList *cellPts;
vtkScalars *inScalars;
vtkCell *cell;
float range[2];
vtkCellArray *newVerts, *newLines, *newPolys;
vtkPoints *newPts;
vtkDataSet *input=this->GetInput();
vtkPolyData *output=this->GetOutput();
int numCells, estimatedSize;
vtkPointData *inPd=input->GetPointData(), *outPd=output->GetPointData();
vtkCellData *inCd=input->GetCellData(), *outCd=output->GetCellData();
int numContours=this->ContourValues->GetNumberOfContours();
float *values=this->ContourValues->GetValues();
vtkScalars *cellScalars;
vtkDebugMacro(<< "Executing contour filter");
if (input->GetDataObjectType() == VTK_UNSTRUCTURED_GRID)
{
vtkDebugMacro(<< "executing contour grid filter");
vtkContourGrid *cgrid;
cgrid = vtkContourGrid::New();
cgrid->SetInput(input);
for (i = 0; i < numContours; i++)
{
cgrid->SetValue(i, values[i]);
}
cgrid->GetOutput()->SetUpdateExtent(output->GetUpdatePiece(),
output->GetUpdateNumberOfPieces(),
output->GetUpdateGhostLevel());
cgrid->Update();
output->ShallowCopy(cgrid->GetOutput());
cgrid->Delete();
} //if type VTK_UNSTRUCTURED_GRID
else
{
numCells = input->GetNumberOfCells();
inScalars = input->GetPointData()->GetScalars();
if ( ! inScalars || numCells < 1 )
{
vtkErrorMacro(<<"No data to contour");
return;
}
inScalars->GetRange(range);
//
// Create objects to hold output of contour operation. First estimate
// allocation size.
//
estimatedSize = (int) pow ((double) numCells, .75);
estimatedSize *= numContours;
estimatedSize = estimatedSize / 1024 * 1024; //multiple of 1024
if (estimatedSize < 1024)
{
estimatedSize = 1024;
}
newPts = vtkPoints::New();
newPts->Allocate(estimatedSize,estimatedSize);
newVerts = vtkCellArray::New();
newVerts->Allocate(estimatedSize,estimatedSize);
newLines = vtkCellArray::New();
newLines->Allocate(estimatedSize,estimatedSize);
newPolys = vtkCellArray::New();
newPolys->Allocate(estimatedSize,estimatedSize);
cellScalars = vtkScalars::New();
cellScalars->Allocate(VTK_CELL_SIZE);
// locator used to merge potentially duplicate points
if ( this->Locator == NULL )
{
this->CreateDefaultLocator();
}
this->Locator->InitPointInsertion (newPts, input->GetBounds(),estimatedSize);
// interpolate data along edge
// if we did not ask for scalars to be computed, don't copy them
if (!this->ComputeScalars)
{
outPd->CopyScalarsOff();
}
outPd->InterpolateAllocate(inPd,estimatedSize,estimatedSize);
outCd->CopyAllocate(inCd,estimatedSize,estimatedSize);
// If enabled, build a scalar tree to accelerate search
//
if ( !this->UseScalarTree )
{
for (cellId=0; cellId < numCells && !abortExecute; cellId++)
{
cell = input->GetCell(cellId);
cellPts = cell->GetPointIds();
inScalars->GetScalars(cellPts,cellScalars);
if ( ! (cellId % 5000) )
{
vtkDebugMacro(<<"Contouring #" << cellId);
this->UpdateProgress ((float)cellId/numCells);
if (this->GetAbortExecute())
{
abortExecute = 1;
break;
}
}
for (i=0; i < numContours; i++)
{
cell->Contour(values[i], cellScalars, this->Locator,
newVerts, newLines, newPolys, inPd, outPd,
inCd, cellId, outCd);
} // for all contour values
} // for all cells
} //if using scalar tree
else
{
if ( this->ScalarTree == NULL )
{
this->ScalarTree = vtkScalarTree::New();
}
this->ScalarTree->SetDataSet(input);
//
// Loop over all contour values. Then for each contour value,
// loop over all cells.
//
for (i=0; i < numContours; i++)
{
for ( this->ScalarTree->InitTraversal(values[i]);
(cell=this->ScalarTree->GetNextCell(cellId,cellPts,cellScalars)) != NULL; )
{
cell->Contour(values[i], cellScalars, this->Locator,
newVerts, newLines, newPolys, inPd, outPd,
inCd, cellId, outCd);
} //for all cells
} //for all contour values
} //using scalar tree
vtkDebugMacro(<<"Created: "
<< newPts->GetNumberOfPoints() << " points, "
<< newVerts->GetNumberOfCells() << " verts, "
<< newLines->GetNumberOfCells() << " lines, "
<< newPolys->GetNumberOfCells() << " triangles");
//
// Update ourselves. Because we don't know up front how many verts, lines,
// polys we've created, take care to reclaim memory.
//
output->SetPoints(newPts);
newPts->Delete();
cellScalars->Delete();
if (newVerts->GetNumberOfCells())
{
output->SetVerts(newVerts);
}
newVerts->Delete();
if (newLines->GetNumberOfCells())
{
output->SetLines(newLines);
}
newLines->Delete();
if (newPolys->GetNumberOfCells())
{
output->SetPolys(newPolys);
}
newPolys->Delete();
this->Locator->Initialize();//releases leftover memory
output->Squeeze();
} //else (for if vtkUnstructuredGrid)
}
// Specify a spatial locator for merging points. By default,
// an instance of vtkMergePoints is used.
void vtkContourFilter::SetLocator(vtkPointLocator *locator)
{
if ( this->Locator == locator )
{
return;
}
if ( this->Locator )
{
this->Locator->UnRegister(this);
this->Locator = NULL;
}
if ( locator )
{
locator->Register(this);
}
this->Locator = locator;
this->Modified();
}
void vtkContourFilter::CreateDefaultLocator()
{
if ( this->Locator == NULL )
{
this->Locator = vtkMergePoints::New();
}
}
void vtkContourFilter::PrintSelf(ostream& os, vtkIndent indent)
{
vtkDataSetToPolyDataFilter::PrintSelf(os,indent);
os << indent << "Compute Gradients: " << (this->ComputeGradients ? "On\n" : "Off\n");
os << indent << "Compute Normals: " << (this->ComputeNormals ? "On\n" : "Off\n");
os << indent << "Compute Scalars: " << (this->ComputeScalars ? "On\n" : "Off\n");
os << indent << "Use Scalar Tree: " << (this->UseScalarTree ? "On\n" : "Off\n");
this->ContourValues->PrintSelf(os,indent);
if ( this->Locator )
{
os << indent << "Locator: " << this->Locator << "\n";
}
else
{
os << indent << "Locator: (none)\n";
}
}
<|endoftext|> |
<commit_before><commit_msg>ui: fix borders missing from height calculation<commit_after><|endoftext|> |
<commit_before>#include <x0/process.hpp>
#include <boost/asio.hpp>
#include <string>
#include <cstdlib>
#include <sys/types.h>
#include <sys/wait.h>
#include <signal.h>
#include <unistd.h>
namespace x0 {
/** invokes \p cmd until its not early aborted with EINTR. */
#define EINTR_LOOP(rv, cmd) \
do { \
rv = cmd; \
} while (rv == -1 && errno == EINTR)
process::process(boost::asio::io_service& io) :
input_(io), output_(io), error_(io), pid_(-1), status_(0)
{
}
process::process(boost::asio::io_service& io, const std::string& exe, const params& args, const environment& env, const std::string& workdir) :
input_(io), output_(io), error_(io), pid_(-1), status_(0)
{
start(exe, args, env, workdir);
}
process::~process()
{
// XXX kill child?
fetch_status();
}
void process::start(const std::string& exe, const params& args, const environment& env, const std::string& workdir)
{
//::fprintf(stderr, "proc[%d] start(exe=%s, args=[...], workdir=%s)\n", getpid(), exe.c_str(), workdir.c_str());
switch (pid_ = fork())
{
case 0: // child
setup_child(exe, args, env, workdir);
break;
case -1: // error
throw boost::system::system_error(boost::system::error_code(errno, boost::system::system_category));
default: // parent
setup_parent();
break;
}
}
void process::terminate()
{
::kill(pid_, SIGTERM);
}
bool process::expired()
{
if (pid_ <= 0)
return true;
switch (fetch_status())
{
case 0:
// we could fetch a status, meaning, program is still running
return false;
case -1:
// oops? waitpid error?
return false;
default:
// waidpid returned value > 0, meaning, program has returned already(?)
return true;
}
}
int process::fetch_status()
{
int rv;
do rv = ::waitpid(pid_, &status_, WNOHANG);
while (rv == -1 && (errno == EINTR || errno == ECHILD));
return rv;
}
void process::setup_parent()
{
// setup I/O
input_.remote().close();
output_.remote().close();
error_.remote().close();
}
void process::setup_child(const std::string& _exe, const params& _args, const environment& _env, const std::string& _workdir)
{
// restore signal handler(s)
::signal(SIGPIPE, SIG_DFL);
// setup environment
int k = 0;
std::vector<char *> env(_env.size() + 1);
for (environment::const_iterator i = _env.cbegin(), e = _env.cend(); i != e; ++i)
{
char *buf = new char[i->first.size() + i->second.size() + 2];
::memcpy(buf, i->first.c_str(), i->first.size());
buf[i->first.size()] = '=';
::memcpy(buf + i->first.size() + 1, i->second.c_str(), i->second.size() + 1);
//::fprintf(stderr, "proc[%d]: setting env[%d]: %s\n", getpid(), k, buf);
//::fflush(stderr);
env[k++] = buf;
}
env[_env.size()] = 0;
// setup args
std::vector<char *> args(_args.size() + 2);
args[0] = const_cast<char *>(_exe.c_str());
//::fprintf(stderr, "args[%d] = %s\n", 0, args[0]);
for (int i = 0, e = _args.size(); i != e; ++i)
{
args[i + 1] = const_cast<char *>(_args[i].c_str());
//::fprintf(stderr, "args[%d] = %s\n", i + 1, args[i + 1]);
}
args[args.size() - 1] = 0;
// chdir
if (!_workdir.empty())
{
::chdir(_workdir.c_str());
}
// setup I/O
int rv;
EINTR_LOOP(rv, ::close(STDIN_FILENO));
EINTR_LOOP(rv, ::close(STDOUT_FILENO));
EINTR_LOOP(rv, ::close(STDERR_FILENO));
EINTR_LOOP(rv, ::dup2(input_.remote().native(), STDIN_FILENO));
EINTR_LOOP(rv, ::dup2(output_.remote().native(), STDOUT_FILENO));
EINTR_LOOP(rv, ::dup2(error_.remote().native(), STDERR_FILENO));
// input_.close();
// output_.close();
// error_.close();
// finally execute
::execve(args[0], &args[0], &env[0]);
// OOPS
::fprintf(stderr, "proc[%d]: execve(%s) error: %s\n", getpid(), args[0], strerror(errno));
::fflush(stderr);
::_exit(1);
}
} // namespace x0
<commit_msg>core: improved process's child process exit handling (fixes defunct childs)<commit_after>#include <x0/process.hpp>
#include <boost/asio.hpp>
#include <string>
#include <cstdlib>
#include <sys/types.h>
#include <sys/wait.h>
#include <signal.h>
#include <unistd.h>
namespace x0 {
/** invokes \p cmd until its not early aborted with EINTR. */
#define EINTR_LOOP(rv, cmd) \
do { \
rv = cmd; \
} while (rv == -1 && errno == EINTR)
process::process(boost::asio::io_service& io) :
input_(io), output_(io), error_(io), pid_(-1), status_(0)
{
}
process::process(boost::asio::io_service& io, const std::string& exe, const params& args, const environment& env, const std::string& workdir) :
input_(io), output_(io), error_(io), pid_(-1), status_(0)
{
start(exe, args, env, workdir);
}
process::~process()
{
int rv;
EINTR_LOOP(rv, ::waitpid(pid_, &status_, 0));
//printf("~process(): rv=%d, errno=%s\n", rv, strerror(errno));
}
void process::start(const std::string& exe, const params& args, const environment& env, const std::string& workdir)
{
//::fprintf(stderr, "proc[%d] start(exe=%s, args=[...], workdir=%s)\n", getpid(), exe.c_str(), workdir.c_str());
switch (pid_ = fork())
{
case 0: // child
setup_child(exe, args, env, workdir);
break;
case -1: // error
throw boost::system::system_error(boost::system::error_code(errno, boost::system::system_category));
default: // parent
setup_parent();
break;
}
}
void process::terminate()
{
::kill(pid_, SIGTERM);
}
bool process::expired()
{
if (pid_ <= 0)
return true;
if ((fetch_status() == -1 && errno == ECHILD)
|| (WIFEXITED(status_) || WIFSIGNALED(status_)))
return true;
return false;
}
int process::fetch_status()
{
int rv;
do rv = ::waitpid(pid_, &status_, WNOHANG);
while (rv == -1 && errno == EINTR);
return rv;
}
void process::setup_parent()
{
// setup I/O
input_.remote().close();
output_.remote().close();
error_.remote().close();
}
void process::setup_child(const std::string& _exe, const params& _args, const environment& _env, const std::string& _workdir)
{
// restore signal handler(s)
::signal(SIGPIPE, SIG_DFL);
// setup environment
int k = 0;
std::vector<char *> env(_env.size() + 1);
for (environment::const_iterator i = _env.cbegin(), e = _env.cend(); i != e; ++i)
{
char *buf = new char[i->first.size() + i->second.size() + 2];
::memcpy(buf, i->first.c_str(), i->first.size());
buf[i->first.size()] = '=';
::memcpy(buf + i->first.size() + 1, i->second.c_str(), i->second.size() + 1);
//::fprintf(stderr, "proc[%d]: setting env[%d]: %s\n", getpid(), k, buf);
//::fflush(stderr);
env[k++] = buf;
}
env[_env.size()] = 0;
// setup args
std::vector<char *> args(_args.size() + 2);
args[0] = const_cast<char *>(_exe.c_str());
//::fprintf(stderr, "args[%d] = %s\n", 0, args[0]);
for (int i = 0, e = _args.size(); i != e; ++i)
{
args[i + 1] = const_cast<char *>(_args[i].c_str());
//::fprintf(stderr, "args[%d] = %s\n", i + 1, args[i + 1]);
}
args[args.size() - 1] = 0;
// chdir
if (!_workdir.empty())
{
::chdir(_workdir.c_str());
}
// setup I/O
int rv;
EINTR_LOOP(rv, ::close(STDIN_FILENO));
EINTR_LOOP(rv, ::close(STDOUT_FILENO));
EINTR_LOOP(rv, ::close(STDERR_FILENO));
EINTR_LOOP(rv, ::dup2(input_.remote().native(), STDIN_FILENO));
EINTR_LOOP(rv, ::dup2(output_.remote().native(), STDOUT_FILENO));
EINTR_LOOP(rv, ::dup2(error_.remote().native(), STDERR_FILENO));
// input_.close();
// output_.close();
// error_.close();
// finally execute
::execve(args[0], &args[0], &env[0]);
// OOPS
::fprintf(stderr, "proc[%d]: execve(%s) error: %s\n", getpid(), args[0], strerror(errno));
::fflush(stderr);
::_exit(1);
}
} // namespace x0
<|endoftext|> |
<commit_before>// -*-c++-*-
#include <osgProducer/Viewer>
#include <osgDB/ReadFile>
#include <osg/Geode>
#include <osg/Geometry>
#include <osg/StateSet>
#include <osg/Material>
#include <osg/Texture2D>
#include <osg/TextureRectangle>
#include <osg/TexMat>
#include <osg/CullFace>
#include <osg/ImageStream>
#include <osgGA/TrackballManipulator>
osg::ImageStream* s_imageStream = 0;
class PostSwapFinishCallback : public Producer::Camera::Callback
{
public:
PostSwapFinishCallback() {}
virtual void operator()(const Producer::Camera& camera)
{
// osg::Timer_t start_tick = osg::Timer::instance()->tick();
osgProducer::OsgSceneHandler* sh = const_cast<osgProducer::OsgSceneHandler*>(dynamic_cast<const osgProducer::OsgSceneHandler*>(camera.getSceneHandler()));
if (s_imageStream && s_imageStream->getPixelBufferObject()) s_imageStream->getPixelBufferObject()->compileBuffer(*(sh->getSceneView()->getState()));
// glFinish();
//osg::notify(osg::NOTICE)<<"callback after PBO "<<osg::Timer::instance()->delta_m(start_tick,osg::Timer::instance()->tick())<<"ms"<<std::endl;
}
};
class MovieEventHandler : public osgGA::GUIEventHandler
{
public:
MovieEventHandler() {}
void set(osg::Node* node);
virtual void accept(osgGA::GUIEventHandlerVisitor& v) { v.visit(*this); }
virtual bool handle(const osgGA::GUIEventAdapter& ea,osgGA::GUIActionAdapter&);
virtual void getUsage(osg::ApplicationUsage& usage) const;
typedef std::vector< osg::ref_ptr<osg::ImageStream> > ImageStreamList;
protected:
virtual ~MovieEventHandler() {}
class FindImageStreamsVisitor : public osg::NodeVisitor
{
public:
FindImageStreamsVisitor(ImageStreamList& imageStreamList):
_imageStreamList(imageStreamList) {}
virtual void apply(osg::Geode& geode)
{
apply(geode.getStateSet());
for(unsigned int i=0;i<geode.getNumDrawables();++i)
{
apply(geode.getDrawable(i)->getStateSet());
}
traverse(geode);
}
virtual void apply(osg::Node& node)
{
apply(node.getStateSet());
traverse(node);
}
inline void apply(osg::StateSet* stateset)
{
if (!stateset) return;
osg::StateAttribute* attr = stateset->getTextureAttribute(0,osg::StateAttribute::TEXTURE);
if (attr)
{
osg::Texture2D* texture2D = dynamic_cast<osg::Texture2D*>(attr);
if (texture2D) apply(dynamic_cast<osg::ImageStream*>(texture2D->getImage()));
osg::TextureRectangle* textureRec = dynamic_cast<osg::TextureRectangle*>(attr);
if (textureRec) apply(dynamic_cast<osg::ImageStream*>(textureRec->getImage()));
}
}
inline void apply(osg::ImageStream* imagestream)
{
if (imagestream)
{
_imageStreamList.push_back(imagestream);
s_imageStream = imagestream;
}
}
ImageStreamList& _imageStreamList;
};
ImageStreamList _imageStreamList;
};
void MovieEventHandler::set(osg::Node* node)
{
_imageStreamList.clear();
if (node)
{
FindImageStreamsVisitor fisv(_imageStreamList);
node->accept(fisv);
}
}
bool MovieEventHandler::handle(const osgGA::GUIEventAdapter& ea,osgGA::GUIActionAdapter&)
{
switch(ea.getEventType())
{
case(osgGA::GUIEventAdapter::KEYDOWN):
{
if (ea.getKey()=='s')
{
for(ImageStreamList::iterator itr=_imageStreamList.begin();
itr!=_imageStreamList.end();
++itr)
{
std::cout<<"Play"<<std::endl;
(*itr)->play();
}
return true;
}
else if (ea.getKey()=='p')
{
for(ImageStreamList::iterator itr=_imageStreamList.begin();
itr!=_imageStreamList.end();
++itr)
{
std::cout<<"Pause"<<std::endl;
(*itr)->pause();
}
return true;
}
else if (ea.getKey()=='r')
{
for(ImageStreamList::iterator itr=_imageStreamList.begin();
itr!=_imageStreamList.end();
++itr)
{
std::cout<<"Restart"<<std::endl;
(*itr)->rewind();
(*itr)->play();
}
return true;
}
else if (ea.getKey()=='l')
{
for(ImageStreamList::iterator itr=_imageStreamList.begin();
itr!=_imageStreamList.end();
++itr)
{
if ( (*itr)->getLoopingMode() == osg::ImageStream::LOOPING)
{
std::cout<<"Toggle Looping Off"<<std::endl;
(*itr)->setLoopingMode( osg::ImageStream::NO_LOOPING );
}
else
{
std::cout<<"Toggle Looping On"<<std::endl;
(*itr)->setLoopingMode( osg::ImageStream::LOOPING );
}
}
return true;
}
return false;
}
default:
return false;
}
}
void MovieEventHandler::getUsage(osg::ApplicationUsage& usage) const
{
usage.addKeyboardMouseBinding("p","Pause movie");
usage.addKeyboardMouseBinding("s","Play movie");
usage.addKeyboardMouseBinding("r","Restart movie");
usage.addKeyboardMouseBinding("l","Toggle looping of movie");
}
osg::Geometry* myCreateTexturedQuadGeometry(const osg::Vec3& pos,float width,float height, osg::Image* image, bool useTextureRectangle)
{
if (useTextureRectangle)
{
osg::Geometry* pictureQuad = osg::createTexturedQuadGeometry(pos,
osg::Vec3(width,0.0f,0.0f),
osg::Vec3(0.0f,0.0f,height),
0.0f,image->t(), image->s(),0.0f);
pictureQuad->getOrCreateStateSet()->setTextureAttributeAndModes(0,
new osg::TextureRectangle(image),
osg::StateAttribute::ON);
return pictureQuad;
}
else
{
osg::Geometry* pictureQuad = osg::createTexturedQuadGeometry(pos,
osg::Vec3(width,0.0f,0.0f),
osg::Vec3(0.0f,0.0f,height),
0.0f,1.0f, 1.0f,0.0f);
osg::Texture2D* texture = new osg::Texture2D(image);
texture->setFilter(osg::Texture::MIN_FILTER,osg::Texture::LINEAR);
pictureQuad->getOrCreateStateSet()->setTextureAttributeAndModes(0,
texture,
osg::StateAttribute::ON);
return pictureQuad;
}
}
int main(int argc, char** argv)
{
// use an ArgumentParser object to manage the program arguments.
osg::ArgumentParser arguments(&argc,argv);
// set up the usage document, in case we need to print out how to use this program.
arguments.getApplicationUsage()->setApplicationName(arguments.getApplicationName());
arguments.getApplicationUsage()->setDescription(arguments.getApplicationName()+" example demonstrates the use of ImageStream for rendering movies as textures.");
arguments.getApplicationUsage()->setCommandLineUsage(arguments.getApplicationName()+" [options] filename ...");
arguments.getApplicationUsage()->addCommandLineOption("-h or --help","Display this information");
bool useTextureRectangle = true;
bool useShader = false;
// construct the viewer.
osgProducer::Viewer viewer(arguments);
while (arguments.read("--texture2D")) useTextureRectangle=false;
while (arguments.read("--shader")) useShader=true;
// set up the value with sensible default event handlers.
viewer.setUpViewer(osgProducer::Viewer::STANDARD_SETTINGS);
// register the handler to add keyboard and mosue handling.
MovieEventHandler* meh = new MovieEventHandler();
viewer.getEventHandlerList().push_front(meh);
// get details on keyboard and mouse bindings used by the viewer.
viewer.getUsage(*arguments.getApplicationUsage());
// if user request help write it out to cout.
if (arguments.read("-h") || arguments.read("--help"))
{
arguments.getApplicationUsage()->write(std::cout);
return 1;
}
osg::ref_ptr<osg::Geode> geode = new osg::Geode;
osg::Vec3 pos(0.0f,0.0f,0.0f);
osg::StateSet* stateset = geode->getOrCreateStateSet();
stateset->setMode(GL_LIGHTING,osg::StateAttribute::OFF);
if (useShader)
{
//useTextureRectangle = false;
static const char *shaderSourceTextureRec = {
"uniform vec4 cutoff_color;\n"
"uniform samplerRect movie_texture;\n"
"void main(void)\n"
"{\n"
" vec4 texture_color = textureRect(movie_texture, gl_TexCoord[0]); \n"
" if (all(lessThanEqual(texture_color,cutoff_color))) discard; \n"
" gl_FragColor = texture_color;\n"
"}\n"
};
static const char *shaderSourceTexture2D = {
"uniform vec4 cutoff_color;\n"
"uniform sampler2D movie_texture;\n"
"void main(void)\n"
"{\n"
" vec4 texture_color = texture2D(movie_texture, gl_TexCoord[0]); \n"
" if (all(lessThanEqual(texture_color,cutoff_color))) discard; \n"
" gl_FragColor = texture_color;\n"
"}\n"
};
osg::Program* program = new osg::Program;
program->addShader(new osg::Shader(osg::Shader::FRAGMENT,
useTextureRectangle ? shaderSourceTextureRec : shaderSourceTexture2D));
stateset->addUniform(new osg::Uniform("cutoff_color",osg::Vec4(0.1f,0.1f,0.1f,1.0f)));
stateset->addUniform(new osg::Uniform("movie_texture",0));
stateset->setAttribute(program);
}
for(int i=1;i<arguments.argc();++i)
{
if (arguments.isString(i))
{
osg::Image* image = osgDB::readImageFile(arguments[i]);
osg::ImageStream* imagestream = dynamic_cast<osg::ImageStream*>(image);
if (imagestream) imagestream->play();
if (image)
{
geode->addDrawable(myCreateTexturedQuadGeometry(pos,image->s(),image->t(),image, useTextureRectangle));
pos.z() += image->t()*1.5f;
}
else
{
std::cout<<"Unable to read file "<<arguments[i]<<std::endl;
}
}
}
if (geode->getNumDrawables()==0)
{
// nothing loaded.
return 1;
}
// pass the model to the MovieEventHandler so it can pick out ImageStream's to manipulate.
meh->set(geode.get());
// report any errors if they have occured when parsing the program aguments.
if (arguments.errors())
{
arguments.writeErrorMessages(std::cout);
return 1;
}
if (arguments.argc()<=1)
{
arguments.getApplicationUsage()->write(std::cout,osg::ApplicationUsage::COMMAND_LINE_OPTION);
return 1;
}
// any option left unread are converted into errors to write out later.
arguments.reportRemainingOptionsAsUnrecognized();
// report any errors if they have occured when parsing the program aguments.
if (arguments.errors())
{
arguments.writeErrorMessages(std::cout);
}
/*
// set up a post swap callback to flush deleted GL objects and compile new GL objects
for(unsigned int cameraNum=0;cameraNum<viewer.getNumberOfCameras();++cameraNum)
{
Producer::Camera* camera=viewer.getCamera(cameraNum);
camera->addPostSwapCallback(new PostSwapFinishCallback());
}
*/
// set the scene to render
viewer.setSceneData(geode.get());
// create the windows and run the threads.
viewer.realize();
while( !viewer.done() )
{
// wait for all cull and draw threads to complete.
viewer.sync();
// update the scene by traversing it with the the update visitor which will
// call all node update callbacks and animations.
viewer.update();
// fire off the cull and draw traversals of the scene.
viewer.frame();
}
// wait for all cull and draw threads to complete before exit.
viewer.sync();
return 0;
}
<commit_msg>Added support for tracking mouse movement and computing the intersection of the mouse position into texture coords.<commit_after>// -*-c++-*-
#include <osgProducer/Viewer>
#include <osgDB/ReadFile>
#include <osg/Geode>
#include <osg/Geometry>
#include <osg/StateSet>
#include <osg/Material>
#include <osg/Texture2D>
#include <osg/TextureRectangle>
#include <osg/TexMat>
#include <osg/CullFace>
#include <osg/ImageStream>
#include <osg/io_utils>
#include <osgGA/TrackballManipulator>
#include <osgGA/EventVisitor>
osg::ImageStream* s_imageStream = 0;
class PostSwapFinishCallback : public Producer::Camera::Callback
{
public:
PostSwapFinishCallback() {}
virtual void operator()(const Producer::Camera& camera)
{
// osg::Timer_t start_tick = osg::Timer::instance()->tick();
osgProducer::OsgSceneHandler* sh = const_cast<osgProducer::OsgSceneHandler*>(dynamic_cast<const osgProducer::OsgSceneHandler*>(camera.getSceneHandler()));
if (s_imageStream && s_imageStream->getPixelBufferObject()) s_imageStream->getPixelBufferObject()->compileBuffer(*(sh->getSceneView()->getState()));
// glFinish();
//osg::notify(osg::NOTICE)<<"callback after PBO "<<osg::Timer::instance()->delta_m(start_tick,osg::Timer::instance()->tick())<<"ms"<<std::endl;
}
};
class MovieEventHandler : public osgGA::GUIEventHandler
{
public:
MovieEventHandler() {}
void set(osg::Node* node);
virtual void accept(osgGA::GUIEventHandlerVisitor& v) { v.visit(*this); }
virtual bool handle(const osgGA::GUIEventAdapter& ea,osgGA::GUIActionAdapter& aa, osg::Object*, osg::NodeVisitor* nv);
virtual void getUsage(osg::ApplicationUsage& usage) const;
typedef std::vector< osg::ref_ptr<osg::ImageStream> > ImageStreamList;
protected:
virtual ~MovieEventHandler() {}
class FindImageStreamsVisitor : public osg::NodeVisitor
{
public:
FindImageStreamsVisitor(ImageStreamList& imageStreamList):
_imageStreamList(imageStreamList) {}
virtual void apply(osg::Geode& geode)
{
apply(geode.getStateSet());
for(unsigned int i=0;i<geode.getNumDrawables();++i)
{
apply(geode.getDrawable(i)->getStateSet());
}
traverse(geode);
}
virtual void apply(osg::Node& node)
{
apply(node.getStateSet());
traverse(node);
}
inline void apply(osg::StateSet* stateset)
{
if (!stateset) return;
osg::StateAttribute* attr = stateset->getTextureAttribute(0,osg::StateAttribute::TEXTURE);
if (attr)
{
osg::Texture2D* texture2D = dynamic_cast<osg::Texture2D*>(attr);
if (texture2D) apply(dynamic_cast<osg::ImageStream*>(texture2D->getImage()));
osg::TextureRectangle* textureRec = dynamic_cast<osg::TextureRectangle*>(attr);
if (textureRec) apply(dynamic_cast<osg::ImageStream*>(textureRec->getImage()));
}
}
inline void apply(osg::ImageStream* imagestream)
{
if (imagestream)
{
_imageStreamList.push_back(imagestream);
s_imageStream = imagestream;
}
}
ImageStreamList& _imageStreamList;
};
ImageStreamList _imageStreamList;
};
void MovieEventHandler::set(osg::Node* node)
{
_imageStreamList.clear();
if (node)
{
FindImageStreamsVisitor fisv(_imageStreamList);
node->accept(fisv);
}
}
bool MovieEventHandler::handle(const osgGA::GUIEventAdapter& ea,osgGA::GUIActionAdapter& aa, osg::Object*, osg::NodeVisitor* nv)
{
switch(ea.getEventType())
{
case(osgGA::GUIEventAdapter::MOVE):
case(osgGA::GUIEventAdapter::PUSH):
case(osgGA::GUIEventAdapter::RELEASE):
{
osgProducer::Viewer* viewer = dynamic_cast<osgProducer::Viewer*>(&aa);
osgUtil::IntersectVisitor::HitList hlist;
if (viewer->computeIntersections(ea.getX(),ea.getY(), nv->getNodePath().back(), hlist))
{
if (!hlist.empty())
{
// use the nearest intersection
osgUtil::Hit& hit = hlist.front();
osg::Drawable* drawable = hit.getDrawable();
osg::Geometry* geometry = drawable ? drawable->asGeometry() : 0;
osg::Vec3Array* vertices = geometry ? dynamic_cast<osg::Vec3Array*>(geometry->getVertexArray()) : 0;
if (vertices)
{
// get the vertex indices.
const osgUtil::Hit::VecIndexList& vil = hit.getVecIndexList();
if (vil.size()==3)
{
int i1 = vil[0];
int i2 = vil[1];
int i3 = vil[2];
osg::Vec3 v1 = (*vertices)[i1];
osg::Vec3 v2 = (*vertices)[i2];
osg::Vec3 v3 = (*vertices)[i3];
osg::Vec3 v = hit.getLocalIntersectPoint();
osg::Vec3 p1 = hit.getLocalLineSegment()->start();
osg::Vec3 p2 = hit.getLocalLineSegment()->end();
osg::Vec3 p12 = p1-p2;
osg::Vec3 v13 = v1-v3;
osg::Vec3 v23 = v2-v3;
osg::Vec3 p1v3 = p1-v3;
osg::Matrix matrix(p12.x(), v13.x(), v23.x(), 0.0,
p12.y(), v13.y(), v23.y(), 0.0,
p12.z(), v13.z(), v23.z(), 0.0,
0.0, 0.0, 0.0, 1.0);
osg::Matrix inverse;
inverse.invert(matrix);
osg::Vec3 ratio = inverse*p1v3;
// extract the baricentric coordinates.
float r1 = ratio.y();
float r2 = ratio.z();
float r3 = 1.0f-r1-r2;
osg::Array* texcoords = (geometry->getNumTexCoordArrays()>0) ? geometry->getTexCoordArray(0) : 0;
osg::Vec2Array* texcoords_Vec2Array = dynamic_cast<osg::Vec2Array*>(texcoords);
if (texcoords_Vec2Array)
{
// we have tex coord array so now we can compute the final tex coord at the point of intersection.
osg::Vec2 tc1 = (*texcoords_Vec2Array)[i1];
osg::Vec2 tc2 = (*texcoords_Vec2Array)[i2];
osg::Vec2 tc3 = (*texcoords_Vec2Array)[i3];
osg::Vec2 tc = tc1*r1 + tc2*r2 + tc3*r3;
osg::notify(osg::NOTICE)<<"We hit tex coords "<<tc<<std::endl;
}
}
else
{
osg::notify(osg::NOTICE)<<"Hit but insufficient indices to work with";
}
}
}
}
else
{
osg::notify(osg::NOTICE)<<"No hit"<<std::endl;
}
break;
}
case(osgGA::GUIEventAdapter::KEYDOWN):
{
if (ea.getKey()=='s')
{
for(ImageStreamList::iterator itr=_imageStreamList.begin();
itr!=_imageStreamList.end();
++itr)
{
std::cout<<"Play"<<std::endl;
(*itr)->play();
}
return true;
}
else if (ea.getKey()=='p')
{
for(ImageStreamList::iterator itr=_imageStreamList.begin();
itr!=_imageStreamList.end();
++itr)
{
std::cout<<"Pause"<<std::endl;
(*itr)->pause();
}
return true;
}
else if (ea.getKey()=='r')
{
for(ImageStreamList::iterator itr=_imageStreamList.begin();
itr!=_imageStreamList.end();
++itr)
{
std::cout<<"Restart"<<std::endl;
(*itr)->rewind();
(*itr)->play();
}
return true;
}
else if (ea.getKey()=='l')
{
for(ImageStreamList::iterator itr=_imageStreamList.begin();
itr!=_imageStreamList.end();
++itr)
{
if ( (*itr)->getLoopingMode() == osg::ImageStream::LOOPING)
{
std::cout<<"Toggle Looping Off"<<std::endl;
(*itr)->setLoopingMode( osg::ImageStream::NO_LOOPING );
}
else
{
std::cout<<"Toggle Looping On"<<std::endl;
(*itr)->setLoopingMode( osg::ImageStream::LOOPING );
}
}
return true;
}
return false;
}
default:
return false;
}
return false;
}
void MovieEventHandler::getUsage(osg::ApplicationUsage& usage) const
{
usage.addKeyboardMouseBinding("p","Pause movie");
usage.addKeyboardMouseBinding("s","Play movie");
usage.addKeyboardMouseBinding("r","Restart movie");
usage.addKeyboardMouseBinding("l","Toggle looping of movie");
}
osg::Geometry* myCreateTexturedQuadGeometry(const osg::Vec3& pos,float width,float height, osg::Image* image, bool useTextureRectangle)
{
if (useTextureRectangle)
{
osg::Geometry* pictureQuad = osg::createTexturedQuadGeometry(pos,
osg::Vec3(width,0.0f,0.0f),
osg::Vec3(0.0f,0.0f,height),
0.0f,image->t(), image->s(),0.0f);
pictureQuad->getOrCreateStateSet()->setTextureAttributeAndModes(0,
new osg::TextureRectangle(image),
osg::StateAttribute::ON);
return pictureQuad;
}
else
{
osg::Geometry* pictureQuad = osg::createTexturedQuadGeometry(pos,
osg::Vec3(width,0.0f,0.0f),
osg::Vec3(0.0f,0.0f,height),
0.0f,1.0f, 1.0f,0.0f);
osg::Texture2D* texture = new osg::Texture2D(image);
texture->setFilter(osg::Texture::MIN_FILTER,osg::Texture::LINEAR);
pictureQuad->getOrCreateStateSet()->setTextureAttributeAndModes(0,
texture,
osg::StateAttribute::ON);
return pictureQuad;
}
}
int main(int argc, char** argv)
{
// use an ArgumentParser object to manage the program arguments.
osg::ArgumentParser arguments(&argc,argv);
// set up the usage document, in case we need to print out how to use this program.
arguments.getApplicationUsage()->setApplicationName(arguments.getApplicationName());
arguments.getApplicationUsage()->setDescription(arguments.getApplicationName()+" example demonstrates the use of ImageStream for rendering movies as textures.");
arguments.getApplicationUsage()->setCommandLineUsage(arguments.getApplicationName()+" [options] filename ...");
arguments.getApplicationUsage()->addCommandLineOption("-h or --help","Display this information");
bool useTextureRectangle = true;
bool useShader = false;
// construct the viewer.
osgProducer::Viewer viewer(arguments);
while (arguments.read("--texture2D")) useTextureRectangle=false;
while (arguments.read("--shader")) useShader=true;
// set up the value with sensible default event handlers.
viewer.setUpViewer(osgProducer::Viewer::STANDARD_SETTINGS);
// get details on keyboard and mouse bindings used by the viewer.
viewer.getUsage(*arguments.getApplicationUsage());
// if user request help write it out to cout.
if (arguments.read("-h") || arguments.read("--help"))
{
arguments.getApplicationUsage()->write(std::cout);
return 1;
}
osg::ref_ptr<osg::Geode> geode = new osg::Geode;
osg::Vec3 pos(0.0f,0.0f,0.0f);
osg::StateSet* stateset = geode->getOrCreateStateSet();
stateset->setMode(GL_LIGHTING,osg::StateAttribute::OFF);
if (useShader)
{
//useTextureRectangle = false;
static const char *shaderSourceTextureRec = {
"uniform vec4 cutoff_color;\n"
"uniform samplerRect movie_texture;\n"
"void main(void)\n"
"{\n"
" vec4 texture_color = textureRect(movie_texture, gl_TexCoord[0]); \n"
" if (all(lessThanEqual(texture_color,cutoff_color))) discard; \n"
" gl_FragColor = texture_color;\n"
"}\n"
};
static const char *shaderSourceTexture2D = {
"uniform vec4 cutoff_color;\n"
"uniform sampler2D movie_texture;\n"
"void main(void)\n"
"{\n"
" vec4 texture_color = texture2D(movie_texture, gl_TexCoord[0]); \n"
" if (all(lessThanEqual(texture_color,cutoff_color))) discard; \n"
" gl_FragColor = texture_color;\n"
"}\n"
};
osg::Program* program = new osg::Program;
program->addShader(new osg::Shader(osg::Shader::FRAGMENT,
useTextureRectangle ? shaderSourceTextureRec : shaderSourceTexture2D));
stateset->addUniform(new osg::Uniform("cutoff_color",osg::Vec4(0.1f,0.1f,0.1f,1.0f)));
stateset->addUniform(new osg::Uniform("movie_texture",0));
stateset->setAttribute(program);
}
for(int i=1;i<arguments.argc();++i)
{
if (arguments.isString(i))
{
osg::Image* image = osgDB::readImageFile(arguments[i]);
osg::ImageStream* imagestream = dynamic_cast<osg::ImageStream*>(image);
if (imagestream) imagestream->play();
if (image)
{
geode->addDrawable(myCreateTexturedQuadGeometry(pos,image->s(),image->t(),image, useTextureRectangle));
pos.z() += image->t()*1.5f;
}
else
{
std::cout<<"Unable to read file "<<arguments[i]<<std::endl;
}
}
}
if (geode->getNumDrawables()==0)
{
// nothing loaded.
return 1;
}
// pass the model to the MovieEventHandler so it can pick out ImageStream's to manipulate.
MovieEventHandler* meh = new MovieEventHandler();
geode->setEventCallback(meh);
meh->set(geode.get());
// report any errors if they have occured when parsing the program aguments.
if (arguments.errors())
{
arguments.writeErrorMessages(std::cout);
return 1;
}
if (arguments.argc()<=1)
{
arguments.getApplicationUsage()->write(std::cout,osg::ApplicationUsage::COMMAND_LINE_OPTION);
return 1;
}
// any option left unread are converted into errors to write out later.
arguments.reportRemainingOptionsAsUnrecognized();
// report any errors if they have occured when parsing the program aguments.
if (arguments.errors())
{
arguments.writeErrorMessages(std::cout);
}
/*
// set up a post swap callback to flush deleted GL objects and compile new GL objects
for(unsigned int cameraNum=0;cameraNum<viewer.getNumberOfCameras();++cameraNum)
{
Producer::Camera* camera=viewer.getCamera(cameraNum);
camera->addPostSwapCallback(new PostSwapFinishCallback());
}
*/
// set the scene to render
viewer.setSceneData(geode.get());
// create the windows and run the threads.
viewer.realize();
while( !viewer.done() )
{
// wait for all cull and draw threads to complete.
viewer.sync();
// update the scene by traversing it with the the update visitor which will
// call all node update callbacks and animations.
viewer.update();
// fire off the cull and draw traversals of the scene.
viewer.frame();
}
// wait for all cull and draw threads to complete before exit.
viewer.sync();
return 0;
}
<|endoftext|> |
<commit_before>/*
Copyright (c) 2017, Vadim Malyshev, [email protected]
All rights reserved
*/
#include "stdafx.h"
#include "network_service.h"
#include "private/network_service_p.h"
#include "tcp_network_socket.h"
#include "udp_socket.h"
#include "service_provider.h"
#include "logger.h"
#include <iostream>
#include "private/socket_task_p.h"
vds::network_service::network_service()
: impl_(new _network_service())
{
}
vds::network_service::~network_service()
{
delete this->impl_;
}
void vds::network_service::register_services(service_registrator & registator)
{
registator.add_service<inetwork_service>(this->impl_);
}
void vds::network_service::start(const service_provider & sp)
{
this->impl_->start(sp);
}
void vds::network_service::stop(const service_provider & sp)
{
this->impl_->stop(sp);
}
vds::async_task<> vds::network_service::prepare_to_stop(const service_provider &sp)
{
return this->impl_->prepare_to_stop(sp);
}
std::string vds::network_service::to_string(const sockaddr & from, size_t from_len)
{
char hbuf[NI_MAXHOST], sbuf[NI_MAXSERV];
auto result = getnameinfo(&from, (socklen_t)from_len,
hbuf, sizeof hbuf,
sbuf, sizeof sbuf,
NI_NUMERICHOST | NI_NUMERICSERV);
return std::string(hbuf) + ":" + std::string(sbuf);
}
std::string vds::network_service::to_string(const sockaddr_in & from)
{
return get_ip_address_string(from) + ":" + std::to_string(ntohs(from.sin_port));
}
std::string vds::network_service::get_ip_address_string(const sockaddr_in & from)
{
char buffer[20];
int len = sizeof(buffer);
inet_ntop(from.sin_family, &(from.sin_addr), buffer, len);
return buffer;
}
/////////////////////////////////////////////////////////////////////////////
vds::_network_service::_network_service()
{
}
vds::_network_service::~_network_service()
{
}
void vds::_network_service::start(const service_provider & sp)
{
#ifdef _WIN32
//Initialize Winsock
WSADATA wsaData;
if (NO_ERROR != WSAStartup(MAKEWORD(2, 2), &wsaData)) {
auto error = WSAGetLastError();
throw std::system_error(error, std::system_category(), "Initiates Winsock");
}
this->handle_ = CreateIoCompletionPort(INVALID_HANDLE_VALUE, NULL, 0, 0);
if (NULL == this->handle_) {
auto error = WSAGetLastError();
throw std::system_error(error, std::system_category(), "Create I/O completion port");
}
//Create worker threads
for (unsigned int i = 0; i < 2 * std::thread::hardware_concurrency(); ++i) {
this->work_threads_.push_back(new std::thread([this, sp] { this->thread_loop(sp); }));
}
#else
this->epoll_set_ = epoll_create(100);
if(0 > this->epoll_set_){
throw std::runtime_error("Out of memory for epoll_create");
}
this->epoll_thread_ = std::thread(
[this, sp] {
auto last_timeout_update = std::chrono::steady_clock::now();
for(;;){
std::unique_lock<std::mutex> lock(this->tasks_mutex_);
if(this->tasks_.empty()){
if(sp.get_shutdown_event().is_shuting_down()){
break;
}
this->tasks_cond_.wait(lock);
continue;
}
lock.unlock();
struct epoll_event events[64];
auto result = epoll_wait(this->epoll_set_, events, sizeof(events) / sizeof(events[0]), 1000);
if(0 > result){
auto error = errno;
if(EINTR == error){
continue;
}
throw std::system_error(error, std::system_category(), "epoll_wait");
}
else if(0 < result){
for(int i = 0; i < result; ++i){
lock.lock();
auto p = this->tasks_.find(events[i].data.fd);
if(this->tasks_.end() != p){
std::shared_ptr<_socket_task> handler = p->second;
lock.unlock();
handler->process(events[i].events);
}
else {
lock.unlock();
}
}
}
}
});
#endif
}
void vds::_network_service::stop(const service_provider & sp)
{
try {
sp.get<logger>()->trace("network", sp, "Stopping network service");
#ifndef _WIN32
this->tasks_cond_.notify_one();
if(this->epoll_thread_.joinable()){
this->epoll_thread_.join();
}
#else
for (auto p : this->work_threads_) {
p->join();
delete p;
}
#endif
#ifdef _WIN32
if (NULL != this->handle_) {
CloseHandle(this->handle_);
}
WSACleanup();
#endif
}
catch (const std::exception & ex) {
sp.get<logger>()->error("network", sp, "Failed stop network service %s", ex.what());
}
catch (...) {
sp.get<logger>()->error("network", sp, "Unhandled error at stopping network service");
}
}
vds::async_task<> vds::_network_service::prepare_to_stop(const service_provider &sp)
{
return async_task<>::empty();
/*
std::set<SOCKET_HANDLE> processed;
std::unique_lock<std::mutex> lock(this->tasks_mutex_);
for(;;){
bool bcontinue = false;
for(auto & p : this->tasks_) {
if(processed.end() != processed.find(p.first)){
continue;
}
processed.emplace(p.first);
std::shared_ptr<_socket_task> handler = p.second;
lock.unlock();
//handler->prepare_to_stop(sp);
bcontinue = true;
break;
}
if(!bcontinue){
break;
}
else {
lock.lock();
}
}
*/
}
#ifdef _WIN32
void vds::_network_service::associate(SOCKET_HANDLE s)
{
if (NULL == CreateIoCompletionPort((HANDLE)s, this->handle_, NULL, 0)) {
auto error = GetLastError();
throw std::system_error(error, std::system_category(), "Associate with input/output completion port");
}
}
void vds::_network_service::thread_loop(const service_provider & sp)
{
while (!sp.get_shutdown_event().is_shuting_down()) {
DWORD dwBytesTransfered = 0;
void * lpContext = NULL;
OVERLAPPED * pOverlapped = NULL;
if (!GetQueuedCompletionStatus(
this->handle_,
&dwBytesTransfered,
(PULONG_PTR)&lpContext,
&pOverlapped,
1000)) {
auto errorCode = GetLastError();
if (errorCode == WAIT_TIMEOUT) {
continue;
}
if (pOverlapped != NULL) {
sp.get<logger>()->error("network", sp, "GetQueuedCompletionStatus %d error %s", errorCode, std::system_error(errorCode, std::system_category(), "GetQueuedCompletionStatus").what());
_socket_task::from_overlapped(pOverlapped)->error(errorCode);
continue;
}
else {
sp.get<logger>()->error("network", sp, "GetQueuedCompletionStatus %d error %s", errorCode, std::system_error(errorCode, std::system_category(), "GetQueuedCompletionStatus").what());
return;
}
}
else {
sp.get<logger>()->error("network", sp, "GetQueuedCompletionStatus is OK");
}
try {
_socket_task::from_overlapped(pOverlapped)->process(dwBytesTransfered);
}
catch (const std::exception & ex) {
auto p = sp.get_property<unhandled_exception_handler>(
service_provider::property_scope::any_scope);
if (nullptr != p) {
p->on_error(sp, std::make_shared<std::exception>(ex));
}
else {
sp.get<logger>()->error(
"network",
sp,
"IO Task error: %s",
ex.what());
}
}
catch (...) {
auto p = sp.get_property<unhandled_exception_handler>(
service_provider::property_scope::any_scope);
if (nullptr != p) {
p->on_error(sp, std::make_shared<std::runtime_error>("Unexcpected error"));
}
else {
sp.get<logger>()->error(
"network",
sp,
"IO Task error: Unexcpected error");
}
}
}
}
#else
void vds::_network_service::associate(
const service_provider & sp,
SOCKET_HANDLE s,
const std::shared_ptr<_socket_task> & handler,
uint32_t event_mask)
{
struct epoll_event event_data;
memset(&event_data, 0, sizeof(event_data));
event_data.events = event_mask;
event_data.data.fd = s;
int result = epoll_ctl(this->epoll_set_, EPOLL_CTL_ADD, s, &event_data);
if(0 > result) {
auto error = errno;
throw std::system_error(error, std::system_category(), "epoll_ctl(EPOLL_CTL_ADD)");
}
std::unique_lock<std::mutex> lock(this->tasks_mutex_);
if(this->tasks_.empty()){
this->tasks_cond_.notify_one();
}
this->tasks_[s] = handler;
}
void vds::_network_service::set_events(
const service_provider & sp,
SOCKET_HANDLE s,
uint32_t event_mask)
{
struct epoll_event event_data;
memset(&event_data, 0, sizeof(event_data));
event_data.events = event_mask;
event_data.data.fd = s;
int result = epoll_ctl(this->epoll_set_, EPOLL_CTL_MOD, s, &event_data);
if(0 > result) {
auto error = errno;
throw std::system_error(error, std::system_category(), "epoll_ctl(EPOLL_CTL_MOD)");
}
}
void vds::_network_service::remove_association(
const service_provider & sp,
SOCKET_HANDLE s)
{
struct epoll_event event_data;
memset(&event_data, 0, sizeof(event_data));
event_data.events = 0;
int result = epoll_ctl(this->epoll_set_, EPOLL_CTL_DEL, s, &event_data);
if(0 > result) {
auto error = errno;
throw std::system_error(error, std::system_category(), "epoll_ctl(EPOLL_CTL_DEL)");
}
std::unique_lock<std::mutex> lock(this->tasks_mutex_);
this->tasks_.erase(s);
}
#endif//_WIN32
<commit_msg>channel new system<commit_after>/*
Copyright (c) 2017, Vadim Malyshev, [email protected]
All rights reserved
*/
#include "stdafx.h"
#include "network_service.h"
#include "private/network_service_p.h"
#include "tcp_network_socket.h"
#include "udp_socket.h"
#include "service_provider.h"
#include "logger.h"
#include <iostream>
#include "private/socket_task_p.h"
vds::network_service::network_service()
: impl_(new _network_service())
{
}
vds::network_service::~network_service()
{
delete this->impl_;
}
void vds::network_service::register_services(service_registrator & registator)
{
registator.add_service<inetwork_service>(this->impl_);
}
void vds::network_service::start(const service_provider & sp)
{
this->impl_->start(sp);
}
void vds::network_service::stop(const service_provider & sp)
{
this->impl_->stop(sp);
}
vds::async_task<> vds::network_service::prepare_to_stop(const service_provider &sp)
{
return this->impl_->prepare_to_stop(sp);
}
std::string vds::network_service::to_string(const sockaddr & from, size_t from_len)
{
char hbuf[NI_MAXHOST], sbuf[NI_MAXSERV];
auto result = getnameinfo(&from, (socklen_t)from_len,
hbuf, sizeof hbuf,
sbuf, sizeof sbuf,
NI_NUMERICHOST | NI_NUMERICSERV);
return std::string(hbuf) + ":" + std::string(sbuf);
}
std::string vds::network_service::to_string(const sockaddr_in & from)
{
return get_ip_address_string(from) + ":" + std::to_string(ntohs(from.sin_port));
}
std::string vds::network_service::get_ip_address_string(const sockaddr_in & from)
{
char buffer[20];
int len = sizeof(buffer);
inet_ntop(from.sin_family, &(from.sin_addr), buffer, len);
return buffer;
}
/////////////////////////////////////////////////////////////////////////////
vds::_network_service::_network_service()
{
}
vds::_network_service::~_network_service()
{
}
void vds::_network_service::start(const service_provider & sp)
{
#ifdef _WIN32
//Initialize Winsock
WSADATA wsaData;
if (NO_ERROR != WSAStartup(MAKEWORD(2, 2), &wsaData)) {
auto error = WSAGetLastError();
throw std::system_error(error, std::system_category(), "Initiates Winsock");
}
this->handle_ = CreateIoCompletionPort(INVALID_HANDLE_VALUE, NULL, 0, 0);
if (NULL == this->handle_) {
auto error = WSAGetLastError();
throw std::system_error(error, std::system_category(), "Create I/O completion port");
}
//Create worker threads
for (unsigned int i = 0; i < 2 * std::thread::hardware_concurrency(); ++i) {
this->work_threads_.push_back(new std::thread([this, sp] { this->thread_loop(sp); }));
}
#else
this->epoll_set_ = epoll_create(100);
if(0 > this->epoll_set_){
throw std::runtime_error("Out of memory for epoll_create");
}
this->epoll_thread_ = std::thread(
[this, sp] {
auto last_timeout_update = std::chrono::steady_clock::now();
for(;;){
std::unique_lock<std::mutex> lock(this->tasks_mutex_);
if(this->tasks_.empty()){
if(sp.get_shutdown_event().is_shuting_down()){
break;
}
this->tasks_cond_.wait(lock);
continue;
}
lock.unlock();
struct epoll_event events[64];
auto result = epoll_wait(this->epoll_set_, events, sizeof(events) / sizeof(events[0]), 1000);
if(0 > result){
auto error = errno;
if(EINTR == error){
continue;
}
throw std::system_error(error, std::system_category(), "epoll_wait");
}
else if(0 < result){
for(int i = 0; i < result; ++i){
lock.lock();
auto p = this->tasks_.find(events[i].data.fd);
if(this->tasks_.end() != p){
std::shared_ptr<_socket_task> handler = p->second;
lock.unlock();
handler->process(events[i].events);
}
else {
lock.unlock();
}
}
}
}
});
#endif
}
void vds::_network_service::stop(const service_provider & sp)
{
try {
sp.get<logger>()->trace("network", sp, "Stopping network service");
#ifndef _WIN32
this->tasks_cond_.notify_one();
if(this->epoll_thread_.joinable()){
this->epoll_thread_.join();
}
#else
for (auto p : this->work_threads_) {
p->join();
delete p;
}
#endif
#ifdef _WIN32
if (NULL != this->handle_) {
CloseHandle(this->handle_);
}
WSACleanup();
#endif
}
catch (const std::exception & ex) {
sp.get<logger>()->error("network", sp, "Failed stop network service %s", ex.what());
}
catch (...) {
sp.get<logger>()->error("network", sp, "Unhandled error at stopping network service");
}
}
vds::async_task<> vds::_network_service::prepare_to_stop(const service_provider &sp)
{
return async_task<>::empty();
/*
std::set<SOCKET_HANDLE> processed;
std::unique_lock<std::mutex> lock(this->tasks_mutex_);
for(;;){
bool bcontinue = false;
for(auto & p : this->tasks_) {
if(processed.end() != processed.find(p.first)){
continue;
}
processed.emplace(p.first);
std::shared_ptr<_socket_task> handler = p.second;
lock.unlock();
//handler->prepare_to_stop(sp);
bcontinue = true;
break;
}
if(!bcontinue){
break;
}
else {
lock.lock();
}
}
*/
}
#ifdef _WIN32
void vds::_network_service::associate(SOCKET_HANDLE s)
{
if (NULL == CreateIoCompletionPort((HANDLE)s, this->handle_, NULL, 0)) {
auto error = GetLastError();
throw std::system_error(error, std::system_category(), "Associate with input/output completion port");
}
}
void vds::_network_service::thread_loop(const service_provider & sp)
{
while (!sp.get_shutdown_event().is_shuting_down()) {
DWORD dwBytesTransfered = 0;
void * lpContext = NULL;
OVERLAPPED * pOverlapped = NULL;
if (!GetQueuedCompletionStatus(
this->handle_,
&dwBytesTransfered,
(PULONG_PTR)&lpContext,
&pOverlapped,
1000)) {
auto errorCode = GetLastError();
if (errorCode == WAIT_TIMEOUT) {
continue;
}
if (pOverlapped != NULL) {
sp.get<logger>()->error("network", sp, "GetQueuedCompletionStatus %d error %s", errorCode, std::system_error(errorCode, std::system_category(), "GetQueuedCompletionStatus").what());
_socket_task::from_overlapped(pOverlapped)->error(errorCode);
continue;
}
else {
sp.get<logger>()->error("network", sp, "GetQueuedCompletionStatus %d error %s", errorCode, std::system_error(errorCode, std::system_category(), "GetQueuedCompletionStatus").what());
return;
}
}
try {
_socket_task::from_overlapped(pOverlapped)->process(dwBytesTransfered);
}
catch (const std::exception & ex) {
auto p = sp.get_property<unhandled_exception_handler>(
service_provider::property_scope::any_scope);
if (nullptr != p) {
p->on_error(sp, std::make_shared<std::exception>(ex));
}
else {
sp.get<logger>()->error(
"network",
sp,
"IO Task error: %s",
ex.what());
}
}
catch (...) {
auto p = sp.get_property<unhandled_exception_handler>(
service_provider::property_scope::any_scope);
if (nullptr != p) {
p->on_error(sp, std::make_shared<std::runtime_error>("Unexcpected error"));
}
else {
sp.get<logger>()->error(
"network",
sp,
"IO Task error: Unexcpected error");
}
}
}
}
#else
void vds::_network_service::associate(
const service_provider & sp,
SOCKET_HANDLE s,
const std::shared_ptr<_socket_task> & handler,
uint32_t event_mask)
{
struct epoll_event event_data;
memset(&event_data, 0, sizeof(event_data));
event_data.events = event_mask;
event_data.data.fd = s;
int result = epoll_ctl(this->epoll_set_, EPOLL_CTL_ADD, s, &event_data);
if(0 > result) {
auto error = errno;
throw std::system_error(error, std::system_category(), "epoll_ctl(EPOLL_CTL_ADD)");
}
std::unique_lock<std::mutex> lock(this->tasks_mutex_);
if(this->tasks_.empty()){
this->tasks_cond_.notify_one();
}
this->tasks_[s] = handler;
}
void vds::_network_service::set_events(
const service_provider & sp,
SOCKET_HANDLE s,
uint32_t event_mask)
{
struct epoll_event event_data;
memset(&event_data, 0, sizeof(event_data));
event_data.events = event_mask;
event_data.data.fd = s;
int result = epoll_ctl(this->epoll_set_, EPOLL_CTL_MOD, s, &event_data);
if(0 > result) {
auto error = errno;
throw std::system_error(error, std::system_category(), "epoll_ctl(EPOLL_CTL_MOD)");
}
}
void vds::_network_service::remove_association(
const service_provider & sp,
SOCKET_HANDLE s)
{
struct epoll_event event_data;
memset(&event_data, 0, sizeof(event_data));
event_data.events = 0;
int result = epoll_ctl(this->epoll_set_, EPOLL_CTL_DEL, s, &event_data);
if(0 > result) {
auto error = errno;
throw std::system_error(error, std::system_category(), "epoll_ctl(EPOLL_CTL_DEL)");
}
std::unique_lock<std::mutex> lock(this->tasks_mutex_);
this->tasks_.erase(s);
}
#endif//_WIN32
<|endoftext|> |
<commit_before>#include "LocalizationResult.hpp"
#include <openMVG/cameras/Camera_Pinhole_Radial.hpp>
#include <openMVG/numeric/numeric.h>
#include <openMVG/sfm/pipelines/localization/SfM_Localizer.hpp>
#include "testing/testing.h"
#include <third_party/stlplus3/filesystemSimplified/file_system.hpp>
#include <vector>
#include <chrono>
#include <random>
using namespace openMVG;
sfm::Image_Localizer_Match_Data generateRandomMatch_Data(std::size_t numPts)
{
sfm::Image_Localizer_Match_Data data;
data.projection_matrix = Mat34::Random();
data.pt3D = Mat::Random(3, numPts);
data.pt2D = Mat::Random(2, numPts);
const std::size_t numInliers = (std::size_t) numPts*0.7;
for(std::size_t i = 0; i < numInliers; ++i)
{
data.vec_inliers.push_back(i);
}
return data;
}
localization::LocalizationResult generateRandomResult(std::size_t numPts)
{
// random matchData
const sfm::Image_Localizer_Match_Data &data = generateRandomMatch_Data(numPts);
// random indMatch3D2D
const std::size_t numInliers = data.vec_inliers.size();
std::vector<pair<IndexT, IndexT> > indMatch3D2D;
indMatch3D2D.reserve(numInliers);
for(std::size_t i = 0; i < numInliers; ++i)
{
indMatch3D2D.emplace_back(i,i);
}
// random pose
geometry::Pose3 pose = geometry::Pose3(Mat3::Random(), Vec3::Random());
// random intrinsics
cameras::Pinhole_Intrinsic_Radial_K3 intrinsics = cameras::Pinhole_Intrinsic_Radial_K3(640, 480, 1400, 320.5, 240.5, 0.001, -0.05, 0.00003);
// random valid
const bool valid = (numInliers % 2 == 0);
std::vector<voctree::DocMatch> matchedImages;
matchedImages.push_back(voctree::DocMatch(2, 0.5));
matchedImages.push_back(voctree::DocMatch(3, 0.8));
return localization::LocalizationResult(data, indMatch3D2D, pose, intrinsics, matchedImages, valid);
}
// generate a random localization result, save it to binary file, load it again
// and compare each value
TEST(LocalizationResult, LoadSaveBinSingle)
{
const double threshold = 1e-10;
const std::string filename = "test_localizationResult.bin";
const localization::LocalizationResult &res = generateRandomResult(10);
localization::LocalizationResult check;
EXPECT_TRUE(localization::save(res, filename));
EXPECT_TRUE(localization::load(check, filename));
// same validity
EXPECT_TRUE(res.isValid() == check.isValid());
// same pose
const Mat3 rotGT = res.getPose().rotation();
const Mat3 rot = check.getPose().rotation();
for(std::size_t i = 0; i < 3; ++i)
{
for(std::size_t j = 0; j < 3; ++j)
{
EXPECT_NEAR(rotGT(i, j), rot(i, j), threshold)
}
}
const Vec3 centerGT = res.getPose().center();
const Vec3 center = check.getPose().center();
EXPECT_NEAR(centerGT(0), center(0), threshold);
EXPECT_NEAR(centerGT(1), center(1), threshold);
EXPECT_NEAR(centerGT(2), center(2), threshold);
// same _indMatch3D2D
const auto idxGT = res.getIndMatch3D2D();
const auto idx = check.getIndMatch3D2D();
EXPECT_TRUE(idxGT.size() == idx.size());
const std::size_t numpts = idxGT.size();
for(std::size_t i = 0; i < numpts; ++i)
{
EXPECT_TRUE(idxGT[i].first == idx[i].first);
EXPECT_TRUE(idxGT[i].second == idx[i].second);
}
// same _matchData
EXPECT_TRUE(res.getInliers().size() == check.getInliers().size());
const auto inliersGT = res.getInliers();
const auto inliers = check.getInliers();
for(std::size_t i = 0; i < res.getInliers().size(); ++i)
{
EXPECT_TRUE(inliersGT[i] == inliers[i]);
}
EXPECT_MATRIX_NEAR(res.getPt3D(), check.getPt3D(), threshold);
EXPECT_MATRIX_NEAR(res.getPt2D(), check.getPt2D(), threshold);
EXPECT_MATRIX_NEAR(res.getProjection(), check.getProjection(), threshold);
// same matchedImages
EXPECT_TRUE(res.getMatchedImages().size() == check.getMatchedImages().size());
const std::vector<voctree::DocMatch>& matchedImagesGT = res.getMatchedImages();
const std::vector<voctree::DocMatch>& matchedImages = check.getMatchedImages();
for(std::size_t i = 0; i < res.getMatchedImages().size(); ++i)
{
EXPECT_TRUE(matchedImagesGT[i] == matchedImages[i]);
}
stlplus::file_delete(filename);
}
TEST(LocalizationResult, LoadSaveBinVector)
{
const double threshold = 1e-10;
const std::size_t numResults = 10;
const std::string filename = "test_localizationResults.bin";
const unsigned seed1 = std::chrono::system_clock::now().time_since_epoch().count();
std::random_device rd;
std::mt19937 gen(seed1);
std::uniform_int_distribution<> numpts(1, 20);
std::vector<localization::LocalizationResult> resGT;
std::vector<localization::LocalizationResult> resCheck;
resGT.reserve(numResults);
resCheck.reserve(numResults);
for(std::size_t i = 0; i < numResults; ++i)
{
resGT.push_back(generateRandomResult(numpts(gen)));
}
EXPECT_TRUE(localization::save(resGT, filename));
EXPECT_TRUE(localization::load(resCheck, filename));
EXPECT_TRUE(resCheck.size() == resGT.size());
// check each element
for(std::size_t i = 0; i < numResults; ++i)
{
const auto res = resGT[i];
const auto check = resCheck[i];
// same validity
EXPECT_TRUE(res.isValid() == check.isValid());
// same pose
const Mat3 rotGT = res.getPose().rotation();
const Mat3 rot = check.getPose().rotation();
for(std::size_t i = 0; i < 3; ++i)
{
for(std::size_t j = 0; j < 3; ++j)
{
EXPECT_NEAR(rotGT(i, j), rot(i, j), threshold)
}
}
const Vec3 centerGT = res.getPose().center();
const Vec3 center = check.getPose().center();
EXPECT_NEAR(centerGT(0), center(0), threshold);
EXPECT_NEAR(centerGT(1), center(1), threshold);
EXPECT_NEAR(centerGT(2), center(2), threshold);
// same _indMatch3D2D
const auto idxGT = res.getIndMatch3D2D();
const auto idx = check.getIndMatch3D2D();
EXPECT_TRUE(idxGT.size() == idx.size());
const std::size_t numpts = idxGT.size();
for(std::size_t j = 0; j < numpts; ++j)
{
EXPECT_TRUE(idxGT[j].first == idx[j].first);
EXPECT_TRUE(idxGT[j].second == idx[j].second);
}
// same _matchData
EXPECT_TRUE(res.getInliers().size() == check.getInliers().size());
const auto inliersGT = res.getInliers();
const auto inliers = check.getInliers();
for(std::size_t j = 0; j < res.getInliers().size(); ++j)
{
EXPECT_TRUE(inliersGT[j] == inliers[j]);
}
EXPECT_MATRIX_NEAR(res.getPt3D(), check.getPt3D(), threshold);
EXPECT_MATRIX_NEAR(res.getPt2D(), check.getPt2D(), threshold);
EXPECT_MATRIX_NEAR(res.getProjection(), check.getProjection(), threshold);
// same matchedImages
EXPECT_TRUE(res.getMatchedImages().size() == check.getMatchedImages().size());
const auto matchedImagesGT = res.getMatchedImages();
const auto matchedImages = check.getMatchedImages();
for(std::size_t j = 0; j < res.getMatchedImages().size(); ++j)
{
EXPECT_TRUE(matchedImagesGT[j] == matchedImages[j]);
}
stlplus::file_delete(filename);
}
}
/* ************************************************************************* */
int main() { TestResult tr; return TestRegistry::runAllTests(tr);}
/* ************************************************************************* */
<commit_msg>[localization] indMatch3D2D has the same size as matched points<commit_after>#include "LocalizationResult.hpp"
#include <openMVG/cameras/Camera_Pinhole_Radial.hpp>
#include <openMVG/numeric/numeric.h>
#include <openMVG/sfm/pipelines/localization/SfM_Localizer.hpp>
#include "testing/testing.h"
#include <third_party/stlplus3/filesystemSimplified/file_system.hpp>
#include <vector>
#include <chrono>
#include <random>
using namespace openMVG;
sfm::Image_Localizer_Match_Data generateRandomMatch_Data(std::size_t numPts)
{
sfm::Image_Localizer_Match_Data data;
data.projection_matrix = Mat34::Random();
data.pt3D = Mat::Random(3, numPts);
data.pt2D = Mat::Random(2, numPts);
const std::size_t numInliers = (std::size_t) numPts*0.7;
for(std::size_t i = 0; i < numInliers; ++i)
{
data.vec_inliers.push_back(i);
}
return data;
}
localization::LocalizationResult generateRandomResult(std::size_t numPts)
{
// random matchData
const sfm::Image_Localizer_Match_Data &data = generateRandomMatch_Data(numPts);
// random indMatch3D2D
std::vector<pair<IndexT, IndexT> > indMatch3D2D;
indMatch3D2D.reserve(numPts);
for(std::size_t i = 0; i < numPts; ++i)
{
indMatch3D2D.emplace_back(i,i);
}
// random pose
geometry::Pose3 pose = geometry::Pose3(Mat3::Random(), Vec3::Random());
// random intrinsics
cameras::Pinhole_Intrinsic_Radial_K3 intrinsics = cameras::Pinhole_Intrinsic_Radial_K3(640, 480, 1400, 320.5, 240.5, 0.001, -0.05, 0.00003);
// random valid
const bool valid = (numPts % 2 == 0);
std::vector<voctree::DocMatch> matchedImages;
matchedImages.push_back(voctree::DocMatch(2, 0.5));
matchedImages.push_back(voctree::DocMatch(3, 0.8));
return localization::LocalizationResult(data, indMatch3D2D, pose, intrinsics, matchedImages, valid);
}
// generate a random localization result, save it to binary file, load it again
// and compare each value
TEST(LocalizationResult, LoadSaveBinSingle)
{
const double threshold = 1e-10;
const std::string filename = "test_localizationResult.bin";
const localization::LocalizationResult &res = generateRandomResult(10);
localization::LocalizationResult check;
EXPECT_TRUE(localization::save(res, filename));
EXPECT_TRUE(localization::load(check, filename));
// same validity
EXPECT_TRUE(res.isValid() == check.isValid());
// same pose
const Mat3 rotGT = res.getPose().rotation();
const Mat3 rot = check.getPose().rotation();
for(std::size_t i = 0; i < 3; ++i)
{
for(std::size_t j = 0; j < 3; ++j)
{
EXPECT_NEAR(rotGT(i, j), rot(i, j), threshold)
}
}
const Vec3 centerGT = res.getPose().center();
const Vec3 center = check.getPose().center();
EXPECT_NEAR(centerGT(0), center(0), threshold);
EXPECT_NEAR(centerGT(1), center(1), threshold);
EXPECT_NEAR(centerGT(2), center(2), threshold);
// same _indMatch3D2D
const auto idxGT = res.getIndMatch3D2D();
const auto idx = check.getIndMatch3D2D();
EXPECT_TRUE(idxGT.size() == idx.size());
const std::size_t numpts = idxGT.size();
for(std::size_t i = 0; i < numpts; ++i)
{
EXPECT_TRUE(idxGT[i].first == idx[i].first);
EXPECT_TRUE(idxGT[i].second == idx[i].second);
}
// same _matchData
EXPECT_TRUE(res.getInliers().size() == check.getInliers().size());
const auto inliersGT = res.getInliers();
const auto inliers = check.getInliers();
for(std::size_t i = 0; i < res.getInliers().size(); ++i)
{
EXPECT_TRUE(inliersGT[i] == inliers[i]);
}
EXPECT_MATRIX_NEAR(res.getPt3D(), check.getPt3D(), threshold);
EXPECT_MATRIX_NEAR(res.getPt2D(), check.getPt2D(), threshold);
EXPECT_MATRIX_NEAR(res.getProjection(), check.getProjection(), threshold);
// same matchedImages
EXPECT_TRUE(res.getMatchedImages().size() == check.getMatchedImages().size());
const std::vector<voctree::DocMatch>& matchedImagesGT = res.getMatchedImages();
const std::vector<voctree::DocMatch>& matchedImages = check.getMatchedImages();
for(std::size_t i = 0; i < res.getMatchedImages().size(); ++i)
{
EXPECT_TRUE(matchedImagesGT[i] == matchedImages[i]);
}
stlplus::file_delete(filename);
}
TEST(LocalizationResult, LoadSaveBinVector)
{
const double threshold = 1e-10;
const std::size_t numResults = 10;
const std::string filename = "test_localizationResults.bin";
const unsigned seed1 = std::chrono::system_clock::now().time_since_epoch().count();
std::random_device rd;
std::mt19937 gen(seed1);
std::uniform_int_distribution<> numpts(1, 20);
std::vector<localization::LocalizationResult> resGT;
std::vector<localization::LocalizationResult> resCheck;
resGT.reserve(numResults);
resCheck.reserve(numResults);
for(std::size_t i = 0; i < numResults; ++i)
{
resGT.push_back(generateRandomResult(numpts(gen)));
}
EXPECT_TRUE(localization::save(resGT, filename));
EXPECT_TRUE(localization::load(resCheck, filename));
EXPECT_TRUE(resCheck.size() == resGT.size());
// check each element
for(std::size_t i = 0; i < numResults; ++i)
{
const auto res = resGT[i];
const auto check = resCheck[i];
// same validity
EXPECT_TRUE(res.isValid() == check.isValid());
// same pose
const Mat3 rotGT = res.getPose().rotation();
const Mat3 rot = check.getPose().rotation();
for(std::size_t i = 0; i < 3; ++i)
{
for(std::size_t j = 0; j < 3; ++j)
{
EXPECT_NEAR(rotGT(i, j), rot(i, j), threshold)
}
}
const Vec3 centerGT = res.getPose().center();
const Vec3 center = check.getPose().center();
EXPECT_NEAR(centerGT(0), center(0), threshold);
EXPECT_NEAR(centerGT(1), center(1), threshold);
EXPECT_NEAR(centerGT(2), center(2), threshold);
// same _indMatch3D2D
const auto idxGT = res.getIndMatch3D2D();
const auto idx = check.getIndMatch3D2D();
EXPECT_TRUE(idxGT.size() == idx.size());
const std::size_t numpts = idxGT.size();
for(std::size_t j = 0; j < numpts; ++j)
{
EXPECT_TRUE(idxGT[j].first == idx[j].first);
EXPECT_TRUE(idxGT[j].second == idx[j].second);
}
// same _matchData
EXPECT_TRUE(res.getInliers().size() == check.getInliers().size());
const auto inliersGT = res.getInliers();
const auto inliers = check.getInliers();
for(std::size_t j = 0; j < res.getInliers().size(); ++j)
{
EXPECT_TRUE(inliersGT[j] == inliers[j]);
}
EXPECT_MATRIX_NEAR(res.getPt3D(), check.getPt3D(), threshold);
EXPECT_MATRIX_NEAR(res.getPt2D(), check.getPt2D(), threshold);
EXPECT_MATRIX_NEAR(res.getProjection(), check.getProjection(), threshold);
// same matchedImages
EXPECT_TRUE(res.getMatchedImages().size() == check.getMatchedImages().size());
const auto matchedImagesGT = res.getMatchedImages();
const auto matchedImages = check.getMatchedImages();
for(std::size_t j = 0; j < res.getMatchedImages().size(); ++j)
{
EXPECT_TRUE(matchedImagesGT[j] == matchedImages[j]);
}
stlplus::file_delete(filename);
}
}
/* ************************************************************************* */
int main() { TestResult tr; return TestRegistry::runAllTests(tr);}
/* ************************************************************************* */
<|endoftext|> |
<commit_before>/*
This file is part of the KDE project
Copyright (C) 2002-2003 Daniel Molkentin <[email protected]>
Copyright (C) 2004 Michael Brade <[email protected]>
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; see the file COPYING. If not, write to
the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
Boston, MA 02111-1307, USA.
*/
#include <qpopupmenu.h>
#include <qclipboard.h>
#include <kapplication.h>
#include <klocale.h>
#include <kdebug.h>
#include <kaction.h>
#include <kiconview.h>
#include <kiconloader.h>
#include <kmessagebox.h>
#include <kxmlguifactory.h>
#include <libkcal/journal.h>
#include <libkdepim/infoextension.h>
#include <libkdepim/sidebarextension.h>
#include "knotes/resourcemanager.h"
#include "knotes_part.h"
class KNotesIconViewItem : public KIconViewItem
{
public:
KNotesIconViewItem( KIconView *parent, KCal::Journal *journal )
: KIconViewItem( parent ),
m_journal( journal )
{
setRenameEnabled( true );
setPixmap( KGlobal::iconLoader()->loadIcon( "knotes", KIcon::Desktop ) );
setText( journal->summary() );
}
KCal::Journal *journal()
{
return m_journal;
}
virtual void setText( const QString & text )
{
KIconViewItem::setText( text );
m_journal->setSummary( text );
}
virtual QString text() const
{
return m_journal->summary();
}
private:
KCal::Journal *m_journal;
};
KNotesPart::KNotesPart( QObject *parent, const char *name )
: DCOPObject("KNotesIface"), KPIM::Part( parent, name ),
m_context_menu( 0 )
{
m_noteList.setAutoDelete( true );
setInstance( new KInstance( "knotes" ) );
// create the actions
new KAction( i18n("&New..."), "knotes", CTRL+Key_N, this, SLOT(newNote()),
actionCollection(), "file_new" );
new KAction( i18n("Rename"), "text", this, SLOT(renameNote()),
actionCollection(), "edit_rename" );
new KAction( i18n("Delete"), "editdelete", 0, this, SLOT(killSelectedNotes()),
actionCollection(), "edit_delete" );
// TODO styleguide: s/New.../New/, s/Rename/Rename.../
// TODO icons: s/editdelete/knotes_delete/ or the other way round in knotes
// create the view
m_notesView = new KIconView();
m_notesView->setSelectionMode( QIconView::Extended );
m_notesView->setItemsMovable( false );
m_notesView->setResizeMode( QIconView::Adjust );
// connect( m_notesView, SIGNAL(executed( QIconViewItem * )),
// this, SLOT(editNote( QIconViewItem * )) );
// connect( m_notesView, SIGNAL(returnPressed( KIconViewItem * )),
// this, SLOT(editNote( QIconViewItem * )) );
connect( m_notesView, SIGNAL(contextMenuRequested( QIconViewItem *, const QPoint & )),
this, SLOT(popupRMB( QIconViewItem *, const QPoint & )) );
setWidget( m_notesView );
new KParts::SideBarExtension( m_notesView, this, "NotesSideBarExtension" );
// KParts::InfoExtension *info = new KParts::InfoExtension( this, "NotesInfoExtension" );
// connect( this, SIGNAL(noteSelected( const QString& )),
// info, SIGNAL(textChanged( const QString& )) );
// connect( this, SIGNAL(noteSelected( const QPixmap& )),
// info, SIGNAL(iconChanged( const QPixmap& )) );
setXMLFile( "knotes_part.rc" );
// create the resource manager
m_manager = new KNotesResourceManager();
connect( m_manager, SIGNAL(sigRegisteredNote( KCal::Journal * )),
this, SLOT(createNote( KCal::Journal * )) );
connect( m_manager, SIGNAL(sigDeregisteredNote( KCal::Journal * )),
this, SLOT(killNote( KCal::Journal * )) );
// read the notes
m_manager->load();
}
KNotesPart::~KNotesPart()
{
delete m_manager;
}
bool KNotesPart::openFile()
{
return false;
}
// public KNotes DCOP interface implementation
QString KNotesPart::newNote( const QString& name, const QString& text )
{
// create the new note
KCal::Journal *journal = new KCal::Journal();
// new notes have the current date/time as title if none was given
if ( !name.isEmpty() )
journal->setSummary( name );
else
journal->setSummary( KGlobal::locale()->formatDateTime( QDateTime::currentDateTime() ) );
// the body of the note
journal->setDescription( text );
m_manager->addNewNote( journal );
showNote( journal->uid() );
return journal->uid();
}
QString KNotesPart::newNoteFromClipboard( const QString& name )
{
const QString& text = KApplication::clipboard()->text();
return newNote( name, text );
}
void KNotesPart::showNote( const QString& id ) const
{
KNotesIconViewItem *note = m_noteList[id];
if ( !note )
return;
m_notesView->ensureItemVisible( note );
m_notesView->setCurrentItem( note );
}
void KNotesPart::hideNote( const QString& ) const
{
// simply does nothing, there is nothing to hide
}
void KNotesPart::killNote( const QString& id )
{
killNote( id, false );
}
void KNotesPart::killNote( const QString& id, bool force )
{
KNotesIconViewItem *note = m_noteList[id];
if ( note && !force && KMessageBox::warningContinueCancelList( m_notesView,
i18n( "Do you really want to delete this note?" ),
m_noteList[id]->text(), i18n("Confirm Delete"),
KGuiItem( i18n("Delete"), "editdelete" ) ) == KMessageBox::Continue )
{
m_manager->deleteNote( m_noteList[id]->journal() );
}
}
QString KNotesPart::name( const QString& id ) const
{
KNotesIconViewItem *note = m_noteList[id];
if ( note )
return note->text();
else
return QString::null;
}
QString KNotesPart::text( const QString& id ) const
{
KNotesIconViewItem *note = m_noteList[id];
if ( note )
return note->journal()->description();
else
return QString::null;
}
void KNotesPart::setName( const QString& id, const QString& newName )
{
KNotesIconViewItem *note = m_noteList[id];
if ( note )
return note->setText( newName );
}
void KNotesPart::setText( const QString& id, const QString& newText )
{
KNotesIconViewItem *note = m_noteList[id];
if ( note )
return note->journal()->setDescription( newText );
}
QMap<QString, QString> KNotesPart::notes() const
{
QMap<QString, QString> notes;
QDictIterator<KNotesIconViewItem> it( m_noteList );
for ( ; it.current(); ++it )
notes.insert( (*it)->journal()->uid(), (*it)->journal()->description() );
return notes;
}
// TODO KDE 4.0: remove
void KNotesPart::sync( const QString& app )
{
}
bool KNotesPart::isNew( const QString& app, const QString& id ) const
{
return true;
}
bool KNotesPart::isModified( const QString& app, const QString& id ) const
{
return true;
}
// private stuff
void KNotesPart::killSelectedNotes()
{
QPtrList<KNotesIconViewItem> items;
QStringList notes;
KNotesIconViewItem *knivi;
for ( QIconViewItem *it = m_notesView->firstItem(); it; it = it->nextItem() )
{
if ( it->isSelected() )
{
knivi = static_cast<KNotesIconViewItem *>( it );
items.append( knivi );
notes.append( knivi->text() );
}
}
if ( items.isEmpty() )
return;
// if ( !lock() )
// return;
int ret = KMessageBox::warningContinueCancelList( m_notesView,
i18n( "Do you really want to delete this note?",
"Do you really want to delete these %n notes?", items.count() ),
notes, i18n("Confirm Delete"),
KGuiItem( i18n("Delete"), "editdelete" )
);
if ( ret == KMessageBox::Continue )
{
QPtrListIterator<KNotesIconViewItem> kniviIt( items );
while ( (knivi = *kniviIt) )
{
++kniviIt;
m_manager->deleteNote( knivi->journal() );
}
}
// unlock();
}
void KNotesPart::popupRMB( QIconViewItem *item, const QPoint& pos )
{
if ( !m_context_menu )
m_context_menu = static_cast<QPopupMenu *>(factory()->container( "note_context", this ));
if ( !m_context_menu || !item )
return;
m_context_menu->popup( pos );
}
// create and kill the icon view item corresponding to the note
void KNotesPart::createNote( KCal::Journal *journal )
{
m_noteList.insert( journal->uid(), new KNotesIconViewItem( m_notesView, journal ) );
}
void KNotesPart::killNote( KCal::Journal *journal )
{
m_noteList.remove( journal->uid() );
}
#include "knotes_part.moc"
<commit_msg>Ok, Danimo just removed my doubts--this InfoExtension is completely antiquated. Byebye.<commit_after>/*
This file is part of the KDE project
Copyright (C) 2002-2003 Daniel Molkentin <[email protected]>
Copyright (C) 2004 Michael Brade <[email protected]>
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; see the file COPYING. If not, write to
the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
Boston, MA 02111-1307, USA.
*/
#include <qpopupmenu.h>
#include <qclipboard.h>
#include <kapplication.h>
#include <klocale.h>
#include <kdebug.h>
#include <kaction.h>
#include <kiconview.h>
#include <kiconloader.h>
#include <kmessagebox.h>
#include <kxmlguifactory.h>
#include <libkcal/journal.h>
#include <libkdepim/infoextension.h>
#include <libkdepim/sidebarextension.h>
#include "knotes/resourcemanager.h"
#include "knotes_part.h"
class KNotesIconViewItem : public KIconViewItem
{
public:
KNotesIconViewItem( KIconView *parent, KCal::Journal *journal )
: KIconViewItem( parent ),
m_journal( journal )
{
setRenameEnabled( true );
setPixmap( KGlobal::iconLoader()->loadIcon( "knotes", KIcon::Desktop ) );
setText( journal->summary() );
}
KCal::Journal *journal()
{
return m_journal;
}
virtual void setText( const QString & text )
{
KIconViewItem::setText( text );
m_journal->setSummary( text );
}
virtual QString text() const
{
return m_journal->summary();
}
private:
KCal::Journal *m_journal;
};
KNotesPart::KNotesPart( QObject *parent, const char *name )
: DCOPObject("KNotesIface"), KPIM::Part( parent, name ),
m_context_menu( 0 )
{
m_noteList.setAutoDelete( true );
setInstance( new KInstance( "knotes" ) );
// create the actions
new KAction( i18n("&New..."), "knotes", CTRL+Key_N, this, SLOT(newNote()),
actionCollection(), "file_new" );
new KAction( i18n("Rename"), "text", this, SLOT(renameNote()),
actionCollection(), "edit_rename" );
new KAction( i18n("Delete"), "editdelete", 0, this, SLOT(killSelectedNotes()),
actionCollection(), "edit_delete" );
// TODO styleguide: s/New.../New/, s/Rename/Rename.../
// TODO icons: s/editdelete/knotes_delete/ or the other way round in knotes
// create the view
m_notesView = new KIconView();
m_notesView->setSelectionMode( QIconView::Extended );
m_notesView->setItemsMovable( false );
m_notesView->setResizeMode( QIconView::Adjust );
// connect( m_notesView, SIGNAL(executed( QIconViewItem * )),
// this, SLOT(editNote( QIconViewItem * )) );
// connect( m_notesView, SIGNAL(returnPressed( KIconViewItem * )),
// this, SLOT(editNote( QIconViewItem * )) );
connect( m_notesView, SIGNAL(contextMenuRequested( QIconViewItem *, const QPoint & )),
this, SLOT(popupRMB( QIconViewItem *, const QPoint & )) );
new KParts::SideBarExtension( m_notesView, this, "NotesSideBarExtension" );
setWidget( m_notesView );
setXMLFile( "knotes_part.rc" );
// create the resource manager
m_manager = new KNotesResourceManager();
connect( m_manager, SIGNAL(sigRegisteredNote( KCal::Journal * )),
this, SLOT(createNote( KCal::Journal * )) );
connect( m_manager, SIGNAL(sigDeregisteredNote( KCal::Journal * )),
this, SLOT(killNote( KCal::Journal * )) );
// read the notes
m_manager->load();
}
KNotesPart::~KNotesPart()
{
delete m_manager;
}
bool KNotesPart::openFile()
{
return false;
}
// public KNotes DCOP interface implementation
QString KNotesPart::newNote( const QString& name, const QString& text )
{
// create the new note
KCal::Journal *journal = new KCal::Journal();
// new notes have the current date/time as title if none was given
if ( !name.isEmpty() )
journal->setSummary( name );
else
journal->setSummary( KGlobal::locale()->formatDateTime( QDateTime::currentDateTime() ) );
// the body of the note
journal->setDescription( text );
m_manager->addNewNote( journal );
showNote( journal->uid() );
return journal->uid();
}
QString KNotesPart::newNoteFromClipboard( const QString& name )
{
const QString& text = KApplication::clipboard()->text();
return newNote( name, text );
}
void KNotesPart::showNote( const QString& id ) const
{
KNotesIconViewItem *note = m_noteList[id];
if ( !note )
return;
m_notesView->ensureItemVisible( note );
m_notesView->setCurrentItem( note );
}
void KNotesPart::hideNote( const QString& ) const
{
// simply does nothing, there is nothing to hide
}
void KNotesPart::killNote( const QString& id )
{
killNote( id, false );
}
void KNotesPart::killNote( const QString& id, bool force )
{
KNotesIconViewItem *note = m_noteList[id];
if ( note && !force && KMessageBox::warningContinueCancelList( m_notesView,
i18n( "Do you really want to delete this note?" ),
m_noteList[id]->text(), i18n("Confirm Delete"),
KGuiItem( i18n("Delete"), "editdelete" ) ) == KMessageBox::Continue )
{
m_manager->deleteNote( m_noteList[id]->journal() );
}
}
QString KNotesPart::name( const QString& id ) const
{
KNotesIconViewItem *note = m_noteList[id];
if ( note )
return note->text();
else
return QString::null;
}
QString KNotesPart::text( const QString& id ) const
{
KNotesIconViewItem *note = m_noteList[id];
if ( note )
return note->journal()->description();
else
return QString::null;
}
void KNotesPart::setName( const QString& id, const QString& newName )
{
KNotesIconViewItem *note = m_noteList[id];
if ( note )
return note->setText( newName );
}
void KNotesPart::setText( const QString& id, const QString& newText )
{
KNotesIconViewItem *note = m_noteList[id];
if ( note )
return note->journal()->setDescription( newText );
}
QMap<QString, QString> KNotesPart::notes() const
{
QMap<QString, QString> notes;
QDictIterator<KNotesIconViewItem> it( m_noteList );
for ( ; it.current(); ++it )
notes.insert( (*it)->journal()->uid(), (*it)->journal()->description() );
return notes;
}
// TODO KDE 4.0: remove
void KNotesPart::sync( const QString& app )
{
}
bool KNotesPart::isNew( const QString& app, const QString& id ) const
{
return true;
}
bool KNotesPart::isModified( const QString& app, const QString& id ) const
{
return true;
}
// private stuff
void KNotesPart::killSelectedNotes()
{
QPtrList<KNotesIconViewItem> items;
QStringList notes;
KNotesIconViewItem *knivi;
for ( QIconViewItem *it = m_notesView->firstItem(); it; it = it->nextItem() )
{
if ( it->isSelected() )
{
knivi = static_cast<KNotesIconViewItem *>( it );
items.append( knivi );
notes.append( knivi->text() );
}
}
if ( items.isEmpty() )
return;
// if ( !lock() )
// return;
int ret = KMessageBox::warningContinueCancelList( m_notesView,
i18n( "Do you really want to delete this note?",
"Do you really want to delete these %n notes?", items.count() ),
notes, i18n("Confirm Delete"),
KGuiItem( i18n("Delete"), "editdelete" )
);
if ( ret == KMessageBox::Continue )
{
QPtrListIterator<KNotesIconViewItem> kniviIt( items );
while ( (knivi = *kniviIt) )
{
++kniviIt;
m_manager->deleteNote( knivi->journal() );
}
}
// unlock();
}
void KNotesPart::popupRMB( QIconViewItem *item, const QPoint& pos )
{
if ( !m_context_menu )
m_context_menu = static_cast<QPopupMenu *>(factory()->container( "note_context", this ));
if ( !m_context_menu || !item )
return;
m_context_menu->popup( pos );
}
// create and kill the icon view item corresponding to the note
void KNotesPart::createNote( KCal::Journal *journal )
{
m_noteList.insert( journal->uid(), new KNotesIconViewItem( m_notesView, journal ) );
}
void KNotesPart::killNote( KCal::Journal *journal )
{
m_noteList.remove( journal->uid() );
}
#include "knotes_part.moc"
<|endoftext|> |
<commit_before>#include <string>
#include <iostream>
#include <mutex>
#include <condition_variable>
#include <atomic>
#include <list>
#include <thread>
#include <exception>
#include <boost/asio.hpp>
#include <boost/bind.hpp>
#include <boost/asio/serial_port.hpp>
#include <boost/asio/write.hpp>
#include <boost/asio/read.hpp>
using namespace::boost::asio;
#include <boost/algorithm/string.hpp>
#define DUMP_VAR(x) std::cout << __func__ << "." << __LINE__ << ":" << #x << "=<" << x <<">" << std::endl;
std::list<std::string> gCarCommand;
std::mutex mtx;
std::condition_variable cv;
static std::string gCarSpeed = "10000";
void push_command(const std::string &cmd)
{
std::unique_lock<std::mutex> lock(mtx);
if("init"==cmd) {
gCarCommand.clear();
}
if("top"==cmd) {
gCarCommand.push_back("a.speed:" + gCarSpeed + "\n");
gCarCommand.push_back("a.turn:fwd\n");
gCarCommand.push_back("b.speed:" + gCarSpeed + "\n");
gCarCommand.push_back("b.turn:fwd\n");
gCarCommand.push_back("c.speed:" + gCarSpeed + "\n");
gCarCommand.push_back("c.turn:fwd\n");
gCarCommand.push_back("d.speed:" + gCarSpeed + "\n");
gCarCommand.push_back("d.turn:fwd\n");
gCarCommand.push_back("run\n");
}
if("buttom"==cmd) {
gCarCommand.push_back("a.speed:" + gCarSpeed + "\n");
gCarCommand.push_back("a.turn:rev\n");
gCarCommand.push_back("b.speed:" + gCarSpeed + "\n");
gCarCommand.push_back("b.turn:rev\n");
gCarCommand.push_back("c.speed:" + gCarSpeed + "\n");
gCarCommand.push_back("c.turn:rev\n");
gCarCommand.push_back("d.speed:" + gCarSpeed + "\n");
gCarCommand.push_back("d.turn:rev\n");
gCarCommand.push_back("run\n");
}
if("left"==cmd) {
gCarCommand.push_back("a.speed:" + gCarSpeed + "\n");
gCarCommand.push_back("a.turn:fwd\n");
gCarCommand.push_back("b.speed:" + gCarSpeed + "\n");
gCarCommand.push_back("b.turn:rev\n");
gCarCommand.push_back("c.speed:" + gCarSpeed + "\n");
gCarCommand.push_back("c.turn:fwd\n");
gCarCommand.push_back("d.speed:" + gCarSpeed + "\n");
gCarCommand.push_back("d.turn:rev\n");
gCarCommand.push_back("run\n");
}
if("right"==cmd) {
gCarCommand.push_back("a.speed:" + gCarSpeed + "\n");
gCarCommand.push_back("a.turn:rev\n");
gCarCommand.push_back("b.speed:" + gCarSpeed + "\n");
gCarCommand.push_back("b.turn:fwd\n");
gCarCommand.push_back("c.speed:" + gCarSpeed + "\n");
gCarCommand.push_back("c.turn:rev\n");
gCarCommand.push_back("d.speed:" + gCarSpeed + "\n");
gCarCommand.push_back("d.turn:fwd\n");
gCarCommand.push_back("run\n");
}
if("stop"==cmd) {
gCarCommand.push_back("stop\n");
}
std::string speedTag("speed=");
auto posSpd = cmd.find(speedTag);
if(posSpd != std::string::npos) {
auto speedStr = cmd.substr(posSpd + speedTag.size());
DUMP_VAR(speedStr);
if(speedStr == "1") {
gCarSpeed = "10000";
}
if(speedStr == "2") {
gCarSpeed = "20000";
}
if(speedStr == "3") {
gCarSpeed = "30000";
}
if(speedStr == "4") {
gCarSpeed = "40000";
}
if(speedStr == "5") {
gCarSpeed = "50000";
}
}
cv.notify_one();
}
void handle_read_content(){
static int i = 0;
DUMP_VAR(i++);
}
void car_uart_main(void)
{
try {
io_service io_;
serial_port port_( io_, "/dev/ttyUSB0" );
port_.set_option( serial_port_base::baud_rate(115200));
while(true) {
std::unique_lock<std::mutex> lock(mtx);
cv.wait(lock);
if(false == gCarCommand.empty()) {
for(auto cmd:gCarCommand) {
boost::asio::write(port_, boost::asio::buffer(cmd.c_str(), cmd.size()));
boost::asio::streambuf b;
boost::asio::async_read(port_,b,boost::bind(&handle_read_content));
}
gCarCommand.clear();
}
}
} catch (std::exception &e) {
DUMP_VAR(e.what());
}
}
<commit_msg>Update car.entry.cpp<commit_after>#include <string>
#include <iostream>
#include <mutex>
#include <condition_variable>
#include <atomic>
#include <list>
#include <thread>
#include <exception>
#include <boost/asio.hpp>
#include <boost/bind.hpp>
#include <boost/asio/serial_port.hpp>
#include <boost/asio/write.hpp>
#include <boost/asio/read.hpp>
using namespace::boost::asio;
#include <boost/algorithm/string.hpp>
#define DUMP_VAR(x) std::cout << __func__ << "." << __LINE__ << ":" << #x << "=<" << x <<">" << std::endl;
std::list<std::string> gCarCommand;
std::mutex mtx;
std::condition_variable cv;
static std::string gCarSpeed = "30000";
void push_command(const std::string &cmd)
{
std::unique_lock<std::mutex> lock(mtx);
if("init"==cmd) {
gCarCommand.clear();
}
if("top"==cmd) {
gCarCommand.push_back("a.speed:" + gCarSpeed + "\n");
gCarCommand.push_back("a.turn:fwd\n");
gCarCommand.push_back("b.speed:" + gCarSpeed + "\n");
gCarCommand.push_back("b.turn:fwd\n");
gCarCommand.push_back("c.speed:" + gCarSpeed + "\n");
gCarCommand.push_back("c.turn:fwd\n");
gCarCommand.push_back("d.speed:" + gCarSpeed + "\n");
gCarCommand.push_back("d.turn:fwd\n");
gCarCommand.push_back("run\n");
}
if("buttom"==cmd) {
gCarCommand.push_back("a.speed:" + gCarSpeed + "\n");
gCarCommand.push_back("a.turn:rev\n");
gCarCommand.push_back("b.speed:" + gCarSpeed + "\n");
gCarCommand.push_back("b.turn:rev\n");
gCarCommand.push_back("c.speed:" + gCarSpeed + "\n");
gCarCommand.push_back("c.turn:rev\n");
gCarCommand.push_back("d.speed:" + gCarSpeed + "\n");
gCarCommand.push_back("d.turn:rev\n");
gCarCommand.push_back("run\n");
}
if("left"==cmd) {
gCarCommand.push_back("a.speed:" + gCarSpeed + "\n");
gCarCommand.push_back("a.turn:fwd\n");
gCarCommand.push_back("b.speed:" + gCarSpeed + "\n");
gCarCommand.push_back("b.turn:rev\n");
gCarCommand.push_back("c.speed:" + gCarSpeed + "\n");
gCarCommand.push_back("c.turn:fwd\n");
gCarCommand.push_back("d.speed:" + gCarSpeed + "\n");
gCarCommand.push_back("d.turn:rev\n");
gCarCommand.push_back("run\n");
}
if("right"==cmd) {
gCarCommand.push_back("a.speed:" + gCarSpeed + "\n");
gCarCommand.push_back("a.turn:rev\n");
gCarCommand.push_back("b.speed:" + gCarSpeed + "\n");
gCarCommand.push_back("b.turn:fwd\n");
gCarCommand.push_back("c.speed:" + gCarSpeed + "\n");
gCarCommand.push_back("c.turn:rev\n");
gCarCommand.push_back("d.speed:" + gCarSpeed + "\n");
gCarCommand.push_back("d.turn:fwd\n");
gCarCommand.push_back("run\n");
}
if("stop"==cmd) {
gCarCommand.push_back("stop\n");
}
std::string speedTag("speed=");
auto posSpd = cmd.find(speedTag);
if(posSpd != std::string::npos) {
auto speedStr = cmd.substr(posSpd + speedTag.size());
DUMP_VAR(speedStr);
if(speedStr == "1") {
gCarSpeed = "10000";
}
if(speedStr == "2") {
gCarSpeed = "20000";
}
if(speedStr == "3") {
gCarSpeed = "30000";
}
if(speedStr == "4") {
gCarSpeed = "40000";
}
if(speedStr == "5") {
gCarSpeed = "50000";
}
}
cv.notify_one();
}
void handle_read_content(){
static int i = 0;
DUMP_VAR(i++);
}
void car_uart_main(void)
{
try {
io_service io_;
serial_port port_( io_, "/dev/ttyUSB0" );
port_.set_option( serial_port_base::baud_rate(115200));
while(true) {
std::unique_lock<std::mutex> lock(mtx);
cv.wait(lock);
if(false == gCarCommand.empty()) {
for(auto cmd:gCarCommand) {
boost::asio::write(port_, boost::asio::buffer(cmd.c_str(), cmd.size()));
boost::asio::streambuf b;
boost::asio::async_read(port_,b,boost::bind(&handle_read_content));
}
gCarCommand.clear();
}
}
} catch (std::exception &e) {
DUMP_VAR(e.what());
}
}
<|endoftext|> |
<commit_before>/*
* Copyright 2018 The Kythe Authors. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "kythe/cxx/indexer/proto/source_tree.h"
#include "absl/container/flat_hash_map.h"
#include "absl/strings/str_join.h"
#include "absl/strings/str_replace.h"
#include "absl/strings/str_split.h"
#include "absl/strings/strip.h"
#include "glog/logging.h"
#include "google/protobuf/io/zero_copy_stream_impl_lite.h"
#include "google/protobuf/stubs/map_util.h"
#include "kythe/cxx/common/path_utils.h"
namespace kythe {
using ::google::protobuf::FindOrDie;
using ::google::protobuf::FindOrNull;
using ::google::protobuf::InsertIfNotPresent;
namespace {
// TODO(justbuchanan): why isn't there a replace_all=false version of
// StrReplace() in open-source abseil?
/// Finds the first occurrence of @oldsub in @s and replaces it with @newsub. If
/// @oldsub is not present, just returns @s.
std::string StringReplaceFirst(absl::string_view s, absl::string_view oldsub,
absl::string_view newsub) {
return absl::StrJoin(absl::StrSplit(s, absl::MaxSplits(oldsub, 1)), newsub);
}
} // namespace
bool PreloadedProtoFileTree::AddFile(const std::string& filename,
const std::string& contents) {
VLOG(1) << filename << " added to PreloadedProtoFileTree";
return InsertIfNotPresent(&file_map_, filename, contents);
}
google::protobuf::io::ZeroCopyInputStream* PreloadedProtoFileTree::Open(
const std::string& filename) {
last_error_ = "";
const std::string* cached_path = FindOrNull(*file_mapping_cache_, filename);
if (cached_path != nullptr) {
std::string* stored_contents = FindOrNull(file_map_, *cached_path);
if (stored_contents == nullptr) {
last_error_ = "Proto file Open(" + filename +
") failed:" + " cached mapping to " + *cached_path +
"no longer valid.";
LOG(ERROR) << last_error_;
return nullptr;
}
return new google::protobuf::io::ArrayInputStream(stored_contents->data(),
stored_contents->size());
}
for (auto& substitution : *substitutions_) {
std::string found_path;
if (substitution.first.empty()) {
found_path = CleanPath(JoinPath(substitution.second, filename));
} else if (filename == substitution.first) {
found_path = substitution.second;
} else if (absl::StartsWith(filename, substitution.first + "/")) {
found_path = CleanPath(StringReplaceFirst(filename, substitution.first,
substitution.second));
}
std::string* stored_contents =
found_path.empty() ? nullptr : FindOrNull(file_map_, found_path);
if (stored_contents != nullptr) {
VLOG(1) << "Proto file Open(" << filename << ") under ["
<< substitution.first << "->" << substitution.second << "]";
if (!InsertIfNotPresent(file_mapping_cache_, filename, found_path)) {
LOG(ERROR) << "Redundant/contradictory data in index or internal bug."
<< " \"" << filename << "\" is mapped twice, first to \""
<< FindOrDie(*file_mapping_cache_, filename)
<< "\" and now to \"" << found_path << "\". Aborting "
<< "new remapping...";
}
return new google::protobuf::io::ArrayInputStream(
stored_contents->data(), stored_contents->size());
}
}
std::string* stored_contents = FindOrNull(file_map_, filename);
if (stored_contents != nullptr) {
VLOG(1) << "Proto file Open(" << filename << ") at root";
return new google::protobuf::io::ArrayInputStream(stored_contents->data(),
stored_contents->size());
}
last_error_ = "Proto file Open(" + filename + ") failed because '" +
filename + "' not recognized by indexer";
LOG(WARNING) << last_error_;
return nullptr;
}
bool PreloadedProtoFileTree::Read(absl::string_view file_path,
std::string* out) {
std::unique_ptr<google::protobuf::io::ZeroCopyInputStream> in_stream(
Open(std::string(file_path)));
if (!in_stream) {
return false;
}
const void* data = nullptr;
int size = 0;
while (in_stream->Next(&data, &size)) {
out->append(static_cast<const char*>(data), size);
}
return true;
}
} // namespace kythe
<commit_msg>chore: preparatory cleanups for a signature change to absl::string_view (#5372)<commit_after>/*
* Copyright 2018 The Kythe Authors. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "kythe/cxx/indexer/proto/source_tree.h"
#include "absl/container/flat_hash_map.h"
#include "absl/strings/str_cat.h"
#include "absl/strings/str_join.h"
#include "absl/strings/str_replace.h"
#include "absl/strings/str_split.h"
#include "absl/strings/strip.h"
#include "glog/logging.h"
#include "google/protobuf/io/zero_copy_stream_impl_lite.h"
#include "google/protobuf/stubs/map_util.h"
#include "kythe/cxx/common/path_utils.h"
namespace kythe {
using ::google::protobuf::FindOrDie;
using ::google::protobuf::FindOrNull;
using ::google::protobuf::InsertIfNotPresent;
namespace {
// TODO(justbuchanan): why isn't there a replace_all=false version of
// StrReplace() in open-source abseil?
/// Finds the first occurrence of @oldsub in @s and replaces it with @newsub. If
/// @oldsub is not present, just returns @s.
std::string StringReplaceFirst(absl::string_view s, absl::string_view oldsub,
absl::string_view newsub) {
return absl::StrJoin(absl::StrSplit(s, absl::MaxSplits(oldsub, 1)), newsub);
}
} // namespace
bool PreloadedProtoFileTree::AddFile(const std::string& filename,
const std::string& contents) {
VLOG(1) << filename << " added to PreloadedProtoFileTree";
return InsertIfNotPresent(&file_map_, filename, contents);
}
google::protobuf::io::ZeroCopyInputStream* PreloadedProtoFileTree::Open(
const std::string& filename) {
last_error_ = "";
const std::string* cached_path = FindOrNull(*file_mapping_cache_, filename);
if (cached_path != nullptr) {
std::string* stored_contents = FindOrNull(file_map_, *cached_path);
if (stored_contents == nullptr) {
last_error_ = absl::StrCat("Proto file Open(", filename,
") failed:", " cached mapping to ",
*cached_path, "no longer valid.");
LOG(ERROR) << last_error_;
return nullptr;
}
return new google::protobuf::io::ArrayInputStream(stored_contents->data(),
stored_contents->size());
}
for (auto& substitution : *substitutions_) {
std::string found_path;
if (substitution.first.empty()) {
found_path = CleanPath(JoinPath(substitution.second, filename));
} else if (filename == substitution.first) {
found_path = substitution.second;
} else if (absl::StartsWith(filename, substitution.first + "/")) {
found_path = CleanPath(StringReplaceFirst(filename, substitution.first,
substitution.second));
}
std::string* stored_contents =
found_path.empty() ? nullptr : FindOrNull(file_map_, found_path);
if (stored_contents != nullptr) {
VLOG(1) << "Proto file Open(" << filename << ") under ["
<< substitution.first << "->" << substitution.second << "]";
if (auto [unused, inserted] =
file_mapping_cache_->emplace(filename, found_path);
!inserted) {
LOG(ERROR) << "Redundant/contradictory data in index or internal bug."
<< " \"" << filename << "\" is mapped twice, first to \""
<< FindOrDie(*file_mapping_cache_, filename)
<< "\" and now to \"" << found_path << "\". Aborting "
<< "new remapping...";
}
return new google::protobuf::io::ArrayInputStream(
stored_contents->data(), stored_contents->size());
}
}
std::string* stored_contents = FindOrNull(file_map_, filename);
if (stored_contents != nullptr) {
VLOG(1) << "Proto file Open(" << filename << ") at root";
return new google::protobuf::io::ArrayInputStream(stored_contents->data(),
stored_contents->size());
}
last_error_ = absl::StrCat("Proto file Open(", filename, ") failed because '",
filename, "' not recognized by indexer");
LOG(WARNING) << last_error_;
return nullptr;
}
bool PreloadedProtoFileTree::Read(absl::string_view file_path,
std::string* out) {
std::unique_ptr<google::protobuf::io::ZeroCopyInputStream> in_stream(
Open({file_path.data(), file_path.size()}));
if (!in_stream) {
return false;
}
const void* data = nullptr;
int size = 0;
while (in_stream->Next(&data, &size)) {
out->append(static_cast<const char*>(data), size);
}
return true;
}
} // namespace kythe
<|endoftext|> |
<commit_before>#include "Mesh.hxx"
#include "setup_constraints.hxx"
#include "../../sdp_solve.hxx"
#include "../../ostream_set.hxx"
#include "../../ostream_map.hxx"
#include "../../ostream_vector.hxx"
#include "../../set_stream_precision.hxx"
namespace
{
void copy_matrices(const std::vector<El::DistMatrix<El::BigFloat>> &input,
std::vector<El::Matrix<El::BigFloat>> &output)
{
output.clear();
output.reserve(input.size());
for(auto &block : input)
{
output.emplace_back(block.Height(), block.Width());
auto &matrix(output.back());
for(int64_t row(0); row < block.LocalHeight(); ++row)
{
for(int64_t column(0); column < block.LocalWidth(); ++column)
{
// TODO: This will break in parallel
matrix(row, column) = block.GetLocal(row, column);
}
}
}
}
void copy_matrix(const El::Matrix<El::BigFloat> &source,
El::DistMatrix<El::BigFloat> &destination)
{
for(int64_t row(0); row < source.Height(); ++row)
{
for(int64_t column(0); column < source.Width(); ++column)
{
// TODO: This will break in parallel
destination.SetLocal(row, column, source(row, column));
}
}
}
void copy_matrix(const El::DistMatrix<El::BigFloat> &source,
El::Matrix<El::BigFloat> &destination)
{
destination.Resize(source.Height(), source.Width());
for(int64_t row(0); row < source.Height(); ++row)
{
for(int64_t column(0); column < source.Width(); ++column)
{
// TODO: This will break in parallel
destination(row, column) = source.GetLocal(row, column);
}
}
}
}
void compute_y_transform(
const std::vector<std::vector<std::vector<std::vector<Function>>>>
&function_blocks,
const std::vector<std::set<El::BigFloat>> &points,
const std::vector<El::BigFloat> &objectives,
const std::vector<El::BigFloat> &normalization,
const SDP_Solver_Parameters ¶meters, const size_t &max_index,
const El::Grid &global_grid,
El::DistMatrix<El::BigFloat, El::STAR, El::STAR> &yp_to_y,
El::DistMatrix<El::BigFloat, El::STAR, El::STAR> &dual_objective_b_star,
El::BigFloat &primal_c_scale);
El::BigFloat eval_weighted(
const El::BigFloat &infinity,
const std::vector<std::vector<std::vector<Function>>> &function_blocks,
const El::BigFloat &x, const std::vector<El::BigFloat> &weights);
std::vector<El::BigFloat>
get_new_points(const Mesh &mesh, const El::BigFloat &block_epsilon);
std::vector<El::BigFloat> compute_optimal(
const std::vector<std::vector<std::vector<std::vector<Function>>>>
&function_blocks,
const std::vector<std::vector<El::BigFloat>> &initial_points,
const std::vector<El::BigFloat> &objectives,
const std::vector<El::BigFloat> &normalization,
const SDP_Solver_Parameters ¶meters_in)
{
if(initial_points.size() != function_blocks.size())
{
throw std::runtime_error(
"Size are different: Positive_Matrix_With_Prefactor: "
+ std::to_string(function_blocks.size())
+ ", initial points: " + std::to_string(initial_points.size()));
}
SDP_Solver_Parameters parameters(parameters_in);
const size_t rank(El::mpi::Rank()), num_procs(El::mpi::Size()),
num_weights(normalization.size());
const size_t num_blocks(initial_points.size());
std::vector<El::BigFloat> weights(num_weights, 0);
std::vector<std::set<El::BigFloat>> points(num_blocks);
std::vector<std::vector<El::BigFloat>> new_points(num_blocks);
// GMP does not have a special infinity value, so we use max double.
const El::BigFloat infinity(std::numeric_limits<double>::max());
// Use the input points and add inifinty
for(size_t block(0); block < num_blocks; ++block)
{
for(auto &point : initial_points.at(block))
{
points.at(block).emplace(point);
}
points.at(block).emplace(infinity);
}
// TODO: This is duplicated from sdp2input/write_output/write_output.cxx
size_t max_index(0);
El::BigFloat max_normalization(0);
for(size_t index(0); index != normalization.size(); ++index)
{
const El::BigFloat element(Abs(normalization[index]));
if(element > max_normalization)
{
max_normalization = element;
max_index = index;
}
}
const El::Grid global_grid;
El::DistMatrix<El::BigFloat, El::STAR, El::STAR> yp_to_y_star(global_grid),
dual_objective_b_star(global_grid);
El::BigFloat primal_c_scale;
compute_y_transform(function_blocks, points, objectives, normalization,
parameters, max_index, global_grid, yp_to_y_star,
dual_objective_b_star, primal_c_scale);
// std::vector<size_t> matrix_dimensions;
// for(size_t block(0); block != num_blocks; ++block)
// {
// matrix_dimensions.insert(matrix_dimensions.end(),
// points.at(block).size(),
// function_blocks[block].size());
// }
// Block_Info block_info(matrix_dimensions, parameters.procs_per_node,
// parameters.proc_granularity, parameters.verbosity);
std::map<size_t, size_t> old_offsets;
El::Matrix<El::BigFloat> y;
std::vector<El::Matrix<El::BigFloat>> x, X, Y;
parameters.duality_gap_threshold = 1.1;
while(parameters.duality_gap_threshold > parameters_in.duality_gap_threshold)
{
std::map<size_t, size_t> new_to_old;
size_t num_constraints(0), old_index(0);
std::vector<size_t> matrix_dimensions;
for(size_t block(0); block != num_blocks; ++block)
{
for(size_t offset(0); offset != points.at(block).size(); ++offset)
{
new_to_old.emplace(num_constraints + offset, old_index + offset);
}
old_index += points.at(block).size();
for(auto &point : new_points.at(block))
{
points.at(block).emplace(point);
}
num_constraints += points.at(block).size();
matrix_dimensions.insert(matrix_dimensions.end(),
points.at(block).size(),
function_blocks[block].size());
if(rank == 0 && parameters.verbosity >= Verbosity::debug)
{
std::cout << "points: " << block << " " << points.at(block)
<< "\n";
}
}
if(rank == 0)
{
std::cout << "num_constraints: " << num_constraints << "\n";
std::cout << "sizes: " << x.size() << " " << X.size() << " "
<< Y.size() << " "
<< "\n";
}
std::vector<std::vector<El::BigFloat>> primal_objective_c;
primal_objective_c.reserve(num_constraints);
std::vector<El::Matrix<El::BigFloat>> free_var_matrix;
free_var_matrix.reserve(num_constraints);
setup_constraints(max_index, num_blocks, infinity, function_blocks,
normalization, points, primal_objective_c,
free_var_matrix);
const El::BigFloat objective_const(objectives.at(max_index)
/ normalization.at(max_index));
Block_Info block_info(matrix_dimensions, parameters.procs_per_node,
parameters.proc_granularity, parameters.verbosity);
El::Grid grid(block_info.mpi_comm.value);
SDP sdp(objective_const, primal_objective_c, free_var_matrix,
yp_to_y_star, dual_objective_b_star, primal_c_scale, block_info,
grid);
SDP_Solver solver(parameters, block_info, grid,
sdp.dual_objective_b.Height());
if(!X.empty())
{
for(auto &block : solver.y.blocks)
{
copy_matrix(y, block);
}
}
// if(!X.empty())
// {
// // TODO: This will break in parallel
// for(size_t new_offset(0);
// new_offset != block_info.block_indices.size(); ++new_offset)
// {
// const size_t new_index(block_info.block_indices[new_offset]);
// auto iter(new_to_old.find(new_index));
// if(iter != new_to_old.end())
// {
// const size_t old_index(iter->second);
// const size_t old_offset(old_offsets.find(old_index)->second);
// copy_matrix(x.at(old_offset),
// solver.x.blocks.at(new_offset));
// copy_matrix(X.at(2 * old_offset),
// solver.X.blocks.at(2 * new_offset));
// copy_matrix(X.at(2 * old_offset + 1),
// solver.X.blocks.at(2 * new_offset + 1));
// copy_matrix(Y.at(2 * old_offset),
// solver.Y.blocks.at(2 * new_offset));
// copy_matrix(Y.at(2 * old_offset + 1),
// solver.Y.blocks.at(2 * new_offset + 1));
// El::ShiftDiagonal(solver.X.blocks.at(2 * new_offset),
// parameters.initial_matrix_scale_primal);
// El::ShiftDiagonal(solver.X.blocks.at(2 * new_offset + 1),
// parameters.initial_matrix_scale_primal);
// El::ShiftDiagonal(solver.Y.blocks.at(2 * new_offset),
// parameters.initial_matrix_scale_dual);
// El::ShiftDiagonal(solver.Y.blocks.at(2 * new_offset + 1),
// parameters.initial_matrix_scale_dual);
// }
// // else
// // {
// // El::Zero(solver.X.blocks.at(2 * new_offset));
// // El::Zero(solver.X.blocks.at(2 * new_offset + 1));
// // El::Zero(solver.Y.blocks.at(2 * new_offset));
// // El::Zero(solver.Y.blocks.at(2 * new_offset + 1));
// // }
// }
// }
bool has_new_points(false);
while(!has_new_points
&& parameters.duality_gap_threshold
> parameters_in.duality_gap_threshold)
{
if(rank == 0)
{
std::cout << "Threshold: " << parameters.duality_gap_threshold
<< "\n";
}
Timers timers(parameters.verbosity >= Verbosity::debug);
SDP_Solver_Terminate_Reason reason
= solver.run(parameters, block_info, sdp, grid, timers);
if(rank == 0)
{
set_stream_precision(std::cout);
std::cout << "-----" << reason << "-----\n"
<< '\n'
<< "primalObjective = " << solver.primal_objective
<< '\n'
<< "dualObjective = " << solver.dual_objective
<< '\n'
<< "dualityGap = " << solver.duality_gap << '\n'
<< "primalError = " << solver.primal_error()
<< '\n'
<< "dualError = " << solver.dual_error << '\n'
<< '\n';
}
if(reason == SDP_Solver_Terminate_Reason::MaxComplementarityExceeded
|| reason == SDP_Solver_Terminate_Reason::MaxIterationsExceeded
|| reason == SDP_Solver_Terminate_Reason::MaxRuntimeExceeded)
{
std::stringstream ss;
ss << "Can not find solution: " << reason;
throw std::runtime_error(ss.str());
}
// y is duplicated among cores, so only need to print out copy on
// the root node.
// THe weight at max_index is determined by the normalization
// condition dot(norm,weights)=1
El::DistMatrix<El::BigFloat> yp(dual_objective_b_star.Height(), 1,
yp_to_y_star.Grid());
El::Zero(yp);
El::DistMatrix<El::BigFloat> y(yp);
El::DistMatrix<El::BigFloat, El::STAR, El::STAR> yp_star(
solver.y.blocks.at(0));
for(int64_t row(0); row != yp.LocalHeight(); ++row)
{
int64_t global_row(yp.GlobalRow(row));
for(int64_t column(0); column != yp.LocalWidth(); ++column)
{
int64_t global_column(yp.GlobalCol(column));
yp.SetLocal(row, column,
yp_star.GetLocal(global_row, global_column));
}
}
El::Gemv(El::Orientation::NORMAL, El::BigFloat(1.0), yp_to_y_star,
yp, El::BigFloat(0.0), y);
El::DistMatrix<El::BigFloat, El::STAR, El::STAR> y_star(y);
weights.at(max_index) = 1;
for(size_t block_row(0); block_row != size_t(y_star.LocalHeight());
++block_row)
{
const size_t index(block_row + (block_row < max_index ? 0 : 1));
weights.at(index) = y_star.GetLocalCRef(block_row, 0);
weights.at(max_index)
-= weights.at(index) * normalization.at(index);
}
weights.at(max_index) /= normalization.at(max_index);
if(rank == 0)
{
std::cout.precision(20);
std::cout << "weight: " << weights << "\n";
El::BigFloat optimal(0);
for(size_t index(0); index < objectives.size(); ++index)
{
optimal += objectives[index] * weights[index];
}
std::cout << "optimal: " << optimal << "\n";
}
std::vector<size_t> num_new_points(num_blocks, 0);
for(size_t block(rank); block < num_blocks; block += num_procs)
{
// TODO: These can both be precomputed
El::BigFloat max_delta(infinity), block_scale(0);
size_t max_degree(0);
for(auto &row : function_blocks[block])
for(auto &column : row)
for(size_t function_index(0);
function_index != column.size(); ++function_index)
{
auto &f(column[function_index]);
max_delta = El::Min(max_delta, f.max_delta);
max_degree
= std::max(max_degree, f.chebyshev_coeffs.size());
for(auto &coeff : f.chebyshev_coeffs)
{
block_scale = std::max(
block_scale,
El::Abs(coeff * weights[function_index]));
}
}
const El::BigFloat block_epsilon(
block_scale * El::limits::Epsilon<El::BigFloat>());
// 1/128 should be a small enough relative error so that we are
// in the regime of convergence. Then the error estimates will
// work
Mesh mesh(
*(points.at(block).begin()), max_delta,
[&](const El::BigFloat &x) {
return eval_weighted(infinity, function_blocks[block], x,
weights);
},
(1.0 / 128), block_epsilon);
std::vector<El::BigFloat> candidates(
get_new_points(mesh, block_epsilon));
new_points.at(block).clear();
for(auto &point : candidates)
{
if(points.at(block).count(point) == 0)
{
new_points.at(block).push_back(point);
++num_new_points.at(block);
}
}
}
El::mpi::AllReduce(num_new_points.data(), num_new_points.size(),
El::mpi::SUM, El::mpi::COMM_WORLD);
for(size_t block(0); block != num_blocks; ++block)
{
new_points.at(block).resize(num_new_points.at(block));
El::mpi::Broadcast(new_points.at(block).data(),
num_new_points.at(block), block % num_procs,
El::mpi::COMM_WORLD);
}
has_new_points
= (find_if(num_new_points.begin(), num_new_points.end(),
[](const size_t &n) { return n != 0; })
!= num_new_points.end());
if(!has_new_points)
{
parameters.duality_gap_threshold *= (1.0 / 8);
}
}
old_offsets.clear();
for(size_t index(0); index != block_info.block_indices.size(); ++index)
{
old_offsets.emplace(block_info.block_indices[index], index);
}
// std::cout << "old offset: "
// << block_info.block_indices << "\n "
// << old_offsets << "\n";
copy_matrices(solver.x.blocks, x);
copy_matrix(solver.y.blocks.front(), y);
copy_matrices(solver.X.blocks, X);
copy_matrices(solver.Y.blocks, Y);
}
return weights;
}
<commit_msg>Clean up<commit_after>#include "Mesh.hxx"
#include "setup_constraints.hxx"
#include "../../sdp_solve.hxx"
#include "../../ostream_set.hxx"
#include "../../ostream_map.hxx"
#include "../../ostream_vector.hxx"
#include "../../set_stream_precision.hxx"
namespace
{
void copy_matrix(const El::Matrix<El::BigFloat> &source,
El::DistMatrix<El::BigFloat> &destination)
{
for(int64_t row(0); row < source.Height(); ++row)
{
for(int64_t column(0); column < source.Width(); ++column)
{
// TODO: This will break in parallel
destination.SetLocal(row, column, source(row, column));
}
}
}
void copy_matrix(const El::DistMatrix<El::BigFloat> &source,
El::Matrix<El::BigFloat> &destination)
{
destination.Resize(source.Height(), source.Width());
for(int64_t row(0); row < source.Height(); ++row)
{
for(int64_t column(0); column < source.Width(); ++column)
{
// TODO: This will break in parallel
destination(row, column) = source.GetLocal(row, column);
}
}
}
}
void compute_y_transform(
const std::vector<std::vector<std::vector<std::vector<Function>>>>
&function_blocks,
const std::vector<std::set<El::BigFloat>> &points,
const std::vector<El::BigFloat> &objectives,
const std::vector<El::BigFloat> &normalization,
const SDP_Solver_Parameters ¶meters, const size_t &max_index,
const El::Grid &global_grid,
El::DistMatrix<El::BigFloat, El::STAR, El::STAR> &yp_to_y,
El::DistMatrix<El::BigFloat, El::STAR, El::STAR> &dual_objective_b_star,
El::BigFloat &primal_c_scale);
El::BigFloat eval_weighted(
const El::BigFloat &infinity,
const std::vector<std::vector<std::vector<Function>>> &function_blocks,
const El::BigFloat &x, const std::vector<El::BigFloat> &weights);
std::vector<El::BigFloat>
get_new_points(const Mesh &mesh, const El::BigFloat &block_epsilon);
std::vector<El::BigFloat> compute_optimal(
const std::vector<std::vector<std::vector<std::vector<Function>>>>
&function_blocks,
const std::vector<std::vector<El::BigFloat>> &initial_points,
const std::vector<El::BigFloat> &objectives,
const std::vector<El::BigFloat> &normalization,
const SDP_Solver_Parameters ¶meters_in)
{
if(initial_points.size() != function_blocks.size())
{
throw std::runtime_error(
"Size are different: Positive_Matrix_With_Prefactor: "
+ std::to_string(function_blocks.size())
+ ", initial points: " + std::to_string(initial_points.size()));
}
SDP_Solver_Parameters parameters(parameters_in);
const size_t rank(El::mpi::Rank()), num_procs(El::mpi::Size()),
num_weights(normalization.size());
const size_t num_blocks(initial_points.size());
std::vector<El::BigFloat> weights(num_weights, 0);
std::vector<std::set<El::BigFloat>> points(num_blocks);
std::vector<std::vector<El::BigFloat>> new_points(num_blocks);
// GMP does not have a special infinity value, so we use max double.
const El::BigFloat infinity(std::numeric_limits<double>::max());
// Use the input points and add inifinty
for(size_t block(0); block < num_blocks; ++block)
{
for(auto &point : initial_points.at(block))
{
points.at(block).emplace(point);
}
points.at(block).emplace(infinity);
}
// TODO: This is duplicated from sdp2input/write_output/write_output.cxx
size_t max_index(0);
El::BigFloat max_normalization(0);
for(size_t index(0); index != normalization.size(); ++index)
{
const El::BigFloat element(Abs(normalization[index]));
if(element > max_normalization)
{
max_normalization = element;
max_index = index;
}
}
const El::Grid global_grid;
El::DistMatrix<El::BigFloat, El::STAR, El::STAR> yp_to_y_star(global_grid),
dual_objective_b_star(global_grid);
El::BigFloat primal_c_scale;
compute_y_transform(function_blocks, points, objectives, normalization,
parameters, max_index, global_grid, yp_to_y_star,
dual_objective_b_star, primal_c_scale);
El::Matrix<El::BigFloat> y_saved(yp_to_y_star.Height(), 1);
El::Zero(y_saved);
parameters.duality_gap_threshold = 1.1;
while(parameters.duality_gap_threshold > parameters_in.duality_gap_threshold)
{
std::map<size_t, size_t> new_to_old;
size_t num_constraints(0), old_index(0);
std::vector<size_t> matrix_dimensions;
for(size_t block(0); block != num_blocks; ++block)
{
for(size_t offset(0); offset != points.at(block).size(); ++offset)
{
new_to_old.emplace(num_constraints + offset, old_index + offset);
}
old_index += points.at(block).size();
for(auto &point : new_points.at(block))
{
points.at(block).emplace(point);
}
num_constraints += points.at(block).size();
matrix_dimensions.insert(matrix_dimensions.end(),
points.at(block).size(),
function_blocks[block].size());
if(rank == 0 && parameters.verbosity >= Verbosity::debug)
{
std::cout << "points: " << block << " " << points.at(block)
<< "\n";
}
}
if(rank == 0)
{
std::cout << "num_constraints: " << num_constraints << "\n";
}
std::vector<std::vector<El::BigFloat>> primal_objective_c;
primal_objective_c.reserve(num_constraints);
std::vector<El::Matrix<El::BigFloat>> free_var_matrix;
free_var_matrix.reserve(num_constraints);
setup_constraints(max_index, num_blocks, infinity, function_blocks,
normalization, points, primal_objective_c,
free_var_matrix);
const El::BigFloat objective_const(objectives.at(max_index)
/ normalization.at(max_index));
Block_Info block_info(matrix_dimensions, parameters.procs_per_node,
parameters.proc_granularity, parameters.verbosity);
El::Grid grid(block_info.mpi_comm.value);
SDP sdp(objective_const, primal_objective_c, free_var_matrix,
yp_to_y_star, dual_objective_b_star, primal_c_scale, block_info,
grid);
SDP_Solver solver(parameters, block_info, grid,
sdp.dual_objective_b.Height());
for(auto &y_block : solver.y.blocks)
{
copy_matrix(y_saved, y_block);
}
bool has_new_points(false);
while(!has_new_points
&& parameters.duality_gap_threshold
> parameters_in.duality_gap_threshold)
{
if(rank == 0)
{
std::cout << "Threshold: " << parameters.duality_gap_threshold
<< "\n";
}
Timers timers(parameters.verbosity >= Verbosity::debug);
SDP_Solver_Terminate_Reason reason
= solver.run(parameters, block_info, sdp, grid, timers);
if(rank == 0)
{
set_stream_precision(std::cout);
std::cout << "-----" << reason << "-----\n"
<< '\n'
<< "primalObjective = " << solver.primal_objective
<< '\n'
<< "dualObjective = " << solver.dual_objective
<< '\n'
<< "dualityGap = " << solver.duality_gap << '\n'
<< "primalError = " << solver.primal_error()
<< '\n'
<< "dualError = " << solver.dual_error << '\n'
<< '\n';
}
if(reason == SDP_Solver_Terminate_Reason::MaxComplementarityExceeded
|| reason == SDP_Solver_Terminate_Reason::MaxIterationsExceeded
|| reason == SDP_Solver_Terminate_Reason::MaxRuntimeExceeded)
{
std::stringstream ss;
ss << "Can not find solution: " << reason;
throw std::runtime_error(ss.str());
}
// y is duplicated among cores, so only need to print out copy on
// the root node.
// THe weight at max_index is determined by the normalization
// condition dot(norm,weights)=1
El::DistMatrix<El::BigFloat> yp(dual_objective_b_star.Height(), 1,
yp_to_y_star.Grid());
El::Zero(yp);
El::DistMatrix<El::BigFloat> y(yp);
El::DistMatrix<El::BigFloat, El::STAR, El::STAR> yp_star(
solver.y.blocks.at(0));
for(int64_t row(0); row != yp.LocalHeight(); ++row)
{
int64_t global_row(yp.GlobalRow(row));
for(int64_t column(0); column != yp.LocalWidth(); ++column)
{
int64_t global_column(yp.GlobalCol(column));
yp.SetLocal(row, column,
yp_star.GetLocal(global_row, global_column));
}
}
El::Gemv(El::Orientation::NORMAL, El::BigFloat(1.0), yp_to_y_star,
yp, El::BigFloat(0.0), y);
El::DistMatrix<El::BigFloat, El::STAR, El::STAR> y_star(y);
weights.at(max_index) = 1;
for(size_t block_row(0); block_row != size_t(y_star.LocalHeight());
++block_row)
{
const size_t index(block_row + (block_row < max_index ? 0 : 1));
weights.at(index) = y_star.GetLocalCRef(block_row, 0);
weights.at(max_index)
-= weights.at(index) * normalization.at(index);
}
weights.at(max_index) /= normalization.at(max_index);
if(rank == 0)
{
std::cout.precision(20);
std::cout << "weight: " << weights << "\n";
El::BigFloat optimal(0);
for(size_t index(0); index < objectives.size(); ++index)
{
optimal += objectives[index] * weights[index];
}
std::cout << "optimal: " << optimal << "\n";
}
std::vector<size_t> num_new_points(num_blocks, 0);
for(size_t block(rank); block < num_blocks; block += num_procs)
{
// TODO: These can both be precomputed
El::BigFloat max_delta(infinity), block_scale(0);
size_t max_degree(0);
for(auto &row : function_blocks[block])
for(auto &column : row)
for(size_t function_index(0);
function_index != column.size(); ++function_index)
{
auto &f(column[function_index]);
max_delta = El::Min(max_delta, f.max_delta);
max_degree
= std::max(max_degree, f.chebyshev_coeffs.size());
for(auto &coeff : f.chebyshev_coeffs)
{
block_scale = std::max(
block_scale,
El::Abs(coeff * weights[function_index]));
}
}
const El::BigFloat block_epsilon(
block_scale * El::limits::Epsilon<El::BigFloat>());
// 1/128 should be a small enough relative error so that we are
// in the regime of convergence. Then the error estimates will
// work
Mesh mesh(
*(points.at(block).begin()), max_delta,
[&](const El::BigFloat &x) {
return eval_weighted(infinity, function_blocks[block], x,
weights);
},
(1.0 / 128), block_epsilon);
std::vector<El::BigFloat> candidates(
get_new_points(mesh, block_epsilon));
new_points.at(block).clear();
for(auto &point : candidates)
{
if(points.at(block).count(point) == 0)
{
new_points.at(block).push_back(point);
++num_new_points.at(block);
}
}
}
El::mpi::AllReduce(num_new_points.data(), num_new_points.size(),
El::mpi::SUM, El::mpi::COMM_WORLD);
for(size_t block(0); block != num_blocks; ++block)
{
new_points.at(block).resize(num_new_points.at(block));
El::mpi::Broadcast(new_points.at(block).data(),
num_new_points.at(block), block % num_procs,
El::mpi::COMM_WORLD);
}
has_new_points
= (find_if(num_new_points.begin(), num_new_points.end(),
[](const size_t &n) { return n != 0; })
!= num_new_points.end());
if(!has_new_points)
{
parameters.duality_gap_threshold *= (1.0 / 8);
}
}
copy_matrix(solver.y.blocks.front(), y_saved);
}
return weights;
}
<|endoftext|> |
<commit_before>/*
Copyright (C) 2001-2011 by Serge Lamikhov-Center
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 ELFIO_DUMP_HPP
#define ELFIO_DUMP_HPP
#include <string>
#include <ostream>
#include <elfio.hpp>
namespace ELFIO {
//------------------------------------------------------------------------------
class dump
{
public:
//------------------------------------------------------------------------------
static void
header( std::ostream& out, elfio& reader )
{
out << "ELF Header\n" << std::endl;
out << " Class: "
<< str_elf_class( reader.get_class() )
<< "(" << (int)reader.get_class() << ")"
<< std::endl;
out << " Encoding: "
<< ( ( ELFDATA2LSB == reader.get_encoding() ) ? "Little endian" : "" )
<< ( ( ELFDATA2MSB == reader.get_encoding() ) ? "Big endian" : "" )
<< ( ( ( ELFDATA2LSB != reader.get_encoding() ) &&
( ELFDATA2MSB != reader.get_encoding() ) ) ? "Unknown" : "" )
<< std::endl;
out << " ELFVersion: "
<< ( ( EV_CURRENT == reader.get_elf_version() ) ? "Current" : "Unknown" )
<< "(" << (int)reader.get_elf_version() << ")"
<< std::endl;
out << " Type: " << std::hex << reader.get_type() << std::endl;
out << " Machine: " << std::hex << reader.get_machine() << std::endl;
out << " Version: " << std::hex << reader.get_version() << std::endl;
out << " Entry: " << std::hex << reader.get_entry() << std::endl;
out << " Flags: " << std::hex << reader.get_flags() << std::endl;
}
//------------------------------------------------------------------------------
static std::string
str_section_type( Elf_Word type )
{
}
static std::string
str_elf_class( Elf_Word type )
{
struct convert
{
Elf_Word type;
const char* str;
};
convert converts[] =
{
{ ELFCLASS32, "ELF32" },
{ ELFCLASS64, "ELF64" },
};
std::string res = "UNKNOWN";
for ( unsigned int i = 0; i < sizeof( converts )/sizeof( convert ); ++i ) {
if ( converts[i].type == type ) {
res = converts[i].str;
break;
}
}
return res;
}
};
} // namespace ELFIO
#endif // ELFIO_DUMP_HPP
<commit_msg>Another change<commit_after>/*
Copyright (C) 2001-2011 by Serge Lamikhov-Center
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 ELFIO_DUMP_HPP
#define ELFIO_DUMP_HPP
#include <string>
#include <ostream>
#include <elfio.hpp>
namespace ELFIO {
//------------------------------------------------------------------------------
class dump
{
public:
//------------------------------------------------------------------------------
static void
header( std::ostream& out, elfio& reader )
{
out << "ELF Header\n" << std::endl;
out << " Class: "
<< str_elf_class( reader.get_class() )
<< " (" << (int)reader.get_class() << ")"
<< std::endl;
out << " Encoding: "
<< ( ( ELFDATA2LSB == reader.get_encoding() ) ? "Little endian" : "" )
<< ( ( ELFDATA2MSB == reader.get_encoding() ) ? "Big endian" : "" )
<< ( ( ( ELFDATA2LSB != reader.get_encoding() ) &&
( ELFDATA2MSB != reader.get_encoding() ) ) ? "Unknown" : "" )
<< std::endl;
out << " ELFVersion: "
<< ( ( EV_CURRENT == reader.get_elf_version() ) ? "Current" : "Unknown" )
<< "(" << (int)reader.get_elf_version() << ")"
<< std::endl;
out << " Type: " << std::hex << reader.get_type() << std::endl;
out << " Machine: " << std::hex << reader.get_machine() << std::endl;
out << " Version: " << std::hex << reader.get_version() << std::endl;
out << " Entry: " << std::hex << reader.get_entry() << std::endl;
out << " Flags: " << std::hex << reader.get_flags() << std::endl;
}
struct convert
{
Elf_Word type;
const char* str;
};
convert converts[] =
{
{ ELFCLASS32, "ELF32" },
{ ELFCLASS64, "ELF64" },
};
//------------------------------------------------------------------------------
template<class T> static std::string
str_section_type( Elf_Word type )
{
}
static std::string
str_elf_class( Elf_Word type )
{
std::string res = "UNKNOWN";
for ( unsigned int i = 0; i < sizeof( converts )/sizeof( convert ); ++i ) {
if ( converts[i].type == type ) {
res = converts[i].str;
break;
}
}
return res;
}
};
} // namespace ELFIO
#endif // ELFIO_DUMP_HPP
<|endoftext|> |
<commit_before><commit_msg>Vulkan: Increase Fence Wait Time<commit_after><|endoftext|> |
<commit_before>/*
* SM2 Encryption
* (C) 2017 Ribose Inc
*
* Botan is released under the Simplified BSD License (see license.txt)
*/
#include <botan/sm2_enc.h>
#include <botan/internal/point_mul.h>
#include <botan/pk_ops.h>
#include <botan/keypair.h>
#include <botan/der_enc.h>
#include <botan/ber_dec.h>
#include <botan/kdf.h>
#include <botan/hash.h>
namespace Botan {
bool SM2_Encryption_PrivateKey::check_key(RandomNumberGenerator& rng,
bool strong) const
{
if(!public_point().on_the_curve())
return false;
if(!strong)
return true;
return KeyPair::encryption_consistency_check(rng, *this, "SM3");
}
SM2_Encryption_PrivateKey::SM2_Encryption_PrivateKey(const AlgorithmIdentifier& alg_id,
const secure_vector<uint8_t>& key_bits) :
EC_PrivateKey(alg_id, key_bits)
{
}
SM2_Encryption_PrivateKey::SM2_Encryption_PrivateKey(RandomNumberGenerator& rng,
const EC_Group& domain,
const BigInt& x) :
EC_PrivateKey(rng, domain, x)
{
}
namespace {
class SM2_Encryption_Operation final : public PK_Ops::Encryption
{
public:
SM2_Encryption_Operation(const SM2_Encryption_PublicKey& key,
RandomNumberGenerator& rng,
const std::string& kdf_hash) :
m_group(key.domain()),
m_kdf_hash(kdf_hash),
m_ws(PointGFp::WORKSPACE_SIZE),
m_mul_public_point(key.public_point(), rng, m_ws)
{}
size_t max_input_bits() const override
{
// This is arbitrary, but assumes SM2 is used for key encapsulation
return 512;
}
secure_vector<uint8_t> encrypt(const uint8_t msg[],
size_t msg_len,
RandomNumberGenerator& rng) override
{
std::unique_ptr<HashFunction> hash = HashFunction::create_or_throw(m_kdf_hash);
std::unique_ptr<KDF> kdf = KDF::create_or_throw("KDF2(" + m_kdf_hash + ")");
const size_t p_bytes = m_group.get_p_bytes();
const BigInt k = m_group.random_scalar(rng);
const PointGFp C1 = m_group.blinded_base_point_multiply(k, rng, m_ws);
const BigInt x1 = C1.get_affine_x();
const BigInt y1 = C1.get_affine_y();
std::vector<uint8_t> x1_bytes(p_bytes);
std::vector<uint8_t> y1_bytes(p_bytes);
BigInt::encode_1363(x1_bytes.data(), x1_bytes.size(), x1);
BigInt::encode_1363(y1_bytes.data(), y1_bytes.size(), y1);
const PointGFp kPB = m_mul_public_point.mul(k, rng, m_group.get_order(), m_ws);
const BigInt x2 = kPB.get_affine_x();
const BigInt y2 = kPB.get_affine_y();
std::vector<uint8_t> x2_bytes(p_bytes);
std::vector<uint8_t> y2_bytes(p_bytes);
BigInt::encode_1363(x2_bytes.data(), x2_bytes.size(), x2);
BigInt::encode_1363(y2_bytes.data(), y2_bytes.size(), y2);
secure_vector<uint8_t> kdf_input;
kdf_input += x2_bytes;
kdf_input += y2_bytes;
const secure_vector<uint8_t> kdf_output =
kdf->derive_key(msg_len, kdf_input.data(), kdf_input.size());
secure_vector<uint8_t> masked_msg(msg_len);
xor_buf(masked_msg.data(), msg, kdf_output.data(), msg_len);
hash->update(x2_bytes);
hash->update(msg, msg_len);
hash->update(y2_bytes);
std::vector<uint8_t> C3(hash->output_length());
hash->final(C3.data());
return DER_Encoder()
.start_cons(SEQUENCE)
.encode(x1)
.encode(y1)
.encode(C3, OCTET_STRING)
.encode(masked_msg, OCTET_STRING)
.end_cons()
.get_contents();
}
private:
const EC_Group m_group;
const std::string m_kdf_hash;
std::vector<BigInt> m_ws;
PointGFp_Var_Point_Precompute m_mul_public_point;
};
class SM2_Decryption_Operation final : public PK_Ops::Decryption
{
public:
SM2_Decryption_Operation(const SM2_Encryption_PrivateKey& key,
RandomNumberGenerator& rng,
const std::string& kdf_hash) :
m_key(key),
m_rng(rng),
m_kdf_hash(kdf_hash)
{}
secure_vector<uint8_t> decrypt(uint8_t& valid_mask,
const uint8_t ciphertext[],
size_t ciphertext_len) override
{
const EC_Group& group = m_key.domain();
const BigInt& cofactor = group.get_cofactor();
const size_t p_bytes = group.get_p_bytes();
valid_mask = 0x00;
std::unique_ptr<HashFunction> hash = HashFunction::create_or_throw(m_kdf_hash);
std::unique_ptr<KDF> kdf = KDF::create_or_throw("KDF2(" + m_kdf_hash + ")");
// Too short to be valid - no timing problem from early return
if(ciphertext_len < 1 + p_bytes*2 + hash->output_length())
{
return secure_vector<uint8_t>();
}
BigInt x1, y1;
secure_vector<uint8_t> C3, masked_msg;
BER_Decoder(ciphertext, ciphertext_len)
.start_cons(SEQUENCE)
.decode(x1)
.decode(y1)
.decode(C3, OCTET_STRING)
.decode(masked_msg, OCTET_STRING)
.end_cons()
.verify_end();
PointGFp C1 = group.point(x1, y1);
C1.randomize_repr(m_rng);
if(!C1.on_the_curve())
return secure_vector<uint8_t>();
if(cofactor > 1 && (C1 * cofactor).is_zero())
{
return secure_vector<uint8_t>();
}
const PointGFp dbC1 = group.blinded_var_point_multiply(
C1, m_key.private_value(), m_rng, m_ws);
const BigInt x2 = dbC1.get_affine_x();
const BigInt y2 = dbC1.get_affine_y();
std::vector<uint8_t> x2_bytes(p_bytes);
std::vector<uint8_t> y2_bytes(p_bytes);
BigInt::encode_1363(x2_bytes.data(), x2_bytes.size(), x2);
BigInt::encode_1363(y2_bytes.data(), y2_bytes.size(), y2);
secure_vector<uint8_t> kdf_input;
kdf_input += x2_bytes;
kdf_input += y2_bytes;
const secure_vector<uint8_t> kdf_output =
kdf->derive_key(masked_msg.size(), kdf_input.data(), kdf_input.size());
xor_buf(masked_msg.data(), kdf_output.data(), kdf_output.size());
hash->update(x2_bytes);
hash->update(masked_msg);
hash->update(y2_bytes);
secure_vector<uint8_t> u = hash->final();
if(constant_time_compare(u.data(), C3.data(), hash->output_length()) == false)
return secure_vector<uint8_t>();
valid_mask = 0xFF;
return masked_msg;
}
private:
const SM2_Encryption_PrivateKey& m_key;
RandomNumberGenerator& m_rng;
const std::string m_kdf_hash;
std::vector<BigInt> m_ws;
};
}
std::unique_ptr<PK_Ops::Encryption>
SM2_Encryption_PublicKey::create_encryption_op(RandomNumberGenerator& rng,
const std::string& params,
const std::string& provider) const
{
if(provider == "base" || provider.empty())
{
const std::string kdf_hash = (params.empty() ? "SM3" : params);
return std::unique_ptr<PK_Ops::Encryption>(new SM2_Encryption_Operation(*this, rng, kdf_hash));
}
throw Provider_Not_Found(algo_name(), provider);
}
std::unique_ptr<PK_Ops::Decryption>
SM2_Encryption_PrivateKey::create_decryption_op(RandomNumberGenerator& rng,
const std::string& params,
const std::string& provider) const
{
if(provider == "base" || provider.empty())
{
const std::string kdf_hash = (params.empty() ? "SM3" : params);
return std::unique_ptr<PK_Ops::Decryption>(new SM2_Decryption_Operation(*this, rng, kdf_hash));
}
throw Provider_Not_Found(algo_name(), provider);
}
}
<commit_msg>Require SM2 ciphertexts be DER encoded<commit_after>/*
* SM2 Encryption
* (C) 2017 Ribose Inc
*
* Botan is released under the Simplified BSD License (see license.txt)
*/
#include <botan/sm2_enc.h>
#include <botan/internal/point_mul.h>
#include <botan/pk_ops.h>
#include <botan/keypair.h>
#include <botan/der_enc.h>
#include <botan/ber_dec.h>
#include <botan/kdf.h>
#include <botan/hash.h>
namespace Botan {
bool SM2_Encryption_PrivateKey::check_key(RandomNumberGenerator& rng,
bool strong) const
{
if(!public_point().on_the_curve())
return false;
if(!strong)
return true;
return KeyPair::encryption_consistency_check(rng, *this, "SM3");
}
SM2_Encryption_PrivateKey::SM2_Encryption_PrivateKey(const AlgorithmIdentifier& alg_id,
const secure_vector<uint8_t>& key_bits) :
EC_PrivateKey(alg_id, key_bits)
{
}
SM2_Encryption_PrivateKey::SM2_Encryption_PrivateKey(RandomNumberGenerator& rng,
const EC_Group& domain,
const BigInt& x) :
EC_PrivateKey(rng, domain, x)
{
}
namespace {
class SM2_Encryption_Operation final : public PK_Ops::Encryption
{
public:
SM2_Encryption_Operation(const SM2_Encryption_PublicKey& key,
RandomNumberGenerator& rng,
const std::string& kdf_hash) :
m_group(key.domain()),
m_kdf_hash(kdf_hash),
m_ws(PointGFp::WORKSPACE_SIZE),
m_mul_public_point(key.public_point(), rng, m_ws)
{}
size_t max_input_bits() const override
{
// This is arbitrary, but assumes SM2 is used for key encapsulation
return 512;
}
secure_vector<uint8_t> encrypt(const uint8_t msg[],
size_t msg_len,
RandomNumberGenerator& rng) override
{
std::unique_ptr<HashFunction> hash = HashFunction::create_or_throw(m_kdf_hash);
std::unique_ptr<KDF> kdf = KDF::create_or_throw("KDF2(" + m_kdf_hash + ")");
const size_t p_bytes = m_group.get_p_bytes();
const BigInt k = m_group.random_scalar(rng);
const PointGFp C1 = m_group.blinded_base_point_multiply(k, rng, m_ws);
const BigInt x1 = C1.get_affine_x();
const BigInt y1 = C1.get_affine_y();
std::vector<uint8_t> x1_bytes(p_bytes);
std::vector<uint8_t> y1_bytes(p_bytes);
BigInt::encode_1363(x1_bytes.data(), x1_bytes.size(), x1);
BigInt::encode_1363(y1_bytes.data(), y1_bytes.size(), y1);
const PointGFp kPB = m_mul_public_point.mul(k, rng, m_group.get_order(), m_ws);
const BigInt x2 = kPB.get_affine_x();
const BigInt y2 = kPB.get_affine_y();
std::vector<uint8_t> x2_bytes(p_bytes);
std::vector<uint8_t> y2_bytes(p_bytes);
BigInt::encode_1363(x2_bytes.data(), x2_bytes.size(), x2);
BigInt::encode_1363(y2_bytes.data(), y2_bytes.size(), y2);
secure_vector<uint8_t> kdf_input;
kdf_input += x2_bytes;
kdf_input += y2_bytes;
const secure_vector<uint8_t> kdf_output =
kdf->derive_key(msg_len, kdf_input.data(), kdf_input.size());
secure_vector<uint8_t> masked_msg(msg_len);
xor_buf(masked_msg.data(), msg, kdf_output.data(), msg_len);
hash->update(x2_bytes);
hash->update(msg, msg_len);
hash->update(y2_bytes);
std::vector<uint8_t> C3(hash->output_length());
hash->final(C3.data());
return DER_Encoder()
.start_cons(SEQUENCE)
.encode(x1)
.encode(y1)
.encode(C3, OCTET_STRING)
.encode(masked_msg, OCTET_STRING)
.end_cons()
.get_contents();
}
private:
const EC_Group m_group;
const std::string m_kdf_hash;
std::vector<BigInt> m_ws;
PointGFp_Var_Point_Precompute m_mul_public_point;
};
class SM2_Decryption_Operation final : public PK_Ops::Decryption
{
public:
SM2_Decryption_Operation(const SM2_Encryption_PrivateKey& key,
RandomNumberGenerator& rng,
const std::string& kdf_hash) :
m_key(key),
m_rng(rng),
m_kdf_hash(kdf_hash)
{}
secure_vector<uint8_t> decrypt(uint8_t& valid_mask,
const uint8_t ciphertext[],
size_t ciphertext_len) override
{
const EC_Group& group = m_key.domain();
const BigInt& cofactor = group.get_cofactor();
const size_t p_bytes = group.get_p_bytes();
valid_mask = 0x00;
std::unique_ptr<HashFunction> hash = HashFunction::create_or_throw(m_kdf_hash);
std::unique_ptr<KDF> kdf = KDF::create_or_throw("KDF2(" + m_kdf_hash + ")");
// Too short to be valid - no timing problem from early return
if(ciphertext_len < 1 + p_bytes*2 + hash->output_length())
{
return secure_vector<uint8_t>();
}
BigInt x1, y1;
secure_vector<uint8_t> C3, masked_msg;
BER_Decoder(ciphertext, ciphertext_len)
.start_cons(SEQUENCE)
.decode(x1)
.decode(y1)
.decode(C3, OCTET_STRING)
.decode(masked_msg, OCTET_STRING)
.end_cons()
.verify_end();
std::vector<uint8_t> recode_ctext;
DER_Encoder(recode_ctext)
.start_cons(SEQUENCE)
.encode(x1)
.encode(y1)
.encode(C3, OCTET_STRING)
.encode(masked_msg, OCTET_STRING)
.end_cons();
if(recode_ctext.size() != ciphertext_len)
return secure_vector<uint8_t>();
if(same_mem(recode_ctext.data(), ciphertext, ciphertext_len) == false)
return secure_vector<uint8_t>();
PointGFp C1 = group.point(x1, y1);
C1.randomize_repr(m_rng);
// Here C1 is publically invalid, so no problem with early return:
if(!C1.on_the_curve())
return secure_vector<uint8_t>();
if(cofactor > 1 && (C1 * cofactor).is_zero())
{
return secure_vector<uint8_t>();
}
const PointGFp dbC1 = group.blinded_var_point_multiply(
C1, m_key.private_value(), m_rng, m_ws);
const BigInt x2 = dbC1.get_affine_x();
const BigInt y2 = dbC1.get_affine_y();
secure_vector<uint8_t> x2_bytes(p_bytes);
secure_vector<uint8_t> y2_bytes(p_bytes);
BigInt::encode_1363(x2_bytes.data(), x2_bytes.size(), x2);
BigInt::encode_1363(y2_bytes.data(), y2_bytes.size(), y2);
secure_vector<uint8_t> kdf_input;
kdf_input += x2_bytes;
kdf_input += y2_bytes;
const secure_vector<uint8_t> kdf_output =
kdf->derive_key(masked_msg.size(), kdf_input.data(), kdf_input.size());
xor_buf(masked_msg.data(), kdf_output.data(), kdf_output.size());
hash->update(x2_bytes);
hash->update(masked_msg);
hash->update(y2_bytes);
secure_vector<uint8_t> u = hash->final();
if(constant_time_compare(u.data(), C3.data(), hash->output_length()) == false)
return secure_vector<uint8_t>();
valid_mask = 0xFF;
return masked_msg;
}
private:
const SM2_Encryption_PrivateKey& m_key;
RandomNumberGenerator& m_rng;
const std::string m_kdf_hash;
std::vector<BigInt> m_ws;
};
}
std::unique_ptr<PK_Ops::Encryption>
SM2_Encryption_PublicKey::create_encryption_op(RandomNumberGenerator& rng,
const std::string& params,
const std::string& provider) const
{
if(provider == "base" || provider.empty())
{
const std::string kdf_hash = (params.empty() ? "SM3" : params);
return std::unique_ptr<PK_Ops::Encryption>(new SM2_Encryption_Operation(*this, rng, kdf_hash));
}
throw Provider_Not_Found(algo_name(), provider);
}
std::unique_ptr<PK_Ops::Decryption>
SM2_Encryption_PrivateKey::create_decryption_op(RandomNumberGenerator& rng,
const std::string& params,
const std::string& provider) const
{
if(provider == "base" || provider.empty())
{
const std::string kdf_hash = (params.empty() ? "SM3" : params);
return std::unique_ptr<PK_Ops::Decryption>(new SM2_Decryption_Operation(*this, rng, kdf_hash));
}
throw Provider_Not_Found(algo_name(), provider);
}
}
<|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: imap3.cxx,v $
*
* $Revision: 1.4 $
*
* last change: $Author: hr $ $Date: 2007-06-27 21:51:21 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_svtools.hxx"
#include <svtools/imap.hxx>
#include <tools/debug.hxx>
/******************************************************************************
|*
|* Ctor
|*
\******************************************************************************/
IMapCompat::IMapCompat( SvStream& rStm, const USHORT nStreamMode ) :
pRWStm ( &rStm ),
nStmMode ( nStreamMode )
{
DBG_ASSERT( nStreamMode == STREAM_READ || nStreamMode == STREAM_WRITE, "Wrong Mode!" );
if ( !pRWStm->GetError() )
{
if ( nStmMode == STREAM_WRITE )
{
nCompatPos = pRWStm->Tell();
pRWStm->SeekRel( 4 );
nTotalSize = nCompatPos + 4;
}
else
{
UINT32 nTotalSizeTmp;
*pRWStm >> nTotalSizeTmp;
nTotalSize = nTotalSizeTmp;
nCompatPos = pRWStm->Tell();
}
}
}
/******************************************************************************
|*
|* Dtor
|*
\******************************************************************************/
IMapCompat::~IMapCompat()
{
if ( !pRWStm->GetError() )
{
if ( nStmMode == STREAM_WRITE )
{
const ULONG nEndPos = pRWStm->Tell();
pRWStm->Seek( nCompatPos );
*pRWStm << (UINT32) ( nEndPos - nTotalSize );
pRWStm->Seek( nEndPos );
}
else
{
const ULONG nReadSize = pRWStm->Tell() - nCompatPos;
if ( nTotalSize > nReadSize )
pRWStm->SeekRel( nTotalSize - nReadSize );
}
}
}
<commit_msg>INTEGRATION: CWS changefileheader (1.4.246); FILE MERGED 2008/03/31 13:02:17 rt 1.4.246.1: #i87441# Change license header to LPGL v3.<commit_after>/*************************************************************************
*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* Copyright 2008 by Sun Microsystems, Inc.
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: imap3.cxx,v $
* $Revision: 1.5 $
*
* This file is part of OpenOffice.org.
*
* OpenOffice.org is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License version 3
* only, as published by the Free Software Foundation.
*
* OpenOffice.org is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License version 3 for more details
* (a copy is included in the LICENSE file that accompanied this code).
*
* You should have received a copy of the GNU Lesser General Public License
* version 3 along with OpenOffice.org. If not, see
* <http://www.openoffice.org/license.html>
* for a copy of the LGPLv3 License.
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_svtools.hxx"
#include <svtools/imap.hxx>
#include <tools/debug.hxx>
/******************************************************************************
|*
|* Ctor
|*
\******************************************************************************/
IMapCompat::IMapCompat( SvStream& rStm, const USHORT nStreamMode ) :
pRWStm ( &rStm ),
nStmMode ( nStreamMode )
{
DBG_ASSERT( nStreamMode == STREAM_READ || nStreamMode == STREAM_WRITE, "Wrong Mode!" );
if ( !pRWStm->GetError() )
{
if ( nStmMode == STREAM_WRITE )
{
nCompatPos = pRWStm->Tell();
pRWStm->SeekRel( 4 );
nTotalSize = nCompatPos + 4;
}
else
{
UINT32 nTotalSizeTmp;
*pRWStm >> nTotalSizeTmp;
nTotalSize = nTotalSizeTmp;
nCompatPos = pRWStm->Tell();
}
}
}
/******************************************************************************
|*
|* Dtor
|*
\******************************************************************************/
IMapCompat::~IMapCompat()
{
if ( !pRWStm->GetError() )
{
if ( nStmMode == STREAM_WRITE )
{
const ULONG nEndPos = pRWStm->Tell();
pRWStm->Seek( nCompatPos );
*pRWStm << (UINT32) ( nEndPos - nTotalSize );
pRWStm->Seek( nEndPos );
}
else
{
const ULONG nReadSize = pRWStm->Tell() - nCompatPos;
if ( nTotalSize > nReadSize )
pRWStm->SeekRel( nTotalSize - nReadSize );
}
}
}
<|endoftext|> |
<commit_before>/****************************************************************************
**
** Copyright (C) 2014 Digia Plc and/or its subsidiary(-ies).
** Contact: http://www.qt-project.org/legal
**
** This file is part of Qt Creator.
**
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Digia. For licensing terms and
** conditions see http://www.qt.io/licensing. For further information
** use the contact form at http://www.qt.io/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 or version 3 as published by the Free
** Software Foundation and appearing in the file LICENSE.LGPLv21 and
** LICENSE.LGPLv3 included in the packaging of this file. Please review the
** following information to ensure the GNU Lesser General Public License
** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Digia gives you certain additional
** rights. These rights are described in the Digia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
****************************************************************************/
#include "currentprojectfilter.h"
#include "projecttree.h"
#include "project.h"
#include <utils/algorithm.h>
#include <QMutexLocker>
#include <QTimer>
using namespace Core;
using namespace ProjectExplorer;
using namespace ProjectExplorer::Internal;
CurrentProjectFilter::CurrentProjectFilter()
: BaseFileFilter(), m_project(0)
{
setId("Files in current project");
setDisplayName(tr("Files in Current Project"));
setShortcutString(QString(QLatin1Char('p')));
setIncludedByDefault(false);
connect(ProjectTree::instance(), &ProjectTree::currentProjectChanged,
this, &CurrentProjectFilter::currentProjectChanged);
connect(SessionManager::instance(), &SessionManager::startupProjectChanged,
this, &CurrentProjectFilter::currentProjectChanged);
}
void CurrentProjectFilter::markFilesAsOutOfDate()
{
setFileIterator(0);
}
void CurrentProjectFilter::prepareSearch(const QString &entry)
{
Q_UNUSED(entry)
if (!fileIterator()) {
QStringList paths;
if (m_project) {
paths = m_project->files(Project::AllFiles);
Utils::sort(paths);
}
setFileIterator(new BaseFileFilter::ListIterator(paths));
}
BaseFileFilter::prepareSearch(entry);
}
void CurrentProjectFilter::currentProjectChanged(ProjectExplorer::Project *project)
{
if (project == m_project)
return;
if (m_project)
disconnect(m_project, SIGNAL(fileListChanged()), this, SLOT(markFilesAsOutOfDate()));
if (project)
connect(project, SIGNAL(fileListChanged()), this, SLOT(markFilesAsOutOfDate()));
m_project = project;
markFilesAsOutOfDate();
}
void CurrentProjectFilter::refresh(QFutureInterface<void> &future)
{
Q_UNUSED(future)
QTimer::singleShot(0, this, SLOT(markFilesAsOutOfDate()));
}
<commit_msg>ProjectExplorer: Fix missing include<commit_after>/****************************************************************************
**
** Copyright (C) 2014 Digia Plc and/or its subsidiary(-ies).
** Contact: http://www.qt-project.org/legal
**
** This file is part of Qt Creator.
**
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Digia. For licensing terms and
** conditions see http://www.qt.io/licensing. For further information
** use the contact form at http://www.qt.io/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 or version 3 as published by the Free
** Software Foundation and appearing in the file LICENSE.LGPLv21 and
** LICENSE.LGPLv3 included in the packaging of this file. Please review the
** following information to ensure the GNU Lesser General Public License
** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Digia gives you certain additional
** rights. These rights are described in the Digia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
****************************************************************************/
#include "currentprojectfilter.h"
#include "projecttree.h"
#include "project.h"
#include "session.h"
#include <utils/algorithm.h>
#include <QMutexLocker>
#include <QTimer>
using namespace Core;
using namespace ProjectExplorer;
using namespace ProjectExplorer::Internal;
CurrentProjectFilter::CurrentProjectFilter()
: BaseFileFilter(), m_project(0)
{
setId("Files in current project");
setDisplayName(tr("Files in Current Project"));
setShortcutString(QString(QLatin1Char('p')));
setIncludedByDefault(false);
connect(ProjectTree::instance(), &ProjectTree::currentProjectChanged,
this, &CurrentProjectFilter::currentProjectChanged);
connect(SessionManager::instance(), &SessionManager::startupProjectChanged,
this, &CurrentProjectFilter::currentProjectChanged);
}
void CurrentProjectFilter::markFilesAsOutOfDate()
{
setFileIterator(0);
}
void CurrentProjectFilter::prepareSearch(const QString &entry)
{
Q_UNUSED(entry)
if (!fileIterator()) {
QStringList paths;
if (m_project) {
paths = m_project->files(Project::AllFiles);
Utils::sort(paths);
}
setFileIterator(new BaseFileFilter::ListIterator(paths));
}
BaseFileFilter::prepareSearch(entry);
}
void CurrentProjectFilter::currentProjectChanged(ProjectExplorer::Project *project)
{
if (project == m_project)
return;
if (m_project)
disconnect(m_project, SIGNAL(fileListChanged()), this, SLOT(markFilesAsOutOfDate()));
if (project)
connect(project, SIGNAL(fileListChanged()), this, SLOT(markFilesAsOutOfDate()));
m_project = project;
markFilesAsOutOfDate();
}
void CurrentProjectFilter::refresh(QFutureInterface<void> &future)
{
Q_UNUSED(future)
QTimer::singleShot(0, this, SLOT(markFilesAsOutOfDate()));
}
<|endoftext|> |
<commit_before>/*************************************************************************
*
* $RCSfile: hints.cxx,v $
*
* $Revision: 1.9 $
*
* last change: $Author: obo $ $Date: 2004-11-16 15:38:18 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the "License"); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#pragma hdrstop
#ifndef _COM_SUN_STAR_I18N_SCRIPTTYPE_HDL_
#include <com/sun/star/i18n/ScriptType.hdl>
#endif
#ifndef _SVX_SCRIPTTYPEITEM_HXX
#include <svx/scripttypeitem.hxx>
#endif
#ifndef _HINTIDS_HXX
#include <hintids.hxx>
#endif
#ifndef _SWTYPES_HXX
#include <swtypes.hxx>
#endif
#ifndef _NDTXT_HXX
#include <ndtxt.hxx>
#endif
#ifndef _ERRHDL_HXX
#include <errhdl.hxx>
#endif
#ifndef _HINTS_HXX
#include <hints.hxx>
#endif
#ifndef _SWERROR_H
#include <error.h>
#endif
SwFmtChg::SwFmtChg( SwFmt *pFmt )
: SwMsgPoolItem( RES_FMT_CHG ),
pChangedFmt( pFmt )
{}
SwInsChr::SwInsChr( xub_StrLen nP )
: SwMsgPoolItem( RES_INS_CHR ),
nPos( nP )
{}
SwInsTxt::SwInsTxt( xub_StrLen nP, xub_StrLen nL )
: SwMsgPoolItem( RES_INS_TXT ),
nPos( nP ),
nLen( nL )
{}
SwDelChr::SwDelChr( xub_StrLen nP )
: SwMsgPoolItem( RES_DEL_CHR ),
nPos( nP )
{}
SwDelTxt::SwDelTxt( xub_StrLen nS, xub_StrLen nL )
: SwMsgPoolItem( RES_DEL_TXT ),
nStart( nS ),
nLen( nL )
{}
SwUpdateAttr::SwUpdateAttr( xub_StrLen nS, xub_StrLen nE, USHORT nW )
: SwMsgPoolItem( RES_UPDATE_ATTR ),
nStart( nS ),
nEnd( nE ),
nWhichAttr( nW )
{}
// SwRefMarkFldUpdate wird verschickt, wenn sich die ReferenzMarkierungen
// Updaten sollen. Um Seiten-/KapitelNummer feststellen zu koennen, muss
// der akt. Frame befragt werden. Dafuer wird das akt. OutputDevice benoetigt.
SwRefMarkFldUpdate::SwRefMarkFldUpdate( const OutputDevice* pOutput )
: SwMsgPoolItem( RES_REFMARKFLD_UPDATE ),
pOut( pOutput )
{
ASSERT( pOut, "es muss ein OutputDevice-Pointer gesetzt werden!" );
}
SwDocPosUpdate::SwDocPosUpdate( const SwTwips nDocPos )
: SwMsgPoolItem( RES_DOCPOS_UPDATE ),
nDocPos(nDocPos)
{}
// SwTableFmlUpdate wird verschickt, wenn sich die Tabelle neu berechnen soll
SwTableFmlUpdate::SwTableFmlUpdate( const SwTable* pNewTbl )
: SwMsgPoolItem( RES_TABLEFML_UPDATE ),
pTbl( pNewTbl ), pHistory( 0 ), nSplitLine( USHRT_MAX ),
eFlags( TBL_CALC )
{
DATA.pDelTbl = 0;
bModified = bBehindSplitLine = FALSE;
ASSERT( pTbl, "es muss ein Table-Pointer gesetzt werden!" );
}
SwAutoFmtGetDocNode::SwAutoFmtGetDocNode( const SwNodes* pNds )
: SwMsgPoolItem( RES_AUTOFMT_DOCNODE ),
pCntntNode( 0 ), pNodes( pNds )
{}
SwAttrSetChg::SwAttrSetChg( const SwAttrSet& rTheSet, SwAttrSet& rSet )
: SwMsgPoolItem( RES_ATTRSET_CHG ),
bDelSet( FALSE ),
pChgSet( &rSet ),
pTheChgdSet( &rTheSet )
{}
SwAttrSetChg::SwAttrSetChg( const SwAttrSetChg& rChgSet )
: SwMsgPoolItem( RES_ATTRSET_CHG ),
bDelSet( TRUE ),
pTheChgdSet( rChgSet.pTheChgdSet )
{
pChgSet = new SwAttrSet( *rChgSet.pChgSet );
}
SwAttrSetChg::~SwAttrSetChg()
{
if( bDelSet )
delete pChgSet;
}
#ifndef PRODUCT
void SwAttrSetChg::ClearItem( USHORT nWhich )
{
ASSERT( bDelSet, "der Set darf nicht veraendert werden!" );
pChgSet->ClearItem( nWhich );
}
#endif
SwMsgPoolItem::SwMsgPoolItem( USHORT nWhich )
: SfxPoolItem( nWhich )
{}
// "Overhead" vom SfxPoolItem
int SwMsgPoolItem::operator==( const SfxPoolItem& ) const
{
ASSERT( FALSE, "SwMsgPoolItem kennt kein ==" );
return 0;
}
SfxPoolItem* SwMsgPoolItem::Clone( SfxItemPool* ) const
{
ASSERT( FALSE, "SwMsgPoolItem kennt kein Clone" );
return 0;
}
/******************************************************************************
* hole aus der Default-Attribut Tabelle ueber den Which-Wert
* das entsprechende default Attribut.
* Ist keines vorhanden, returnt ein 0-Pointer !!!
* inline (hintids.hxx) im PRODUCT.
******************************************************************************/
#ifndef PRODUCT
const SfxPoolItem* GetDfltAttr( USHORT nWhich )
{
ASSERT_ID( nWhich < POOLATTR_END && nWhich >= POOLATTR_BEGIN,
ERR_OUTOFSCOPE );
SfxPoolItem *pHt = aAttrTab[ nWhich - POOLATTR_BEGIN ];
ASSERT( pHt, "GetDfltFmtAttr(): Dflt == 0" );
return pHt;
}
#endif
SwCondCollCondChg::SwCondCollCondChg( SwFmt *pFmt )
: SwMsgPoolItem( RES_CONDCOLL_CONDCHG ), pChangedFmt( pFmt )
{
}
SwVirtPageNumInfo::SwVirtPageNumInfo( const SwPageFrm *pPg ) :
SwMsgPoolItem( RES_VIRTPAGENUM_INFO ),
pPage( 0 ),
pOrigPage( pPg ),
pFrm( 0 )
{
}
SwNumRuleInfo::SwNumRuleInfo( const String& rRuleName )
: SwMsgPoolItem( RES_GETNUMNODES ), rName( rRuleName )
{
}
void SwNumRuleInfo::AddNode( SwTxtNode& rNd )
{
aList.Insert(rNd.GetIndex(), &rNd);
}
SwNRuleLowerLevel::SwNRuleLowerLevel( const String& rRuleName, BYTE nSrchLvl )
: SwMsgPoolItem( RES_GETLOWERNUMLEVEL ), rName( rRuleName ),
nLvl(nSrchLvl)
{
}
SwFindNearestNode::SwFindNearestNode( const SwNode& rNd )
: SwMsgPoolItem( RES_FINDNEARESTNODE ), pNd( &rNd ), pFnd( 0 )
{
}
void SwFindNearestNode::CheckNode( const SwNode& rNd )
{
if( &pNd->GetNodes() == &rNd.GetNodes() )
{
ULONG nIdx = rNd.GetIndex();
if( nIdx < pNd->GetIndex() &&
( !pFnd || nIdx > pFnd->GetIndex() ) &&
nIdx > rNd.GetNodes().GetEndOfExtras().GetIndex() )
pFnd = &rNd;
}
}
USHORT GetWhichOfScript( USHORT nWhich, USHORT nScript )
{
static const USHORT aLangMap[3] =
{ RES_CHRATR_LANGUAGE, RES_CHRATR_CJK_LANGUAGE, RES_CHRATR_CTL_LANGUAGE };
static const USHORT aFontMap[3] =
{ RES_CHRATR_FONT, RES_CHRATR_CJK_FONT, RES_CHRATR_CTL_FONT};
static const USHORT aFontSizeMap[3] =
{ RES_CHRATR_FONTSIZE, RES_CHRATR_CJK_FONTSIZE, RES_CHRATR_CTL_FONTSIZE };
static const USHORT aWeightMap[3] =
{ RES_CHRATR_WEIGHT, RES_CHRATR_CJK_WEIGHT, RES_CHRATR_CTL_WEIGHT};
static const USHORT aPostureMap[3] =
{ RES_CHRATR_POSTURE, RES_CHRATR_CJK_POSTURE, RES_CHRATR_CTL_POSTURE};
const USHORT* pM;
switch( nWhich )
{
case RES_CHRATR_LANGUAGE:
case RES_CHRATR_CJK_LANGUAGE:
case RES_CHRATR_CTL_LANGUAGE:
pM = aLangMap;
break;
case RES_CHRATR_FONT:
case RES_CHRATR_CJK_FONT:
case RES_CHRATR_CTL_FONT:
pM = aFontMap;
break;
case RES_CHRATR_FONTSIZE:
case RES_CHRATR_CJK_FONTSIZE:
case RES_CHRATR_CTL_FONTSIZE:
pM = aFontSizeMap;
break;
case RES_CHRATR_WEIGHT:
case RES_CHRATR_CJK_WEIGHT:
case RES_CHRATR_CTL_WEIGHT:
pM = aWeightMap;
break;
case RES_CHRATR_POSTURE:
case RES_CHRATR_CJK_POSTURE:
case RES_CHRATR_CTL_POSTURE:
pM = aPostureMap;
break;
default:
pM = 0;
}
USHORT nRet;
if( pM )
{
using namespace ::com::sun::star::i18n;
{
if( ScriptType::WEAK == nScript )
nScript = GetI18NScriptTypeOfLanguage( (USHORT)GetAppLanguage() );
switch( nScript)
{
case ScriptType::COMPLEX: ++pM; // no break;
case ScriptType::ASIAN: ++pM; // no break;
default: nRet = *pM;
}
}
}
else
nRet = nWhich;
return nRet;
}
<commit_msg>INTEGRATION: CWS ooo19126 (1.9.460); FILE MERGED 2005/09/05 13:38:33 rt 1.9.460.1: #i54170# Change license header: remove SISSL<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: hints.cxx,v $
*
* $Revision: 1.10 $
*
* last change: $Author: rt $ $Date: 2005-09-09 02:58:12 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#pragma hdrstop
#ifndef _COM_SUN_STAR_I18N_SCRIPTTYPE_HDL_
#include <com/sun/star/i18n/ScriptType.hdl>
#endif
#ifndef _SVX_SCRIPTTYPEITEM_HXX
#include <svx/scripttypeitem.hxx>
#endif
#ifndef _HINTIDS_HXX
#include <hintids.hxx>
#endif
#ifndef _SWTYPES_HXX
#include <swtypes.hxx>
#endif
#ifndef _NDTXT_HXX
#include <ndtxt.hxx>
#endif
#ifndef _ERRHDL_HXX
#include <errhdl.hxx>
#endif
#ifndef _HINTS_HXX
#include <hints.hxx>
#endif
#ifndef _SWERROR_H
#include <error.h>
#endif
SwFmtChg::SwFmtChg( SwFmt *pFmt )
: SwMsgPoolItem( RES_FMT_CHG ),
pChangedFmt( pFmt )
{}
SwInsChr::SwInsChr( xub_StrLen nP )
: SwMsgPoolItem( RES_INS_CHR ),
nPos( nP )
{}
SwInsTxt::SwInsTxt( xub_StrLen nP, xub_StrLen nL )
: SwMsgPoolItem( RES_INS_TXT ),
nPos( nP ),
nLen( nL )
{}
SwDelChr::SwDelChr( xub_StrLen nP )
: SwMsgPoolItem( RES_DEL_CHR ),
nPos( nP )
{}
SwDelTxt::SwDelTxt( xub_StrLen nS, xub_StrLen nL )
: SwMsgPoolItem( RES_DEL_TXT ),
nStart( nS ),
nLen( nL )
{}
SwUpdateAttr::SwUpdateAttr( xub_StrLen nS, xub_StrLen nE, USHORT nW )
: SwMsgPoolItem( RES_UPDATE_ATTR ),
nStart( nS ),
nEnd( nE ),
nWhichAttr( nW )
{}
// SwRefMarkFldUpdate wird verschickt, wenn sich die ReferenzMarkierungen
// Updaten sollen. Um Seiten-/KapitelNummer feststellen zu koennen, muss
// der akt. Frame befragt werden. Dafuer wird das akt. OutputDevice benoetigt.
SwRefMarkFldUpdate::SwRefMarkFldUpdate( const OutputDevice* pOutput )
: SwMsgPoolItem( RES_REFMARKFLD_UPDATE ),
pOut( pOutput )
{
ASSERT( pOut, "es muss ein OutputDevice-Pointer gesetzt werden!" );
}
SwDocPosUpdate::SwDocPosUpdate( const SwTwips nDocPos )
: SwMsgPoolItem( RES_DOCPOS_UPDATE ),
nDocPos(nDocPos)
{}
// SwTableFmlUpdate wird verschickt, wenn sich die Tabelle neu berechnen soll
SwTableFmlUpdate::SwTableFmlUpdate( const SwTable* pNewTbl )
: SwMsgPoolItem( RES_TABLEFML_UPDATE ),
pTbl( pNewTbl ), pHistory( 0 ), nSplitLine( USHRT_MAX ),
eFlags( TBL_CALC )
{
DATA.pDelTbl = 0;
bModified = bBehindSplitLine = FALSE;
ASSERT( pTbl, "es muss ein Table-Pointer gesetzt werden!" );
}
SwAutoFmtGetDocNode::SwAutoFmtGetDocNode( const SwNodes* pNds )
: SwMsgPoolItem( RES_AUTOFMT_DOCNODE ),
pCntntNode( 0 ), pNodes( pNds )
{}
SwAttrSetChg::SwAttrSetChg( const SwAttrSet& rTheSet, SwAttrSet& rSet )
: SwMsgPoolItem( RES_ATTRSET_CHG ),
bDelSet( FALSE ),
pChgSet( &rSet ),
pTheChgdSet( &rTheSet )
{}
SwAttrSetChg::SwAttrSetChg( const SwAttrSetChg& rChgSet )
: SwMsgPoolItem( RES_ATTRSET_CHG ),
bDelSet( TRUE ),
pTheChgdSet( rChgSet.pTheChgdSet )
{
pChgSet = new SwAttrSet( *rChgSet.pChgSet );
}
SwAttrSetChg::~SwAttrSetChg()
{
if( bDelSet )
delete pChgSet;
}
#ifndef PRODUCT
void SwAttrSetChg::ClearItem( USHORT nWhich )
{
ASSERT( bDelSet, "der Set darf nicht veraendert werden!" );
pChgSet->ClearItem( nWhich );
}
#endif
SwMsgPoolItem::SwMsgPoolItem( USHORT nWhich )
: SfxPoolItem( nWhich )
{}
// "Overhead" vom SfxPoolItem
int SwMsgPoolItem::operator==( const SfxPoolItem& ) const
{
ASSERT( FALSE, "SwMsgPoolItem kennt kein ==" );
return 0;
}
SfxPoolItem* SwMsgPoolItem::Clone( SfxItemPool* ) const
{
ASSERT( FALSE, "SwMsgPoolItem kennt kein Clone" );
return 0;
}
/******************************************************************************
* hole aus der Default-Attribut Tabelle ueber den Which-Wert
* das entsprechende default Attribut.
* Ist keines vorhanden, returnt ein 0-Pointer !!!
* inline (hintids.hxx) im PRODUCT.
******************************************************************************/
#ifndef PRODUCT
const SfxPoolItem* GetDfltAttr( USHORT nWhich )
{
ASSERT_ID( nWhich < POOLATTR_END && nWhich >= POOLATTR_BEGIN,
ERR_OUTOFSCOPE );
SfxPoolItem *pHt = aAttrTab[ nWhich - POOLATTR_BEGIN ];
ASSERT( pHt, "GetDfltFmtAttr(): Dflt == 0" );
return pHt;
}
#endif
SwCondCollCondChg::SwCondCollCondChg( SwFmt *pFmt )
: SwMsgPoolItem( RES_CONDCOLL_CONDCHG ), pChangedFmt( pFmt )
{
}
SwVirtPageNumInfo::SwVirtPageNumInfo( const SwPageFrm *pPg ) :
SwMsgPoolItem( RES_VIRTPAGENUM_INFO ),
pPage( 0 ),
pOrigPage( pPg ),
pFrm( 0 )
{
}
SwNumRuleInfo::SwNumRuleInfo( const String& rRuleName )
: SwMsgPoolItem( RES_GETNUMNODES ), rName( rRuleName )
{
}
void SwNumRuleInfo::AddNode( SwTxtNode& rNd )
{
aList.Insert(rNd.GetIndex(), &rNd);
}
SwNRuleLowerLevel::SwNRuleLowerLevel( const String& rRuleName, BYTE nSrchLvl )
: SwMsgPoolItem( RES_GETLOWERNUMLEVEL ), rName( rRuleName ),
nLvl(nSrchLvl)
{
}
SwFindNearestNode::SwFindNearestNode( const SwNode& rNd )
: SwMsgPoolItem( RES_FINDNEARESTNODE ), pNd( &rNd ), pFnd( 0 )
{
}
void SwFindNearestNode::CheckNode( const SwNode& rNd )
{
if( &pNd->GetNodes() == &rNd.GetNodes() )
{
ULONG nIdx = rNd.GetIndex();
if( nIdx < pNd->GetIndex() &&
( !pFnd || nIdx > pFnd->GetIndex() ) &&
nIdx > rNd.GetNodes().GetEndOfExtras().GetIndex() )
pFnd = &rNd;
}
}
USHORT GetWhichOfScript( USHORT nWhich, USHORT nScript )
{
static const USHORT aLangMap[3] =
{ RES_CHRATR_LANGUAGE, RES_CHRATR_CJK_LANGUAGE, RES_CHRATR_CTL_LANGUAGE };
static const USHORT aFontMap[3] =
{ RES_CHRATR_FONT, RES_CHRATR_CJK_FONT, RES_CHRATR_CTL_FONT};
static const USHORT aFontSizeMap[3] =
{ RES_CHRATR_FONTSIZE, RES_CHRATR_CJK_FONTSIZE, RES_CHRATR_CTL_FONTSIZE };
static const USHORT aWeightMap[3] =
{ RES_CHRATR_WEIGHT, RES_CHRATR_CJK_WEIGHT, RES_CHRATR_CTL_WEIGHT};
static const USHORT aPostureMap[3] =
{ RES_CHRATR_POSTURE, RES_CHRATR_CJK_POSTURE, RES_CHRATR_CTL_POSTURE};
const USHORT* pM;
switch( nWhich )
{
case RES_CHRATR_LANGUAGE:
case RES_CHRATR_CJK_LANGUAGE:
case RES_CHRATR_CTL_LANGUAGE:
pM = aLangMap;
break;
case RES_CHRATR_FONT:
case RES_CHRATR_CJK_FONT:
case RES_CHRATR_CTL_FONT:
pM = aFontMap;
break;
case RES_CHRATR_FONTSIZE:
case RES_CHRATR_CJK_FONTSIZE:
case RES_CHRATR_CTL_FONTSIZE:
pM = aFontSizeMap;
break;
case RES_CHRATR_WEIGHT:
case RES_CHRATR_CJK_WEIGHT:
case RES_CHRATR_CTL_WEIGHT:
pM = aWeightMap;
break;
case RES_CHRATR_POSTURE:
case RES_CHRATR_CJK_POSTURE:
case RES_CHRATR_CTL_POSTURE:
pM = aPostureMap;
break;
default:
pM = 0;
}
USHORT nRet;
if( pM )
{
using namespace ::com::sun::star::i18n;
{
if( ScriptType::WEAK == nScript )
nScript = GetI18NScriptTypeOfLanguage( (USHORT)GetAppLanguage() );
switch( nScript)
{
case ScriptType::COMPLEX: ++pM; // no break;
case ScriptType::ASIAN: ++pM; // no break;
default: nRet = *pM;
}
}
}
else
nRet = nWhich;
return nRet;
}
<|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: flyfrm.hxx,v $
*
* $Revision: 1.22 $
*
* last change: $Author: vg $ $Date: 2007-10-22 15:10:53 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#ifndef _FLYFRM_HXX
#define _FLYFRM_HXX
#include "layfrm.hxx"
class SwPageFrm;
class SwFlyFrmFmt;
class SwFmtFrmSize;
struct SwCrsrMoveState;
class SwBorderAttrs;
class SwVirtFlyDrawObj;
class SwSpzFrmFmts;
class SwAttrSetChg;
class PolyPolygon;
// OD 2004-03-22 #i26791#
#ifndef _ANCHOREDOBJECT_HXX
#include <anchoredobject.hxx>
#endif
//Sucht ausgehend von pOldAnch einen Anker fuer Absatzgebundene Rahmen.
//Wird beim Draggen von Absatzgebundenen Objekten zur Ankeranzeige sowie
//fuer Ankerwechsel benoetigt.
//implementiert in layout/flycnt.cxx
const SwCntntFrm *FindAnchor( const SwFrm *pOldAnch, const Point &rNew,
const BOOL bBody = FALSE );
// berechnet das Rechteck, in dem das Objekt bewegt bzw. resized werden darf
BOOL CalcClipRect( const SdrObject *pSdrObj, SwRect &rRect, BOOL bMove = TRUE );
//allg. Basisklasse fuer alle Freifliegenden Rahmen
// OD 2004-03-22 #i26791# - inherit also from <SwAnchoredFlyFrm>
class SwFlyFrm : public SwLayoutFrm, public SwAnchoredObject
{
//darf Locken. Definiert in frmtool.cxx
friend void AppendObjs ( const SwSpzFrmFmts *, ULONG, SwFrm *, SwPageFrm * );
friend void AppendAllObjs( const SwSpzFrmFmts * );
friend void Notify( SwFlyFrm *, SwPageFrm *pOld, const SwRect &rOld,
const SwRect* pOldPrt );
void InitDrawObj( BOOL bNotify ); //Wird von den CToren gerufen.
void FinitDrawObj(); //Wird vom CTor gerufen.
void _UpdateAttr( SfxPoolItem*, SfxPoolItem*, BYTE &,
SwAttrSetChg *pa = 0, SwAttrSetChg *pb = 0 );
using SwLayoutFrm::CalcRel;
protected:
SwFlyFrm *pPrevLink, // Vorgaenger/Nachfolger fuer Verkettung mit
*pNextLink; // Textfluss
// OD 2004-05-27 #i26791# - moved to <SwAnchoredObject>
// Point aRelPos; //Die Relative Position zum Master
private:
BOOL bLocked :1; //Cntnt-gebundene Flys muessen derart blockiert werden
//koennen, dass sie nicht Formatiert werden; :MakeAll
//returnt dann sofort. Dies ist bei Seitenwechseln
//waehrend der Formatierung notwendig.
//Auch wahrend des RootCTors ist dies notwendig da
//sonst der Anker formatiert wird obwohl die Root noch
//nicht korrekt an der Shell haengt und weil sonst
//initial zuviel Formatiert wuerde.
BOOL bNotifyBack:1; //TRUE wenn am Ende eines MakeAll() der Background
//vom NotifyDTor benachrichtigt werden muss.
protected:
BOOL bInvalid :1; //Pos, PrtArea od. SSize wurden Invalidiert, sie werden
//gleich wieder Validiert, denn sie muessen _immer_
//gueltig sein. Damit in LayAction korrekt gearbeitet
//werden kann muss hier festgehalten werden, dass sie
//invalidiert wurden. Ausnahmen bestaetigen die Regelt!
BOOL bMinHeight:1; //TRUE wenn die vom Attribut vorgegebene Hoehe eine
//eine Minimalhoehe ist (der Frm also bei Bedarf
//darueberhinaus wachsen kann).
BOOL bHeightClipped :1; //TRUE wenn der Fly nicht die Pos/Size anhand der Attrs
BOOL bWidthClipped :1; //formatieren konnte, weil z.B. nicht genug Raum vorh.
//war.
BOOL bFormatHeightOnly :1; //Damit nach einer Anpassung der Breite
//(CheckClip) nur das Format aufgerufen wird;
//nicht aber die Breite anhand der Attribute
//wieder bestimmt wird.
BOOL bInCnt :1; // FLY_IN_CNTNT, als Zeichen verankert
BOOL bAtCnt :1; // FLY_AT_CNTNT, am Absatz verankert
BOOL bLayout :1; // FLY_PAGE, FLY_AT_FLY, an Seite oder Rahmen
BOOL bAutoPosition :1; // FLY_AUTO_CNTNT, im Text verankerter Rahmen
BOOL bNoShrink :1; // temporary forbud of shrinking to avoid loops
BOOL bLockDeleteContent :1; // If the flag is set, the content of the
// fly frame is not deleted if moved to
// invisible layer.
friend class SwNoTxtFrm; // Darf NotifyBackground rufen
// virtual void NotifyBackground( SwPageFrm *pPage,
// const SwRect& rRect, PrepareHint eHint) = 0;
virtual void Format( const SwBorderAttrs *pAttrs = 0 );
void MakePrtArea( const SwBorderAttrs &rAttrs );
void Lock() { bLocked = TRUE; }
void Unlock() { bLocked = FALSE; }
void SetMinHeight() { bMinHeight = TRUE; }
void ResetMinHeight(){ bMinHeight = FALSE; }
Size CalcRel( const SwFmtFrmSize &rSz ) const;
SwTwips CalcAutoWidth() const;
SwFlyFrm( SwFlyFrmFmt*, SwFrm *pAnchor );
/** method to assure that anchored object is registered at the correct
page frame
OD 2004-07-02 #i28701#
@author OD
*/
virtual void RegisterAtCorrectPage();
// --> OD 2006-08-10 #i68520#
virtual const bool _SetObjTop( const SwTwips _nTop );
virtual const bool _SetObjLeft( const SwTwips _nLeft );
// <--
// --> OD 2006-10-05 #i70122#
virtual const SwRect GetObjBoundRect() const;
// <--
public:
// OD 2004-03-23 #i26791#
TYPEINFO();
virtual ~SwFlyFrm();
virtual void Modify( SfxPoolItem*, SfxPoolItem* );
// erfrage vom Client Informationen
virtual BOOL GetInfo( SfxPoolItem& ) const;
virtual void Paint( const SwRect& ) const;
virtual Size ChgSize( const Size& aNewSize );
virtual BOOL GetCrsrOfst( SwPosition *, Point&,
SwCrsrMoveState* = 0 ) const;
virtual void CheckDirection( BOOL bVert );
virtual void Cut();
#ifndef PRODUCT
virtual void Paste( SwFrm* pParent, SwFrm* pSibling = 0 );
#endif
SwTwips _Shrink( SwTwips, BOOL bTst );
SwTwips _Grow ( SwTwips, BOOL bTst );
void _Invalidate( SwPageFrm *pPage = 0 );
BOOL FrmSizeChg( const SwFmtFrmSize & );
SwFlyFrm *GetPrevLink() { return pPrevLink; }
SwFlyFrm *GetNextLink() { return pNextLink; }
static void ChainFrames( SwFlyFrm *pMaster, SwFlyFrm *pFollow );
static void UnchainFrames( SwFlyFrm *pMaster, SwFlyFrm *pFollow );
SwFlyFrm *FindChainNeighbour( SwFrmFmt &rFmt, SwFrm *pAnch = 0 );
// OD 2004-03-24 #i26791#
const SwVirtFlyDrawObj* GetVirtDrawObj() const;
SwVirtFlyDrawObj *GetVirtDrawObj();
void NotifyDrawObj();
void ChgRelPos( const Point &rAbsPos );
BOOL IsInvalid() const { return bInvalid; }
void Invalidate() const { ((SwFlyFrm*)this)->bInvalid = TRUE; }
void Validate() const { ((SwFlyFrm*)this)->bInvalid = FALSE; }
BOOL IsMinHeight() const { return bMinHeight; }
BOOL IsLocked() const { return bLocked; }
BOOL IsAutoPos() const { return bAutoPosition; }
BOOL IsFlyInCntFrm() const { return bInCnt; }
BOOL IsFlyFreeFrm() const { return bAtCnt || bLayout; }
BOOL IsFlyLayFrm() const { return bLayout; }
BOOL IsFlyAtCntFrm() const { return bAtCnt; }
BOOL IsNotifyBack() const { return bNotifyBack; }
void SetNotifyBack() { bNotifyBack = TRUE; }
void ResetNotifyBack() { bNotifyBack = FALSE; }
BOOL IsNoShrink() const { return bNoShrink; }
void SetNoShrink( BOOL bNew ) { bNoShrink = bNew; }
BOOL IsLockDeleteContent() const { return bLockDeleteContent; }
void SetLockDeleteContent( BOOL bNew ) { bLockDeleteContent = bNew; }
BOOL IsClipped() const { return bHeightClipped || bWidthClipped; }
BOOL IsHeightClipped() const { return bHeightClipped; }
BOOL IsWidthClipped() const { return bWidthClipped; }
BOOL IsLowerOf( const SwLayoutFrm* pUpper ) const;
inline BOOL IsUpperOf( const SwFlyFrm& _rLower ) const
{
return _rLower.IsLowerOf( this );
}
SwFrm *FindLastLower();
// OD 16.04.2003 #i13147# - add parameter <_bForPaint> to avoid load of
// the graphic during paint. Default value: sal_False
BOOL GetContour( PolyPolygon& rContour,
const sal_Bool _bForPaint = sal_False ) const;
//Auf dieser Shell painten (PreView, Print-Flag usw. rekursiv beachten)?.
static BOOL IsPaint( SdrObject *pObj, const ViewShell *pSh );
/** SwFlyFrm::IsBackgroundTransparent - for feature #99657#
OD 12.08.2002
determines, if background of fly frame has to be drawn transparent
definition found in /core/layout/paintfrm.cxx
@author OD
@return true, if background color is transparent or a existing background
graphic is transparent.
*/
const sal_Bool IsBackgroundTransparent() const;
/** SwFlyFrm::IsShadowTransparent - for feature #99657#
OD 05.08.2002
determine, if shadow color of fly frame has to be drawn transparent
definition found in /core/layout/paintfrm.cxx
@author OD
@return true, if shadow color is transparent.
*/
const sal_Bool IsShadowTransparent() const;
// OD 2004-01-19 #110582#
void Chain( SwFrm* _pAnchor );
void Unchain();
void InsertCnt();
void DeleteCnt();
// OD 2004-02-12 #110582#-2
void InsertColumns();
// OD 2004-03-23 #i26791# - pure virtual methods of base class <SwAnchoredObject>
virtual void MakeObjPos();
virtual void InvalidateObjPos();
virtual SwFrmFmt& GetFrmFmt();
virtual const SwFrmFmt& GetFrmFmt() const;
virtual const SwRect GetObjRect() const;
/** method to determine, if a format on the Writer fly frame is possible
OD 2004-05-11 #i28701#
refine 'IsFormatPossible'-conditions of method
<SwAnchoredObject::IsFormatPossible()> by:
format isn't possible, if Writer fly frame is locked resp. col-locked.
@author OD
*/
virtual bool IsFormatPossible() const;
};
#endif
<commit_msg>INTEGRATION: CWS swcolsel (1.20.10); FILE MERGED 2007/11/08 16:03:47 ama 1.20.10.3: RESYNC: (1.21-1.22); FILE MERGED 2007/10/05 16:15:12 ama 1.20.10.2: RESYNC: (1.20-1.21); FILE MERGED 2007/05/23 14:21:33 ama 1.20.10.1: Fix #1596#: Block selection<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: flyfrm.hxx,v $
*
* $Revision: 1.23 $
*
* last change: $Author: ihi $ $Date: 2007-11-22 15:34:56 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#ifndef _FLYFRM_HXX
#define _FLYFRM_HXX
#include "layfrm.hxx"
class SwPageFrm;
class SwFlyFrmFmt;
class SwFmtFrmSize;
struct SwCrsrMoveState;
class SwBorderAttrs;
class SwVirtFlyDrawObj;
class SwSpzFrmFmts;
class SwAttrSetChg;
class PolyPolygon;
// OD 2004-03-22 #i26791#
#ifndef _ANCHOREDOBJECT_HXX
#include <anchoredobject.hxx>
#endif
//Sucht ausgehend von pOldAnch einen Anker fuer Absatzgebundene Rahmen.
//Wird beim Draggen von Absatzgebundenen Objekten zur Ankeranzeige sowie
//fuer Ankerwechsel benoetigt.
//implementiert in layout/flycnt.cxx
const SwCntntFrm *FindAnchor( const SwFrm *pOldAnch, const Point &rNew,
const BOOL bBody = FALSE );
// berechnet das Rechteck, in dem das Objekt bewegt bzw. resized werden darf
BOOL CalcClipRect( const SdrObject *pSdrObj, SwRect &rRect, BOOL bMove = TRUE );
//allg. Basisklasse fuer alle Freifliegenden Rahmen
// OD 2004-03-22 #i26791# - inherit also from <SwAnchoredFlyFrm>
class SwFlyFrm : public SwLayoutFrm, public SwAnchoredObject
{
//darf Locken. Definiert in frmtool.cxx
friend void AppendObjs ( const SwSpzFrmFmts *, ULONG, SwFrm *, SwPageFrm * );
friend void AppendAllObjs( const SwSpzFrmFmts * );
friend void Notify( SwFlyFrm *, SwPageFrm *pOld, const SwRect &rOld,
const SwRect* pOldPrt );
void InitDrawObj( BOOL bNotify ); //Wird von den CToren gerufen.
void FinitDrawObj(); //Wird vom CTor gerufen.
void _UpdateAttr( SfxPoolItem*, SfxPoolItem*, BYTE &,
SwAttrSetChg *pa = 0, SwAttrSetChg *pb = 0 );
using SwLayoutFrm::CalcRel;
protected:
SwFlyFrm *pPrevLink, // Vorgaenger/Nachfolger fuer Verkettung mit
*pNextLink; // Textfluss
// OD 2004-05-27 #i26791# - moved to <SwAnchoredObject>
// Point aRelPos; //Die Relative Position zum Master
private:
BOOL bLocked :1; //Cntnt-gebundene Flys muessen derart blockiert werden
//koennen, dass sie nicht Formatiert werden; :MakeAll
//returnt dann sofort. Dies ist bei Seitenwechseln
//waehrend der Formatierung notwendig.
//Auch wahrend des RootCTors ist dies notwendig da
//sonst der Anker formatiert wird obwohl die Root noch
//nicht korrekt an der Shell haengt und weil sonst
//initial zuviel Formatiert wuerde.
BOOL bNotifyBack:1; //TRUE wenn am Ende eines MakeAll() der Background
//vom NotifyDTor benachrichtigt werden muss.
protected:
BOOL bInvalid :1; //Pos, PrtArea od. SSize wurden Invalidiert, sie werden
//gleich wieder Validiert, denn sie muessen _immer_
//gueltig sein. Damit in LayAction korrekt gearbeitet
//werden kann muss hier festgehalten werden, dass sie
//invalidiert wurden. Ausnahmen bestaetigen die Regelt!
BOOL bMinHeight:1; //TRUE wenn die vom Attribut vorgegebene Hoehe eine
//eine Minimalhoehe ist (der Frm also bei Bedarf
//darueberhinaus wachsen kann).
BOOL bHeightClipped :1; //TRUE wenn der Fly nicht die Pos/Size anhand der Attrs
BOOL bWidthClipped :1; //formatieren konnte, weil z.B. nicht genug Raum vorh.
//war.
BOOL bFormatHeightOnly :1; //Damit nach einer Anpassung der Breite
//(CheckClip) nur das Format aufgerufen wird;
//nicht aber die Breite anhand der Attribute
//wieder bestimmt wird.
BOOL bInCnt :1; // FLY_IN_CNTNT, als Zeichen verankert
BOOL bAtCnt :1; // FLY_AT_CNTNT, am Absatz verankert
BOOL bLayout :1; // FLY_PAGE, FLY_AT_FLY, an Seite oder Rahmen
BOOL bAutoPosition :1; // FLY_AUTO_CNTNT, im Text verankerter Rahmen
BOOL bNoShrink :1; // temporary forbud of shrinking to avoid loops
BOOL bLockDeleteContent :1; // If the flag is set, the content of the
// fly frame is not deleted if moved to
// invisible layer.
friend class SwNoTxtFrm; // Darf NotifyBackground rufen
// virtual void NotifyBackground( SwPageFrm *pPage,
// const SwRect& rRect, PrepareHint eHint) = 0;
virtual void Format( const SwBorderAttrs *pAttrs = 0 );
void MakePrtArea( const SwBorderAttrs &rAttrs );
void Lock() { bLocked = TRUE; }
void Unlock() { bLocked = FALSE; }
void SetMinHeight() { bMinHeight = TRUE; }
void ResetMinHeight(){ bMinHeight = FALSE; }
Size CalcRel( const SwFmtFrmSize &rSz ) const;
SwTwips CalcAutoWidth() const;
SwFlyFrm( SwFlyFrmFmt*, SwFrm *pAnchor );
/** method to assure that anchored object is registered at the correct
page frame
OD 2004-07-02 #i28701#
@author OD
*/
virtual void RegisterAtCorrectPage();
// --> OD 2006-08-10 #i68520#
virtual const bool _SetObjTop( const SwTwips _nTop );
virtual const bool _SetObjLeft( const SwTwips _nLeft );
// <--
// --> OD 2006-10-05 #i70122#
virtual const SwRect GetObjBoundRect() const;
// <--
public:
// OD 2004-03-23 #i26791#
TYPEINFO();
virtual ~SwFlyFrm();
virtual void Modify( SfxPoolItem*, SfxPoolItem* );
// erfrage vom Client Informationen
virtual BOOL GetInfo( SfxPoolItem& ) const;
virtual void Paint( const SwRect& ) const;
virtual Size ChgSize( const Size& aNewSize );
virtual BOOL GetCrsrOfst( SwPosition *, Point&,
SwCrsrMoveState* = 0 ) const;
virtual void CheckDirection( BOOL bVert );
virtual void Cut();
#ifndef PRODUCT
virtual void Paste( SwFrm* pParent, SwFrm* pSibling = 0 );
#endif
SwTwips _Shrink( SwTwips, BOOL bTst );
SwTwips _Grow ( SwTwips, BOOL bTst );
void _Invalidate( SwPageFrm *pPage = 0 );
BOOL FrmSizeChg( const SwFmtFrmSize & );
SwFlyFrm *GetPrevLink() const { return pPrevLink; }
SwFlyFrm *GetNextLink() const { return pNextLink; }
static void ChainFrames( SwFlyFrm *pMaster, SwFlyFrm *pFollow );
static void UnchainFrames( SwFlyFrm *pMaster, SwFlyFrm *pFollow );
SwFlyFrm *FindChainNeighbour( SwFrmFmt &rFmt, SwFrm *pAnch = 0 );
// OD 2004-03-24 #i26791#
const SwVirtFlyDrawObj* GetVirtDrawObj() const;
SwVirtFlyDrawObj *GetVirtDrawObj();
void NotifyDrawObj();
void ChgRelPos( const Point &rAbsPos );
BOOL IsInvalid() const { return bInvalid; }
void Invalidate() const { ((SwFlyFrm*)this)->bInvalid = TRUE; }
void Validate() const { ((SwFlyFrm*)this)->bInvalid = FALSE; }
BOOL IsMinHeight() const { return bMinHeight; }
BOOL IsLocked() const { return bLocked; }
BOOL IsAutoPos() const { return bAutoPosition; }
BOOL IsFlyInCntFrm() const { return bInCnt; }
BOOL IsFlyFreeFrm() const { return bAtCnt || bLayout; }
BOOL IsFlyLayFrm() const { return bLayout; }
BOOL IsFlyAtCntFrm() const { return bAtCnt; }
BOOL IsNotifyBack() const { return bNotifyBack; }
void SetNotifyBack() { bNotifyBack = TRUE; }
void ResetNotifyBack() { bNotifyBack = FALSE; }
BOOL IsNoShrink() const { return bNoShrink; }
void SetNoShrink( BOOL bNew ) { bNoShrink = bNew; }
BOOL IsLockDeleteContent() const { return bLockDeleteContent; }
void SetLockDeleteContent( BOOL bNew ) { bLockDeleteContent = bNew; }
BOOL IsClipped() const { return bHeightClipped || bWidthClipped; }
BOOL IsHeightClipped() const { return bHeightClipped; }
BOOL IsWidthClipped() const { return bWidthClipped; }
BOOL IsLowerOf( const SwLayoutFrm* pUpper ) const;
inline BOOL IsUpperOf( const SwFlyFrm& _rLower ) const
{
return _rLower.IsLowerOf( this );
}
SwFrm *FindLastLower();
// OD 16.04.2003 #i13147# - add parameter <_bForPaint> to avoid load of
// the graphic during paint. Default value: sal_False
BOOL GetContour( PolyPolygon& rContour,
const sal_Bool _bForPaint = sal_False ) const;
//Auf dieser Shell painten (PreView, Print-Flag usw. rekursiv beachten)?.
static BOOL IsPaint( SdrObject *pObj, const ViewShell *pSh );
/** SwFlyFrm::IsBackgroundTransparent - for feature #99657#
OD 12.08.2002
determines, if background of fly frame has to be drawn transparent
definition found in /core/layout/paintfrm.cxx
@author OD
@return true, if background color is transparent or a existing background
graphic is transparent.
*/
const sal_Bool IsBackgroundTransparent() const;
/** SwFlyFrm::IsShadowTransparent - for feature #99657#
OD 05.08.2002
determine, if shadow color of fly frame has to be drawn transparent
definition found in /core/layout/paintfrm.cxx
@author OD
@return true, if shadow color is transparent.
*/
const sal_Bool IsShadowTransparent() const;
// OD 2004-01-19 #110582#
void Chain( SwFrm* _pAnchor );
void Unchain();
void InsertCnt();
void DeleteCnt();
// OD 2004-02-12 #110582#-2
void InsertColumns();
// OD 2004-03-23 #i26791# - pure virtual methods of base class <SwAnchoredObject>
virtual void MakeObjPos();
virtual void InvalidateObjPos();
virtual SwFrmFmt& GetFrmFmt();
virtual const SwFrmFmt& GetFrmFmt() const;
virtual const SwRect GetObjRect() const;
/** method to determine, if a format on the Writer fly frame is possible
OD 2004-05-11 #i28701#
refine 'IsFormatPossible'-conditions of method
<SwAnchoredObject::IsFormatPossible()> by:
format isn't possible, if Writer fly frame is locked resp. col-locked.
@author OD
*/
virtual bool IsFormatPossible() const;
};
#endif
<|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: bookmark.hxx,v $
*
* $Revision: 1.6 $
*
* last change: $Author: hr $ $Date: 2007-09-27 11:54:32 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#ifndef _BOOKMARK_HXX
#define _BOOKMARK_HXX
#ifndef _SVX_STDDLG_HXX //autogen
#include <svx/stddlg.hxx>
#endif
#ifndef _SV_FIXED_HXX //autogen
#include <vcl/fixed.hxx>
#endif
#ifndef _BUTTON_HXX //autogen
#include <vcl/button.hxx>
#endif
#include "swlbox.hxx" // SwComboBox
class SwWrtShell;
class SfxRequest;
/*--------------------------------------------------------------------
Beschreibung:
--------------------------------------------------------------------*/
class BookmarkCombo : public SwComboBox
{
USHORT GetFirstSelEntryPos() const;
USHORT GetNextSelEntryPos(USHORT nPos) const;
USHORT GetSelEntryPos(USHORT nPos) const;
virtual long PreNotify(NotifyEvent& rNEvt);
public:
BookmarkCombo( Window* pWin, const ResId& rResId );
USHORT GetSelectEntryCount() const;
USHORT GetSelectEntryPos( USHORT nSelIndex = 0 ) const;
static const String aForbiddenChars;
};
/*--------------------------------------------------------------------
Beschreibung:
--------------------------------------------------------------------*/
class SwInsertBookmarkDlg: public SvxStandardDialog
{
BookmarkCombo aBookmarkBox;
FixedLine aBookmarkFl;
OKButton aOkBtn;
CancelButton aCancelBtn;
PushButton aDeleteBtn;
String sRemoveWarning;
SwWrtShell &rSh;
SfxRequest& rReq;
DECL_LINK( ModifyHdl, BookmarkCombo * );
DECL_LINK( DeleteHdl, Button * );
virtual void Apply();
public:
SwInsertBookmarkDlg( Window *pParent, SwWrtShell &rSh, SfxRequest& rReq );
~SwInsertBookmarkDlg();
};
#endif
<commit_msg>INTEGRATION: CWS changefileheader (1.6.242); FILE MERGED 2008/04/01 15:59:08 thb 1.6.242.2: #i85898# Stripping all external header guards 2008/03/31 16:58:27 rt 1.6.242.1: #i87441# Change license header to LPGL v3.<commit_after>/*************************************************************************
*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* Copyright 2008 by Sun Microsystems, Inc.
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: bookmark.hxx,v $
* $Revision: 1.7 $
*
* This file is part of OpenOffice.org.
*
* OpenOffice.org is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License version 3
* only, as published by the Free Software Foundation.
*
* OpenOffice.org is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License version 3 for more details
* (a copy is included in the LICENSE file that accompanied this code).
*
* You should have received a copy of the GNU Lesser General Public License
* version 3 along with OpenOffice.org. If not, see
* <http://www.openoffice.org/license.html>
* for a copy of the LGPLv3 License.
*
************************************************************************/
#ifndef _BOOKMARK_HXX
#define _BOOKMARK_HXX
#include <svx/stddlg.hxx>
#include <vcl/fixed.hxx>
#ifndef _BUTTON_HXX //autogen
#include <vcl/button.hxx>
#endif
#include "swlbox.hxx" // SwComboBox
class SwWrtShell;
class SfxRequest;
/*--------------------------------------------------------------------
Beschreibung:
--------------------------------------------------------------------*/
class BookmarkCombo : public SwComboBox
{
USHORT GetFirstSelEntryPos() const;
USHORT GetNextSelEntryPos(USHORT nPos) const;
USHORT GetSelEntryPos(USHORT nPos) const;
virtual long PreNotify(NotifyEvent& rNEvt);
public:
BookmarkCombo( Window* pWin, const ResId& rResId );
USHORT GetSelectEntryCount() const;
USHORT GetSelectEntryPos( USHORT nSelIndex = 0 ) const;
static const String aForbiddenChars;
};
/*--------------------------------------------------------------------
Beschreibung:
--------------------------------------------------------------------*/
class SwInsertBookmarkDlg: public SvxStandardDialog
{
BookmarkCombo aBookmarkBox;
FixedLine aBookmarkFl;
OKButton aOkBtn;
CancelButton aCancelBtn;
PushButton aDeleteBtn;
String sRemoveWarning;
SwWrtShell &rSh;
SfxRequest& rReq;
DECL_LINK( ModifyHdl, BookmarkCombo * );
DECL_LINK( DeleteHdl, Button * );
virtual void Apply();
public:
SwInsertBookmarkDlg( Window *pParent, SwWrtShell &rSh, SfxRequest& rReq );
~SwInsertBookmarkDlg();
};
#endif
<|endoftext|> |
<commit_before><commit_msg>sal_uInt16 to sal_(u)Int32 + some constifications<commit_after><|endoftext|> |
<commit_before><commit_msg>drop unused helpids fully<commit_after><|endoftext|> |
<commit_before>#include "ros_video_components/ros_signal_strength.hpp"
#define RECT_X 0
#define RECT_Y 0
#define RECT_WIDTH RECT_X*40
#define RECT_HEIGHT 150
#define MAXDATA 100
#define MAXNUM 5
#define NUMCOLOR 3
#define GREEN 4
#define YELLOW 2
#define RED 1
#define HASH MAXDATA/MAXNUM
#define TOO_WEAK MAXDATA/20
ROS_Signal_Strength::ROS_Signal_Strength(QQuickItem * parent) :
QQuickPaintedItem(parent),
topic_value("/rover/signal"),
ros_ready(false),
data(50) {
}
void ROS_Signal_Strength::setup(ros::NodeHandle * nh) {
signal_sub = nh->subscribe(
"/rover/signal", //TODO
1,
&ROS_Signal_Strength::receive_signal,
this
);
ros_ready = true;
}
void ROS_Signal_Strength::paint(QPainter * painter) {
//int data = 82; //int data = getSignalStrength();
// http://doc.qt.io/qt-4.8/qpainter.html#setViewport
int x = RECT_X;
int y = RECT_Y;
int widthV = width();// / RECT_WIDTH;
int heightV = height();// / RECT_HEIGHT;
QLinearGradient linearGradient(0, 0, 100, 100);
int num = 0;
float hash = HASH;
if(data >= MAXDATA) {
num = MAXNUM;
}else if(data <= TOO_WEAK) {
num = 0;
linearGradient.setColorAt(0.0, Qt::white);
painter->setBrush(linearGradient);
}else{
num = (data/hash) + 1;
}
painter->drawRect(x, y, widthV - 1, heightV - 1); //draw the main rectangle
int i = 0;
int barWidth = widthV/MAXNUM;
int barHeight = heightV/MAXNUM;
y += ((MAXNUM-1) * heightV) /MAXNUM;
const int increment = heightV/MAXNUM;
if(num == 0) {
ROS_INFO("NO SIGNAL\n");
}else {
for(i = 1; i <= num; i++) {
if(num >= GREEN) {
linearGradient.setColorAt(0.2, Qt::green);
}else if(num >= YELLOW) {
linearGradient.setColorAt(0.2, Qt::yellow);
}else {
linearGradient.setColorAt(0.2, Qt::red);
}
painter->setBrush(linearGradient);
painter->drawRect(x, y, barWidth, barHeight);
x += barWidth; //move x along
barHeight += increment; //increase height
y -= increment; //decrease height
}
}
}
void ROS_Signal_Strength::set_topic(const QString & new_value) {
ROS_INFO("set_topic");
if(topic_value != new_value) {
topic_value = new_value;
if(ros_ready) {
signal_sub.shutdown();
signal_sub = nh->subscribe(
topic_value.toStdString(), //TODO
1,
&ROS_Signal_Strength::receive_signal,
this
);
}
emit topic_changed();
}
}
QString ROS_Signal_Strength::get_topic() const {
return topic_value;
}
void ROS_Signal_Strength::receive_signal(const std_msgs::Float32::ConstPtr & msg) {
data = msg->data;
ROS_INFO("Received signal message");
update();
}
<commit_msg>Further cleanup minor<commit_after>#include "ros_video_components/ros_signal_strength.hpp"
#define RECT_X 0
#define RECT_Y 0
#define RECT_WIDTH RECT_X*40
#define RECT_HEIGHT 150
#define MAXDATA 100
#define MAXNUM 5
#define NUMCOLOR 3
#define GREEN 4
#define YELLOW 2
#define RED 1
#define HASH MAXDATA/MAXNUM
#define TOO_WEAK MAXDATA/20
ROS_Signal_Strength::ROS_Signal_Strength(QQuickItem * parent) :
QQuickPaintedItem(parent),
topic_value("/rover/signal"),
ros_ready(false),
data(50) {
}
void ROS_Signal_Strength::setup(ros::NodeHandle * nh) {
signal_sub = nh->subscribe(
"/rover/signal", //TODO
1,
&ROS_Signal_Strength::receive_signal,
this
);
ros_ready = true;
}
void ROS_Signal_Strength::paint(QPainter * painter) {
int x = RECT_X;
int y = RECT_Y;
int widthV = width();// / RECT_WIDTH;
int heightV = height();// / RECT_HEIGHT;
QLinearGradient linearGradient(0, 0, 100, 100);
int num = 0;
float hash = HASH;
if(data >= MAXDATA) {
num = MAXNUM;
} else if(data <= TOO_WEAK) {
num = 0;
linearGradient.setColorAt(0.0, Qt::white);
painter->setBrush(linearGradient);
} else {
num = (data/hash) + 1;
}
//draw the outer main rectangle
painter->drawRect(x, y, widthV - 1, heightV - 1);
int i = 0;
int barWidth = widthV/MAXNUM;
int barHeight = heightV/MAXNUM;
y += ((MAXNUM-1) * heightV) /MAXNUM;
const int increment = heightV/MAXNUM;
if(num == 0) {
ROS_INFO("NO SIGNAL\n");
} else {
for(i = 1; i <= num; i++) {
if (num >= GREEN) {
linearGradient.setColorAt(0.2, Qt::green);
} else if (num >= YELLOW) {
linearGradient.setColorAt(0.2, Qt::yellow);
} else {
linearGradient.setColorAt(0.2, Qt::red);
}
painter->setBrush(linearGradient);
painter->drawRect(x, y, barWidth, barHeight);
x += barWidth; //move x along
barHeight += increment; //increase height
y -= increment; //decrease height
}
}
}
void ROS_Signal_Strength::set_topic(const QString & new_value) {
ROS_INFO("set_topic");
if(topic_value != new_value) {
topic_value = new_value;
if(ros_ready) {
signal_sub.shutdown();
signal_sub = nh->subscribe(
topic_value.toStdString(), //TODO
1,
&ROS_Signal_Strength::receive_signal,
this
);
}
emit topic_changed();
}
}
QString ROS_Signal_Strength::get_topic() const {
return topic_value;
}
void ROS_Signal_Strength::
receive_signal(const std_msgs::Float32::ConstPtr & msg) {
data = msg->data;
ROS_INFO("Received signal message");
update();
}
<|endoftext|> |
<commit_before>/*************************************************************************
*
* $RCSfile: view1.cxx,v $
*
* $Revision: 1.10 $
*
* last change: $Author: kz $ $Date: 2004-10-04 19:32:53 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the "License"); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#pragma hdrstop
#ifndef _SVDPAGV_HXX //autogen
#include <svx/svdpagv.hxx>
#endif
#ifndef _SVDVIEW_HXX //autogen
#include <svx/svdview.hxx>
#endif
#ifndef _SVX_RULER_HXX //autogen
#include <svx/ruler.hxx>
#endif
#ifndef _IDXMRK_HXX
#include <idxmrk.hxx>
#endif
#ifndef _VIEW_HXX
#include <view.hxx>
#endif
#ifndef _WRTSH_HXX
#include <wrtsh.hxx>
#endif
#ifndef _SWMODULE_HXX
#include <swmodule.hxx>
#endif
#ifndef _VIEWOPT_HXX
#include <viewopt.hxx>
#endif
#ifndef _DOCSH_HXX
#include <docsh.hxx>
#endif
#ifndef _GLOBDOC_HXX
#include <globdoc.hxx>
#endif
#ifndef _NAVIPI_HXX
#include <navipi.hxx>
#endif
#ifndef _FLDWRAP_HXX
#include <fldwrap.hxx>
#endif
#ifndef _REDLNDLG_HXX
#include <redlndlg.hxx>
#endif
#ifndef _DPAGE_HXX
#include <dpage.hxx>
#endif
#ifndef _EDTWIN_HXX
#include <edtwin.hxx>
#endif
#ifndef _SWFORMATCLIPBOARD_HXX
#include "formatclipboard.hxx"
#endif
#ifndef _CMDID_H
#include <cmdid.h>
#endif
// header for class SfxRequest
#ifndef _SFXREQUEST_HXX
#include <sfx2/request.hxx>
#endif
#include <sfx2/viewfrm.hxx>
extern int bDocSzUpdated;
/*--------------------------------------------------------------------
Beschreibung:
--------------------------------------------------------------------*/
void SwView::Activate(BOOL bMDIActivate)
{
// aktuelle View anmelden an der DocShell
// die View bleibt solange an der DocShell
// aktiv bis Sie zerstoert wird oder durch Activate eine
// neue gesetzt wird
SwDocShell* pDocSh = GetDocShell();
if(pDocSh)
pDocSh->SetView(this);
SwModule* pSwMod = SW_MOD();
pSwMod->SetView(this);
// Dokumentgroesse hat sich geaendert
if(!bDocSzUpdated)
DocSzChgd(aDocSz);
pHRuler->SetActive( TRUE );
pVRuler->SetActive( TRUE );
if ( bMDIActivate )
{
pWrtShell->ShGetFcs(FALSE); // Selektionen sichtbar
if( sSwViewData.Len() )
{
ReadUserData( sSwViewData, FALSE );
sSwViewData.Erase();
}
AttrChangedNotify(pWrtShell);
// Flddlg ggf neu initialisieren (z.B. fuer TYP_SETVAR)
USHORT nId = SwFldDlgWrapper::GetChildWindowId();
SfxViewFrame* pVFrame = GetViewFrame();
SwFldDlgWrapper *pWrp = (SwFldDlgWrapper*)pVFrame->GetChildWindow(nId);
if (pWrp)
pWrp->ReInitDlg(GetDocShell());
// RedlineDlg ggf neu initialisieren
nId = SwRedlineAcceptChild::GetChildWindowId();
SwRedlineAcceptChild *pRed = (SwRedlineAcceptChild*)pVFrame->GetChildWindow(nId);
if (pRed)
pRed->ReInitDlg(GetDocShell());
// reinit IdxMarkDlg
nId = SwInsertIdxMarkWrapper::GetChildWindowId();
SwInsertIdxMarkWrapper *pIdxMrk = (SwInsertIdxMarkWrapper*)pVFrame->GetChildWindow(nId);
if (pIdxMrk)
pIdxMrk->ReInitDlg(*pWrtShell);
// reinit AuthMarkDlg
nId = SwInsertAuthMarkWrapper::GetChildWindowId();
SwInsertAuthMarkWrapper *pAuthMrk = (SwInsertAuthMarkWrapper*)pVFrame->
GetChildWindow(nId);
if (pAuthMrk)
pAuthMrk->ReInitDlg(*pWrtShell);
}
else
//Wenigstens das Notify rufen (vorsichtshalber wegen der SlotFilter
AttrChangedNotify(pWrtShell);
SfxViewShell::Activate(bMDIActivate);
}
/*--------------------------------------------------------------------
Beschreibung:
--------------------------------------------------------------------*/
void SwView::Deactivate(BOOL bMDIActivate)
{
extern BOOL bFlushCharBuffer ;
// Befinden sich noch Zeichen im Input Buffer?
if( bFlushCharBuffer )
GetEditWin().FlushInBuffer();
if( bMDIActivate )
{
pWrtShell->ShLooseFcs(); // Selektionen unsichtbar
pHRuler->SetActive( FALSE );
pVRuler->SetActive( FALSE );
}
SfxViewShell::Deactivate(bMDIActivate);
}
/*--------------------------------------------------------------------
Beschreibung:
--------------------------------------------------------------------*/
void SwView::MarginChanged()
{
GetWrtShell().SetBrowseBorder( GetMargin() );
}
/*--------------------------------------------------------------------
--------------------------------------------------------------------*/
void SwView::ExecFormatPaintbrush(SfxRequest& rReq)
{
if(!pFormatClipboard)
return;
if( pFormatClipboard->HasContent() )
{
pFormatClipboard->Erase();
SwApplyTemplate aTemplate;
GetEditWin().SetApplyTemplate(aTemplate);
}
else
{
bool bPersistentCopy = false;
const SfxItemSet *pArgs = rReq.GetArgs();
if( pArgs && pArgs->Count() >= 1 )
{
bPersistentCopy = static_cast<bool>(((SfxBoolItem &)pArgs->Get(
SID_FORMATPAINTBRUSH)).GetValue());
}
pFormatClipboard->Copy( GetWrtShell(), GetPool(), bPersistentCopy );
SwApplyTemplate aTemplate;
aTemplate.pFormatClipboard = pFormatClipboard;
GetEditWin().SetApplyTemplate(aTemplate);
}
GetViewFrame()->GetBindings().Invalidate(SID_FORMATPAINTBRUSH);
}
void SwView::StateFormatPaintbrush(SfxItemSet &rSet)
{
if(!pFormatClipboard)
return;
bool bHasContent = pFormatClipboard && pFormatClipboard->HasContent();
rSet.Put(SfxBoolItem(SID_FORMATPAINTBRUSH, bHasContent));
if(!bHasContent)
{
if( !pFormatClipboard->CanCopyThisType( GetWrtShell().GetSelectionType() ) )
rSet.DisableItem( SID_FORMATPAINTBRUSH );
}
}
<commit_msg>INTEGRATION: CWS ooo19126 (1.10.578); FILE MERGED 2005/09/05 13:47:46 rt 1.10.578.1: #i54170# Change license header: remove SISSL<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: view1.cxx,v $
*
* $Revision: 1.11 $
*
* last change: $Author: rt $ $Date: 2005-09-09 11:12:14 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#pragma hdrstop
#ifndef _SVDPAGV_HXX //autogen
#include <svx/svdpagv.hxx>
#endif
#ifndef _SVDVIEW_HXX //autogen
#include <svx/svdview.hxx>
#endif
#ifndef _SVX_RULER_HXX //autogen
#include <svx/ruler.hxx>
#endif
#ifndef _IDXMRK_HXX
#include <idxmrk.hxx>
#endif
#ifndef _VIEW_HXX
#include <view.hxx>
#endif
#ifndef _WRTSH_HXX
#include <wrtsh.hxx>
#endif
#ifndef _SWMODULE_HXX
#include <swmodule.hxx>
#endif
#ifndef _VIEWOPT_HXX
#include <viewopt.hxx>
#endif
#ifndef _DOCSH_HXX
#include <docsh.hxx>
#endif
#ifndef _GLOBDOC_HXX
#include <globdoc.hxx>
#endif
#ifndef _NAVIPI_HXX
#include <navipi.hxx>
#endif
#ifndef _FLDWRAP_HXX
#include <fldwrap.hxx>
#endif
#ifndef _REDLNDLG_HXX
#include <redlndlg.hxx>
#endif
#ifndef _DPAGE_HXX
#include <dpage.hxx>
#endif
#ifndef _EDTWIN_HXX
#include <edtwin.hxx>
#endif
#ifndef _SWFORMATCLIPBOARD_HXX
#include "formatclipboard.hxx"
#endif
#ifndef _CMDID_H
#include <cmdid.h>
#endif
// header for class SfxRequest
#ifndef _SFXREQUEST_HXX
#include <sfx2/request.hxx>
#endif
#include <sfx2/viewfrm.hxx>
extern int bDocSzUpdated;
/*--------------------------------------------------------------------
Beschreibung:
--------------------------------------------------------------------*/
void SwView::Activate(BOOL bMDIActivate)
{
// aktuelle View anmelden an der DocShell
// die View bleibt solange an der DocShell
// aktiv bis Sie zerstoert wird oder durch Activate eine
// neue gesetzt wird
SwDocShell* pDocSh = GetDocShell();
if(pDocSh)
pDocSh->SetView(this);
SwModule* pSwMod = SW_MOD();
pSwMod->SetView(this);
// Dokumentgroesse hat sich geaendert
if(!bDocSzUpdated)
DocSzChgd(aDocSz);
pHRuler->SetActive( TRUE );
pVRuler->SetActive( TRUE );
if ( bMDIActivate )
{
pWrtShell->ShGetFcs(FALSE); // Selektionen sichtbar
if( sSwViewData.Len() )
{
ReadUserData( sSwViewData, FALSE );
sSwViewData.Erase();
}
AttrChangedNotify(pWrtShell);
// Flddlg ggf neu initialisieren (z.B. fuer TYP_SETVAR)
USHORT nId = SwFldDlgWrapper::GetChildWindowId();
SfxViewFrame* pVFrame = GetViewFrame();
SwFldDlgWrapper *pWrp = (SwFldDlgWrapper*)pVFrame->GetChildWindow(nId);
if (pWrp)
pWrp->ReInitDlg(GetDocShell());
// RedlineDlg ggf neu initialisieren
nId = SwRedlineAcceptChild::GetChildWindowId();
SwRedlineAcceptChild *pRed = (SwRedlineAcceptChild*)pVFrame->GetChildWindow(nId);
if (pRed)
pRed->ReInitDlg(GetDocShell());
// reinit IdxMarkDlg
nId = SwInsertIdxMarkWrapper::GetChildWindowId();
SwInsertIdxMarkWrapper *pIdxMrk = (SwInsertIdxMarkWrapper*)pVFrame->GetChildWindow(nId);
if (pIdxMrk)
pIdxMrk->ReInitDlg(*pWrtShell);
// reinit AuthMarkDlg
nId = SwInsertAuthMarkWrapper::GetChildWindowId();
SwInsertAuthMarkWrapper *pAuthMrk = (SwInsertAuthMarkWrapper*)pVFrame->
GetChildWindow(nId);
if (pAuthMrk)
pAuthMrk->ReInitDlg(*pWrtShell);
}
else
//Wenigstens das Notify rufen (vorsichtshalber wegen der SlotFilter
AttrChangedNotify(pWrtShell);
SfxViewShell::Activate(bMDIActivate);
}
/*--------------------------------------------------------------------
Beschreibung:
--------------------------------------------------------------------*/
void SwView::Deactivate(BOOL bMDIActivate)
{
extern BOOL bFlushCharBuffer ;
// Befinden sich noch Zeichen im Input Buffer?
if( bFlushCharBuffer )
GetEditWin().FlushInBuffer();
if( bMDIActivate )
{
pWrtShell->ShLooseFcs(); // Selektionen unsichtbar
pHRuler->SetActive( FALSE );
pVRuler->SetActive( FALSE );
}
SfxViewShell::Deactivate(bMDIActivate);
}
/*--------------------------------------------------------------------
Beschreibung:
--------------------------------------------------------------------*/
void SwView::MarginChanged()
{
GetWrtShell().SetBrowseBorder( GetMargin() );
}
/*--------------------------------------------------------------------
--------------------------------------------------------------------*/
void SwView::ExecFormatPaintbrush(SfxRequest& rReq)
{
if(!pFormatClipboard)
return;
if( pFormatClipboard->HasContent() )
{
pFormatClipboard->Erase();
SwApplyTemplate aTemplate;
GetEditWin().SetApplyTemplate(aTemplate);
}
else
{
bool bPersistentCopy = false;
const SfxItemSet *pArgs = rReq.GetArgs();
if( pArgs && pArgs->Count() >= 1 )
{
bPersistentCopy = static_cast<bool>(((SfxBoolItem &)pArgs->Get(
SID_FORMATPAINTBRUSH)).GetValue());
}
pFormatClipboard->Copy( GetWrtShell(), GetPool(), bPersistentCopy );
SwApplyTemplate aTemplate;
aTemplate.pFormatClipboard = pFormatClipboard;
GetEditWin().SetApplyTemplate(aTemplate);
}
GetViewFrame()->GetBindings().Invalidate(SID_FORMATPAINTBRUSH);
}
void SwView::StateFormatPaintbrush(SfxItemSet &rSet)
{
if(!pFormatClipboard)
return;
bool bHasContent = pFormatClipboard && pFormatClipboard->HasContent();
rSet.Put(SfxBoolItem(SID_FORMATPAINTBRUSH, bHasContent));
if(!bHasContent)
{
if( !pFormatClipboard->CanCopyThisType( GetWrtShell().GetSelectionType() ) )
rSet.DisableItem( SID_FORMATPAINTBRUSH );
}
}
<|endoftext|> |
<commit_before>#include "options.h"
namespace nng {
options::options() {
}
option_names::option_names() {
}
const std::string option_names::socket_name = NNG_OPT_SOCKNAME;
const std::string option_names::compat_domain = NNG_OPT_DOMAIN;
const std::string option_names::raw = NNG_OPT_RAW;
const std::string option_names::linger_usec = NNG_OPT_LINGER;
const std::string option_names::receive_buffer = NNG_OPT_RECVBUF;
const std::string option_names::send_buffer = NNG_OPT_SENDBUF;
const std::string option_names::receive_file_descriptor = NNG_OPT_RECVFD;
const std::string option_names::send_file_descriptor = NNG_OPT_SENDFD;
const std::string option_names::receive_timeout_usec = NNG_OPT_RECVTIMEO;
const std::string option_names::send_timeout_usec = NNG_OPT_SENDTIMEO;
const std::string option_names::local_address = NNG_OPT_LOCADDR;
const std::string option_names::remote_address = NNG_OPT_REMADDR;
const std::string option_names::url = NNG_OPT_URL;
const std::string option_names::max_ttl = NNG_OPT_MAXTTL;
const std::string option_names::protocol = NNG_OPT_PROTOCOL;
const std::string option_names::transport = NNG_OPT_TRANSPORT;
const std::string option_names::max_receive_size = NNG_OPT_RECVMAXSZ;
const std::string option_names::min_reconnect_time_usec = NNG_OPT_RECONNMINT;
const std::string option_names::max_reconnect_time_usec = NNG_OPT_RECONNMAXT;
const std::string option_names::pair1_polyamorous = NNG_OPT_PAIR1_POLY;
const std::string option_names::sub_subscribe = NNG_OPT_SUB_SUBSCRIBE;
const std::string option_names::surveyor_survey_time_usec = NNG_OPT_SURVEYOR_SURVEYTIME;
}
<commit_msg>added missing options definition<commit_after>#include "options.h"
namespace nng {
options::options() {
}
option_names::option_names() {
}
const std::string option_names::socket_name = NNG_OPT_SOCKNAME;
const std::string option_names::compat_domain = NNG_OPT_DOMAIN;
const std::string option_names::raw = NNG_OPT_RAW;
const std::string option_names::linger_usec = NNG_OPT_LINGER;
const std::string option_names::receive_buffer = NNG_OPT_RECVBUF;
const std::string option_names::send_buffer = NNG_OPT_SENDBUF;
const std::string option_names::receive_file_descriptor = NNG_OPT_RECVFD;
const std::string option_names::send_file_descriptor = NNG_OPT_SENDFD;
const std::string option_names::receive_timeout_usec = NNG_OPT_RECVTIMEO;
const std::string option_names::send_timeout_usec = NNG_OPT_SENDTIMEO;
const std::string option_names::local_address = NNG_OPT_LOCADDR;
const std::string option_names::remote_address = NNG_OPT_REMADDR;
const std::string option_names::url = NNG_OPT_URL;
const std::string option_names::max_ttl = NNG_OPT_MAXTTL;
const std::string option_names::protocol = NNG_OPT_PROTOCOL;
const std::string option_names::transport = NNG_OPT_TRANSPORT;
const std::string option_names::max_receive_size = NNG_OPT_RECVMAXSZ;
const std::string option_names::min_reconnect_time_usec = NNG_OPT_RECONNMINT;
const std::string option_names::max_reconnect_time_usec = NNG_OPT_RECONNMAXT;
const std::string option_names::pair1_polyamorous = NNG_OPT_PAIR1_POLY;
const std::string option_names::sub_subscribe = NNG_OPT_SUB_SUBSCRIBE;
const std::string option_names::sub_unsubscribe = NNG_OPT_SUB_UNSUBSCRIBE;
const std::string option_names::surveyor_survey_time_usec = NNG_OPT_SURVEYOR_SURVEYTIME;
}
<|endoftext|> |
<commit_before>// [WriteFile Name=FeatureLayerDefinitionExpression, Category=Features]
// [Legal]
// Copyright 2016 Esri.
// 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.
// [Legal]
#include "FeatureLayerDefinitionExpression.h"
#include "Map.h"
#include "MapQuickView.h"
#include "FeatureLayer.h"
#include "Basemap.h"
#include "SpatialReference.h"
#include "ServiceFeatureTable.h"
#include "Viewpoint.h"
#include "Point.h"
#include <QUrl>
using namespace Esri::ArcGISRuntime;
FeatureLayerDefinitionExpression::FeatureLayerDefinitionExpression(QQuickItem* parent) :
QQuickItem(parent),
m_map(nullptr),
m_mapView(nullptr),
m_featureLayer(nullptr),
m_initialized(false)
{
}
FeatureLayerDefinitionExpression::~FeatureLayerDefinitionExpression()
{
}
void FeatureLayerDefinitionExpression::componentComplete()
{
QQuickItem::componentComplete();
//! [Obtain the instantiated map view in Cpp]
// find QML MapView component
m_mapView = findChild<MapQuickView*>("mapView");
m_mapView->setWrapAroundMode(WrapAroundMode::Disabled);
// Create a map using the topographic basemap
m_map = new Map(Basemap::topographic(this), this);
m_map->setInitialViewpoint(Viewpoint(Point(-13630484, 4545415, SpatialReference(102100)), 300000));
// Set map to map view
m_mapView->setMap(m_map);
//! [Obtain the instantiated map view in Cpp]
// create the feature table
ServiceFeatureTable* featureTable = new ServiceFeatureTable(QUrl("http://sampleserver6.arcgisonline.com/arcgis/rest/services/SF311/FeatureServer/0"), this);
// create the feature layer using the feature table
m_featureLayer = new FeatureLayer(featureTable, this);
connect(m_featureLayer, &FeatureLayer::loadStatusChanged,[this](LoadStatus loadStatus)
{
loadStatus == LoadStatus::Loaded ? m_initialized = true : m_initialized = false;
emit layerInitializedChanged();
});
// add the feature layer to the map
m_map->operationalLayers()->append(m_featureLayer);
}
bool FeatureLayerDefinitionExpression::layerInitialized() const
{
return m_initialized;
}
void FeatureLayerDefinitionExpression::setDefExpression(QString whereClause)
{
m_featureLayer->setDefinitionExpression(whereClause);
}
<commit_msg>featurelayer > def expression comment to show where def expression is<commit_after>// [WriteFile Name=FeatureLayerDefinitionExpression, Category=Features]
// [Legal]
// Copyright 2016 Esri.
// 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.
// [Legal]
#include "FeatureLayerDefinitionExpression.h"
#include "Map.h"
#include "MapQuickView.h"
#include "FeatureLayer.h"
#include "Basemap.h"
#include "SpatialReference.h"
#include "ServiceFeatureTable.h"
#include "Viewpoint.h"
#include "Point.h"
#include <QUrl>
using namespace Esri::ArcGISRuntime;
FeatureLayerDefinitionExpression::FeatureLayerDefinitionExpression(QQuickItem* parent) :
QQuickItem(parent),
m_map(nullptr),
m_mapView(nullptr),
m_featureLayer(nullptr),
m_initialized(false)
{
}
FeatureLayerDefinitionExpression::~FeatureLayerDefinitionExpression()
{
}
void FeatureLayerDefinitionExpression::componentComplete()
{
QQuickItem::componentComplete();
//! [Obtain the instantiated map view in Cpp]
// find QML MapView component
m_mapView = findChild<MapQuickView*>("mapView");
m_mapView->setWrapAroundMode(WrapAroundMode::Disabled);
// Create a map using the topographic basemap
m_map = new Map(Basemap::topographic(this), this);
m_map->setInitialViewpoint(Viewpoint(Point(-13630484, 4545415, SpatialReference(102100)), 300000));
// Set map to map view
m_mapView->setMap(m_map);
//! [Obtain the instantiated map view in Cpp]
// create the feature table
ServiceFeatureTable* featureTable = new ServiceFeatureTable(QUrl("http://sampleserver6.arcgisonline.com/arcgis/rest/services/SF311/FeatureServer/0"), this);
// create the feature layer using the feature table
m_featureLayer = new FeatureLayer(featureTable, this);
connect(m_featureLayer, &FeatureLayer::loadStatusChanged,[this](LoadStatus loadStatus)
{
loadStatus == LoadStatus::Loaded ? m_initialized = true : m_initialized = false;
emit layerInitializedChanged();
});
// add the feature layer to the map
m_map->operationalLayers()->append(m_featureLayer);
}
bool FeatureLayerDefinitionExpression::layerInitialized() const
{
return m_initialized;
}
void FeatureLayerDefinitionExpression::setDefExpression(QString whereClause)
{
// SQL whereClause will be defined in QML with
// definitionExpressionSample.setDefExpression(whereClause)
m_featureLayer->setDefinitionExpression(whereClause);
}
<|endoftext|> |
<commit_before>/*
* Copyright (c) 2010 ARM Limited
* All rights reserved
*
* The license below extends only to copyright in the software and shall
* not be construed as granting a license to any other intellectual
* property including but not limited to intellectual property relating
* to a hardware implementation of the functionality of the software
* licensed hereunder. You may use the software subject to the license
* terms below provided that you ensure that this notice is replicated
* unmodified and in its entirety in all distributions of the software,
* modified or unmodified, in source code or in binary form.
*
* Copyright (c) 2007-2008 The Florida State University
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met: redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer;
* redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution;
* neither the name of the copyright holders 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.
*
* Authors: Stephen Hines
*/
#ifndef __ARCH_ARM_MACROMEM_HH__
#define __ARCH_ARM_MACROMEM_HH__
#include "arch/arm/insts/pred_inst.hh"
#include "arch/arm/tlb.hh"
namespace ArmISA
{
static inline unsigned int
number_of_ones(int32_t val)
{
uint32_t ones = 0;
for (int i = 0; i < 32; i++ )
{
if ( val & (1<<i) )
ones++;
}
return ones;
}
class MicroOp : public PredOp
{
protected:
MicroOp(const char *mnem, ExtMachInst machInst, OpClass __opClass)
: PredOp(mnem, machInst, __opClass)
{
}
public:
void
setDelayedCommit()
{
flags[IsDelayedCommit] = true;
}
};
/**
* Microops of the form IntRegA = IntRegB op Imm
*/
class MicroIntOp : public MicroOp
{
protected:
RegIndex ura, urb;
uint8_t imm;
MicroIntOp(const char *mnem, ExtMachInst machInst, OpClass __opClass,
RegIndex _ura, RegIndex _urb, uint8_t _imm)
: MicroOp(mnem, machInst, __opClass),
ura(_ura), urb(_urb), imm(_imm)
{
}
};
/**
* Memory microops which use IntReg + Imm addressing
*/
class MicroMemOp : public MicroIntOp
{
protected:
bool up;
unsigned memAccessFlags;
MicroMemOp(const char *mnem, ExtMachInst machInst, OpClass __opClass,
RegIndex _ura, RegIndex _urb, bool _up, uint8_t _imm)
: MicroIntOp(mnem, machInst, __opClass, _ura, _urb, _imm),
up(_up), memAccessFlags(TLB::MustBeOne | TLB::AlignWord)
{
}
};
class MacroMemOp : public PredMacroOp
{
protected:
MacroMemOp(const char *mnem, ExtMachInst machInst, OpClass __opClass,
IntRegIndex rn, bool index, bool up, bool user,
bool writeback, bool load, uint32_t reglist);
};
class MacroVFPMemOp : public PredMacroOp
{
protected:
MacroVFPMemOp(const char *mnem, ExtMachInst machInst, OpClass __opClass,
IntRegIndex rn, RegIndex vd, bool single, bool up,
bool writeback, bool load, uint32_t offset);
};
}
#endif //__ARCH_ARM_INSTS_MACROMEM_HH__
<commit_msg>ARM: Add comments to the classes in macromem.hh.<commit_after>/*
* Copyright (c) 2010 ARM Limited
* All rights reserved
*
* The license below extends only to copyright in the software and shall
* not be construed as granting a license to any other intellectual
* property including but not limited to intellectual property relating
* to a hardware implementation of the functionality of the software
* licensed hereunder. You may use the software subject to the license
* terms below provided that you ensure that this notice is replicated
* unmodified and in its entirety in all distributions of the software,
* modified or unmodified, in source code or in binary form.
*
* Copyright (c) 2007-2008 The Florida State University
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met: redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer;
* redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution;
* neither the name of the copyright holders 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.
*
* Authors: Stephen Hines
*/
#ifndef __ARCH_ARM_MACROMEM_HH__
#define __ARCH_ARM_MACROMEM_HH__
#include "arch/arm/insts/pred_inst.hh"
#include "arch/arm/tlb.hh"
namespace ArmISA
{
static inline unsigned int
number_of_ones(int32_t val)
{
uint32_t ones = 0;
for (int i = 0; i < 32; i++ )
{
if ( val & (1<<i) )
ones++;
}
return ones;
}
/**
* Base class for Memory microops
*/
class MicroOp : public PredOp
{
protected:
MicroOp(const char *mnem, ExtMachInst machInst, OpClass __opClass)
: PredOp(mnem, machInst, __opClass)
{
}
public:
void
setDelayedCommit()
{
flags[IsDelayedCommit] = true;
}
};
/**
* Microops of the form IntRegA = IntRegB op Imm
*/
class MicroIntOp : public MicroOp
{
protected:
RegIndex ura, urb;
uint8_t imm;
MicroIntOp(const char *mnem, ExtMachInst machInst, OpClass __opClass,
RegIndex _ura, RegIndex _urb, uint8_t _imm)
: MicroOp(mnem, machInst, __opClass),
ura(_ura), urb(_urb), imm(_imm)
{
}
};
/**
* Memory microops which use IntReg + Imm addressing
*/
class MicroMemOp : public MicroIntOp
{
protected:
bool up;
unsigned memAccessFlags;
MicroMemOp(const char *mnem, ExtMachInst machInst, OpClass __opClass,
RegIndex _ura, RegIndex _urb, bool _up, uint8_t _imm)
: MicroIntOp(mnem, machInst, __opClass, _ura, _urb, _imm),
up(_up), memAccessFlags(TLB::MustBeOne | TLB::AlignWord)
{
}
};
/**
* Base class for microcoded integer memory instructions.
*/
class MacroMemOp : public PredMacroOp
{
protected:
MacroMemOp(const char *mnem, ExtMachInst machInst, OpClass __opClass,
IntRegIndex rn, bool index, bool up, bool user,
bool writeback, bool load, uint32_t reglist);
};
/**
* Base class for microcoded floating point memory instructions.
*/
class MacroVFPMemOp : public PredMacroOp
{
protected:
MacroVFPMemOp(const char *mnem, ExtMachInst machInst, OpClass __opClass,
IntRegIndex rn, RegIndex vd, bool single, bool up,
bool writeback, bool load, uint32_t offset);
};
}
#endif //__ARCH_ARM_INSTS_MACROMEM_HH__
<|endoftext|> |
<commit_before>/****************************************************************************
**
** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation ([email protected])
**
** This file is part of the Qt Mobility Components.
**
** $QT_BEGIN_LICENSE:LGPL$
** No Commercial Usage
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions
** contained in the Technology Preview License Agreement accompanying
** this package.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights. These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** If you have questions regarding the use of this file, please contact
** Nokia at [email protected].
**
**
**
**
**
**
**
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include "qremoteservicecontrol_p.h"
#include "ipcendpoint_p.h"
#include "objectendpoint_p.h"
#include <QLocalServer>
#include <QLocalSocket>
#include <QDataStream>
#include <QTimer>
#include <QProcess>
#include <time.h>
// Needed for ::Sleep, while we wait for a better solution
#ifdef Q_OS_WIN
#include <Windows.h>
#include <Winbase.h>
#endif
QTM_BEGIN_NAMESPACE
//IPC based on QLocalSocket
class LocalSocketEndPoint : public QServiceIpcEndPoint
{
Q_OBJECT
public:
LocalSocketEndPoint(QLocalSocket* s, QObject* parent = 0)
: QServiceIpcEndPoint(parent), socket(s)
{
Q_ASSERT(socket);
socket->setParent(this);
connect(s, SIGNAL(readyRead()), this, SLOT(readIncoming()));
connect(s, SIGNAL(disconnected()), this, SIGNAL(disconnected()));
if (socket->bytesAvailable())
QTimer::singleShot(0, this, SLOT(readIncoming()));
}
~LocalSocketEndPoint()
{
}
protected:
void flushPackage(const QServicePackage& package)
{
QByteArray block;
QDataStream out(&block, QIODevice::WriteOnly);
out.setVersion(QDataStream::Qt_4_6);
out << package;
socket->write(block);
}
protected slots:
void readIncoming()
{
QDataStream in(socket);
in.setVersion(QDataStream::Qt_4_6);
while(socket->bytesAvailable()) {
QServicePackage package;
in >> package;
incoming.enqueue(package);
}
emit readyRead();
}
private:
QLocalSocket* socket;
};
QRemoteServiceControlPrivate::QRemoteServiceControlPrivate(QObject* parent)
: QObject(parent)
{
}
void QRemoteServiceControlPrivate::publishServices( const QString& ident)
{
createServiceEndPoint(ident) ;
}
void QRemoteServiceControlPrivate::processIncoming()
{
qDebug() << "Processing incoming connect";
if (localServer->hasPendingConnections()) {
QLocalSocket* s = localServer->nextPendingConnection();
//LocalSocketEndPoint owns socket
LocalSocketEndPoint* ipcEndPoint = new LocalSocketEndPoint(s);
ObjectEndPoint* endpoint = new ObjectEndPoint(ObjectEndPoint::Service, ipcEndPoint, this);
Q_UNUSED(endpoint);
}
}
/*
Creates endpoint on service side.
*/
bool QRemoteServiceControlPrivate::createServiceEndPoint(const QString& ident)
{
//other IPC mechanisms such as dbus may have to publish the
//meta object definition for all registered service types
QLocalServer::removeServer(ident);
qDebug() << "Start listening for incoming connections";
localServer = new QLocalServer(this);
if ( !localServer->listen(ident) ) {
qWarning() << "Cannot create local socket endpoint";
return false;
}
connect(localServer, SIGNAL(newConnection()), this, SLOT(processIncoming()));
if (localServer->hasPendingConnections())
QTimer::singleShot(0, this, SLOT(processIncoming()));
return true;
}
/*
Creates endpoint on client side.
*/
QObject* QRemoteServiceControlPrivate::proxyForService(const QRemoteServiceIdentifier& typeIdent, const QString& location)
{
QLocalSocket* socket = new QLocalSocket();
//location format: protocol:address
QString address = location.section(':', 1, 1);
socket->connectToServer(address);
if (!socket->isValid()) {
qWarning() << "Cannot connect to remote service, trying to start service " << location;
// try starting the service by hand
QProcess *service = new QProcess();
service->start(address);
service->waitForStarted();
if(service->error() != QProcess::UnknownError || service->state() != QProcess::Running) {
qWarning() << "Unable to start service " << address << service->error() << service->errorString() << service->state();
return false;
}
int i;
socket->connectToServer(address);
for(i = 0; !socket->isValid() && i < 100; i++){
if(service->state() != QProcess::Running){
qWarning() << "Service died on startup" << service->errorString();
return false;
}
// Temporary hack till we can improve startup signaling
#ifdef Q_OS_WIN
::Sleep(10);
#else
struct timespec tm;
tm.tv_sec = 0;
tm.tv_nsec = 1000000;
nanosleep(&tm, 0x0);
#endif
socket->connectToServer(address);
// keep trying for a while
}
qDebug() << "Number of loops: " << i;
if(!socket->isValid()){
qWarning() << "Server failed to start within waiting period";
return false;
}
}
LocalSocketEndPoint* ipcEndPoint = new LocalSocketEndPoint(socket);
ObjectEndPoint* endPoint = new ObjectEndPoint(ObjectEndPoint::Client, ipcEndPoint);
QObject *proxy = endPoint->constructProxy(typeIdent);
QObject::connect(proxy, SIGNAL(destroyed()), endPoint, SLOT(deleteLater()));
return proxy;
}
#include "moc_qremoteservicecontrol_p.cpp"
#include "qremoteservicecontrol_p.moc"
QTM_END_NAMESPACE
<commit_msg>Updated LocalSocket IPC with XML extensions<commit_after>/****************************************************************************
**
** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation ([email protected])
**
** This file is part of the Qt Mobility Components.
**
** $QT_BEGIN_LICENSE:LGPL$
** No Commercial Usage
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions
** contained in the Technology Preview License Agreement accompanying
** this package.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights. These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** If you have questions regarding the use of this file, please contact
** Nokia at [email protected].
**
**
**
**
**
**
**
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include "qremoteservicecontrol_p.h"
#include "ipcendpoint_p.h"
#include "objectendpoint_p.h"
#include <QLocalServer>
#include <QLocalSocket>
#include <QDataStream>
#include <QTimer>
#include <QProcess>
#include <time.h>
// Needed for ::Sleep, while we wait for a better solution
#ifdef Q_OS_WIN
#include <Windows.h>
#include <Winbase.h>
#endif
QTM_BEGIN_NAMESPACE
//IPC based on QLocalSocket
class LocalSocketEndPoint : public QServiceIpcEndPoint
{
Q_OBJECT
public:
LocalSocketEndPoint(QLocalSocket* s, QObject* parent = 0)
: QServiceIpcEndPoint(parent), socket(s)
{
Q_ASSERT(socket);
socket->setParent(this);
connect(s, SIGNAL(readyRead()), this, SLOT(readIncoming()));
connect(s, SIGNAL(disconnected()), this, SIGNAL(disconnected()));
if (socket->bytesAvailable())
QTimer::singleShot(0, this, SLOT(readIncoming()));
}
~LocalSocketEndPoint()
{
}
protected:
void flushPackage(const QServicePackage& package)
{
QByteArray block;
QDataStream out(&block, QIODevice::WriteOnly);
out.setVersion(QDataStream::Qt_4_6);
out << package;
socket->write(block);
}
protected slots:
void readIncoming()
{
QDataStream in(socket);
in.setVersion(QDataStream::Qt_4_6);
while(socket->bytesAvailable()) {
QServicePackage package;
in >> package;
incoming.enqueue(package);
}
emit readyRead();
}
private:
QLocalSocket* socket;
};
QRemoteServiceControlPrivate::QRemoteServiceControlPrivate(QObject* parent)
: QObject(parent)
{
}
void QRemoteServiceControlPrivate::publishServices( const QString& ident)
{
createServiceEndPoint(ident) ;
}
void QRemoteServiceControlPrivate::processIncoming()
{
qDebug() << "Processing incoming connect";
if (localServer->hasPendingConnections()) {
QLocalSocket* s = localServer->nextPendingConnection();
//LocalSocketEndPoint owns socket
LocalSocketEndPoint* ipcEndPoint = new LocalSocketEndPoint(s);
ObjectEndPoint* endpoint = new ObjectEndPoint(ObjectEndPoint::Service, ipcEndPoint, this);
Q_UNUSED(endpoint);
}
}
/*
Creates endpoint on service side.
*/
bool QRemoteServiceControlPrivate::createServiceEndPoint(const QString& ident)
{
//other IPC mechanisms such as dbus may have to publish the
//meta object definition for all registered service types
QLocalServer::removeServer(ident);
qDebug() << "Start listening for incoming connections";
localServer = new QLocalServer(this);
if ( !localServer->listen(ident) ) {
qWarning() << "Cannot create local socket endpoint";
return false;
}
connect(localServer, SIGNAL(newConnection()), this, SLOT(processIncoming()));
if (localServer->hasPendingConnections())
QTimer::singleShot(0, this, SLOT(processIncoming()));
return true;
}
/*
Creates endpoint on client side.
*/
QObject* QRemoteServiceControlPrivate::proxyForService(const QRemoteServiceIdentifier& typeIdent, const QString& location)
{
QLocalSocket* socket = new QLocalSocket();
socket->connectToServer(location);
if (!socket->isValid()) {
qWarning() << "Cannot connect to remote service, trying to start service " << location;
// try starting the service by hand
QProcess *service = new QProcess();
service->start(location);
service->waitForStarted();
if(service->error() != QProcess::UnknownError || service->state() != QProcess::Running) {
qWarning() << "Unable to start service " << location << service->error() << service->errorString() << service->state();
return false;
}
int i;
socket->connectToServer(location);
for(i = 0; !socket->isValid() && i < 100; i++){
if(service->state() != QProcess::Running){
qWarning() << "Service died on startup" << service->errorString();
return false;
}
// Temporary hack till we can improve startup signaling
#ifdef Q_OS_WIN
::Sleep(10);
#else
struct timespec tm;
tm.tv_sec = 0;
tm.tv_nsec = 1000000;
nanosleep(&tm, 0x0);
#endif
socket->connectToServer(location);
// keep trying for a while
}
qDebug() << "Number of loops: " << i;
if(!socket->isValid()){
qWarning() << "Server failed to start within waiting period";
return false;
}
}
LocalSocketEndPoint* ipcEndPoint = new LocalSocketEndPoint(socket);
ObjectEndPoint* endPoint = new ObjectEndPoint(ObjectEndPoint::Client, ipcEndPoint);
QObject *proxy = endPoint->constructProxy(typeIdent);
QObject::connect(proxy, SIGNAL(destroyed()), endPoint, SLOT(deleteLater()));
return proxy;
}
#include "moc_qremoteservicecontrol_p.cpp"
#include "qremoteservicecontrol_p.moc"
QTM_END_NAMESPACE
<|endoftext|> |
<commit_before>//
// @file ensemble.cpp
//
//
#include "ensemble.h"
#include "plugin_factory.h"
#include <numeric>
#include <stddef.h>
#include <stdint.h>
#define HIMAN_AUXILIARY_INCLUDE
#include "fetcher.h"
#undef HIMAN_AUXILIARY_INCLUDE
namespace
{
std::vector<double> RemoveMissingValues(const std::vector<double>& vec)
{
std::vector<double> ret;
ret.reserve(vec.size());
for (const auto& v : vec)
{
if (!himan::IsValid(v))
{
ret.emplace_back(v);
}
}
return ret;
}
}
namespace himan
{
ensemble::ensemble(const param& parameter, size_t expectedEnsembleSize)
: itsParam(parameter),
itsExpectedEnsembleSize(expectedEnsembleSize),
itsForecasts(),
itsEnsembleType(kPerturbedEnsemble),
itsLogger(logger("ensemble")),
itsMaximumMissingForecasts(0)
{
itsDesiredForecasts.reserve(expectedEnsembleSize);
itsDesiredForecasts.push_back(forecast_type(kEpsControl, 0));
for (size_t i = 1; i < itsDesiredForecasts.capacity(); i++)
{
itsDesiredForecasts.push_back(forecast_type(kEpsPerturbation, static_cast<double>(i)));
}
}
ensemble::ensemble(const param& parameter, size_t expectedEnsembleSize,
const std::vector<forecast_type>& controlForecasts)
: itsParam(parameter),
itsExpectedEnsembleSize(expectedEnsembleSize),
itsForecasts(),
itsEnsembleType(kPerturbedEnsemble),
itsLogger(logger("ensemble")),
itsMaximumMissingForecasts(0)
{
ASSERT(controlForecasts.size() < expectedEnsembleSize);
itsDesiredForecasts.reserve(expectedEnsembleSize);
for (const auto& c : controlForecasts)
{
itsDesiredForecasts.push_back(c);
}
for (size_t i = controlForecasts.size(); i < itsDesiredForecasts.capacity(); i++)
{
itsDesiredForecasts.push_back(forecast_type(kEpsPerturbation, static_cast<double>(i)));
}
}
ensemble::ensemble()
: itsExpectedEnsembleSize(0),
itsEnsembleType(kPerturbedEnsemble),
itsLogger(logger("ensemble")),
itsMaximumMissingForecasts(0)
{
}
ensemble::~ensemble() {}
ensemble::ensemble(const ensemble& other)
: itsParam(other.itsParam),
itsExpectedEnsembleSize(other.itsExpectedEnsembleSize),
itsDesiredForecasts(other.itsDesiredForecasts),
itsForecasts(other.itsForecasts),
itsEnsembleType(other.itsEnsembleType),
itsLogger(logger("ensemble")),
itsMaximumMissingForecasts(other.itsMaximumMissingForecasts)
{
}
ensemble& ensemble::operator=(const ensemble& other)
{
itsParam = other.itsParam;
itsExpectedEnsembleSize = other.itsExpectedEnsembleSize;
itsDesiredForecasts = other.itsDesiredForecasts;
itsForecasts = other.itsForecasts;
itsEnsembleType = other.itsEnsembleType;
itsMaximumMissingForecasts = other.itsMaximumMissingForecasts;
itsLogger = logger("ensemble");
return *this;
}
void ensemble::Fetch(std::shared_ptr<const plugin_configuration> config, const forecast_time& time,
const level& forecastLevel)
{
auto f = GET_PLUGIN(fetcher);
// We need to clear the forecasts vector every time we fetch to support ensembles
// with a rotating member scheme (GLAMEPS). This means that the index of the forecast
// doesn't reflect its position in the ensemble.
itsForecasts.clear();
int numMissingForecasts = 0;
for (const auto& desired : itsDesiredForecasts)
{
try
{
auto info = f->Fetch(config, time, forecastLevel, itsParam, desired, false);
itsForecasts.push_back(info);
}
catch (HPExceptionType& e)
{
if (e != kFileDataNotFound)
{
itsLogger.Fatal("Unable to proceed");
himan::Abort();
}
else
{
numMissingForecasts++;
}
}
}
VerifyValidForecastCount(numMissingForecasts);
}
void ensemble::VerifyValidForecastCount(int numMissingForecasts)
{
// This is for data that might not have all the fields for every timestep
if (itsMaximumMissingForecasts > 0)
{
if (numMissingForecasts >= itsMaximumMissingForecasts)
{
itsLogger.Fatal("maximum number of missing fields (" + std::to_string(itsMaximumMissingForecasts) +
") reached, aborting");
himan::Abort();
}
}
// Normally, we don't except any of the fields to be missing, but at this point
// we've already catched the exceptions
else
{
if (numMissingForecasts > 0)
{
itsLogger.Fatal("missing " + std::to_string(numMissingForecasts) + " of " +
std::to_string(itsMaximumMissingForecasts) + " allowed missing fields of data");
throw kFileDataNotFound;
}
}
itsLogger.Info("succesfully loaded " + std::to_string(itsForecasts.size()) + "/" +
std::to_string(itsDesiredForecasts.size()) + " fields");
}
void ensemble::ResetLocation()
{
for (auto& f : itsForecasts)
{
f->ResetLocation();
}
}
bool ensemble::FirstLocation()
{
for (auto& f : itsForecasts)
{
if (!f->FirstLocation())
{
return false;
}
}
return true;
}
bool ensemble::NextLocation()
{
for (auto& f : itsForecasts)
{
if (!f->NextLocation())
{
return false;
}
}
return true;
}
std::vector<double> ensemble::Values() const
{
std::vector<double> ret;
ret.reserve(Size());
std::for_each(itsForecasts.begin(), itsForecasts.end(), [&](const info_t& Info) { ret.emplace_back(Info->Value()); });
return ret;
}
std::vector<double> ensemble::SortedValues() const
{
std::vector<double> v = RemoveMissingValues(Values());
std::sort(v.begin(), v.end());
return v;
}
double ensemble::Mean() const
{
std::vector<double> v = RemoveMissingValues(Values());
if (v.size() == 0)
{
return MissingDouble();
}
return std::accumulate(v.begin(), v.end(), 0.0) / static_cast<double>(v.size());
}
double ensemble::Variance() const
{
std::vector<double> values = RemoveMissingValues(Values());
if (values.size() == 0)
{
return MissingDouble();
}
const double mean = std::accumulate(values.begin(), values.end(), 0.0) / static_cast<double>(values.size());
double sum = 0.0;
for (const auto& x : values)
{
const double t = x - mean;
sum += t * t;
}
return sum / static_cast<double>(values.size());
}
double ensemble::CentralMoment(int N) const
{
std::vector<double> v = RemoveMissingValues(Values());
double mu = Mean();
std::for_each(v.begin(), v.end(), [=](double& d) { d = std::pow(d - mu, N); });
return std::accumulate(v.begin(), v.end(), 0.0) / static_cast<double>(v.size());
}
HPEnsembleType ensemble::EnsembleType() const { return itsEnsembleType; }
size_t ensemble::Size() const { return itsForecasts.size(); }
size_t ensemble::ExpectedSize() const { return itsExpectedEnsembleSize; }
info_t ensemble::Forecast(size_t i)
{
if (itsForecasts.size() <= i)
{
throw kFileDataNotFound;
}
return itsForecasts[i];
}
} // namespace himan
<commit_msg>Glitch O_O<commit_after>//
// @file ensemble.cpp
//
//
#include "ensemble.h"
#include "plugin_factory.h"
#include <numeric>
#include <stddef.h>
#include <stdint.h>
#define HIMAN_AUXILIARY_INCLUDE
#include "fetcher.h"
#undef HIMAN_AUXILIARY_INCLUDE
namespace
{
std::vector<double> RemoveMissingValues(const std::vector<double>& vec)
{
std::vector<double> ret;
ret.reserve(vec.size());
for (const auto& v : vec)
{
if (himan::IsValid(v))
{
ret.emplace_back(v);
}
}
return ret;
}
}
namespace himan
{
ensemble::ensemble(const param& parameter, size_t expectedEnsembleSize)
: itsParam(parameter),
itsExpectedEnsembleSize(expectedEnsembleSize),
itsForecasts(),
itsEnsembleType(kPerturbedEnsemble),
itsLogger(logger("ensemble")),
itsMaximumMissingForecasts(0)
{
itsDesiredForecasts.reserve(expectedEnsembleSize);
itsDesiredForecasts.push_back(forecast_type(kEpsControl, 0));
for (size_t i = 1; i < itsDesiredForecasts.capacity(); i++)
{
itsDesiredForecasts.push_back(forecast_type(kEpsPerturbation, static_cast<double>(i)));
}
}
ensemble::ensemble(const param& parameter, size_t expectedEnsembleSize,
const std::vector<forecast_type>& controlForecasts)
: itsParam(parameter),
itsExpectedEnsembleSize(expectedEnsembleSize),
itsForecasts(),
itsEnsembleType(kPerturbedEnsemble),
itsLogger(logger("ensemble")),
itsMaximumMissingForecasts(0)
{
ASSERT(controlForecasts.size() < expectedEnsembleSize);
itsDesiredForecasts.reserve(expectedEnsembleSize);
for (const auto& c : controlForecasts)
{
itsDesiredForecasts.push_back(c);
}
for (size_t i = controlForecasts.size(); i < itsDesiredForecasts.capacity(); i++)
{
itsDesiredForecasts.push_back(forecast_type(kEpsPerturbation, static_cast<double>(i)));
}
}
ensemble::ensemble()
: itsExpectedEnsembleSize(0),
itsEnsembleType(kPerturbedEnsemble),
itsLogger(logger("ensemble")),
itsMaximumMissingForecasts(0)
{
}
ensemble::~ensemble() {}
ensemble::ensemble(const ensemble& other)
: itsParam(other.itsParam),
itsExpectedEnsembleSize(other.itsExpectedEnsembleSize),
itsDesiredForecasts(other.itsDesiredForecasts),
itsForecasts(other.itsForecasts),
itsEnsembleType(other.itsEnsembleType),
itsLogger(logger("ensemble")),
itsMaximumMissingForecasts(other.itsMaximumMissingForecasts)
{
}
ensemble& ensemble::operator=(const ensemble& other)
{
itsParam = other.itsParam;
itsExpectedEnsembleSize = other.itsExpectedEnsembleSize;
itsDesiredForecasts = other.itsDesiredForecasts;
itsForecasts = other.itsForecasts;
itsEnsembleType = other.itsEnsembleType;
itsMaximumMissingForecasts = other.itsMaximumMissingForecasts;
itsLogger = logger("ensemble");
return *this;
}
void ensemble::Fetch(std::shared_ptr<const plugin_configuration> config, const forecast_time& time,
const level& forecastLevel)
{
auto f = GET_PLUGIN(fetcher);
// We need to clear the forecasts vector every time we fetch to support ensembles
// with a rotating member scheme (GLAMEPS). This means that the index of the forecast
// doesn't reflect its position in the ensemble.
itsForecasts.clear();
int numMissingForecasts = 0;
for (const auto& desired : itsDesiredForecasts)
{
try
{
auto info = f->Fetch(config, time, forecastLevel, itsParam, desired, false);
itsForecasts.push_back(info);
}
catch (HPExceptionType& e)
{
if (e != kFileDataNotFound)
{
itsLogger.Fatal("Unable to proceed");
himan::Abort();
}
else
{
numMissingForecasts++;
}
}
}
VerifyValidForecastCount(numMissingForecasts);
}
void ensemble::VerifyValidForecastCount(int numMissingForecasts)
{
// This is for data that might not have all the fields for every timestep
if (itsMaximumMissingForecasts > 0)
{
if (numMissingForecasts >= itsMaximumMissingForecasts)
{
itsLogger.Fatal("maximum number of missing fields (" + std::to_string(itsMaximumMissingForecasts) +
") reached, aborting");
himan::Abort();
}
}
// Normally, we don't except any of the fields to be missing, but at this point
// we've already catched the exceptions
else
{
if (numMissingForecasts > 0)
{
itsLogger.Fatal("missing " + std::to_string(numMissingForecasts) + " of " +
std::to_string(itsMaximumMissingForecasts) + " allowed missing fields of data");
throw kFileDataNotFound;
}
}
itsLogger.Info("succesfully loaded " + std::to_string(itsForecasts.size()) + "/" +
std::to_string(itsDesiredForecasts.size()) + " fields");
}
void ensemble::ResetLocation()
{
for (auto& f : itsForecasts)
{
f->ResetLocation();
}
}
bool ensemble::FirstLocation()
{
for (auto& f : itsForecasts)
{
if (!f->FirstLocation())
{
return false;
}
}
return true;
}
bool ensemble::NextLocation()
{
for (auto& f : itsForecasts)
{
if (!f->NextLocation())
{
return false;
}
}
return true;
}
std::vector<double> ensemble::Values() const
{
std::vector<double> ret;
ret.reserve(Size());
std::for_each(itsForecasts.begin(), itsForecasts.end(), [&](const info_t& Info) { ret.emplace_back(Info->Value()); });
return ret;
}
std::vector<double> ensemble::SortedValues() const
{
std::vector<double> v = RemoveMissingValues(Values());
std::sort(v.begin(), v.end());
return v;
}
double ensemble::Mean() const
{
std::vector<double> v = RemoveMissingValues(Values());
if (v.size() == 0)
{
return MissingDouble();
}
return std::accumulate(v.begin(), v.end(), 0.0) / static_cast<double>(v.size());
}
double ensemble::Variance() const
{
std::vector<double> values = RemoveMissingValues(Values());
if (values.size() == 0)
{
return MissingDouble();
}
const double mean = std::accumulate(values.begin(), values.end(), 0.0) / static_cast<double>(values.size());
double sum = 0.0;
for (const auto& x : values)
{
const double t = x - mean;
sum += t * t;
}
return sum / static_cast<double>(values.size());
}
double ensemble::CentralMoment(int N) const
{
std::vector<double> v = RemoveMissingValues(Values());
double mu = Mean();
std::for_each(v.begin(), v.end(), [=](double& d) { d = std::pow(d - mu, N); });
return std::accumulate(v.begin(), v.end(), 0.0) / static_cast<double>(v.size());
}
HPEnsembleType ensemble::EnsembleType() const { return itsEnsembleType; }
size_t ensemble::Size() const { return itsForecasts.size(); }
size_t ensemble::ExpectedSize() const { return itsExpectedEnsembleSize; }
info_t ensemble::Forecast(size_t i)
{
if (itsForecasts.size() <= i)
{
throw kFileDataNotFound;
}
return itsForecasts[i];
}
} // namespace himan
<|endoftext|> |
<commit_before>// Author: Valeri Fine 21/01/2002
/****************************************************************************
** $Id$
**
** Copyright (C) 2002 by Valeri Fine. Brookhaven National Laboratory.
** All rights reserved.
**
** This file may be distributed under the terms of the Q Public License
** as defined by Trolltech AS of Norway and appearing in the file
** LICENSE.QPL included in the packaging of this file.
**
*****************************************************************************/
/////////////////////////////////////////////////////////////////////////////////
//
// TQtPadFont class is Qt QFont class with TAttText ROOT class interface
//
/////////////////////////////////////////////////////////////////////////////////
#include "TQtPadFont.h"
#include "TSystem.h"
#include "TMath.h"
#include <QFontMetrics>
#include <QDebug>
TString TQtPadFont::fgRomanFontName = "Times New Roman";
TString TQtPadFont::fgArialFontName = "Arial";
TString TQtPadFont::fgCourierFontName = "Courier New";
TString TQtPadFont::fgSymbolFontFamily= "Symbol";
//______________________________________________________________________________
static float CalibrateFont()
{
// Use the ROOT font with ID=1 to calibrate the current font on fly;
// Environment variable ROOTFONTFACTOR allows to set the factor manually
static float fontCalibFactor = -1;
if (fontCalibFactor < 0 ) {
const char * envFactor = gSystem->Getenv("ROOTFONTFACTOR");
bool ok=false;
if (envFactor && envFactor[0])
fontCalibFactor= QString(envFactor).toFloat(&ok);
if (!ok) {
TQtPadFont pattern;
pattern.SetTextFont(62);
int w,h;
QFontMetrics metrics(pattern);
w = metrics.width("This is a PX distribution");
h = metrics.height();
// X11 returns h = 12
// XFT returns h = 14
// WIN32 TTF returns h = 16
// Nimbus Roman returns h = 18
// Qt4 XFT h = 21
qDebug() << " Font metric w = " << w <<" h = "<< h
<< "points=" << pattern.pointSize()
<< "pixels=" << pattern.pixelSize()
<< pattern;
float f;
switch (h) {
case 12: f = 1.10; break;// it was f = 1.13 :-(;
case 14: f = 0.915; break;// it was f = 0.94 :-(;
case 16: f = 0.965; break;// to be tested yet
case 18: f = 0.92; break;// to be tested yet
case 20: f = 0.99; break;// to be tested yet
case 21: f = 0.90; break;// to be tested yet
default: f = 1.10; break;
}
fontCalibFactor = f;
}
}
return fontCalibFactor;
}
//______________________________________________________________________________
static inline float FontMagicFactor(float size)
{
// Adjust the font size to match that for Postscipt format
static float calibration =0;
if (calibration == 0) calibration = CalibrateFont();
return TMath::Max(calibration*size,Float_t(1.0));
}
//______________________________________________________________________________
TQtPadFont::TQtPadFont(): TAttText()
{fTextFont = -1;fTextSize = -1; }
//______________________________________________________________________________
void TQtPadFont::SetTextFont(const char *fontname, int italic_, int bold_)
{
//*-* mode : Option message
//*-* italic : Italic attribut of the TTF font
//*-* bold : Weight attribute of the TTF font
//*-* fontname : the name of True Type Font (TTF) to draw text.
//*-*
//*-* Set text font to specified name. This function returns 0 if
//*-* the specified font is found, 1 if not.
this->setWeight((long) bold_*10);
this->setItalic((Bool_t)italic_);
this->setFamily(fontname);
#if QT_VERSION >= 0x40000
if (!strcmp(fontname,RomanFontName())) {
this->setStyleHint(QFont::Serif);
} else if (!strcmp(fontname,ArialFontName())) {
this->setStyleHint(QFont::SansSerif);
} else if (!strcmp(fontname,CourierFontName())){
this->setStyleHint(QFont::TypeWriter);
}
this->setStyleStrategy(QFont::PreferDevice);
#if 0
qDebug() << "TQtPadFont::SetTextFont:" << fontname
<< this->lastResortFamily ()
<< this->lastResortFont ()
<< this->substitute (fontname)
<< "ROOT font number=" << fTextFont;
#endif
#endif
#if 0
qDebug() << "TGQt::SetTextFont font:" << fontname
<< " bold=" << bold_
<< " italic="<< italic_;
#endif
}
//______________________________________________________________________________
void TQtPadFont::SetTextFont(Font_t fontnumber)
{
//*-*-*-*-*-*-*-*-*-*-*-*-*Set current text font number*-*-*-*-*-*-*-*-*-*-*-*
//*-* ===========================
//*-* List of the currently supported fonts (screen and PostScript)
//*-* =============================================================
//*-* Font ID X11 Win32 TTF lfItalic lfWeight x 10
//*-* 1 : times-medium-i-normal "Times New Roman" 1 5
//*-* 2 : times-bold-r-normal "Times New Roman" 0 8
//*-* 3 : times-bold-i-normal "Times New Roman" 1 8
//*-* 4 : helvetica-medium-r-normal "Arial" 0 5
//*-* 5 : helvetica-medium-o-normal "Arial" 1 5
//*-* 6 : helvetica-bold-r-normal "Arial" 0 8
//*-* 7 : helvetica-bold-o-normal "Arial" 1 8
//*-* 8 : courier-medium-r-normal "Courier New" 0 5
//*-* 9 : courier-medium-o-normal "Courier New" 1 5
//*-* 10 : courier-bold-r-normal "Courier New" 0 8
//*-* 11 : courier-bold-o-normal "Courier New" 1 8
//*-* 12 : symbol-medium-r-normal "Symbol" 0 6
//*-* 13 : times-medium-r-normal "Times New Roman" 0 5
//*-* 14 : "Wingdings" 0 5
if ( (fTextFont == fontnumber) || (fontnumber <0) ) return;
TAttText::SetTextFont(fontnumber);
int it, bld;
const char *fontName = RomanFontName();
switch(fTextFont/10) {
case 1:
it = 1;
bld = 5;
fontName = RomanFontName();
break;
case 2:
it = 0;
bld = 8;
fontName = RomanFontName();
break;
case 3:
it = 1;
bld = 8;
fontName = RomanFontName();
break;
case 4:
it = 0;
bld = 5;
fontName = ArialFontName();
break;
case 5:
it = 1;
bld = 5;
fontName = ArialFontName();
break;
case 6:
it = 0;
bld = 8;
fontName = ArialFontName();
break;
case 7:
it = 1;
bld = 8;
fontName = ArialFontName();
break;
case 8:
it = 0;
bld = 5;
fontName = CourierFontName();
break;
case 9:
it = 1;
bld = 5;
fontName = CourierFontName();
break;
case 10:
it = 0;
bld = 8;
fontName = CourierFontName();
break;
case 11:
it = 1;
bld = 8;
fontName = CourierFontName();
break;
case 12:
it = 0;
bld = 5;
fontName = SymbolFontFamily();
break;
case 13:
it = 0;
bld = 5;
fontName = RomanFontName();
break;
case 14:
it = 0;
bld = 5;
fontName = "Wingdings";
break;
default:
it = 0;
bld = 5;
fontName = RomanFontName();
break;
}
SetTextFont(fontName, it, bld);
}
//______________________________________________________________________________
void TQtPadFont::SetTextSize(Float_t textsize)
{
//*-*-*-*-*-*-*-*-*-*-*-*-*Set current text size*-*-*-*-*-*-*-*-*-*-*-*-*-*-*
//*-* =====================
if ( fTextSize != textsize ) {
TAttText::SetTextSize(textsize);
if (fTextSize > 0) {
Int_t tsize =(Int_t)( textsize+0.5);
SetTextSizePixels(int(FontMagicFactor(tsize)));
}
}
}
//______________________________________________________________________________
void TQtPadFont::SetTextSizePixels(Int_t npixels)
{
// Set the text pixel size
TAttText::SetTextSizePixels(npixels);
this->setPixelSize(npixels);
}
//______________________________________________________________________________
const char *TQtPadFont::RomanFontName()
{
// Get the system name for the "Roman" font
return fgRomanFontName;
}
//______________________________________________________________________________
const char *TQtPadFont::ArialFontName()
{
// Get the system name for the "Arial" font
return fgArialFontName;
}
//______________________________________________________________________________
const char *TQtPadFont::CourierFontName()
{
// Get the system name for the "Courier" font
return fgCourierFontName;
}
//______________________________________________________________________________
const char *TQtPadFont::SymbolFontFamily()
{
// Get the system name for the "Symbol" font
return fgSymbolFontFamily;
}
//______________________________________________________________________________
void TQtPadFont::SetSymbolFontFamily(const char *symbolFnName)
{
// Set the system name for the "Symbol" font
fgSymbolFontFamily = symbolFnName; // we need the TString here !!!
}
//______________________________________________________________________________
void TQtPadFont::SetTextMaginfy(Float_t mgn)
{
//
// Scale the font accroding the inout mgn magnification factor
// mgn : magnification factor
// -------
// see: TVirtualX::DrawText(int x, int y, float angle, float mgn, const char *text, TVirtualX::ETextMode /*mode*/)
//
Int_t tsize = (Int_t)(fTextSize+0.5);
if (TMath::Abs(mgn-1) >0.05) this->setPixelSize(int(mgn*FontMagicFactor(tsize)));
}
<commit_msg>From Valeri Fine: Remove a confusing debug statement<commit_after>// Author: Valeri Fine 21/01/2002
/****************************************************************************
** $Id$
**
** Copyright (C) 2002 by Valeri Fine. Brookhaven National Laboratory.
** All rights reserved.
**
** This file may be distributed under the terms of the Q Public License
** as defined by Trolltech AS of Norway and appearing in the file
** LICENSE.QPL included in the packaging of this file.
**
*****************************************************************************/
/////////////////////////////////////////////////////////////////////////////////
//
// TQtPadFont class is Qt QFont class with TAttText ROOT class interface
//
/////////////////////////////////////////////////////////////////////////////////
#include "TQtPadFont.h"
#include "TSystem.h"
#include "TMath.h"
#include <QFontMetrics>
#include <QDebug>
TString TQtPadFont::fgRomanFontName = "Times New Roman";
TString TQtPadFont::fgArialFontName = "Arial";
TString TQtPadFont::fgCourierFontName = "Courier New";
TString TQtPadFont::fgSymbolFontFamily= "Symbol";
//______________________________________________________________________________
static float CalibrateFont()
{
// Use the ROOT font with ID=1 to calibrate the current font on fly;
// Environment variable ROOTFONTFACTOR allows to set the factor manually
static float fontCalibFactor = -1;
if (fontCalibFactor < 0 ) {
const char * envFactor = gSystem->Getenv("ROOTFONTFACTOR");
bool ok=false;
if (envFactor && envFactor[0])
fontCalibFactor= QString(envFactor).toFloat(&ok);
if (!ok) {
TQtPadFont pattern;
pattern.SetTextFont(62);
int w,h;
QFontMetrics metrics(pattern);
w = metrics.width("This is a PX distribution");
h = metrics.height();
// X11 returns h = 12
// XFT returns h = 14
// WIN32 TTF returns h = 16
// Nimbus Roman returns h = 18
// Qt4 XFT h = 21
#if 0
qDebug() << " Font metric w = " << w <<" h = "<< h
<< "points=" << pattern.pointSize()
<< "pixels=" << pattern.pixelSize()
<< pattern;
#endif
float f;
switch (h) {
case 12: f = 1.10; break;// it was f = 1.13 :-(;
case 14: f = 0.915; break;// it was f = 0.94 :-(;
case 16: f = 0.965; break;// to be tested yet
case 18: f = 0.92; break;// to be tested yet
case 20: f = 0.99; break;// to be tested yet
case 21: f = 0.90; break;// to be tested yet
default: f = 1.10; break;
}
fontCalibFactor = f;
}
}
return fontCalibFactor;
}
//______________________________________________________________________________
static inline float FontMagicFactor(float size)
{
// Adjust the font size to match that for Postscipt format
static float calibration =0;
if (calibration == 0) calibration = CalibrateFont();
return TMath::Max(calibration*size,Float_t(1.0));
}
//______________________________________________________________________________
TQtPadFont::TQtPadFont(): TAttText()
{fTextFont = -1;fTextSize = -1; }
//______________________________________________________________________________
void TQtPadFont::SetTextFont(const char *fontname, int italic_, int bold_)
{
//*-* mode : Option message
//*-* italic : Italic attribut of the TTF font
//*-* bold : Weight attribute of the TTF font
//*-* fontname : the name of True Type Font (TTF) to draw text.
//*-*
//*-* Set text font to specified name. This function returns 0 if
//*-* the specified font is found, 1 if not.
this->setWeight((long) bold_*10);
this->setItalic((Bool_t)italic_);
this->setFamily(fontname);
#if QT_VERSION >= 0x40000
if (!strcmp(fontname,RomanFontName())) {
this->setStyleHint(QFont::Serif);
} else if (!strcmp(fontname,ArialFontName())) {
this->setStyleHint(QFont::SansSerif);
} else if (!strcmp(fontname,CourierFontName())){
this->setStyleHint(QFont::TypeWriter);
}
this->setStyleStrategy(QFont::PreferDevice);
#if 0
qDebug() << "TQtPadFont::SetTextFont:" << fontname
<< this->lastResortFamily ()
<< this->lastResortFont ()
<< this->substitute (fontname)
<< "ROOT font number=" << fTextFont;
#endif
#endif
#if 0
qDebug() << "TGQt::SetTextFont font:" << fontname
<< " bold=" << bold_
<< " italic="<< italic_;
#endif
}
//______________________________________________________________________________
void TQtPadFont::SetTextFont(Font_t fontnumber)
{
//*-*-*-*-*-*-*-*-*-*-*-*-*Set current text font number*-*-*-*-*-*-*-*-*-*-*-*
//*-* ===========================
//*-* List of the currently supported fonts (screen and PostScript)
//*-* =============================================================
//*-* Font ID X11 Win32 TTF lfItalic lfWeight x 10
//*-* 1 : times-medium-i-normal "Times New Roman" 1 5
//*-* 2 : times-bold-r-normal "Times New Roman" 0 8
//*-* 3 : times-bold-i-normal "Times New Roman" 1 8
//*-* 4 : helvetica-medium-r-normal "Arial" 0 5
//*-* 5 : helvetica-medium-o-normal "Arial" 1 5
//*-* 6 : helvetica-bold-r-normal "Arial" 0 8
//*-* 7 : helvetica-bold-o-normal "Arial" 1 8
//*-* 8 : courier-medium-r-normal "Courier New" 0 5
//*-* 9 : courier-medium-o-normal "Courier New" 1 5
//*-* 10 : courier-bold-r-normal "Courier New" 0 8
//*-* 11 : courier-bold-o-normal "Courier New" 1 8
//*-* 12 : symbol-medium-r-normal "Symbol" 0 6
//*-* 13 : times-medium-r-normal "Times New Roman" 0 5
//*-* 14 : "Wingdings" 0 5
if ( (fTextFont == fontnumber) || (fontnumber <0) ) return;
TAttText::SetTextFont(fontnumber);
int it, bld;
const char *fontName = RomanFontName();
switch(fTextFont/10) {
case 1:
it = 1;
bld = 5;
fontName = RomanFontName();
break;
case 2:
it = 0;
bld = 8;
fontName = RomanFontName();
break;
case 3:
it = 1;
bld = 8;
fontName = RomanFontName();
break;
case 4:
it = 0;
bld = 5;
fontName = ArialFontName();
break;
case 5:
it = 1;
bld = 5;
fontName = ArialFontName();
break;
case 6:
it = 0;
bld = 8;
fontName = ArialFontName();
break;
case 7:
it = 1;
bld = 8;
fontName = ArialFontName();
break;
case 8:
it = 0;
bld = 5;
fontName = CourierFontName();
break;
case 9:
it = 1;
bld = 5;
fontName = CourierFontName();
break;
case 10:
it = 0;
bld = 8;
fontName = CourierFontName();
break;
case 11:
it = 1;
bld = 8;
fontName = CourierFontName();
break;
case 12:
it = 0;
bld = 5;
fontName = SymbolFontFamily();
break;
case 13:
it = 0;
bld = 5;
fontName = RomanFontName();
break;
case 14:
it = 0;
bld = 5;
fontName = "Wingdings";
break;
default:
it = 0;
bld = 5;
fontName = RomanFontName();
break;
}
SetTextFont(fontName, it, bld);
}
//______________________________________________________________________________
void TQtPadFont::SetTextSize(Float_t textsize)
{
//*-*-*-*-*-*-*-*-*-*-*-*-*Set current text size*-*-*-*-*-*-*-*-*-*-*-*-*-*-*
//*-* =====================
if ( fTextSize != textsize ) {
TAttText::SetTextSize(textsize);
if (fTextSize > 0) {
Int_t tsize =(Int_t)( textsize+0.5);
SetTextSizePixels(int(FontMagicFactor(tsize)));
}
}
}
//______________________________________________________________________________
void TQtPadFont::SetTextSizePixels(Int_t npixels)
{
// Set the text pixel size
TAttText::SetTextSizePixels(npixels);
this->setPixelSize(npixels);
}
//______________________________________________________________________________
const char *TQtPadFont::RomanFontName()
{
// Get the system name for the "Roman" font
return fgRomanFontName;
}
//______________________________________________________________________________
const char *TQtPadFont::ArialFontName()
{
// Get the system name for the "Arial" font
return fgArialFontName;
}
//______________________________________________________________________________
const char *TQtPadFont::CourierFontName()
{
// Get the system name for the "Courier" font
return fgCourierFontName;
}
//______________________________________________________________________________
const char *TQtPadFont::SymbolFontFamily()
{
// Get the system name for the "Symbol" font
return fgSymbolFontFamily;
}
//______________________________________________________________________________
void TQtPadFont::SetSymbolFontFamily(const char *symbolFnName)
{
// Set the system name for the "Symbol" font
fgSymbolFontFamily = symbolFnName; // we need the TString here !!!
}
//______________________________________________________________________________
void TQtPadFont::SetTextMaginfy(Float_t mgn)
{
//
// Scale the font accroding the inout mgn magnification factor
// mgn : magnification factor
// -------
// see: TVirtualX::DrawText(int x, int y, float angle, float mgn, const char *text, TVirtualX::ETextMode /*mode*/)
//
Int_t tsize = (Int_t)(fTextSize+0.5);
if (TMath::Abs(mgn-1) >0.05) this->setPixelSize(int(mgn*FontMagicFactor(tsize)));
}
<|endoftext|> |
<commit_before>//------------------------------------------------------------------------------
// CLING - the C++ LLVM-based InterpreterG :)
// version: $Id$
// author: Vassil Vassilev <[email protected]>
//------------------------------------------------------------------------------
#include "cling/Interpreter/ClangInternalState.h"
#include "clang/AST/ASTContext.h"
#include "clang/Lex/Preprocessor.h"
#include "clang/AST/RecursiveASTVisitor.h"
#include "clang/Basic/Builtins.h"
#include "clang/Basic/SourceManager.h"
#include "llvm/ADT/SmallString.h"
#include "llvm/IR/Module.h"
#include "llvm/Support/FileSystem.h"
#include "llvm/Support/Path.h"
#include "llvm/Support/raw_ostream.h"
#include "llvm/Support/Signals.h"
#include <cstdio>
#include <string>
#include <time.h>
using namespace clang;
namespace cling {
ClangInternalState::ClangInternalState(ASTContext& AC, Preprocessor& PP,
llvm::Module& M, const std::string& name)
: m_ASTContext(AC), m_Preprocessor(PP), m_Module(M), m_DiffCommand("diff -u ")
, m_Name(name) {
store();
}
ClangInternalState::~ClangInternalState() {
// cleanup the temporary files:
remove(m_LookupTablesFile.c_str());
remove(m_IncludedFilesFile.c_str());
remove(m_ASTFile.c_str());
remove(m_LLVMModuleFile.c_str());
remove(m_MacrosFile.c_str());
}
void ClangInternalState::store() {
m_LookupTablesOS.reset(createOutputFile("lookup", &m_LookupTablesFile));
m_IncludedFilesOS.reset(createOutputFile("included", &m_IncludedFilesFile));
m_ASTOS.reset(createOutputFile("ast", &m_ASTFile));
m_LLVMModuleOS.reset(createOutputFile("module", &m_LLVMModuleFile));
m_MacrosOS.reset(createOutputFile("macros", &m_MacrosFile));
printLookupTables(*m_LookupTablesOS.get(), m_ASTContext);
printIncludedFiles(*m_IncludedFilesOS.get(),
m_ASTContext.getSourceManager());
printAST(*m_ASTOS.get(), m_ASTContext);
printLLVMModule(*m_LLVMModuleOS.get(), m_Module);
printMacroDefinitions(*m_MacrosOS.get(), m_Preprocessor);
}
namespace {
std::string getCurrentTimeAsString() {
time_t rawtime;
struct tm * timeinfo;
char buffer [80];
time (&rawtime);
timeinfo = localtime (&rawtime);
strftime (buffer, 80, "%I_%M_%S", timeinfo);
return buffer;
}
}
// Copied with modifications from CompilerInstance.cpp
llvm::raw_fd_ostream*
ClangInternalState::createOutputFile(llvm::StringRef OutFile,
std::string *TempPathName/*=0*/,
bool RemoveFileOnSignal/*=true*/) {
llvm::OwningPtr<llvm::raw_fd_ostream> OS;
std::string OSFile;
llvm::SmallString<256> OutputPath;
llvm::sys::path::system_temp_directory(/*erasedOnReboot*/false, OutputPath);
// Only create the temporary if the parent directory exists (or create
// missing directories is true) and we can actually write to OutPath,
// otherwise we want to fail early.
llvm::SmallString<256> TempPath(OutputPath);
llvm::sys::fs::make_absolute(TempPath);
assert(llvm::sys::fs::is_directory(TempPath.str()) && "Must be a folder.");
// Create a temporary file.
llvm::sys::path::append(TempPath, OutFile);
TempPath += "-" + getCurrentTimeAsString();
TempPath += "-%%%%%%%%";
int fd;
if (llvm::sys::fs::createUniqueFile(TempPath.str(), fd, TempPath)
== llvm::errc::success) {
OS.reset(new llvm::raw_fd_ostream(fd, /*shouldClose=*/true));
OSFile = TempPath.str();
}
// Make sure the out stream file gets removed if we crash.
if (RemoveFileOnSignal)
llvm::sys::RemoveFileOnSignal(OSFile);
if (TempPathName)
*TempPathName = OSFile;
return OS.take();
}
void ClangInternalState::compare(ClangInternalState& other) {
std::string differences = "";
// Ignore the builtins
typedef llvm::SmallVector<const char*, 1024> Builtins;
Builtins builtinNames;
m_ASTContext.BuiltinInfo.GetBuiltinNames(builtinNames);
for (Builtins::iterator I = builtinNames.begin();
I != builtinNames.end();) {
if (llvm::StringRef(*I).startswith("__builtin"))
I = builtinNames.erase(I);
else
++I;
}
builtinNames.push_back(".*__builtin.*");
if (differentContent(m_LookupTablesFile, other.m_LookupTablesFile,
differences, &builtinNames)) {
llvm::errs() << "Differences in the lookup tables\n";
llvm::errs() << differences << "\n";
differences = "";
}
if (differentContent(m_IncludedFilesFile, other.m_IncludedFilesFile,
differences)) {
llvm::errs() << "Differences in the included files\n";
llvm::errs() << differences << "\n";
differences = "";
}
if (differentContent(m_ASTFile, other.m_ASTFile, differences)) {
llvm::errs() << "Differences in the AST \n";
llvm::errs() << differences << "\n";
differences = "";
}
if (differentContent(m_LLVMModuleFile, other.m_LLVMModuleFile, differences)){
llvm::errs() << "Differences in the llvm Module \n";
llvm::errs() << differences << "\n";
differences = "";
}
if (differentContent(m_MacrosFile, other.m_MacrosFile, differences)){
llvm::errs() << "Differences in the Macro Definitions \n";
llvm::errs() << differences << "\n";
differences = "";
}
}
bool ClangInternalState::differentContent(const std::string& file1,
const std::string& file2,
std::string& differences,
const llvm::SmallVectorImpl<const char*>* ignores/*=0*/) const {
std::string diffCall = m_DiffCommand;
if (ignores) {
for (size_t i = 0, e = ignores->size(); i < e; ++i) {
diffCall += " --ignore-matching-lines=\".*";
diffCall += (*ignores)[i];
diffCall += ".*\"";
}
}
FILE* pipe = popen((diffCall + " " + file1 + " " + file2).c_str() , "r");
assert(pipe && "Error creating the pipe");
assert(differences.empty() && "Must be empty");
char buffer[128];
while(!feof(pipe)) {
if(fgets(buffer, 128, pipe) != NULL)
differences += buffer;
}
pclose(pipe);
return !differences.empty();
}
class DumpLookupTables : public RecursiveASTVisitor<DumpLookupTables> {
private:
llvm::raw_ostream& m_OS;
public:
DumpLookupTables(llvm::raw_ostream& OS) : m_OS(OS) { }
bool VisitDecl(Decl* D) {
if (DeclContext* DC = dyn_cast<DeclContext>(D))
VisitDeclContext(DC);
return true;
}
bool VisitDeclContext(DeclContext* DC) {
DC->dumpLookups(m_OS);
return true;
}
};
void ClangInternalState::printLookupTables(llvm::raw_ostream& Out,
ASTContext& C) {
DumpLookupTables dumper(Out);
dumper.TraverseDecl(C.getTranslationUnitDecl());
}
void ClangInternalState::printIncludedFiles(llvm::raw_ostream& Out,
SourceManager& SM) {
for (clang::SourceManager::fileinfo_iterator I = SM.fileinfo_begin(),
E = SM.fileinfo_end(); I != E; ++I) {
const clang::SrcMgr::ContentCache &C = *I->second;
const clang::FileEntry *FE = C.OrigEntry;
// Our error recovery purges the cache of the FileEntry, but keeps
// the FileEntry's pointer so that if it was used by smb (like the
// SourceManager) it wouldn't be dangling. In that case we shouldn't
// print the FileName, because semantically it is not there.
if (!FE->getSize() && !FE->getModificationTime())
continue;
std::string fileName(FE->getName());
if (!(fileName.compare(0, 5, "/usr/") == 0 &&
fileName.find("/bits/") != std::string::npos)) {
Out << fileName << '\n';
}
}
}
void ClangInternalState::printAST(llvm::raw_ostream& Out, ASTContext& C) {
TranslationUnitDecl* TU = C.getTranslationUnitDecl();
unsigned Indentation = 0;
bool PrintInstantiation = false;
std::string ErrMsg;
clang::PrintingPolicy policy = C.getPrintingPolicy();
TU->print(Out, policy, Indentation, PrintInstantiation);
// TODO: For future when we relpace the bump allocation with slab.
//
//Out << "Allocated memory: " << C.getAllocatedMemory();
//Out << "Side table allocated memory: " << C.getSideTableAllocatedMemory();
Out.flush();
}
void ClangInternalState::printLLVMModule(llvm::raw_ostream& Out,
llvm::Module& M) {
M.print(Out, /*AssemblyAnnotationWriter*/ 0);
}
void ClangInternalState::printMacroDefinitions(llvm::raw_ostream& Out,
clang::Preprocessor& PP) {
for (clang::Preprocessor::macro_iterator I = PP.macro_begin(),
E = PP.macro_end(); I != E; ++I) {
const MacroInfo* MI = (*I).second->getMacroInfo();
PP.DumpMacro(*MI);
}
}
} // end namespace cling
<commit_msg>Print macro to ostream instead of llvm::errs().<commit_after>//------------------------------------------------------------------------------
// CLING - the C++ LLVM-based InterpreterG :)
// version: $Id$
// author: Vassil Vassilev <[email protected]>
//------------------------------------------------------------------------------
#include "cling/Interpreter/ClangInternalState.h"
#include "clang/AST/ASTContext.h"
#include "clang/Lex/Preprocessor.h"
#include "clang/AST/RecursiveASTVisitor.h"
#include "clang/Basic/Builtins.h"
#include "clang/Basic/SourceManager.h"
#include "llvm/ADT/SmallString.h"
#include "llvm/IR/Module.h"
#include "llvm/Support/FileSystem.h"
#include "llvm/Support/Path.h"
#include "llvm/Support/raw_ostream.h"
#include "llvm/Support/Signals.h"
#include <cstdio>
#include <string>
#include <time.h>
using namespace clang;
namespace cling {
ClangInternalState::ClangInternalState(ASTContext& AC, Preprocessor& PP,
llvm::Module& M, const std::string& name)
: m_ASTContext(AC), m_Preprocessor(PP), m_Module(M), m_DiffCommand("diff -u ")
, m_Name(name) {
store();
}
ClangInternalState::~ClangInternalState() {
// cleanup the temporary files:
remove(m_LookupTablesFile.c_str());
remove(m_IncludedFilesFile.c_str());
remove(m_ASTFile.c_str());
remove(m_LLVMModuleFile.c_str());
remove(m_MacrosFile.c_str());
}
void ClangInternalState::store() {
m_LookupTablesOS.reset(createOutputFile("lookup", &m_LookupTablesFile));
m_IncludedFilesOS.reset(createOutputFile("included", &m_IncludedFilesFile));
m_ASTOS.reset(createOutputFile("ast", &m_ASTFile));
m_LLVMModuleOS.reset(createOutputFile("module", &m_LLVMModuleFile));
m_MacrosOS.reset(createOutputFile("macros", &m_MacrosFile));
printLookupTables(*m_LookupTablesOS.get(), m_ASTContext);
printIncludedFiles(*m_IncludedFilesOS.get(),
m_ASTContext.getSourceManager());
printAST(*m_ASTOS.get(), m_ASTContext);
printLLVMModule(*m_LLVMModuleOS.get(), m_Module);
printMacroDefinitions(*m_MacrosOS.get(), m_Preprocessor);
}
namespace {
std::string getCurrentTimeAsString() {
time_t rawtime;
struct tm * timeinfo;
char buffer [80];
time (&rawtime);
timeinfo = localtime (&rawtime);
strftime (buffer, 80, "%I_%M_%S", timeinfo);
return buffer;
}
}
// Copied with modifications from CompilerInstance.cpp
llvm::raw_fd_ostream*
ClangInternalState::createOutputFile(llvm::StringRef OutFile,
std::string *TempPathName/*=0*/,
bool RemoveFileOnSignal/*=true*/) {
llvm::OwningPtr<llvm::raw_fd_ostream> OS;
std::string OSFile;
llvm::SmallString<256> OutputPath;
llvm::sys::path::system_temp_directory(/*erasedOnReboot*/false, OutputPath);
// Only create the temporary if the parent directory exists (or create
// missing directories is true) and we can actually write to OutPath,
// otherwise we want to fail early.
llvm::SmallString<256> TempPath(OutputPath);
llvm::sys::fs::make_absolute(TempPath);
assert(llvm::sys::fs::is_directory(TempPath.str()) && "Must be a folder.");
// Create a temporary file.
llvm::sys::path::append(TempPath, OutFile);
TempPath += "-" + getCurrentTimeAsString();
TempPath += "-%%%%%%%%";
int fd;
if (llvm::sys::fs::createUniqueFile(TempPath.str(), fd, TempPath)
== llvm::errc::success) {
OS.reset(new llvm::raw_fd_ostream(fd, /*shouldClose=*/true));
OSFile = TempPath.str();
}
// Make sure the out stream file gets removed if we crash.
if (RemoveFileOnSignal)
llvm::sys::RemoveFileOnSignal(OSFile);
if (TempPathName)
*TempPathName = OSFile;
return OS.take();
}
void ClangInternalState::compare(ClangInternalState& other) {
std::string differences = "";
// Ignore the builtins
typedef llvm::SmallVector<const char*, 1024> Builtins;
Builtins builtinNames;
m_ASTContext.BuiltinInfo.GetBuiltinNames(builtinNames);
for (Builtins::iterator I = builtinNames.begin();
I != builtinNames.end();) {
if (llvm::StringRef(*I).startswith("__builtin"))
I = builtinNames.erase(I);
else
++I;
}
builtinNames.push_back(".*__builtin.*");
if (differentContent(m_LookupTablesFile, other.m_LookupTablesFile,
differences, &builtinNames)) {
llvm::errs() << "Differences in the lookup tables\n";
llvm::errs() << differences << "\n";
differences = "";
}
if (differentContent(m_IncludedFilesFile, other.m_IncludedFilesFile,
differences)) {
llvm::errs() << "Differences in the included files\n";
llvm::errs() << differences << "\n";
differences = "";
}
if (differentContent(m_ASTFile, other.m_ASTFile, differences)) {
llvm::errs() << "Differences in the AST \n";
llvm::errs() << differences << "\n";
differences = "";
}
if (differentContent(m_LLVMModuleFile, other.m_LLVMModuleFile, differences)){
llvm::errs() << "Differences in the llvm Module \n";
llvm::errs() << differences << "\n";
differences = "";
}
if (differentContent(m_MacrosFile, other.m_MacrosFile, differences)){
llvm::errs() << "Differences in the Macro Definitions \n";
llvm::errs() << differences << "\n";
differences = "";
}
}
bool ClangInternalState::differentContent(const std::string& file1,
const std::string& file2,
std::string& differences,
const llvm::SmallVectorImpl<const char*>* ignores/*=0*/) const {
std::string diffCall = m_DiffCommand;
if (ignores) {
for (size_t i = 0, e = ignores->size(); i < e; ++i) {
diffCall += " --ignore-matching-lines=\".*";
diffCall += (*ignores)[i];
diffCall += ".*\"";
}
}
FILE* pipe = popen((diffCall + " " + file1 + " " + file2).c_str() , "r");
assert(pipe && "Error creating the pipe");
assert(differences.empty() && "Must be empty");
char buffer[128];
while(!feof(pipe)) {
if(fgets(buffer, 128, pipe) != NULL)
differences += buffer;
}
pclose(pipe);
return !differences.empty();
}
class DumpLookupTables : public RecursiveASTVisitor<DumpLookupTables> {
private:
llvm::raw_ostream& m_OS;
public:
DumpLookupTables(llvm::raw_ostream& OS) : m_OS(OS) { }
bool VisitDecl(Decl* D) {
if (DeclContext* DC = dyn_cast<DeclContext>(D))
VisitDeclContext(DC);
return true;
}
bool VisitDeclContext(DeclContext* DC) {
DC->dumpLookups(m_OS);
return true;
}
};
void ClangInternalState::printLookupTables(llvm::raw_ostream& Out,
ASTContext& C) {
DumpLookupTables dumper(Out);
dumper.TraverseDecl(C.getTranslationUnitDecl());
}
void ClangInternalState::printIncludedFiles(llvm::raw_ostream& Out,
SourceManager& SM) {
for (clang::SourceManager::fileinfo_iterator I = SM.fileinfo_begin(),
E = SM.fileinfo_end(); I != E; ++I) {
const clang::SrcMgr::ContentCache &C = *I->second;
const clang::FileEntry *FE = C.OrigEntry;
// Our error recovery purges the cache of the FileEntry, but keeps
// the FileEntry's pointer so that if it was used by smb (like the
// SourceManager) it wouldn't be dangling. In that case we shouldn't
// print the FileName, because semantically it is not there.
if (!FE->getSize() && !FE->getModificationTime())
continue;
std::string fileName(FE->getName());
if (!(fileName.compare(0, 5, "/usr/") == 0 &&
fileName.find("/bits/") != std::string::npos)) {
Out << fileName << '\n';
}
}
}
void ClangInternalState::printAST(llvm::raw_ostream& Out, ASTContext& C) {
TranslationUnitDecl* TU = C.getTranslationUnitDecl();
unsigned Indentation = 0;
bool PrintInstantiation = false;
std::string ErrMsg;
clang::PrintingPolicy policy = C.getPrintingPolicy();
TU->print(Out, policy, Indentation, PrintInstantiation);
// TODO: For future when we relpace the bump allocation with slab.
//
//Out << "Allocated memory: " << C.getAllocatedMemory();
//Out << "Side table allocated memory: " << C.getSideTableAllocatedMemory();
Out.flush();
}
void ClangInternalState::printLLVMModule(llvm::raw_ostream& Out,
llvm::Module& M) {
M.print(Out, /*AssemblyAnnotationWriter*/ 0);
}
void ClangInternalState::printMacroDefinitions(llvm::raw_ostream& Out,
clang::Preprocessor& PP) {
for (clang::Preprocessor::macro_iterator I = PP.macro_begin(),
E = PP.macro_end(); I != E; ++I) {
const MacroInfo* MI = (*I).second->getMacroInfo();
PP.printMacro(*MI, Out);
}
}
} // end namespace cling
<|endoftext|> |
<commit_before>#include "encoder.h"
#include "reader_util.h"
#include "scope_guard.h"
#include <exception>
#ifdef LCF_SUPPORT_ICU
# include <unicode/ucsdet.h>
# include <unicode/ucnv.h>
#else
# ifdef _MSC_VER
# error MSVC builds require ICU
# endif
#endif
#ifdef _WIN32
# define WIN32_LEAN_AND_MEAN
# ifndef NOMINMAX
# define NOMINMAX
# endif
# include <windows.h>
#else
# ifndef LCF_SUPPORT_ICU
# include <iconv.h>
# endif
# include <locale>
#endif
#if defined(__MORPHOS__) || defined(__amigaos4__)
#define ICONV_CONST const
#endif
Encoder::Encoder(std::string encoding)
: _encoding(std::move(encoding))
{
Init();
}
Encoder::~Encoder() {
Reset();
}
void Encoder::Encode(std::string& str) {
if (_encoding.empty() || str.empty()) {
return;
}
Convert(str, _conv_runtime, _conv_storage);
}
void Encoder::Decode(std::string& str) {
if (_encoding.empty() || str.empty()) {
return;
}
Convert(str, _conv_storage, _conv_runtime);
}
void Encoder::Init() {
if (_encoding.empty()) {
return;
}
auto code_page = atoi(_encoding.c_str());
const auto& storage_encoding = code_page > 0
? ReaderUtil::CodepageToEncoding(code_page)
: _encoding;
#ifdef LCF_SUPPORT_ICU
auto status = U_ZERO_ERROR;
constexpr auto runtime_encoding = "UTF-8";
auto conv_runtime = ucnv_open(runtime_encoding, &status);
if (conv_runtime == nullptr) {
fprintf(stderr, "liblcf: ucnv_open() error for encoding \"%s\": %s\n", runtime_encoding, u_errorName(status));
throw std::runtime_error("ucnv_open() failed");
}
status = U_ZERO_ERROR;
auto sg = makeScopeGuard([&]() { ucnv_close(conv_runtime); });
auto conv_storage = ucnv_open(storage_encoding.c_str(), &status);
if (conv_storage == nullptr) {
fprintf(stderr, "liblcf: ucnv_open() error for dest encoding \"%s\": %s\n", storage_encoding.c_str(), u_errorName(status));
throw std::runtime_error("ucnv_open() failed");
}
sg.Dismiss();
_conv_runtime = conv_runtime;
_conv_storage = conv_storage;
#else
_conv_runtime = const_cast<char*>("UTF-8");
_conv_storage = const_cast<char*>(_encoding.c_str());
#endif
}
void Encoder::Reset() {
#ifdef LCF_SUPPORT_ICU
auto* conv = reinterpret_cast<UConverter*>(_conv_runtime);
if (conv) ucnv_close(conv);
conv = reinterpret_cast<UConverter*>(_conv_storage);
if (conv) ucnv_close(conv);
#endif
}
void Encoder::Convert(std::string& str, void* conv_dst_void, void* conv_src_void) {
#ifdef LCF_SUPPORT_ICU
const auto& src = str;
auto* conv_dst = reinterpret_cast<UConverter*>(conv_dst_void);
auto* conv_src = reinterpret_cast<UConverter*>(conv_src_void);
auto status = U_ZERO_ERROR;
_buffer.resize(src.size() * 4);
const auto* src_p = src.c_str();
auto* dst_p = _buffer.data();
ucnv_convertEx(conv_dst, conv_src,
&dst_p, dst_p + _buffer.size(),
&src_p, src_p + src.size(),
nullptr, nullptr, nullptr, nullptr,
true, true,
&status);
if (U_FAILURE(status)) {
fprintf(stderr, "liblcf: ucnv_convertEx() error when encoding \"%s\": %s\n", src.c_str(), u_errorName(status));
_buffer.clear();
}
str.assign(_buffer.data(), dst_p);
return;
#else
auto* conv_dst = reinterpret_cast<const char*>(conv_dst_void);
auto* conv_src = reinterpret_cast<const char*>(conv_src_void);
iconv_t cd = iconv_open(conv_dst, conv_src);
if (cd == (iconv_t)-1)
return;
char *src = &str.front();
size_t src_left = str.size();
size_t dst_size = str.size() * 5 + 10;
_buffer.resize(dst_size);
char *dst = _buffer.data();
size_t dst_left = dst_size;
# ifdef ICONV_CONST
char ICONV_CONST *p = src;
# else
char *p = src;
# endif
char *q = dst;
size_t status = iconv(cd, &p, &src_left, &q, &dst_left);
iconv_close(cd);
if (status == (size_t) -1 || src_left > 0) {
str.clear();
return;
}
*q++ = '\0';
str.assign(dst, dst_size - dst_left);
return;
#endif
}
<commit_msg>Don't try to encode utf-8 to utf-8<commit_after>#include "encoder.h"
#include "reader_util.h"
#include "scope_guard.h"
#include <exception>
#ifdef LCF_SUPPORT_ICU
# include <unicode/ucsdet.h>
# include <unicode/ucnv.h>
#else
# ifdef _MSC_VER
# error MSVC builds require ICU
# endif
#endif
#ifdef _WIN32
# define WIN32_LEAN_AND_MEAN
# ifndef NOMINMAX
# define NOMINMAX
# endif
# include <windows.h>
#else
# ifndef LCF_SUPPORT_ICU
# include <iconv.h>
# endif
# include <locale>
#endif
#if defined(__MORPHOS__) || defined(__amigaos4__)
#define ICONV_CONST const
#endif
static std::string filterUtf8Compatible(std::string enc) {
#ifdef LCF_SUPPORT_ICU
if (ucnv_compareNames(enc.c_str(), "UTF-8") == 0) {
return "";
}
#endif
return enc;
}
Encoder::Encoder(std::string encoding)
: _encoding(filterUtf8Compatible(std::move(encoding)))
{
Init();
}
Encoder::~Encoder() {
Reset();
}
void Encoder::Encode(std::string& str) {
if (_encoding.empty() || str.empty()) {
return;
}
Convert(str, _conv_runtime, _conv_storage);
}
void Encoder::Decode(std::string& str) {
if (_encoding.empty() || str.empty()) {
return;
}
Convert(str, _conv_storage, _conv_runtime);
}
void Encoder::Init() {
if (_encoding.empty()) {
return;
}
auto code_page = atoi(_encoding.c_str());
const auto& storage_encoding = code_page > 0
? ReaderUtil::CodepageToEncoding(code_page)
: _encoding;
#ifdef LCF_SUPPORT_ICU
auto status = U_ZERO_ERROR;
constexpr auto runtime_encoding = "UTF-8";
auto conv_runtime = ucnv_open(runtime_encoding, &status);
if (conv_runtime == nullptr) {
fprintf(stderr, "liblcf: ucnv_open() error for encoding \"%s\": %s\n", runtime_encoding, u_errorName(status));
throw std::runtime_error("ucnv_open() failed");
}
status = U_ZERO_ERROR;
auto sg = makeScopeGuard([&]() { ucnv_close(conv_runtime); });
auto conv_storage = ucnv_open(storage_encoding.c_str(), &status);
if (conv_storage == nullptr) {
fprintf(stderr, "liblcf: ucnv_open() error for dest encoding \"%s\": %s\n", storage_encoding.c_str(), u_errorName(status));
throw std::runtime_error("ucnv_open() failed");
}
sg.Dismiss();
_conv_runtime = conv_runtime;
_conv_storage = conv_storage;
#else
_conv_runtime = const_cast<char*>("UTF-8");
_conv_storage = const_cast<char*>(_encoding.c_str());
#endif
}
void Encoder::Reset() {
#ifdef LCF_SUPPORT_ICU
auto* conv = reinterpret_cast<UConverter*>(_conv_runtime);
if (conv) ucnv_close(conv);
conv = reinterpret_cast<UConverter*>(_conv_storage);
if (conv) ucnv_close(conv);
#endif
}
void Encoder::Convert(std::string& str, void* conv_dst_void, void* conv_src_void) {
#ifdef LCF_SUPPORT_ICU
const auto& src = str;
auto* conv_dst = reinterpret_cast<UConverter*>(conv_dst_void);
auto* conv_src = reinterpret_cast<UConverter*>(conv_src_void);
auto status = U_ZERO_ERROR;
_buffer.resize(src.size() * 4);
const auto* src_p = src.c_str();
auto* dst_p = _buffer.data();
ucnv_convertEx(conv_dst, conv_src,
&dst_p, dst_p + _buffer.size(),
&src_p, src_p + src.size(),
nullptr, nullptr, nullptr, nullptr,
true, true,
&status);
if (U_FAILURE(status)) {
fprintf(stderr, "liblcf: ucnv_convertEx() error when encoding \"%s\": %s\n", src.c_str(), u_errorName(status));
_buffer.clear();
}
str.assign(_buffer.data(), dst_p);
return;
#else
auto* conv_dst = reinterpret_cast<const char*>(conv_dst_void);
auto* conv_src = reinterpret_cast<const char*>(conv_src_void);
iconv_t cd = iconv_open(conv_dst, conv_src);
if (cd == (iconv_t)-1)
return;
char *src = &str.front();
size_t src_left = str.size();
size_t dst_size = str.size() * 5 + 10;
_buffer.resize(dst_size);
char *dst = _buffer.data();
size_t dst_left = dst_size;
# ifdef ICONV_CONST
char ICONV_CONST *p = src;
# else
char *p = src;
# endif
char *q = dst;
size_t status = iconv(cd, &p, &src_left, &q, &dst_left);
iconv_close(cd);
if (status == (size_t) -1 || src_left > 0) {
str.clear();
return;
}
*q++ = '\0';
str.assign(dst, dst_size - dst_left);
return;
#endif
}
<|endoftext|> |
<commit_before>//===-- lib/MC/Disassembler.cpp - Disassembler Public C Interface ---------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "Disassembler.h"
#include "llvm-c/Disassembler.h"
#include "llvm/MC/MCAsmInfo.h"
#include "llvm/MC/MCContext.h"
#include "llvm/MC/MCDisassembler.h"
#include "llvm/MC/MCInst.h"
#include "llvm/MC/MCInstPrinter.h"
#include "llvm/MC/MCRegisterInfo.h"
#include "llvm/Support/MemoryObject.h"
#include "llvm/Support/TargetRegistry.h"
#include "llvm/Support/ErrorHandling.h"
namespace llvm {
class Target;
} // namespace llvm
using namespace llvm;
// LLVMCreateDisasm() creates a disassembler for the TripleName. Symbolic
// disassembly is supported by passing a block of information in the DisInfo
// parameter and specifying the TagType and callback functions as described in
// the header llvm-c/Disassembler.h . The pointer to the block and the
// functions can all be passed as NULL. If successful, this returns a
// disassembler context. If not, it returns NULL.
//
LLVMDisasmContextRef LLVMCreateDisasm(const char *TripleName, void *DisInfo,
int TagType, LLVMOpInfoCallback GetOpInfo,
LLVMSymbolLookupCallback SymbolLookUp) {
// Get the target.
std::string Error;
const Target *TheTarget = TargetRegistry::lookupTarget(TripleName, Error);
assert(TheTarget && "Unable to create target!");
// Get the assembler info needed to setup the MCContext.
const MCAsmInfo *MAI = TheTarget->createMCAsmInfo(TripleName);
assert(MAI && "Unable to create target asm info!");
const MCRegisterInfo *MRI = TheTarget->createMCRegInfo(TripleName);
assert(MRI && "Unable to create target register info!");
// Package up features to be passed to target/subtarget
std::string FeaturesStr;
std::string CPU;
const MCSubtargetInfo *STI = TheTarget->createMCSubtargetInfo(TripleName, CPU,
FeaturesStr);
assert(STI && "Unable to create subtarget info!");
// Set up the MCContext for creating symbols and MCExpr's.
MCContext *Ctx = new MCContext(*MAI, *MRI, 0);
assert(Ctx && "Unable to create MCContext!");
// Set up disassembler.
MCDisassembler *DisAsm = TheTarget->createMCDisassembler(*STI);
assert(DisAsm && "Unable to create disassembler!");
DisAsm->setupForSymbolicDisassembly(GetOpInfo, SymbolLookUp, DisInfo, Ctx);
// Set up the instruction printer.
int AsmPrinterVariant = MAI->getAssemblerDialect();
MCInstPrinter *IP = TheTarget->createMCInstPrinter(AsmPrinterVariant,
*MAI, *STI);
assert(IP && "Unable to create instruction printer!");
LLVMDisasmContext *DC = new LLVMDisasmContext(TripleName, DisInfo, TagType,
GetOpInfo, SymbolLookUp,
TheTarget, MAI, MRI,
Ctx, DisAsm, IP);
assert(DC && "Allocation failure!");
return DC;
}
//
// LLVMDisasmDispose() disposes of the disassembler specified by the context.
//
void LLVMDisasmDispose(LLVMDisasmContextRef DCR){
LLVMDisasmContext *DC = (LLVMDisasmContext *)DCR;
delete DC;
}
namespace {
//
// The memory object created by LLVMDisasmInstruction().
//
class DisasmMemoryObject : public MemoryObject {
uint8_t *Bytes;
uint64_t Size;
uint64_t BasePC;
public:
DisasmMemoryObject(uint8_t *bytes, uint64_t size, uint64_t basePC) :
Bytes(bytes), Size(size), BasePC(basePC) {}
uint64_t getBase() const { return BasePC; }
uint64_t getExtent() { return Size; }
int readByte(uint64_t Addr, uint8_t *Byte) {
if (Addr - BasePC >= Size)
return -1;
*Byte = Bytes[Addr - BasePC];
return 0;
}
};
} // end anonymous namespace
//
// LLVMDisasmInstruction() disassembles a single instruction using the
// disassembler context specified in the parameter DC. The bytes of the
// instruction are specified in the parameter Bytes, and contains at least
// BytesSize number of bytes. The instruction is at the address specified by
// the PC parameter. If a valid instruction can be disassembled its string is
// returned indirectly in OutString which whos size is specified in the
// parameter OutStringSize. This function returns the number of bytes in the
// instruction or zero if there was no valid instruction. If this function
// returns zero the caller will have to pick how many bytes they want to step
// over by printing a .byte, .long etc. to continue.
//
size_t LLVMDisasmInstruction(LLVMDisasmContextRef DCR, uint8_t *Bytes,
uint64_t BytesSize, uint64_t PC, char *OutString,
size_t OutStringSize){
LLVMDisasmContext *DC = (LLVMDisasmContext *)DCR;
// Wrap the pointer to the Bytes, BytesSize and PC in a MemoryObject.
DisasmMemoryObject MemoryObject(Bytes, BytesSize, PC);
uint64_t Size;
MCInst Inst;
const MCDisassembler *DisAsm = DC->getDisAsm();
MCInstPrinter *IP = DC->getIP();
MCDisassembler::DecodeStatus S;
S = DisAsm->getInstruction(Inst, Size, MemoryObject, PC,
/*REMOVE*/ nulls(), DC->CommentStream);
switch (S) {
case MCDisassembler::Fail:
case MCDisassembler::SoftFail:
// FIXME: Do something different for soft failure modes?
return 0;
case MCDisassembler::Success: {
DC->CommentStream.flush();
StringRef Comments = DC->CommentsToEmit.str();
SmallVector<char, 64> InsnStr;
raw_svector_ostream OS(InsnStr);
IP->printInst(&Inst, OS, Comments);
OS.flush();
// Tell the comment stream that the vector changed underneath it.
DC->CommentsToEmit.clear();
DC->CommentStream.resync();
assert(OutStringSize != 0 && "Output buffer cannot be zero size");
size_t OutputSize = std::min(OutStringSize-1, InsnStr.size());
std::memcpy(OutString, InsnStr.data(), OutputSize);
OutString[OutputSize] = '\0'; // Terminate string.
return Size;
}
}
llvm_unreachable("Invalid DecodeStatus!");
}
<commit_msg>Put back the initializing the targets in the disassembler API with a comment as to why this is needed. This broke the darwin's otool(1) program. This change was made in r144385.<commit_after>//===-- lib/MC/Disassembler.cpp - Disassembler Public C Interface ---------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "Disassembler.h"
#include "llvm-c/Disassembler.h"
#include "llvm/MC/MCAsmInfo.h"
#include "llvm/MC/MCContext.h"
#include "llvm/MC/MCDisassembler.h"
#include "llvm/MC/MCInst.h"
#include "llvm/MC/MCInstPrinter.h"
#include "llvm/MC/MCRegisterInfo.h"
#include "llvm/Support/MemoryObject.h"
#include "llvm/Support/TargetRegistry.h"
#include "llvm/Support/TargetSelect.h"
#include "llvm/Support/ErrorHandling.h"
namespace llvm {
class Target;
} // namespace llvm
using namespace llvm;
// LLVMCreateDisasm() creates a disassembler for the TripleName. Symbolic
// disassembly is supported by passing a block of information in the DisInfo
// parameter and specifying the TagType and callback functions as described in
// the header llvm-c/Disassembler.h . The pointer to the block and the
// functions can all be passed as NULL. If successful, this returns a
// disassembler context. If not, it returns NULL.
//
LLVMDisasmContextRef LLVMCreateDisasm(const char *TripleName, void *DisInfo,
int TagType, LLVMOpInfoCallback GetOpInfo,
LLVMSymbolLookupCallback SymbolLookUp) {
// Initialize targets and assembly printers/parsers.
// FIXME: Clients are responsible for initializing the targets. And this
// would be done by calling routines in "llvm-c/Target.h" which are static
// line functions. But the current use of LLVMCreateDisasm() is to dynamically
// load libLTO with ldopen() and then lookup the symbols using dlsym().
// And since these initialize routines are static that does not work which
// is why the call to them in this 'C' library API was added back.
llvm::InitializeAllTargetInfos();
llvm::InitializeAllTargetMCs();
llvm::InitializeAllAsmParsers();
llvm::InitializeAllDisassemblers();
// Get the target.
std::string Error;
const Target *TheTarget = TargetRegistry::lookupTarget(TripleName, Error);
assert(TheTarget && "Unable to create target!");
// Get the assembler info needed to setup the MCContext.
const MCAsmInfo *MAI = TheTarget->createMCAsmInfo(TripleName);
assert(MAI && "Unable to create target asm info!");
const MCRegisterInfo *MRI = TheTarget->createMCRegInfo(TripleName);
assert(MRI && "Unable to create target register info!");
// Package up features to be passed to target/subtarget
std::string FeaturesStr;
std::string CPU;
const MCSubtargetInfo *STI = TheTarget->createMCSubtargetInfo(TripleName, CPU,
FeaturesStr);
assert(STI && "Unable to create subtarget info!");
// Set up the MCContext for creating symbols and MCExpr's.
MCContext *Ctx = new MCContext(*MAI, *MRI, 0);
assert(Ctx && "Unable to create MCContext!");
// Set up disassembler.
MCDisassembler *DisAsm = TheTarget->createMCDisassembler(*STI);
assert(DisAsm && "Unable to create disassembler!");
DisAsm->setupForSymbolicDisassembly(GetOpInfo, SymbolLookUp, DisInfo, Ctx);
// Set up the instruction printer.
int AsmPrinterVariant = MAI->getAssemblerDialect();
MCInstPrinter *IP = TheTarget->createMCInstPrinter(AsmPrinterVariant,
*MAI, *STI);
assert(IP && "Unable to create instruction printer!");
LLVMDisasmContext *DC = new LLVMDisasmContext(TripleName, DisInfo, TagType,
GetOpInfo, SymbolLookUp,
TheTarget, MAI, MRI,
Ctx, DisAsm, IP);
assert(DC && "Allocation failure!");
return DC;
}
//
// LLVMDisasmDispose() disposes of the disassembler specified by the context.
//
void LLVMDisasmDispose(LLVMDisasmContextRef DCR){
LLVMDisasmContext *DC = (LLVMDisasmContext *)DCR;
delete DC;
}
namespace {
//
// The memory object created by LLVMDisasmInstruction().
//
class DisasmMemoryObject : public MemoryObject {
uint8_t *Bytes;
uint64_t Size;
uint64_t BasePC;
public:
DisasmMemoryObject(uint8_t *bytes, uint64_t size, uint64_t basePC) :
Bytes(bytes), Size(size), BasePC(basePC) {}
uint64_t getBase() const { return BasePC; }
uint64_t getExtent() { return Size; }
int readByte(uint64_t Addr, uint8_t *Byte) {
if (Addr - BasePC >= Size)
return -1;
*Byte = Bytes[Addr - BasePC];
return 0;
}
};
} // end anonymous namespace
//
// LLVMDisasmInstruction() disassembles a single instruction using the
// disassembler context specified in the parameter DC. The bytes of the
// instruction are specified in the parameter Bytes, and contains at least
// BytesSize number of bytes. The instruction is at the address specified by
// the PC parameter. If a valid instruction can be disassembled its string is
// returned indirectly in OutString which whos size is specified in the
// parameter OutStringSize. This function returns the number of bytes in the
// instruction or zero if there was no valid instruction. If this function
// returns zero the caller will have to pick how many bytes they want to step
// over by printing a .byte, .long etc. to continue.
//
size_t LLVMDisasmInstruction(LLVMDisasmContextRef DCR, uint8_t *Bytes,
uint64_t BytesSize, uint64_t PC, char *OutString,
size_t OutStringSize){
LLVMDisasmContext *DC = (LLVMDisasmContext *)DCR;
// Wrap the pointer to the Bytes, BytesSize and PC in a MemoryObject.
DisasmMemoryObject MemoryObject(Bytes, BytesSize, PC);
uint64_t Size;
MCInst Inst;
const MCDisassembler *DisAsm = DC->getDisAsm();
MCInstPrinter *IP = DC->getIP();
MCDisassembler::DecodeStatus S;
S = DisAsm->getInstruction(Inst, Size, MemoryObject, PC,
/*REMOVE*/ nulls(), DC->CommentStream);
switch (S) {
case MCDisassembler::Fail:
case MCDisassembler::SoftFail:
// FIXME: Do something different for soft failure modes?
return 0;
case MCDisassembler::Success: {
DC->CommentStream.flush();
StringRef Comments = DC->CommentsToEmit.str();
SmallVector<char, 64> InsnStr;
raw_svector_ostream OS(InsnStr);
IP->printInst(&Inst, OS, Comments);
OS.flush();
// Tell the comment stream that the vector changed underneath it.
DC->CommentsToEmit.clear();
DC->CommentStream.resync();
assert(OutStringSize != 0 && "Output buffer cannot be zero size");
size_t OutputSize = std::min(OutStringSize-1, InsnStr.size());
std::memcpy(OutString, InsnStr.data(), OutputSize);
OutString[OutputSize] = '\0'; // Terminate string.
return Size;
}
}
llvm_unreachable("Invalid DecodeStatus!");
}
<|endoftext|> |
<commit_before>/*
* Copyright (C) 2015 Luke San Antonio
* All rights reserved.
*/
#include "sdl_helper.h"
#include "common/log.h"
namespace redc
{
SDL_Init_Lock::SDL_Init_Lock(SDL_Init_Lock&& l) : window(l.window),
gl_context(l.gl_context)
{
l.window = nullptr;
l.gl_context = nullptr;
}
SDL_Init_Lock& SDL_Init_Lock::operator=(SDL_Init_Lock&& l)
{
window = l.window;
gl_context = l.gl_context;
l.window = nullptr;
l.gl_context = nullptr;
return *this;
}
SDL_Init_Lock::~SDL_Init_Lock()
{
// If we don't have both for any reason, don't bother deallocating either.
if(window && gl_context)
{
// That way, if we accidentally partially move we won't do the aggressive
// SDL_Quit call.
SDL_GL_DeleteContext(gl_context);
SDL_DestroyWindow(window);
SDL_Quit();
}
}
SDL_Init_Lock init_sdl(std::string title, Vec<int> res, bool fullscreen,
bool vsync)
{
// Initialize SDL
if(SDL_Init(SDL_INIT_VIDEO))
{
log_e("Failed to init SDL");
return {};
}
SDL_version version;
SDL_GetVersion(&version);
log_i("Initialized SDL %.%.%", version.major, version.minor, version.patch);
// Initialize window
auto flags = SDL_WINDOW_OPENGL | SDL_WINDOW_RESIZABLE;
if(fullscreen) flags |= SDL_WINDOW_FULLSCREEN;
SDL_Init_Lock ret;
ret.window = SDL_CreateWindow(title.c_str(), SDL_WINDOWPOS_UNDEFINED,
SDL_WINDOWPOS_UNDEFINED, res.x, res.y,
flags);
if(!ret.window)
{
SDL_Quit();
log_e("Failed to initialize SDL for resolution %x%", res.x, res.y);
return ret;
}
// Initialize OpenGL context
SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 3);
SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 3);
SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK,
SDL_GL_CONTEXT_PROFILE_CORE);
SDL_GL_SetAttribute(SDL_GL_CONTEXT_FLAGS,
SDL_GL_CONTEXT_FORWARD_COMPATIBLE_FLAG);
if(vsync) SDL_GL_SetSwapInterval(1);
else SDL_GL_SetSwapInterval(0);
ret.gl_context = SDL_GL_CreateContext(ret.window);
SDL_GL_MakeCurrent(ret.window, ret.gl_context);
gladLoadGLLoader((GLADloadproc) SDL_GL_GetProcAddress);
int opengl_maj, opengl_min;
glGetIntegerv(GL_MAJOR_VERSION, &opengl_maj);
glGetIntegerv(GL_MINOR_VERSION, &opengl_min);
log_i("OpenGL core profile %.%", opengl_maj, opengl_min);
return ret;
}
}
<commit_msg>Properly set vsync and log on error<commit_after>/*
* Copyright (C) 2015 Luke San Antonio
* All rights reserved.
*/
#include "sdl_helper.h"
#include "common/log.h"
namespace redc
{
SDL_Init_Lock::SDL_Init_Lock(SDL_Init_Lock&& l) : window(l.window),
gl_context(l.gl_context)
{
l.window = nullptr;
l.gl_context = nullptr;
}
SDL_Init_Lock& SDL_Init_Lock::operator=(SDL_Init_Lock&& l)
{
window = l.window;
gl_context = l.gl_context;
l.window = nullptr;
l.gl_context = nullptr;
return *this;
}
SDL_Init_Lock::~SDL_Init_Lock()
{
// If we don't have both for any reason, don't bother deallocating either.
if(window && gl_context)
{
// That way, if we accidentally partially move we won't do the aggressive
// SDL_Quit call.
SDL_GL_DeleteContext(gl_context);
SDL_DestroyWindow(window);
SDL_Quit();
}
}
SDL_Init_Lock init_sdl(std::string title, Vec<int> res, bool fullscreen,
bool vsync)
{
// Initialize SDL
if(SDL_Init(SDL_INIT_VIDEO))
{
log_e("Failed to init SDL");
return {};
}
SDL_version version;
SDL_GetVersion(&version);
log_i("Initialized SDL %.%.%", version.major, version.minor, version.patch);
// Initialize window
auto flags = SDL_WINDOW_OPENGL | SDL_WINDOW_RESIZABLE;
if(fullscreen) flags |= SDL_WINDOW_FULLSCREEN;
SDL_Init_Lock ret;
ret.window = SDL_CreateWindow(title.c_str(), SDL_WINDOWPOS_UNDEFINED,
SDL_WINDOWPOS_UNDEFINED, res.x, res.y,
flags);
if(!ret.window)
{
SDL_Quit();
log_e("Failed to initialize SDL for resolution %x%", res.x, res.y);
return ret;
}
// Initialize OpenGL context
SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 3);
SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 3);
SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK,
SDL_GL_CONTEXT_PROFILE_CORE);
SDL_GL_SetAttribute(SDL_GL_CONTEXT_FLAGS,
SDL_GL_CONTEXT_FORWARD_COMPATIBLE_FLAG);
ret.gl_context = SDL_GL_CreateContext(ret.window);
SDL_GL_MakeCurrent(ret.window, ret.gl_context);
// Set vsync setting
int sync_interval = 0;
if(vsync) sync_interval = 1;
if(SDL_GL_SetSwapInterval(sync_interval) == -1)
{
// Shit, failed to set that
log_w("Failed to set swap interval: %", SDL_GetError());
}
gladLoadGLLoader((GLADloadproc) SDL_GL_GetProcAddress);
int opengl_maj, opengl_min;
glGetIntegerv(GL_MAJOR_VERSION, &opengl_maj);
glGetIntegerv(GL_MINOR_VERSION, &opengl_min);
log_i("OpenGL core profile %.%", opengl_maj, opengl_min);
return ret;
}
}
<|endoftext|> |
<commit_before>#include <iostream>
#include <vector>
#include <math.h>
using namespace std;
vector <char> characters = {'a', 'b', 'c', 'd', 'e',
'f', 'g', 'h', 'i', 'j',
'k', 'l', 'm', 'n', 'o',
'p', 'q', 'r', 's', 't',
'u', 'v', 'w', 'x', 'y',
'z', 'A', 'B', 'C', 'D',
'E', 'F', 'G', 'H', 'I',
'J', 'K', 'L', 'M', 'N',
'O', 'P', 'Q', 'R', 'S',
'T', 'U', 'V', 'W', 'X',
'Y', 'Z', '1', '2', '3',
'4', '5', '6', '7', '8',
'9', '0', '`', '~', '!',
'@', '#', '$', '%', '^',
'&', '&', '*', '(', ')',
'-', '_', '=', '+', '[',
'{', ']', '}', '\\', '|',
';', ':', '\'', '"', ',',
'<', '.', '>', '/', '?',
' '};
int get_d (int e, int t)
{
vector <int> e_multiples;
for (int i = 1; i <= t; i++)
{
e_multiples.push_back(e * i);
}
//for (int i = 0; i < e_multiples.size(); i++)
//{
// cout << e_multiples.at(i) << " ";
//}
//cout << endl;
for (int i = 1; i <= t; i++)
{
for (int j = 0; j < e_multiples.size(); j++)
{
//cout << (t * i) + 1 << endl;
if ((t * i) + 1 == e_multiples.at(j))
{
return j + 1;
}
}
}
}
int find_index (char a)
{
for (int i = 0; i < characters.size(); i++)
{
if (a == characters.at(i))
{
return i;
}
}
}
int encrypt (int m, int e, int n)
{
int c = 1;
for (int i = 0; i < (e / 2); i++)
{
c *= ((m * m) % n);
c %= n;
//cout << "c = " << c << endl;
}
if (e % 2 == 1)
{
c *= m;
}
return c;
}
int main(int argc, const char * argv[])
{
int p, q, n, totient, e, d;
do {
cout << "please enter a prime number p" << endl;
cin >> p; //assumes p is prime
cout << "please enter different prime number q" << endl;
cin >> q; //assumes q is prime and different than p
n = p * q;
cout << "n = " << n << endl;
if (n <= characters.size())
{
cout << "please choose larger p and q" << endl;
}
} while (n <= characters.size());
totient = (p - 1) * (q - 1);
cout << "totient = " << totient << endl;
cout << "choose a number e that is relatively prime to the totient" << endl;
cin >> e; //assumes e is entered correctly
d = get_d(e, totient);
cout << "d = " << d << endl;
string input;
cout << "Enter a sentence you would like to encrypt: " << endl;
cin.ignore();
getline(cin, input);
string encrypted;
for (int i = 0; i < input.size(); i++)
{
int m = find_index(input.at(i));
//cout << "m = " << m + 2 << endl;
encrypted += to_string(encrypt(m + 2, e, n)); //m+2 so that the number 0 or 1 is never exponentiated
//cout << "encrypted = " << encrypted << endl;
encrypted += " ";
}
return 0;
}
<commit_msg>modified output<commit_after>#include <iostream>
#include <vector>
#include <math.h>
using namespace std;
vector <char> characters = {'a', 'b', 'c', 'd', 'e',
'f', 'g', 'h', 'i', 'j',
'k', 'l', 'm', 'n', 'o',
'p', 'q', 'r', 's', 't',
'u', 'v', 'w', 'x', 'y',
'z', 'A', 'B', 'C', 'D',
'E', 'F', 'G', 'H', 'I',
'J', 'K', 'L', 'M', 'N',
'O', 'P', 'Q', 'R', 'S',
'T', 'U', 'V', 'W', 'X',
'Y', 'Z', '1', '2', '3',
'4', '5', '6', '7', '8',
'9', '0', '`', '~', '!',
'@', '#', '$', '%', '^',
'&', '&', '*', '(', ')',
'-', '_', '=', '+', '[',
'{', ']', '}', '\\', '|',
';', ':', '\'', '"', ',',
'<', '.', '>', '/', '?',
' '};
int get_d (int e, int t)
{
vector <int> e_multiples;
for (int i = 1; i <= t; i++)
{
e_multiples.push_back(e * i);
}
//for (int i = 0; i < e_multiples.size(); i++)
//{
// cout << e_multiples.at(i) << " ";
//}
//cout << endl;
for (int i = 1; i <= t; i++)
{
for (int j = 0; j < e_multiples.size(); j++)
{
//cout << (t * i) + 1 << endl;
if ((t * i) + 1 == e_multiples.at(j))
{
return j + 1;
}
}
}
}
int find_index (char a)
{
for (int i = 0; i < characters.size(); i++)
{
if (a == characters.at(i))
{
return i;
}
}
}
int encrypt (int m, int e, int n)
{
int c = 1;
for (int i = 0; i < (e / 2); i++)
{
c *= ((m * m) % n);
c %= n;
//cout << "c = " << c << endl;
}
if (e % 2 == 1)
{
c *= m;
}
return c;
}
int main(int argc, const char * argv[])
{
int p, q, n, totient, e, d;
do {
cout << "please enter a prime number p" << endl;
cin >> p; //assumes p is prime
cout << "please enter different prime number q" << endl;
cin >> q; //assumes q is prime and different than p
n = p * q;
cout << "n = " << n << endl;
if (n <= characters.size())
{
cout << "please choose larger p and q" << endl;
}
} while (n <= characters.size());
totient = (p - 1) * (q - 1);
cout << "totient = " << totient << endl;
cout << "choose a number e that is relatively prime to the totient" << endl;
cin >> e; //assumes e is entered correctly
d = get_d(e, totient);
cout << "d = " << d << endl;
string input;
cout << "Enter a sentence you would like to encrypt: " << endl;
cin.ignore();
getline(cin, input);
string encrypted;
for (int i = 0; i < input.size(); i++)
{
int m = find_index(input.at(i));
//cout << "m = " << m + 2 << endl;
encrypted += to_string(encrypt(m + 2, e, n)); //m+2 so that the number 0 or 1 is never exponentiated
//cout << "encrypted = " << encrypted << endl;
encrypted += " ";
}
//cout << "your sentence encrypted: " << endl;
cout << encrypted << endl;
return 0;
}
<|endoftext|> |
<commit_before>/*
* Copyright (C) 2015 deipi.com LLC and contributors. All rights reserved.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to
* deal in the Software without restriction, including without limitation the
* rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
* sell copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
* IN THE SOFTWARE.
*/
#include "endpoint.h"
#include "length.h"
#include <iostream>
#include <limits.h>
#include <unistd.h>
Node local_node;
char *normalize_path(const char * src, char * dst)
{
int levels = 0;
char * ret = dst;
for (int i = 0; *src && i < PATH_MAX; i++) {
char ch = *src++;
if (ch == '.' && (levels || dst == ret || *(dst - 1) == '/' )) {
*dst++ = ch;
levels++;
} else if (ch == '/') {
while (levels && dst > ret) {
if (*--dst == '/') levels -= 1;
}
if (dst == ret || *(dst - 1) != '/') {
*dst++ = ch;
}
} else {
*dst++ = ch;
levels = 0;
}
}
*dst++ = '\0';
return ret;
}
std::string Node::serialise() const
{
std::string node_str;
if (!name.empty()) {
node_str.append(encode_length(addr.sin_addr.s_addr));
node_str.append(encode_length(http_port));
node_str.append(encode_length(binary_port));
node_str.append(serialise_string(name));
}
return node_str;
}
size_t Node::unserialise(const char **p, const char *end)
{
size_t length;
const char *ptr = *p;
if ((length = decode_length(&ptr, end, false)) == -1) {
return -1;
}
addr.sin_addr.s_addr = (int)length;
if ((length = decode_length(&ptr, end, false)) == -1) {
return -1;
}
http_port = (int)length;
if ((length = decode_length(&ptr, end, false)) == -1) {
return -1;
}
binary_port = (int)length;
name.clear();
if (unserialise_string(name, &ptr, end) == -1 || name.empty()) {
return -1;
}
*p = ptr;
return end - ptr;
}
size_t Node::unserialise(const std::string &s)
{
const char *ptr = s.data();
return unserialise(&ptr, ptr + s.size());
}
Endpoint::Endpoint()
: mastery_level(-1) { }
Endpoint::Endpoint(const std::string &uri_, const Node *node_, long long mastery_level_, std::string node_name_)
: node_name(node_name_),
mastery_level(mastery_level_)
{
std::string uri(uri_);
char actualpath[PATH_MAX + 1];
std::string base(getcwd(actualpath, PATH_MAX));
normalize_path(base.c_str(), actualpath);
base = actualpath;
std::string protocol = slice_before(uri, "://");
if (protocol.empty()) {
protocol = "file";
}
search = slice_after(uri, "?");
path = slice_after(uri, "/");
std::string userpass = slice_before(uri, "@");
password = slice_after(userpass, ":");
user = userpass;
std::string portstring = slice_after(uri, ":");
port = atoi(portstring.c_str());
if (protocol.empty() || protocol == "file") {
if (path.empty()) {
path = uri;
} else {
path = uri + "/" + path;
}
port = 0;
search = "";
password = "";
user = "";
} else {
host = uri;
if (!port) port = XAPIAND_BINARY_SERVERPORT;
}
path = actualpath + path;
normalize_path(path.c_str(), actualpath);
path = actualpath;
if (path.substr(0, base.size()) == base) {
path.erase(0, base.size());
} else {
path = "";
}
if (protocol == "file") {
if (!node_) {
node_ = &local_node;
}
protocol = "xapian";
host = node_->host();
port = node_->binary_port;
}
}
std::string Endpoint::slice_after(std::string &subject, std::string delimiter) {
size_t delimiter_location = subject.find(delimiter);
size_t delimiter_length = delimiter.length();
std::string output = "";
if (delimiter_location < std::string::npos) {
size_t start = delimiter_location + delimiter_length;
output = subject.substr(start, subject.length() - start);
subject = subject.substr(0, delimiter_location);
}
return output;
}
std::string Endpoint::slice_before(std::string &subject, std::string delimiter) {
size_t delimiter_location = subject.find(delimiter);
size_t delimiter_length = delimiter.length();
std::string output = "";
if (delimiter_location < std::string::npos) {
size_t start = delimiter_location + delimiter_length;
output = subject.substr(0, delimiter_location);
subject = subject.substr(start, subject.length() - start);
}
return output;
}
std::string Endpoint::as_string() const {
std::string ret;
if (path.empty()) {
return ret;
}
ret += "xapian://";
if (!user.empty() || !password.empty()) {
ret += user;
if (!password.empty()) {
ret += ":" + password;
}
ret += "@";
}
ret += host;
if (port > 0) {
char port_[100];
snprintf(port_, sizeof(port_), "%d", port);
ret += ":";
ret += port_;
}
if (!host.empty() || port > 0) {
ret += "/";
}
ret += path;
if (!search.empty()) {
ret += "?" + search;
}
return ret;
}
bool Endpoint::operator<(const Endpoint & other) const
{
return as_string() < other.as_string();
}
size_t Endpoint::hash() const {
std::hash<Endpoint> hash_fn;
return hash_fn(*this);
}
std::string Endpoints::as_string() const {
std::string ret;
endpoints_set_t::const_iterator j(cbegin());
for (int i=0; j != cend(); j++, i++) {
if (i) ret += ";";
ret += (*j).as_string();
}
return ret;
}
size_t Endpoints::hash() const {
std::hash<Endpoints> hash_fn;
return hash_fn(*this);
}
bool operator == (Endpoint const& le, Endpoint const& re)
{
std::hash<Endpoint> hash_fn;
return hash_fn(le) == hash_fn(re);
}
bool operator == (Endpoints const& le, Endpoints const& re)
{
std::hash<Endpoints> hash_fn;
return hash_fn(le) == hash_fn(re);
}
size_t std::hash<Endpoint>::operator()(const Endpoint &e) const
{
std::hash<std::string> hash_fn;
return hash_fn(e.as_string());
}
size_t std::hash<Endpoints>::operator()(const Endpoints &e) const
{
size_t hash = 0;
std::hash<Endpoint> hash_fn;
endpoints_set_t::const_iterator j(e.cbegin());
for (int i = 0; j != e.cend(); j++, i++) {
hash ^= hash_fn(*j);
}
return hash;
}
<commit_msg>Fix warning (type in unserialise)<commit_after>/*
* Copyright (C) 2015 deipi.com LLC and contributors. All rights reserved.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to
* deal in the Software without restriction, including without limitation the
* rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
* sell copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
* IN THE SOFTWARE.
*/
#include "endpoint.h"
#include "length.h"
#include <iostream>
#include <limits.h>
#include <unistd.h>
Node local_node;
char *normalize_path(const char * src, char * dst)
{
int levels = 0;
char * ret = dst;
for (int i = 0; *src && i < PATH_MAX; i++) {
char ch = *src++;
if (ch == '.' && (levels || dst == ret || *(dst - 1) == '/' )) {
*dst++ = ch;
levels++;
} else if (ch == '/') {
while (levels && dst > ret) {
if (*--dst == '/') levels -= 1;
}
if (dst == ret || *(dst - 1) != '/') {
*dst++ = ch;
}
} else {
*dst++ = ch;
levels = 0;
}
}
*dst++ = '\0';
return ret;
}
std::string Node::serialise() const
{
std::string node_str;
if (!name.empty()) {
node_str.append(encode_length(addr.sin_addr.s_addr));
node_str.append(encode_length(http_port));
node_str.append(encode_length(binary_port));
node_str.append(serialise_string(name));
}
return node_str;
}
ssize_t Node::unserialise(const char **p, const char *end)
{
ssize_t length;
const char *ptr = *p;
if ((length = decode_length(&ptr, end, false)) == -1) {
return -1;
}
addr.sin_addr.s_addr = (int)length;
if ((length = decode_length(&ptr, end, false)) == -1) {
return -1;
}
http_port = (int)length;
if ((length = decode_length(&ptr, end, false)) == -1) {
return -1;
}
binary_port = (int)length;
name.clear();
if (unserialise_string(name, &ptr, end) == -1 || name.empty()) {
return -1;
}
*p = ptr;
return end - ptr;
}
ssize_t Node::unserialise(const std::string &s)
{
const char *ptr = s.data();
return unserialise(&ptr, ptr + s.size());
}
Endpoint::Endpoint()
: mastery_level(-1) { }
Endpoint::Endpoint(const std::string &uri_, const Node *node_, long long mastery_level_, std::string node_name_)
: node_name(node_name_),
mastery_level(mastery_level_)
{
std::string uri(uri_);
char actualpath[PATH_MAX + 1];
std::string base(getcwd(actualpath, PATH_MAX));
normalize_path(base.c_str(), actualpath);
base = actualpath;
std::string protocol = slice_before(uri, "://");
if (protocol.empty()) {
protocol = "file";
}
search = slice_after(uri, "?");
path = slice_after(uri, "/");
std::string userpass = slice_before(uri, "@");
password = slice_after(userpass, ":");
user = userpass;
std::string portstring = slice_after(uri, ":");
port = atoi(portstring.c_str());
if (protocol.empty() || protocol == "file") {
if (path.empty()) {
path = uri;
} else {
path = uri + "/" + path;
}
port = 0;
search = "";
password = "";
user = "";
} else {
host = uri;
if (!port) port = XAPIAND_BINARY_SERVERPORT;
}
path = actualpath + path;
normalize_path(path.c_str(), actualpath);
path = actualpath;
if (path.substr(0, base.size()) == base) {
path.erase(0, base.size());
} else {
path = "";
}
if (protocol == "file") {
if (!node_) {
node_ = &local_node;
}
protocol = "xapian";
host = node_->host();
port = node_->binary_port;
}
}
std::string Endpoint::slice_after(std::string &subject, std::string delimiter) {
size_t delimiter_location = subject.find(delimiter);
size_t delimiter_length = delimiter.length();
std::string output = "";
if (delimiter_location < std::string::npos) {
size_t start = delimiter_location + delimiter_length;
output = subject.substr(start, subject.length() - start);
subject = subject.substr(0, delimiter_location);
}
return output;
}
std::string Endpoint::slice_before(std::string &subject, std::string delimiter) {
size_t delimiter_location = subject.find(delimiter);
size_t delimiter_length = delimiter.length();
std::string output = "";
if (delimiter_location < std::string::npos) {
size_t start = delimiter_location + delimiter_length;
output = subject.substr(0, delimiter_location);
subject = subject.substr(start, subject.length() - start);
}
return output;
}
std::string Endpoint::as_string() const {
std::string ret;
if (path.empty()) {
return ret;
}
ret += "xapian://";
if (!user.empty() || !password.empty()) {
ret += user;
if (!password.empty()) {
ret += ":" + password;
}
ret += "@";
}
ret += host;
if (port > 0) {
char port_[100];
snprintf(port_, sizeof(port_), "%d", port);
ret += ":";
ret += port_;
}
if (!host.empty() || port > 0) {
ret += "/";
}
ret += path;
if (!search.empty()) {
ret += "?" + search;
}
return ret;
}
bool Endpoint::operator<(const Endpoint & other) const
{
return as_string() < other.as_string();
}
size_t Endpoint::hash() const {
std::hash<Endpoint> hash_fn;
return hash_fn(*this);
}
std::string Endpoints::as_string() const {
std::string ret;
endpoints_set_t::const_iterator j(cbegin());
for (int i=0; j != cend(); j++, i++) {
if (i) ret += ";";
ret += (*j).as_string();
}
return ret;
}
size_t Endpoints::hash() const {
std::hash<Endpoints> hash_fn;
return hash_fn(*this);
}
bool operator == (Endpoint const& le, Endpoint const& re)
{
std::hash<Endpoint> hash_fn;
return hash_fn(le) == hash_fn(re);
}
bool operator == (Endpoints const& le, Endpoints const& re)
{
std::hash<Endpoints> hash_fn;
return hash_fn(le) == hash_fn(re);
}
size_t std::hash<Endpoint>::operator()(const Endpoint &e) const
{
std::hash<std::string> hash_fn;
return hash_fn(e.as_string());
}
size_t std::hash<Endpoints>::operator()(const Endpoints &e) const
{
size_t hash = 0;
std::hash<Endpoint> hash_fn;
endpoints_set_t::const_iterator j(e.cbegin());
for (int i = 0; j != e.cend(); j++, i++) {
hash ^= hash_fn(*j);
}
return hash;
}
<|endoftext|> |
<commit_before>#include "serializer.h"
#include <cmath>
#include <cstdint>
#include <cstdlib>
#include <limits>
namespace rapscallion {
void serializer<std::uint_least64_t>::write(Serializer& s, std::uint_least64_t value) {
while (value >= 0x80) {
s.addByte((uint8_t)(value & 0x7F) | 0x80);
value >>= 7;
}
s.addByte((uint8_t)value);
}
void serializer<long>::write(Serializer& s, const long v) {
std::uint_least64_t val = (std::abs(v) << 1) | (v < 0 ? 1 : 0);
serializer<std::uint_least64_t>::write(s, val);
}
void serializer<int>::write(Serializer& s, const int v) {
serializer<long>::write(s, v);
}
void serializer<std::string>::write(Serializer& s, const std::string& value) {
serializer<std::uint_least64_t>::write(s, value.size());
for (auto& c : value) s.addByte(c);
}
void serializer<bool>::write(Serializer& s, const bool b) {
serializer<std::uint_least64_t>::write(s, b ? 1 : 0);
}
namespace {
enum Type {
// First position of enum, because it is zero, must be covered with a value for which the sign doesn't matter
NaN,
Infinity,
Zero,
Normal
};
struct float_repr {
// Can fit an exponent of 32-2=20 bits, can support octuple-precision IEEE754 floats
std::int_least32_t exponent;
// Can support double precision IEEE754 floats (quadruple requires 112 bits, octuple 236 bits)
std::uint_least64_t fraction;
// One bit reserved for sign bit
static constexpr unsigned fraction_bits = 63 - 1;
bool is_negative;
Type type;
};
auto bitreverse(std::uint_least64_t b) -> decltype(b)
{
b = ((b & 0xFFFFFFFF00000000ULL) >> 32) | ((b & 0x00000000FFFFFFFFULL) << 32);
b = ((b & 0xFFFF0000FFFF0000ULL) >> 16) | ((b & 0x0000FFFF0000FFFFULL) << 16);
b = ((b & 0xFF00FF00FF00FF00ULL) >> 8) | ((b & 0x00FF00FF00FF00FFULL) << 8);
b = ((b & 0xF0F0F0F0F0F0F0F0ULL) >> 4) | ((b & 0x0F0F0F0F0F0F0F0FULL) << 4);
b = ((b & 0xCCCCCCCCCCCCCCCCULL) >> 2) | ((b & 0x3333333333333333ULL) << 2);
b = ((b & 0xAAAAAAAAAAAAAAAAULL) >> 1) | ((b & 0x5555555555555555ULL) << 1);
return b;
}
}
template <>
struct serializer<float_repr> {
static void write(Serializer& s, float_repr const &b) {
// Using multiplication to avoid bit shifting a signed integer
switch(b.type) {
default:
{
serializer<decltype(+b.exponent)>::write(s, b.is_negative ? -b.type : b.type);
}
break;
case Normal:
{
const decltype(b.exponent) exponent
= b.exponent * 2 + (b.exponent < 0 ? -b.is_negative : b.is_negative);
const decltype(b.fraction) reversed_fraction
= bitreverse(b.fraction);
serializer<decltype(+exponent)>::write(s, exponent < 0 ? exponent - 2 : exponent + 3);
serializer<decltype(+b.fraction)>::write(s, reversed_fraction);
}
break;
};
}
static float_repr read(Deserializer& s) {
float_repr result;
auto exponent = serializer<decltype(result.exponent)>::read(s);
if (exponent < 3 && exponent >= -2) {
result.is_negative = (exponent < 0);
result.type = (Type)std::abs(exponent);
} else {
exponent = (exponent < 0) ? exponent + 2 : exponent - 3;
result.is_negative = !!((exponent/ 1) % 2);
result.type = Normal;
result.exponent = exponent / 2;
const auto reversed_fraction = serializer<decltype(result.fraction)>::read(s);
result.fraction = bitreverse(reversed_fraction);
}
return result;
}
};
void serializer<double>::write(Serializer& s, double const b) {
switch (std::fpclassify(b)) {
case FP_ZERO:
serializer<float_repr>::write(s, { 0, 0, !!std::signbit(b), Zero });
break;
case FP_INFINITE:
serializer<float_repr>::write(s, { 0, 0, !!std::signbit(b), Infinity });
break;
case FP_NAN:
// The bit reversal is to ensure the most efficient encoding can be used
serializer<float_repr>::write(s, { 0, 0, false, NaN });
break;
case FP_NORMAL:
case FP_SUBNORMAL:
float_repr repr;
repr.type = Normal;
repr.is_negative = !!std::signbit(b);
// Make the fraction a positive integer
repr.fraction = std::ldexp(std::abs(std::frexp(b, &repr.exponent)), repr.fraction_bits);
serializer<decltype(repr)>::write(s, repr);
break;
}
}
double serializer<double>::read(Deserializer& s) {
const auto repr = serializer<float_repr>::read(s);
switch(repr.type) {
case Zero:
return (repr.is_negative ? -0.0 : 0.0);
case Infinity:
return repr.is_negative ? -std::numeric_limits<double>::infinity() : std::numeric_limits<double>::infinity();
case NaN:
return std::numeric_limits<double>::quiet_NaN();
default:
return (repr.is_negative ? -1.0 : 1.0) * std::ldexp(static_cast<double>(repr.fraction), repr.exponent - repr.fraction_bits);
}
}
void serializer<float>::write(Serializer& s, float const b) {
serializer<double>::write(s, b);
}
float serializer<float>::read(Deserializer& s) {
return serializer<double>::read(s);
}
std::uint_least64_t serializer<std::uint_least64_t>::read(Deserializer& s) {
std::uint_least64_t val = 0,
offs = 0,
b = s.getByte();
while (b & 0x80) {
val |= (b & 0x7F) << offs;
offs += 7;
b = s.getByte();
}
val |= b << offs;
return val;
}
long serializer<long>::read(Deserializer& s) {
const auto val = serializer<std::uint_least64_t>::read(s);
auto value = static_cast<long>(val >> 1);
if (val & 1) value = -value;
return value;
}
int serializer<int>::read(Deserializer& s) {
return serializer<long>::read(s);
}
std::string serializer<std::string>::read(Deserializer& s) {
const auto length = serializer<std::uint_least64_t>::read(s);
const uint8_t* ptr = s.ptr;
const uint8_t* end = ptr + length;
if (end > s.end)
throw parse_exception("buffer underrun");
s.ptr = end;
return std::string(reinterpret_cast<const char*>(ptr), length);
}
bool serializer<bool>::read(Deserializer& s) {
return serializer<std::uint_least64_t>::read(s) > 0;
}
}
<commit_msg>Don't leave space for sign bit in fraction<commit_after>#include "serializer.h"
#include <cmath>
#include <cstdint>
#include <cstdlib>
#include <limits>
namespace rapscallion {
void serializer<std::uint_least64_t>::write(Serializer& s, std::uint_least64_t value) {
while (value >= 0x80) {
s.addByte((uint8_t)(value & 0x7F) | 0x80);
value >>= 7;
}
s.addByte((uint8_t)value);
}
void serializer<long>::write(Serializer& s, const long v) {
std::uint_least64_t val = (std::abs(v) << 1) | (v < 0 ? 1 : 0);
serializer<std::uint_least64_t>::write(s, val);
}
void serializer<int>::write(Serializer& s, const int v) {
serializer<long>::write(s, v);
}
void serializer<std::string>::write(Serializer& s, const std::string& value) {
serializer<std::uint_least64_t>::write(s, value.size());
for (auto& c : value) s.addByte(c);
}
void serializer<bool>::write(Serializer& s, const bool b) {
serializer<std::uint_least64_t>::write(s, b ? 1 : 0);
}
namespace {
enum Type {
// First position of enum, because it is zero, must be covered with a value for which the sign doesn't matter
NaN,
Infinity,
Zero,
Normal
};
struct float_repr {
// Can fit an exponent of 32-2=20 bits, can support octuple-precision IEEE754 floats
std::int_least32_t exponent;
// Can support double precision IEEE754 floats (quadruple requires 112 bits, octuple 236 bits)
std::uint_least64_t fraction;
static constexpr unsigned fraction_bits = 64;
bool is_negative;
Type type;
};
auto bitreverse(std::uint_least64_t b) -> decltype(b)
{
b = ((b & 0xFFFFFFFF00000000ULL) >> 32) | ((b & 0x00000000FFFFFFFFULL) << 32);
b = ((b & 0xFFFF0000FFFF0000ULL) >> 16) | ((b & 0x0000FFFF0000FFFFULL) << 16);
b = ((b & 0xFF00FF00FF00FF00ULL) >> 8) | ((b & 0x00FF00FF00FF00FFULL) << 8);
b = ((b & 0xF0F0F0F0F0F0F0F0ULL) >> 4) | ((b & 0x0F0F0F0F0F0F0F0FULL) << 4);
b = ((b & 0xCCCCCCCCCCCCCCCCULL) >> 2) | ((b & 0x3333333333333333ULL) << 2);
b = ((b & 0xAAAAAAAAAAAAAAAAULL) >> 1) | ((b & 0x5555555555555555ULL) << 1);
return b;
}
}
template <>
struct serializer<float_repr> {
static void write(Serializer& s, float_repr const &b) {
// Using multiplication to avoid bit shifting a signed integer
switch(b.type) {
default:
{
serializer<decltype(+b.exponent)>::write(s, b.is_negative ? -b.type : b.type);
}
break;
case Normal:
{
const decltype(b.exponent) exponent
= b.exponent * 2 + (b.exponent < 0 ? -b.is_negative : b.is_negative);
const decltype(b.fraction) reversed_fraction
= bitreverse(b.fraction);
serializer<decltype(+exponent)>::write(s, exponent < 0 ? exponent - 2 : exponent + 3);
serializer<decltype(+b.fraction)>::write(s, reversed_fraction);
}
break;
};
}
static float_repr read(Deserializer& s) {
float_repr result;
auto exponent = serializer<decltype(result.exponent)>::read(s);
if (exponent < 3 && exponent >= -2) {
result.is_negative = (exponent < 0);
result.type = (Type)std::abs(exponent);
} else {
exponent = (exponent < 0) ? exponent + 2 : exponent - 3;
result.is_negative = !!((exponent/ 1) % 2);
result.type = Normal;
result.exponent = exponent / 2;
const auto reversed_fraction = serializer<decltype(result.fraction)>::read(s);
result.fraction = bitreverse(reversed_fraction);
}
return result;
}
};
void serializer<double>::write(Serializer& s, double const b) {
switch (std::fpclassify(b)) {
case FP_ZERO:
serializer<float_repr>::write(s, { 0, 0, !!std::signbit(b), Zero });
break;
case FP_INFINITE:
serializer<float_repr>::write(s, { 0, 0, !!std::signbit(b), Infinity });
break;
case FP_NAN:
// The bit reversal is to ensure the most efficient encoding can be used
serializer<float_repr>::write(s, { 0, 0, false, NaN });
break;
case FP_NORMAL:
case FP_SUBNORMAL:
float_repr repr;
repr.type = Normal;
repr.is_negative = !!std::signbit(b);
// Make the fraction a positive integer
repr.fraction = std::ldexp(std::abs(std::frexp(b, &repr.exponent)), repr.fraction_bits);
serializer<decltype(repr)>::write(s, repr);
break;
}
}
double serializer<double>::read(Deserializer& s) {
const auto repr = serializer<float_repr>::read(s);
switch(repr.type) {
case Zero:
return (repr.is_negative ? -0.0 : 0.0);
case Infinity:
return repr.is_negative ? -std::numeric_limits<double>::infinity() : std::numeric_limits<double>::infinity();
case NaN:
return std::numeric_limits<double>::quiet_NaN();
default:
return (repr.is_negative ? -1.0 : 1.0) * std::ldexp(static_cast<double>(repr.fraction), repr.exponent - repr.fraction_bits);
}
}
void serializer<float>::write(Serializer& s, float const b) {
serializer<double>::write(s, b);
}
float serializer<float>::read(Deserializer& s) {
return serializer<double>::read(s);
}
std::uint_least64_t serializer<std::uint_least64_t>::read(Deserializer& s) {
std::uint_least64_t val = 0,
offs = 0,
b = s.getByte();
while (b & 0x80) {
val |= (b & 0x7F) << offs;
offs += 7;
b = s.getByte();
}
val |= b << offs;
return val;
}
long serializer<long>::read(Deserializer& s) {
const auto val = serializer<std::uint_least64_t>::read(s);
auto value = static_cast<long>(val >> 1);
if (val & 1) value = -value;
return value;
}
int serializer<int>::read(Deserializer& s) {
return serializer<long>::read(s);
}
std::string serializer<std::string>::read(Deserializer& s) {
const auto length = serializer<std::uint_least64_t>::read(s);
const uint8_t* ptr = s.ptr;
const uint8_t* end = ptr + length;
if (end > s.end)
throw parse_exception("buffer underrun");
s.ptr = end;
return std::string(reinterpret_cast<const char*>(ptr), length);
}
bool serializer<bool>::read(Deserializer& s) {
return serializer<std::uint_least64_t>::read(s) > 0;
}
}
<|endoftext|> |
<commit_before>//
// Copyright 2015 The ANGLE 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.
//
// deqp_libtester_main.cpp: Entry point for tester DLL.
#include <cstdio>
#include <iostream>
#include "angle_deqp_libtester.h"
#include "common/angleutils.h"
#include "deMath.h"
#include "deUniquePtr.hpp"
#include "tcuApp.hpp"
#include "tcuCommandLine.hpp"
#include "tcuDefs.hpp"
#include "tcuPlatform.hpp"
#include "tcuRandomOrderExecutor.h"
#include "tcuResource.hpp"
#include "tcuTestLog.hpp"
#if (DE_OS == DE_OS_WIN32)
#include <Windows.h>
#elif (DE_OS == DE_OS_UNIX)
#include <sys/unistd.h>
#include <sys/stat.h>
#include <sys/types.h>
#endif
tcu::Platform *createPlatform();
namespace
{
tcu::Platform *g_platform = nullptr;
tcu::CommandLine *g_cmdLine = nullptr;
tcu::DirArchive *g_archive = nullptr;
tcu::TestLog *g_log = nullptr;
tcu::TestContext *g_testCtx = nullptr;
tcu::TestPackageRoot *g_root = nullptr;
tcu::RandomOrderExecutor *g_executor = nullptr;
const char *g_dEQPDataSearchDirs[] =
{
"data",
"third_party/deqp/data",
"../third_party/deqp/src/data",
"deqp_support/data",
"third_party/deqp/src/data",
"../../third_party/deqp/src/data"
};
// TODO(jmadill): upstream to dEQP?
#if (DE_OS == DE_OS_WIN32)
deBool deIsDir(const char *filename)
{
DWORD attribs = GetFileAttributesA(filename);
return (attribs != INVALID_FILE_ATTRIBUTES) &&
((attribs & FILE_ATTRIBUTE_DIRECTORY) > 0);
}
#elif (DE_OS == DE_OS_UNIX)
deBool deIsDir(const char *filename)
{
struct stat st;
int result = stat(filename, &st);
return result == 0 && ((st.st_mode & S_IFDIR) == S_IFDIR);
}
#else
#error TODO(jmadill): support other platforms
#endif
const char *FindDataDir()
{
for (size_t dirIndex = 0; dirIndex < ArraySize(g_dEQPDataSearchDirs); ++dirIndex)
{
if (deIsDir(g_dEQPDataSearchDirs[dirIndex]))
{
return g_dEQPDataSearchDirs[dirIndex];
}
}
return nullptr;
}
bool InitPlatform()
{
try
{
#if (DE_OS != DE_OS_WIN32)
// Set stdout to line-buffered mode (will be fully buffered by default if stdout is pipe).
setvbuf(stdout, DE_NULL, _IOLBF, 4 * 1024);
#endif
g_platform = createPlatform();
if (!deSetRoundingMode(DE_ROUNDINGMODE_TO_NEAREST))
{
std::cout << "Failed to set floating point rounding mode." << std::endl;
return false;
}
const char *deqpDataDir = FindDataDir();
if (deqpDataDir == nullptr)
{
std::cout << "Failed to find dEQP data directory." << std::endl;
return false;
}
// TODO(jmadill): filter arguments
const char *emptyString = "";
g_cmdLine = new tcu::CommandLine(1, &emptyString);
g_archive = new tcu::DirArchive(deqpDataDir);
g_log = new tcu::TestLog(g_cmdLine->getLogFileName(), g_cmdLine->getLogFlags());
g_testCtx = new tcu::TestContext(*g_platform, *g_archive, *g_log, *g_cmdLine, DE_NULL);
g_root = new tcu::TestPackageRoot(*g_testCtx, tcu::TestPackageRegistry::getSingleton());
g_executor = new tcu::RandomOrderExecutor(*g_root, *g_testCtx);
}
catch (const std::exception& e)
{
tcu::die("%s", e.what());
return false;
}
return true;
}
} // anonymous namespace
// Exported to the tester app.
ANGLE_LIBTESTER_EXPORT int deqp_libtester_main(int argc, const char *argv[])
{
InitPlatform();
try
{
de::UniquePtr<tcu::App> app(new tcu::App(*g_platform, *g_archive, *g_log, *g_cmdLine));
// Main loop.
for (;;)
{
if (!app->iterate())
break;
}
}
catch (const std::exception &e)
{
deqp_libtester_shutdown_platform();
tcu::die("%s", e.what());
}
deqp_libtester_shutdown_platform();
return 0;
}
ANGLE_LIBTESTER_EXPORT void deqp_libtester_shutdown_platform()
{
delete g_executor;
delete g_root;
delete g_testCtx;
delete g_log;
delete g_archive;
delete g_cmdLine;
delete g_platform;
}
ANGLE_LIBTESTER_EXPORT bool deqp_libtester_run(const char *caseName)
{
if (g_platform == nullptr && !InitPlatform())
{
tcu::die("Failed to initialize platform.");
}
try
{
// Poll platform events
const bool platformOk = g_platform->processEvents();
if (platformOk)
{
const tcu::TestStatus &result = g_executor->execute(caseName);
switch (result.getCode())
{
case QP_TEST_RESULT_PASS:
case QP_TEST_RESULT_NOT_SUPPORTED:
return true;
case QP_TEST_RESULT_QUALITY_WARNING:
std::cout << "Quality warning! " << result.getDescription() << std::endl;
return true;
case QP_TEST_RESULT_COMPATIBILITY_WARNING:
std::cout << "Compatiblity warning! " << result.getDescription() << std::endl;
return true;
default:
return false;
}
}
else
{
std::cout << "Aborted test!" << std::endl;
}
}
catch (const std::exception &e)
{
std::cout << "Exception running test: " << e.what() << std::endl;
}
return false;
}
<commit_msg>Fix command line being ignored in non-gtest dEQP tests<commit_after>//
// Copyright 2015 The ANGLE 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.
//
// deqp_libtester_main.cpp: Entry point for tester DLL.
#include <cstdio>
#include <iostream>
#include "angle_deqp_libtester.h"
#include "common/angleutils.h"
#include "deMath.h"
#include "deUniquePtr.hpp"
#include "tcuApp.hpp"
#include "tcuCommandLine.hpp"
#include "tcuDefs.hpp"
#include "tcuPlatform.hpp"
#include "tcuRandomOrderExecutor.h"
#include "tcuResource.hpp"
#include "tcuTestLog.hpp"
#if (DE_OS == DE_OS_WIN32)
#include <Windows.h>
#elif (DE_OS == DE_OS_UNIX)
#include <sys/unistd.h>
#include <sys/stat.h>
#include <sys/types.h>
#endif
tcu::Platform *createPlatform();
namespace
{
tcu::Platform *g_platform = nullptr;
tcu::CommandLine *g_cmdLine = nullptr;
tcu::DirArchive *g_archive = nullptr;
tcu::TestLog *g_log = nullptr;
tcu::TestContext *g_testCtx = nullptr;
tcu::TestPackageRoot *g_root = nullptr;
tcu::RandomOrderExecutor *g_executor = nullptr;
const char *g_dEQPDataSearchDirs[] =
{
"data",
"third_party/deqp/data",
"../third_party/deqp/src/data",
"deqp_support/data",
"third_party/deqp/src/data",
"../../third_party/deqp/src/data"
};
// TODO(jmadill): upstream to dEQP?
#if (DE_OS == DE_OS_WIN32)
deBool deIsDir(const char *filename)
{
DWORD attribs = GetFileAttributesA(filename);
return (attribs != INVALID_FILE_ATTRIBUTES) &&
((attribs & FILE_ATTRIBUTE_DIRECTORY) > 0);
}
#elif (DE_OS == DE_OS_UNIX)
deBool deIsDir(const char *filename)
{
struct stat st;
int result = stat(filename, &st);
return result == 0 && ((st.st_mode & S_IFDIR) == S_IFDIR);
}
#else
#error TODO(jmadill): support other platforms
#endif
const char *FindDataDir()
{
for (size_t dirIndex = 0; dirIndex < ArraySize(g_dEQPDataSearchDirs); ++dirIndex)
{
if (deIsDir(g_dEQPDataSearchDirs[dirIndex]))
{
return g_dEQPDataSearchDirs[dirIndex];
}
}
return nullptr;
}
bool InitPlatform(int argc, const char *argv[])
{
try
{
#if (DE_OS != DE_OS_WIN32)
// Set stdout to line-buffered mode (will be fully buffered by default if stdout is pipe).
setvbuf(stdout, DE_NULL, _IOLBF, 4 * 1024);
#endif
g_platform = createPlatform();
if (!deSetRoundingMode(DE_ROUNDINGMODE_TO_NEAREST))
{
std::cout << "Failed to set floating point rounding mode." << std::endl;
return false;
}
const char *deqpDataDir = FindDataDir();
if (deqpDataDir == nullptr)
{
std::cout << "Failed to find dEQP data directory." << std::endl;
return false;
}
g_cmdLine = new tcu::CommandLine(argc, argv);
g_archive = new tcu::DirArchive(deqpDataDir);
g_log = new tcu::TestLog(g_cmdLine->getLogFileName(), g_cmdLine->getLogFlags());
g_testCtx = new tcu::TestContext(*g_platform, *g_archive, *g_log, *g_cmdLine, DE_NULL);
g_root = new tcu::TestPackageRoot(*g_testCtx, tcu::TestPackageRegistry::getSingleton());
g_executor = new tcu::RandomOrderExecutor(*g_root, *g_testCtx);
}
catch (const std::exception& e)
{
tcu::die("%s", e.what());
return false;
}
return true;
}
} // anonymous namespace
// Exported to the tester app.
ANGLE_LIBTESTER_EXPORT int deqp_libtester_main(int argc, const char *argv[])
{
if (!InitPlatform(argc, argv))
{
tcu::die("Could not initialize the dEQP platform");
}
try
{
de::UniquePtr<tcu::App> app(new tcu::App(*g_platform, *g_archive, *g_log, *g_cmdLine));
// Main loop.
for (;;)
{
if (!app->iterate())
break;
}
}
catch (const std::exception &e)
{
deqp_libtester_shutdown_platform();
tcu::die("%s", e.what());
}
deqp_libtester_shutdown_platform();
return 0;
}
ANGLE_LIBTESTER_EXPORT void deqp_libtester_shutdown_platform()
{
delete g_executor;
delete g_root;
delete g_testCtx;
delete g_log;
delete g_archive;
delete g_cmdLine;
delete g_platform;
}
ANGLE_LIBTESTER_EXPORT bool deqp_libtester_run(const char *caseName)
{
const char *emptyString = "";
if (g_platform == nullptr && !InitPlatform(1, &emptyString))
{
tcu::die("Failed to initialize platform.");
}
try
{
// Poll platform events
const bool platformOk = g_platform->processEvents();
if (platformOk)
{
const tcu::TestStatus &result = g_executor->execute(caseName);
switch (result.getCode())
{
case QP_TEST_RESULT_PASS:
case QP_TEST_RESULT_NOT_SUPPORTED:
return true;
case QP_TEST_RESULT_QUALITY_WARNING:
std::cout << "Quality warning! " << result.getDescription() << std::endl;
return true;
case QP_TEST_RESULT_COMPATIBILITY_WARNING:
std::cout << "Compatiblity warning! " << result.getDescription() << std::endl;
return true;
default:
return false;
}
}
else
{
std::cout << "Aborted test!" << std::endl;
}
}
catch (const std::exception &e)
{
std::cout << "Exception running test: " << e.what() << std::endl;
}
return false;
}
<|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: xexptran.hxx,v $
*
* $Revision: 1.8 $
*
* last change: $Author: obo $ $Date: 2006-10-12 14:37:39 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#ifndef _XEXPTRANSFORM_HXX
#define _XEXPTRANSFORM_HXX
#ifndef _RTL_USTRING_
#include <rtl/ustring.hxx>
#endif
#ifndef _B2D_MATRIX3D_HXX
#include <goodies/matrix3d.hxx>
#endif
#ifndef _COM_SUN_STAR_DRAWING_POINTSEQUENCESEQUENCE_HPP_
#include <com/sun/star/drawing/PointSequenceSequence.hpp>
#endif
#ifndef _COM_SUN_STAR_DRAWING_POINTSEQUENCE_HPP_
#include <com/sun/star/drawing/PointSequence.hpp>
#endif
#ifndef _COM_SUN_STAR_AWT_SIZE_HPP_
#include <com/sun/star/awt/Size.hpp>
#endif
#ifndef _COM_SUN_STAR_DRAWING_FLAGSEQUENCESEQUENCE_HPP_
#include <com/sun/star/drawing/FlagSequenceSequence.hpp>
#endif
#ifndef _COM_SUN_STAR_DRAWING_FLAGSEQUENCE_HPP_
#include <com/sun/star/drawing/FlagSequence.hpp>
#endif
#ifndef _COM_SUN_STAR_DRAWING_HOMOGENMATRIX_HPP_
#include <com/sun/star/drawing/HomogenMatrix.hpp>
#endif
#ifndef _VCL_MAPUNIT_HXX
#include <vcl/mapunit.hxx>
#endif
//////////////////////////////////////////////////////////////////////////////
struct ImpSdXMLExpTransObj2DBase;
struct ImpSdXMLExpTransObj3DBase;
class SvXMLUnitConverter;
class Vector3D;
class Matrix3D;
class Matrix4D;
//////////////////////////////////////////////////////////////////////////////
DECLARE_LIST(ImpSdXMLExpTransObj2DBaseList, ImpSdXMLExpTransObj2DBase*)
DECLARE_LIST(ImpSdXMLExpTransObj3DBaseList, ImpSdXMLExpTransObj3DBase*)
//////////////////////////////////////////////////////////////////////////////
class SdXMLImExTransform2D
{
ImpSdXMLExpTransObj2DBaseList maList;
rtl::OUString msString;
void EmptyList();
public:
SdXMLImExTransform2D() {}
SdXMLImExTransform2D(const rtl::OUString& rNew, const SvXMLUnitConverter& rConv);
~SdXMLImExTransform2D() { EmptyList(); }
void AddRotate(double fNew);
void AddScale(const Vector2D& rNew);
void AddTranslate(const Vector2D& rNew);
void AddSkewX(double fNew);
void AddSkewY(double fNew);
void AddMatrix(const Matrix3D& rNew);
sal_Bool NeedsAction() const { return (sal_Bool)(maList.Count() > 0L); }
void GetFullTransform(Matrix3D& rFullTrans);
const rtl::OUString& GetExportString(const SvXMLUnitConverter& rConv);
void SetString(const rtl::OUString& rNew, const SvXMLUnitConverter& rConv);
};
//////////////////////////////////////////////////////////////////////////////
class SdXMLImExTransform3D
{
ImpSdXMLExpTransObj3DBaseList maList;
rtl::OUString msString;
void EmptyList();
public:
SdXMLImExTransform3D() {}
SdXMLImExTransform3D(const rtl::OUString& rNew, const SvXMLUnitConverter& rConv);
~SdXMLImExTransform3D() { EmptyList(); }
void AddRotateX(double fNew);
void AddRotateY(double fNew);
void AddRotateZ(double fNew);
void AddScale(const Vector3D& rNew);
void AddTranslate(const Vector3D& rNew);
void AddMatrix(const Matrix4D& rNew);
void AddHomogenMatrix(const com::sun::star::drawing::HomogenMatrix& xHomMat);
sal_Bool NeedsAction() const { return (sal_Bool)(maList.Count() > 0L); }
void GetFullTransform(Matrix4D& rFullTrans);
BOOL GetFullHomogenTransform(com::sun::star::drawing::HomogenMatrix& xHomMat);
const rtl::OUString& GetExportString(const SvXMLUnitConverter& rConv);
void SetString(const rtl::OUString& rNew, const SvXMLUnitConverter& rConv);
};
//////////////////////////////////////////////////////////////////////////////
class SdXMLImExViewBox
{
rtl::OUString msString;
sal_Int32 mnX;
sal_Int32 mnY;
sal_Int32 mnW;
sal_Int32 mnH;
public:
SdXMLImExViewBox(sal_Int32 nX = 0L, sal_Int32 nY = 0L, sal_Int32 nW = 1000L, sal_Int32 nH = 1000L);
SdXMLImExViewBox(const rtl::OUString& rNew, const SvXMLUnitConverter& rConv);
sal_Int32 GetX() const { return mnX; }
sal_Int32 GetY() const { return mnY; }
sal_Int32 GetWidth() const { return mnW; }
sal_Int32 GetHeight() const { return mnH; }
const rtl::OUString& GetExportString();
};
//////////////////////////////////////////////////////////////////////////////
class SdXMLImExPointsElement
{
rtl::OUString msString;
com::sun::star::drawing::PointSequenceSequence maPoly;
public:
SdXMLImExPointsElement(com::sun::star::drawing::PointSequence* pPoints,
const SdXMLImExViewBox& rViewBox,
const com::sun::star::awt::Point& rObjectPos,
const com::sun::star::awt::Size& rObjectSize,
// #96328#
const sal_Bool bClosed = sal_True);
SdXMLImExPointsElement(const rtl::OUString& rNew,
const SdXMLImExViewBox& rViewBox,
const com::sun::star::awt::Point& rObjectPos,
const com::sun::star::awt::Size& rObjectSize,
const SvXMLUnitConverter& rConv);
const rtl::OUString& GetExportString() const { return msString; }
const com::sun::star::drawing::PointSequenceSequence& GetPointSequenceSequence() const { return maPoly; }
};
//////////////////////////////////////////////////////////////////////////////
class SdXMLImExSvgDElement
{
rtl::OUString msString;
const SdXMLImExViewBox& mrViewBox;
sal_Bool mbIsClosed;
sal_Bool mbIsCurve;
sal_Int32 mnLastX;
sal_Int32 mnLastY;
com::sun::star::drawing::PointSequenceSequence maPoly;
com::sun::star::drawing::FlagSequenceSequence maFlag;
public:
SdXMLImExSvgDElement(const SdXMLImExViewBox& rViewBox);
SdXMLImExSvgDElement(const rtl::OUString& rNew,
const SdXMLImExViewBox& rViewBox,
const com::sun::star::awt::Point& rObjectPos,
const com::sun::star::awt::Size& rObjectSize,
const SvXMLUnitConverter& rConv);
void AddPolygon(
com::sun::star::drawing::PointSequence* pPoints,
com::sun::star::drawing::FlagSequence* pFlags,
const com::sun::star::awt::Point& rObjectPos,
const com::sun::star::awt::Size& rObjectSize,
sal_Bool bClosed = FALSE, sal_Bool bRelative = TRUE);
const rtl::OUString& GetExportString() const { return msString; }
sal_Bool IsClosed() const { return mbIsClosed; }
sal_Bool IsCurve() const { return mbIsCurve; }
const com::sun::star::drawing::PointSequenceSequence& GetPointSequenceSequence() const { return maPoly; }
const com::sun::star::drawing::FlagSequenceSequence& GetFlagSequenceSequence() const { return maFlag; }
};
#endif // _XEXPTRANSFORM_HXX
<commit_msg>INTEGRATION: CWS aw024 (1.5.460); FILE MERGED 2006/11/13 11:10:46 aw 1.5.460.5: changes after resync 2006/11/10 04:49:05 aw 1.5.460.4: RESYNC: (1.7-1.8); FILE MERGED 2006/07/04 14:05:47 aw 1.5.460.3: RESYNC: (1.6-1.7); FILE MERGED 2005/09/17 06:44:40 aw 1.5.460.2: RESYNC: (1.5-1.6); FILE MERGED 2004/12/28 15:24:15 aw 1.5.460.1: #i39528<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: xexptran.hxx,v $
*
* $Revision: 1.9 $
*
* last change: $Author: ihi $ $Date: 2006-11-14 14:13:14 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#ifndef _XEXPTRANSFORM_HXX
#define _XEXPTRANSFORM_HXX
#ifndef _RTL_USTRING_
#include <rtl/ustring.hxx>
#endif
#ifndef _COM_SUN_STAR_DRAWING_POINTSEQUENCESEQUENCE_HPP_
#include <com/sun/star/drawing/PointSequenceSequence.hpp>
#endif
#ifndef _COM_SUN_STAR_DRAWING_POINTSEQUENCE_HPP_
#include <com/sun/star/drawing/PointSequence.hpp>
#endif
#ifndef _COM_SUN_STAR_AWT_SIZE_HPP_
#include <com/sun/star/awt/Size.hpp>
#endif
#ifndef _COM_SUN_STAR_DRAWING_FLAGSEQUENCESEQUENCE_HPP_
#include <com/sun/star/drawing/FlagSequenceSequence.hpp>
#endif
#ifndef _COM_SUN_STAR_DRAWING_FLAGSEQUENCE_HPP_
#include <com/sun/star/drawing/FlagSequence.hpp>
#endif
#ifndef _COM_SUN_STAR_DRAWING_HOMOGENMATRIX_HPP_
#include <com/sun/star/drawing/HomogenMatrix.hpp>
#endif
#ifndef _VCL_MAPUNIT_HXX
#include <vcl/mapunit.hxx>
#endif
#include <vector>
//////////////////////////////////////////////////////////////////////////////
// predeclarations
struct ImpSdXMLExpTransObj2DBase;
struct ImpSdXMLExpTransObj3DBase;
class SvXMLUnitConverter;
namespace basegfx
{
class B2DTuple;
class B2DHomMatrix;
class B3DTuple;
class B3DHomMatrix;
} // end of namespace basegfx
//////////////////////////////////////////////////////////////////////////////
typedef ::std::vector< ImpSdXMLExpTransObj2DBase* > ImpSdXMLExpTransObj2DBaseList;
typedef ::std::vector< ImpSdXMLExpTransObj3DBase* > ImpSdXMLExpTransObj3DBaseList;
//////////////////////////////////////////////////////////////////////////////
class SdXMLImExTransform2D
{
ImpSdXMLExpTransObj2DBaseList maList;
rtl::OUString msString;
void EmptyList();
public:
SdXMLImExTransform2D() {}
SdXMLImExTransform2D(const rtl::OUString& rNew, const SvXMLUnitConverter& rConv);
~SdXMLImExTransform2D() { EmptyList(); }
void AddRotate(double fNew);
void AddScale(const ::basegfx::B2DTuple& rNew);
void AddTranslate(const ::basegfx::B2DTuple& rNew);
void AddSkewX(double fNew);
void AddSkewY(double fNew);
void AddMatrix(const ::basegfx::B2DHomMatrix& rNew);
bool NeedsAction() const { return 0L != maList.size(); }
void GetFullTransform(::basegfx::B2DHomMatrix& rFullTrans);
const rtl::OUString& GetExportString(const SvXMLUnitConverter& rConv);
void SetString(const rtl::OUString& rNew, const SvXMLUnitConverter& rConv);
};
//////////////////////////////////////////////////////////////////////////////
class SdXMLImExTransform3D
{
ImpSdXMLExpTransObj3DBaseList maList;
rtl::OUString msString;
void EmptyList();
public:
SdXMLImExTransform3D() {}
SdXMLImExTransform3D(const rtl::OUString& rNew, const SvXMLUnitConverter& rConv);
~SdXMLImExTransform3D() { EmptyList(); }
void AddRotateX(double fNew);
void AddRotateY(double fNew);
void AddRotateZ(double fNew);
void AddScale(const ::basegfx::B3DTuple& rNew);
void AddTranslate(const ::basegfx::B3DTuple& rNew);
void AddMatrix(const ::basegfx::B3DHomMatrix& rNew);
void AddHomogenMatrix(const com::sun::star::drawing::HomogenMatrix& xHomMat);
bool NeedsAction() const { return 0L != maList.size(); }
void GetFullTransform(::basegfx::B3DHomMatrix& rFullTrans);
bool GetFullHomogenTransform(com::sun::star::drawing::HomogenMatrix& xHomMat);
const rtl::OUString& GetExportString(const SvXMLUnitConverter& rConv);
void SetString(const rtl::OUString& rNew, const SvXMLUnitConverter& rConv);
};
//////////////////////////////////////////////////////////////////////////////
class SdXMLImExViewBox
{
rtl::OUString msString;
sal_Int32 mnX;
sal_Int32 mnY;
sal_Int32 mnW;
sal_Int32 mnH;
public:
SdXMLImExViewBox(sal_Int32 nX = 0L, sal_Int32 nY = 0L, sal_Int32 nW = 1000L, sal_Int32 nH = 1000L);
SdXMLImExViewBox(const rtl::OUString& rNew, const SvXMLUnitConverter& rConv);
sal_Int32 GetX() const { return mnX; }
sal_Int32 GetY() const { return mnY; }
sal_Int32 GetWidth() const { return mnW; }
sal_Int32 GetHeight() const { return mnH; }
const rtl::OUString& GetExportString();
};
//////////////////////////////////////////////////////////////////////////////
class SdXMLImExPointsElement
{
rtl::OUString msString;
com::sun::star::drawing::PointSequenceSequence maPoly;
public:
SdXMLImExPointsElement(com::sun::star::drawing::PointSequence* pPoints,
const SdXMLImExViewBox& rViewBox,
const com::sun::star::awt::Point& rObjectPos,
const com::sun::star::awt::Size& rObjectSize,
// #96328#
const bool bClosed = true);
SdXMLImExPointsElement(const rtl::OUString& rNew,
const SdXMLImExViewBox& rViewBox,
const com::sun::star::awt::Point& rObjectPos,
const com::sun::star::awt::Size& rObjectSize,
const SvXMLUnitConverter& rConv);
const rtl::OUString& GetExportString() const { return msString; }
const com::sun::star::drawing::PointSequenceSequence& GetPointSequenceSequence() const { return maPoly; }
};
//////////////////////////////////////////////////////////////////////////////
class SdXMLImExSvgDElement
{
rtl::OUString msString;
const SdXMLImExViewBox& mrViewBox;
bool mbIsClosed;
bool mbIsCurve;
sal_Int32 mnLastX;
sal_Int32 mnLastY;
com::sun::star::drawing::PointSequenceSequence maPoly;
com::sun::star::drawing::FlagSequenceSequence maFlag;
public:
SdXMLImExSvgDElement(const SdXMLImExViewBox& rViewBox);
SdXMLImExSvgDElement(const rtl::OUString& rNew,
const SdXMLImExViewBox& rViewBox,
const com::sun::star::awt::Point& rObjectPos,
const com::sun::star::awt::Size& rObjectSize,
const SvXMLUnitConverter& rConv);
void AddPolygon(
com::sun::star::drawing::PointSequence* pPoints,
com::sun::star::drawing::FlagSequence* pFlags,
const com::sun::star::awt::Point& rObjectPos,
const com::sun::star::awt::Size& rObjectSize,
bool bClosed = false, bool bRelative = true);
const rtl::OUString& GetExportString() const { return msString; }
bool IsClosed() const { return mbIsClosed; }
bool IsCurve() const { return mbIsCurve; }
const com::sun::star::drawing::PointSequenceSequence& GetPointSequenceSequence() const { return maPoly; }
const com::sun::star::drawing::FlagSequenceSequence& GetFlagSequenceSequence() const { return maFlag; }
};
#endif // _XEXPTRANSFORM_HXX
<|endoftext|> |
<commit_before>// The libMesh Finite Element Library.
// Copyright (C) 2002-2021 Benjamin S. Kirk, John W. Peterson, Roy H. Stogner
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
// Local Includes
#include "libmesh/libmesh_config.h"
#ifdef LIBMESH_ENABLE_PERIODIC
#include "libmesh/periodic_boundaries.h"
#include "libmesh/boundary_info.h"
#include "libmesh/elem.h"
#include "libmesh/mesh_base.h"
#include "libmesh/periodic_boundary.h"
#include "libmesh/point_locator_base.h"
#include "libmesh/remote_elem.h"
namespace libMesh
{
PeriodicBoundaries::~PeriodicBoundaries() = default;
PeriodicBoundaryBase * PeriodicBoundaries::boundary(boundary_id_type id)
{
iterator i = this->find(id);
if (i == this->end())
return nullptr;
return i->second.get();
}
const PeriodicBoundaryBase * PeriodicBoundaries::boundary(boundary_id_type id) const
{
const_iterator i = this->find(id);
if (i == this->end())
return nullptr;
return i->second.get();
}
const Elem * PeriodicBoundaries::neighbor(boundary_id_type boundary_id,
const PointLocatorBase & point_locator,
const Elem * e,
unsigned int side,
unsigned int * neigh_side) const
{
std::unique_ptr<const Elem> neigh_side_proxy;
// Find a point on that side (and only that side)
Point p = e->build_side_ptr(side)->vertex_average();
const PeriodicBoundaryBase * b = this->boundary(boundary_id);
libmesh_assert (b);
p = b->get_corresponding_pos(p);
std::set<const Elem *> candidate_elements;
point_locator.operator()(p, candidate_elements);
// We might have found multiple elements, e.g. if two distinct periodic
// boundaries are overlapping (see systems_of_equations_ex9, for example).
// As a result, we need to search for the element that has boundary_id.
const MeshBase & mesh = point_locator.get_mesh();
for(const Elem * elem_it : candidate_elements)
{
std::vector<unsigned int> neigh_sides =
mesh.get_boundary_info().sides_with_boundary_id(elem_it, b->pairedboundary);
for (auto ns : neigh_sides)
{
if (neigh_side)
{
elem_it->build_side_ptr(neigh_side_proxy, ns);
if (neigh_side_proxy->contains_point(p))
{
*neigh_side = ns;
return elem_it;
}
}
else
// checking contains_point is too expensive if we don't
// definitely need it to find neigh_side
return elem_it;
}
}
// If we should have found a periodic neighbor but didn't then
// either we're on a ghosted element with a remote periodic neighbor
// or we're on a mesh with an inconsistent periodic boundary.
libmesh_assert_msg(!mesh.is_serial() &&
(e->processor_id() != mesh.processor_id()),
"Periodic boundary neighbor not found");
if (neigh_side)
*neigh_side = libMesh::invalid_uint;
return remote_elem;
}
} // namespace libMesh
#endif // LIBMESH_ENABLE_PERIODIC
<commit_msg>Turn assert into error in PBCs::neighbor()<commit_after>// The libMesh Finite Element Library.
// Copyright (C) 2002-2021 Benjamin S. Kirk, John W. Peterson, Roy H. Stogner
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
// Local Includes
#include "libmesh/libmesh_config.h"
#ifdef LIBMESH_ENABLE_PERIODIC
#include "libmesh/periodic_boundaries.h"
#include "libmesh/boundary_info.h"
#include "libmesh/elem.h"
#include "libmesh/mesh_base.h"
#include "libmesh/periodic_boundary.h"
#include "libmesh/point_locator_base.h"
#include "libmesh/remote_elem.h"
namespace libMesh
{
PeriodicBoundaries::~PeriodicBoundaries() = default;
PeriodicBoundaryBase * PeriodicBoundaries::boundary(boundary_id_type id)
{
iterator i = this->find(id);
if (i == this->end())
return nullptr;
return i->second.get();
}
const PeriodicBoundaryBase * PeriodicBoundaries::boundary(boundary_id_type id) const
{
const_iterator i = this->find(id);
if (i == this->end())
return nullptr;
return i->second.get();
}
const Elem * PeriodicBoundaries::neighbor(boundary_id_type boundary_id,
const PointLocatorBase & point_locator,
const Elem * e,
unsigned int side,
unsigned int * neigh_side) const
{
std::unique_ptr<const Elem> neigh_side_proxy;
// Find a point on that side (and only that side)
Point p = e->build_side_ptr(side)->vertex_average();
const PeriodicBoundaryBase * b = this->boundary(boundary_id);
libmesh_assert (b);
p = b->get_corresponding_pos(p);
std::set<const Elem *> candidate_elements;
point_locator.operator()(p, candidate_elements);
// We might have found multiple elements, e.g. if two distinct periodic
// boundaries are overlapping (see systems_of_equations_ex9, for example).
// As a result, we need to search for the element that has boundary_id.
const MeshBase & mesh = point_locator.get_mesh();
for(const Elem * elem_it : candidate_elements)
{
std::vector<unsigned int> neigh_sides =
mesh.get_boundary_info().sides_with_boundary_id(elem_it, b->pairedboundary);
for (auto ns : neigh_sides)
{
if (neigh_side)
{
elem_it->build_side_ptr(neigh_side_proxy, ns);
if (neigh_side_proxy->contains_point(p))
{
*neigh_side = ns;
return elem_it;
}
}
else
// checking contains_point is too expensive if we don't
// definitely need it to find neigh_side
return elem_it;
}
}
// If we should have found a periodic neighbor but didn't then
// either we're on a ghosted element with a remote periodic neighbor
// or we're on a mesh with an inconsistent periodic boundary.
libmesh_error_msg_if(mesh.is_serial() ||
(e->processor_id() == mesh.processor_id()),
"Periodic boundary neighbor not found");
if (neigh_side)
*neigh_side = libMesh::invalid_uint;
return remote_elem;
}
} // namespace libMesh
#endif // LIBMESH_ENABLE_PERIODIC
<|endoftext|> |
<commit_before>/*************************************************************************
*
* $RCSfile: xmlerror.hxx,v $
*
* $Revision: 1.3 $
*
* last change: $Author: dvo $ $Date: 2001-09-24 14:05:33 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the "License"); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#ifndef _XMLOFF_XMLERROR_HXX
#define _XMLOFF_XMLERROR_HXX
#ifndef _SAL_TYPES_H_
#include <sal/types.h>
#endif
// STL includes
#include <vector>
// masks for the error ID fields
#define XMLERROR_MASK_FLAG 0xF0000000
#define XMLERROR_MASK_CLASS 0x00FF0000
#define XMLERROR_MASK_NUMBER 0x0000FFFF
// error flags:
#define XMLERROR_FLAG_WARNING 0x10000000
#define XMLERROR_FLAG_ERROR 0x20000000
#define XMLERROR_FLAG_SEVERE 0x40000000
// error classes: Error ID
#define XMLERROR_CLASS_IO 0x00010000
#define XMLERROR_CLASS_FORMAT 0x00020000
#define XMLERROR_CLASS_API 0x00040000
#define XMLERROR_CLASS_OTHER 0x00080000
// error numbers, listed by error class
// Within each class, errors should be numbered consecutively. Please
// allways add to error code below the appropriate comment.
// I/O errors:
// format errors:
#define XMLERROR_SAX ( XMLERROR_CLASS_FORMAT | 0x00000001 )
// API errors:
#define XMLERROR_STYLE_PROP_VALUE ( XMLERROR_CLASS_API | 0x00000001 )
#define XMLERROR_STYLE_PROP_UNKNOWN ( XMLERROR_CLASS_API | 0x00000002 )
#define XMLERROR_STYLE_PROP_OTHER ( XMLERROR_CLASS_API | 0x00000003 )
// other errors:
#define XMLERROR_CANCEL ( XMLERROR_CLASS_OTHER | 0x00000001 )
// 16bit error flag constants for use in the
// SvXMLExport/SvXMLImport error flags
#define ERROR_NO 0x0000
#define ERROR_DO_NOTHING 0x0001
#define ERROR_ERROR_OCCURED 0x0002
#define ERROR_WARNING_OCCURED 0x0004
// forward declarations
namespace rtl { class OUString; }
namespace com { namespace sun { namespace star {
namespace uno { template<class X> class Sequence; }
namespace uno { template<class X> class Reference; }
namespace xml { namespace sax { class XLocator; } }
} } }
class ErrorRecord;
/**
* The XMLErrors is used to collect all errors and warnings that occur
* for appropriate processing.
*/
class XMLErrors
{
/// definition of type for error list
typedef ::std::vector<ErrorRecord> ErrorList;
ErrorList aErrors; /// list of error records
public:
XMLErrors();
~XMLErrors();
/// add a new entry to the list of error messages
void AddRecord(
sal_Int32 nId, /// error ID == error flags + error class + error number
const ::com::sun::star::uno::Sequence<
::rtl::OUString> & rParams, /// parameters for error message
const ::rtl::OUString& rExceptionMessage, /// original exception string
sal_Int32 nRow, /// XLocator: file row number
sal_Int32 nColumn, /// XLocator: file column number
const ::rtl::OUString& rPublicId, /// XLocator: file public ID
const ::rtl::OUString& rSystemId ); /// XLocator: file system ID
void AddRecord(
sal_Int32 nId, /// error ID == error flags + error class + error number
const ::com::sun::star::uno::Sequence<
::rtl::OUString> & rParams, /// parameters for error message
const ::rtl::OUString& rExceptionMessage, /// original exception string
const ::com::sun::star::uno::Reference<
::com::sun::star::xml::sax::XLocator> & rLocator); /// location
void AddRecord(
sal_Int32 nId, /// error ID == error flags + error class + error number
const ::com::sun::star::uno::Sequence<
::rtl::OUString> & rParams, /// parameters for error message
const ::rtl::OUString& rExceptionMessage); /// original exception string
void AddRecord(
sal_Int32 nId, /// error ID == error flags + error class + error number
const ::com::sun::star::uno::Sequence<
::rtl::OUString> & rParams); /// parameters for error message
};
#endif
<commit_msg>#91636# error code for general API errors<commit_after>/*************************************************************************
*
* $RCSfile: xmlerror.hxx,v $
*
* $Revision: 1.4 $
*
* last change: $Author: dvo $ $Date: 2001-09-28 08:39:06 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the "License"); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#ifndef _XMLOFF_XMLERROR_HXX
#define _XMLOFF_XMLERROR_HXX
#ifndef _SAL_TYPES_H_
#include <sal/types.h>
#endif
// STL includes
#include <vector>
// masks for the error ID fields
#define XMLERROR_MASK_FLAG 0xF0000000
#define XMLERROR_MASK_CLASS 0x00FF0000
#define XMLERROR_MASK_NUMBER 0x0000FFFF
// error flags:
#define XMLERROR_FLAG_WARNING 0x10000000
#define XMLERROR_FLAG_ERROR 0x20000000
#define XMLERROR_FLAG_SEVERE 0x40000000
// error classes: Error ID
#define XMLERROR_CLASS_IO 0x00010000
#define XMLERROR_CLASS_FORMAT 0x00020000
#define XMLERROR_CLASS_API 0x00040000
#define XMLERROR_CLASS_OTHER 0x00080000
// error numbers, listed by error class
// Within each class, errors should be numbered consecutively. Please
// allways add to error code below the appropriate comment.
// I/O errors:
// format errors:
#define XMLERROR_SAX ( XMLERROR_CLASS_FORMAT | 0x00000001 )
// API errors:
#define XMLERROR_STYLE_PROP_VALUE ( XMLERROR_CLASS_API | 0x00000001 )
#define XMLERROR_STYLE_PROP_UNKNOWN ( XMLERROR_CLASS_API | 0x00000002 )
#define XMLERROR_STYLE_PROP_OTHER ( XMLERROR_CLASS_API | 0x00000003 )
#define XMLERROR_API ( XMLERROR_CLASS_API | 0x00000004 )
// other errors:
#define XMLERROR_CANCEL ( XMLERROR_CLASS_OTHER | 0x00000001 )
// 16bit error flag constants for use in the
// SvXMLExport/SvXMLImport error flags
#define ERROR_NO 0x0000
#define ERROR_DO_NOTHING 0x0001
#define ERROR_ERROR_OCCURED 0x0002
#define ERROR_WARNING_OCCURED 0x0004
// forward declarations
namespace rtl { class OUString; }
namespace com { namespace sun { namespace star {
namespace uno { template<class X> class Sequence; }
namespace uno { template<class X> class Reference; }
namespace xml { namespace sax { class XLocator; } }
} } }
class ErrorRecord;
/**
* The XMLErrors is used to collect all errors and warnings that occur
* for appropriate processing.
*/
class XMLErrors
{
/// definition of type for error list
typedef ::std::vector<ErrorRecord> ErrorList;
ErrorList aErrors; /// list of error records
public:
XMLErrors();
~XMLErrors();
/// add a new entry to the list of error messages
void AddRecord(
sal_Int32 nId, /// error ID == error flags + error class + error number
const ::com::sun::star::uno::Sequence<
::rtl::OUString> & rParams, /// parameters for error message
const ::rtl::OUString& rExceptionMessage, /// original exception string
sal_Int32 nRow, /// XLocator: file row number
sal_Int32 nColumn, /// XLocator: file column number
const ::rtl::OUString& rPublicId, /// XLocator: file public ID
const ::rtl::OUString& rSystemId ); /// XLocator: file system ID
void AddRecord(
sal_Int32 nId, /// error ID == error flags + error class + error number
const ::com::sun::star::uno::Sequence<
::rtl::OUString> & rParams, /// parameters for error message
const ::rtl::OUString& rExceptionMessage, /// original exception string
const ::com::sun::star::uno::Reference<
::com::sun::star::xml::sax::XLocator> & rLocator); /// location
void AddRecord(
sal_Int32 nId, /// error ID == error flags + error class + error number
const ::com::sun::star::uno::Sequence<
::rtl::OUString> & rParams, /// parameters for error message
const ::rtl::OUString& rExceptionMessage); /// original exception string
void AddRecord(
sal_Int32 nId, /// error ID == error flags + error class + error number
const ::com::sun::star::uno::Sequence<
::rtl::OUString> & rParams); /// parameters for error message
};
#endif
<|endoftext|> |
<commit_before>/* IBM_PROLOG_BEGIN_TAG */
/* This is an automatically generated prolog. */
/* */
/* $Source: src/usr/diag/prdf/common/plat/mem/prdfMemRowRepair.C $ */
/* */
/* OpenPOWER HostBoot Project */
/* */
/* Contributors Listed Below - COPYRIGHT 2018,2020 */
/* [+] International Business Machines Corp. */
/* */
/* */
/* Licensed under the Apache License, Version 2.0 (the "License"); */
/* you may not use this file except in compliance with the License. */
/* You may obtain a copy of the License at */
/* */
/* http://www.apache.org/licenses/LICENSE-2.0 */
/* */
/* Unless required by applicable law or agreed to in writing, software */
/* distributed under the License is distributed on an "AS IS" BASIS, */
/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or */
/* implied. See the License for the specific language governing */
/* permissions and limitations under the License. */
/* */
/* IBM_PROLOG_END_TAG */
/** @file prdfMemRowRepair.C */
#include <prdfMemRowRepair.H>
#include <UtilHash.H>
#include <iipServiceDataCollector.h>
#include <prdfParserUtils.H>
#include <prdfErrlUtil.H>
#include <prdfMemUtils.H>
#include <fapi2.H>
#ifdef __HOSTBOOT_MODULE
#include <rowRepairsFuncs.H>
#endif // __HOSTBOOT_MODULE
namespace PRDF
{
using namespace PlatServices;
using namespace PARSERUTILS;
using namespace TARGETING;
//------------------------------------------------------------------------------
bool MemRowRepair::nonZero() const
{
bool o_nonZero = false;
for ( uint32_t i = 0; i < ROW_REPAIR::ROW_REPAIR_SIZE; i++ )
{
if ( 0 != iv_data[i] )
{
o_nonZero = true;
break;
}
}
return o_nonZero;
}
//##############################################################################
// Utility Functions
//##############################################################################
template<TARGETING::TYPE T, fapi2::TargetType F>
uint32_t __getRowRepairData( TargetHandle_t i_dimm, const MemRank & i_rank,
MemRowRepair & o_rowRepair )
{
#define PRDF_FUNC "[PlatServices::__getRowRepairData] "
uint32_t o_rc = SUCCESS;
/* TODO RTC 247259
#ifdef __HOSTBOOT_MODULE
uint8_t l_data[ROW_REPAIR::ROW_REPAIR_SIZE] = {0};
errlHndl_t l_errl = nullptr;
// get port select
uint8_t l_ps = getDimmPort( i_dimm );
// get mba
TargetHandle_t l_mba = getConnectedParent( i_dimm, T );
fapi2::Target<F> l_fapiMba( l_mba );
//p10cleanup
// FAPI_INVOKE_HWP( l_errl, getRowRepair, l_fapiMba, i_rank.getDimmSlct(),
// i_rank.getRankSlct(), l_data, l_ps );
if ( nullptr != l_errl )
{
PRDF_ERR( PRDF_FUNC "getRowRepair() failed: i_dimm=0x%08x "
"l_ps=%d ds=%d rs=%d", getHuid(i_dimm), l_ps,
i_rank.getDimmSlct(), i_rank.getRankSlct() );
PRDF_COMMIT_ERRL( l_errl, ERRL_ACTION_REPORT );
o_rc = FAIL;
}
else
{
o_rowRepair = MemRowRepair( i_dimm, i_rank, l_data );
}
#endif // __HOSTBOOT_MODULE
*/
return o_rc;
#undef PRDF_FUNC
}
template<>
uint32_t getRowRepairData<TYPE_MEM_PORT>( TargetHandle_t i_dimm,
const MemRank & i_rank, MemRowRepair & o_rowRepair )
{
return __getRowRepairData<TYPE_MEM_PORT, fapi2::TARGET_TYPE_MEM_PORT>(
i_dimm, i_rank, o_rowRepair );
}
template<>
uint32_t getRowRepairData<TYPE_OCMB_CHIP>( TargetHandle_t i_dimm,
const MemRank & i_rank, MemRowRepair & o_rowRepair )
{
return __getRowRepairData<TYPE_OCMB_CHIP, fapi2::TARGET_TYPE_OCMB_CHIP>(
i_dimm, i_rank, o_rowRepair );
}
//------------------------------------------------------------------------------
template<TARGETING::TYPE T, fapi2::TargetType F>
uint32_t __setRowRepairData( TargetHandle_t i_dimm, const MemRank & i_rank,
const MemRowRepair & i_rowRepair )
{
#define PRDF_FUNC "[PlatServices::__setRowRepairData] "
uint32_t o_rc = SUCCESS;
/* TODO RTC 247259
#ifdef __HOSTBOOT_MODULE
if ( !areDramRepairsDisabled() )
{
uint8_t l_data[ROW_REPAIR::ROW_REPAIR_SIZE] = {0};
memcpy( l_data, i_rowRepair.getData(), sizeof(l_data) );
errlHndl_t l_errl = nullptr;
// get port select
uint8_t l_ps = getDimmPort( i_dimm );
// get mba
TargetHandle_t l_mba = getConnectedParent(i_dimm, T);
fapi2::Target<F> l_fapiMba( l_mba );
//p10cleanup
// FAPI_INVOKE_HWP( l_errl, setRowRepair, l_fapiMba, i_rank.getDimmSlct(),
// i_rank.getRankSlct(), l_data, l_ps );
if ( nullptr != l_errl )
{
PRDF_ERR( PRDF_FUNC "setRowRepair() failed: i_dimm=0x%08x "
"l_ps=%d ds=%d rs=%d", getHuid(i_dimm), l_ps,
i_rank.getDimmSlct(), i_rank.getRankSlct() );
PRDF_COMMIT_ERRL( l_errl, ERRL_ACTION_REPORT );
o_rc = FAIL;
}
}
#endif // __HOSTBOOT_MODULE
*/
return o_rc;
#undef PRDF_FUNC
}
template<>
uint32_t setRowRepairData<TYPE_OCMB_CHIP>( TargetHandle_t i_dimm,
const MemRank & i_rank,
const MemRowRepair & i_rowRepair )
{
return __setRowRepairData<TYPE_OCMB_CHIP, fapi2::TARGET_TYPE_OCMB_CHIP>(
i_dimm, i_rank, i_rowRepair );
}
//------------------------------------------------------------------------------
template<TARGETING::TYPE T>
void __setRowRepairDataHelper( const MemAddr & i_addr, uint32_t & io_tmp )
{
#ifdef __HOSTBOOT_MODULE
// Bank is stored as "MCBIST: b0-b2,bg0-bg1 (5-bit)" in a MemAddr.
// bank group - 2 bits (bg1-bg0)
uint64_t l_bnkGrp = i_addr.getBank() & 0x03;
l_bnkGrp = MemUtils::reverseBits( l_bnkGrp, 2 );
io_tmp = ( io_tmp << 2 ) | ( l_bnkGrp & 0x03 );
// bank - 3 bits (b2-b0)
uint64_t l_bnk = (i_addr.getBank() & 0x1C) >> 2;
l_bnk = MemUtils::reverseBits( l_bnk, 3 );
io_tmp = ( io_tmp << 3 ) | ( l_bnk & 0x03 );
// Row is stored as "MCBIST: r0-r17 (18-bit)" in a MemAddr.
uint64_t l_row = MemUtils::reverseBits( i_addr.getRow(), 18 );
// row - 18 bits (r17-r0)
io_tmp = ( io_tmp << 18 ) | ( l_row & 0x0003ffff );
#endif // __HOSTBOOT_MODULE
}
template
void __setRowRepairDataHelper<TYPE_OCMB_CHIP>( const MemAddr & i_addr,
uint32_t & io_tmp );
//------------------------------------------------------------------------------
template<TARGETING::TYPE T>
uint32_t setRowRepairData( TargetHandle_t i_dimm,
const MemRank & i_rank,
const MemAddr & i_addr,
uint8_t i_dram )
{
#define PRDF_FUNC "[PlatServices::setRowRepairData] "
uint32_t o_rc = SUCCESS;
#ifdef __HOSTBOOT_MODULE
if ( !areDramRepairsDisabled() )
{
uint32_t l_tmp = 0;
// The format for a row repair is 32 bits total:
// 5 bits : DRAM position (x8: 0-9, x4: 0-19)
// 3 bits : slave ranks(0-7)
// 2 bits : bank group(0-3) (bg1-bg0)
// 3 bits : bank(0-7) (b2-b0)
// 18 bits: row (r17-r0)
// 1 bit : repair validity (0: invalid, 1: valid)
// dram - 5 bits
l_tmp = ( l_tmp << 5 ) | ( i_dram & 0x1f );
// slave rank - 3 bits
l_tmp = ( l_tmp << 3 ) | ( i_addr.getRank().getSlave() & 0x07 );
// bank group, bank, and row - 23 bits
__setRowRepairDataHelper<T>( i_addr, l_tmp );
// validity - 1 bit
l_tmp = ( l_tmp << 1 ) | 0x1;
// ROW_REPAIR_SIZE = 4
uint8_t l_data[ROW_REPAIR::ROW_REPAIR_SIZE] = {0};
memcpy( l_data, &l_tmp, sizeof(l_data) );
MemRowRepair l_rowRepair( i_dimm, i_rank, l_data );
o_rc = setRowRepairData<T>( i_dimm, i_rank, l_rowRepair );
if ( SUCCESS != o_rc )
{
PRDF_ERR( PRDF_FUNC "setRowRepairData() failed" );
}
}
#endif // __HOSTBOOT_MODULE
return o_rc;
#undef PRDF_FUNC
}
template
uint32_t setRowRepairData<TYPE_OCMB_CHIP>( TargetHandle_t i_dimm,
const MemRank & i_rank,
const MemAddr & i_addr,
uint8_t i_dram );
//------------------------------------------------------------------------------
template<TARGETING::TYPE T>
uint32_t clearRowRepairData( TargetHandle_t i_dimm, const MemRank & i_rank )
{
#define PRDF_FUNC "[PlatServices::clearRowRepairData] "
uint32_t o_rc = SUCCESS;
#ifdef __HOSTBOOT_MODULE
if ( !areDramRepairsDisabled() )
{
uint8_t l_data[ROW_REPAIR::ROW_REPAIR_SIZE] = {0};
memset( l_data, 0, sizeof(l_data) );
MemRowRepair l_rowRepair( i_dimm, i_rank, l_data );
o_rc = setRowRepairData<T>( i_dimm, i_rank, l_rowRepair );
if ( SUCCESS != o_rc )
{
PRDF_ERR( PRDF_FUNC "setRowRepairData() failed" )
}
}
#endif // __HOSTBOOT_MODULE
return o_rc;
#undef PRDF_FUNC
}
template
uint32_t clearRowRepairData<TYPE_OCMB_CHIP>( TargetHandle_t i_dimm,
const MemRank & i_rank );
//------------------------------------------------------------------------------
} // end namespace PRDF
<commit_msg>PRD: Include target_types.H in prdfMemRowRepair.C for P10<commit_after>/* IBM_PROLOG_BEGIN_TAG */
/* This is an automatically generated prolog. */
/* */
/* $Source: src/usr/diag/prdf/common/plat/mem/prdfMemRowRepair.C $ */
/* */
/* OpenPOWER HostBoot Project */
/* */
/* Contributors Listed Below - COPYRIGHT 2018,2020 */
/* [+] International Business Machines Corp. */
/* */
/* */
/* Licensed under the Apache License, Version 2.0 (the "License"); */
/* you may not use this file except in compliance with the License. */
/* You may obtain a copy of the License at */
/* */
/* http://www.apache.org/licenses/LICENSE-2.0 */
/* */
/* Unless required by applicable law or agreed to in writing, software */
/* distributed under the License is distributed on an "AS IS" BASIS, */
/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or */
/* implied. See the License for the specific language governing */
/* permissions and limitations under the License. */
/* */
/* IBM_PROLOG_END_TAG */
/** @file prdfMemRowRepair.C */
#include <prdfMemRowRepair.H>
#include <UtilHash.H>
#include <iipServiceDataCollector.h>
#include <prdfParserUtils.H>
#include <prdfErrlUtil.H>
#include <prdfMemUtils.H>
#include <target_types.H>
#ifdef __HOSTBOOT_MODULE
#include <rowRepairsFuncs.H>
#endif // __HOSTBOOT_MODULE
namespace PRDF
{
using namespace PlatServices;
using namespace PARSERUTILS;
using namespace TARGETING;
//------------------------------------------------------------------------------
bool MemRowRepair::nonZero() const
{
bool o_nonZero = false;
for ( uint32_t i = 0; i < ROW_REPAIR::ROW_REPAIR_SIZE; i++ )
{
if ( 0 != iv_data[i] )
{
o_nonZero = true;
break;
}
}
return o_nonZero;
}
//##############################################################################
// Utility Functions
//##############################################################################
template<TARGETING::TYPE T, fapi2::TargetType F>
uint32_t __getRowRepairData( TargetHandle_t i_dimm, const MemRank & i_rank,
MemRowRepair & o_rowRepair )
{
#define PRDF_FUNC "[PlatServices::__getRowRepairData] "
uint32_t o_rc = SUCCESS;
/* TODO RTC 247259
#ifdef __HOSTBOOT_MODULE
uint8_t l_data[ROW_REPAIR::ROW_REPAIR_SIZE] = {0};
errlHndl_t l_errl = nullptr;
// get port select
uint8_t l_ps = getDimmPort( i_dimm );
// get mba
TargetHandle_t l_mba = getConnectedParent( i_dimm, T );
fapi2::Target<F> l_fapiMba( l_mba );
//p10cleanup
// FAPI_INVOKE_HWP( l_errl, getRowRepair, l_fapiMba, i_rank.getDimmSlct(),
// i_rank.getRankSlct(), l_data, l_ps );
if ( nullptr != l_errl )
{
PRDF_ERR( PRDF_FUNC "getRowRepair() failed: i_dimm=0x%08x "
"l_ps=%d ds=%d rs=%d", getHuid(i_dimm), l_ps,
i_rank.getDimmSlct(), i_rank.getRankSlct() );
PRDF_COMMIT_ERRL( l_errl, ERRL_ACTION_REPORT );
o_rc = FAIL;
}
else
{
o_rowRepair = MemRowRepair( i_dimm, i_rank, l_data );
}
#endif // __HOSTBOOT_MODULE
*/
return o_rc;
#undef PRDF_FUNC
}
template<>
uint32_t getRowRepairData<TYPE_MEM_PORT>( TargetHandle_t i_dimm,
const MemRank & i_rank, MemRowRepair & o_rowRepair )
{
return __getRowRepairData<TYPE_MEM_PORT, fapi2::TARGET_TYPE_MEM_PORT>(
i_dimm, i_rank, o_rowRepair );
}
template<>
uint32_t getRowRepairData<TYPE_OCMB_CHIP>( TargetHandle_t i_dimm,
const MemRank & i_rank, MemRowRepair & o_rowRepair )
{
return __getRowRepairData<TYPE_OCMB_CHIP, fapi2::TARGET_TYPE_OCMB_CHIP>(
i_dimm, i_rank, o_rowRepair );
}
//------------------------------------------------------------------------------
template<TARGETING::TYPE T, fapi2::TargetType F>
uint32_t __setRowRepairData( TargetHandle_t i_dimm, const MemRank & i_rank,
const MemRowRepair & i_rowRepair )
{
#define PRDF_FUNC "[PlatServices::__setRowRepairData] "
uint32_t o_rc = SUCCESS;
/* TODO RTC 247259
#ifdef __HOSTBOOT_MODULE
if ( !areDramRepairsDisabled() )
{
uint8_t l_data[ROW_REPAIR::ROW_REPAIR_SIZE] = {0};
memcpy( l_data, i_rowRepair.getData(), sizeof(l_data) );
errlHndl_t l_errl = nullptr;
// get port select
uint8_t l_ps = getDimmPort( i_dimm );
// get mba
TargetHandle_t l_mba = getConnectedParent(i_dimm, T);
fapi2::Target<F> l_fapiMba( l_mba );
//p10cleanup
// FAPI_INVOKE_HWP( l_errl, setRowRepair, l_fapiMba, i_rank.getDimmSlct(),
// i_rank.getRankSlct(), l_data, l_ps );
if ( nullptr != l_errl )
{
PRDF_ERR( PRDF_FUNC "setRowRepair() failed: i_dimm=0x%08x "
"l_ps=%d ds=%d rs=%d", getHuid(i_dimm), l_ps,
i_rank.getDimmSlct(), i_rank.getRankSlct() );
PRDF_COMMIT_ERRL( l_errl, ERRL_ACTION_REPORT );
o_rc = FAIL;
}
}
#endif // __HOSTBOOT_MODULE
*/
return o_rc;
#undef PRDF_FUNC
}
template<>
uint32_t setRowRepairData<TYPE_OCMB_CHIP>( TargetHandle_t i_dimm,
const MemRank & i_rank,
const MemRowRepair & i_rowRepair )
{
return __setRowRepairData<TYPE_OCMB_CHIP, fapi2::TARGET_TYPE_OCMB_CHIP>(
i_dimm, i_rank, i_rowRepair );
}
//------------------------------------------------------------------------------
template<TARGETING::TYPE T>
void __setRowRepairDataHelper( const MemAddr & i_addr, uint32_t & io_tmp )
{
#ifdef __HOSTBOOT_MODULE
// Bank is stored as "MCBIST: b0-b2,bg0-bg1 (5-bit)" in a MemAddr.
// bank group - 2 bits (bg1-bg0)
uint64_t l_bnkGrp = i_addr.getBank() & 0x03;
l_bnkGrp = MemUtils::reverseBits( l_bnkGrp, 2 );
io_tmp = ( io_tmp << 2 ) | ( l_bnkGrp & 0x03 );
// bank - 3 bits (b2-b0)
uint64_t l_bnk = (i_addr.getBank() & 0x1C) >> 2;
l_bnk = MemUtils::reverseBits( l_bnk, 3 );
io_tmp = ( io_tmp << 3 ) | ( l_bnk & 0x03 );
// Row is stored as "MCBIST: r0-r17 (18-bit)" in a MemAddr.
uint64_t l_row = MemUtils::reverseBits( i_addr.getRow(), 18 );
// row - 18 bits (r17-r0)
io_tmp = ( io_tmp << 18 ) | ( l_row & 0x0003ffff );
#endif // __HOSTBOOT_MODULE
}
template
void __setRowRepairDataHelper<TYPE_OCMB_CHIP>( const MemAddr & i_addr,
uint32_t & io_tmp );
//------------------------------------------------------------------------------
template<TARGETING::TYPE T>
uint32_t setRowRepairData( TargetHandle_t i_dimm,
const MemRank & i_rank,
const MemAddr & i_addr,
uint8_t i_dram )
{
#define PRDF_FUNC "[PlatServices::setRowRepairData] "
uint32_t o_rc = SUCCESS;
#ifdef __HOSTBOOT_MODULE
if ( !areDramRepairsDisabled() )
{
uint32_t l_tmp = 0;
// The format for a row repair is 32 bits total:
// 5 bits : DRAM position (x8: 0-9, x4: 0-19)
// 3 bits : slave ranks(0-7)
// 2 bits : bank group(0-3) (bg1-bg0)
// 3 bits : bank(0-7) (b2-b0)
// 18 bits: row (r17-r0)
// 1 bit : repair validity (0: invalid, 1: valid)
// dram - 5 bits
l_tmp = ( l_tmp << 5 ) | ( i_dram & 0x1f );
// slave rank - 3 bits
l_tmp = ( l_tmp << 3 ) | ( i_addr.getRank().getSlave() & 0x07 );
// bank group, bank, and row - 23 bits
__setRowRepairDataHelper<T>( i_addr, l_tmp );
// validity - 1 bit
l_tmp = ( l_tmp << 1 ) | 0x1;
// ROW_REPAIR_SIZE = 4
uint8_t l_data[ROW_REPAIR::ROW_REPAIR_SIZE] = {0};
memcpy( l_data, &l_tmp, sizeof(l_data) );
MemRowRepair l_rowRepair( i_dimm, i_rank, l_data );
o_rc = setRowRepairData<T>( i_dimm, i_rank, l_rowRepair );
if ( SUCCESS != o_rc )
{
PRDF_ERR( PRDF_FUNC "setRowRepairData() failed" );
}
}
#endif // __HOSTBOOT_MODULE
return o_rc;
#undef PRDF_FUNC
}
template
uint32_t setRowRepairData<TYPE_OCMB_CHIP>( TargetHandle_t i_dimm,
const MemRank & i_rank,
const MemAddr & i_addr,
uint8_t i_dram );
//------------------------------------------------------------------------------
template<TARGETING::TYPE T>
uint32_t clearRowRepairData( TargetHandle_t i_dimm, const MemRank & i_rank )
{
#define PRDF_FUNC "[PlatServices::clearRowRepairData] "
uint32_t o_rc = SUCCESS;
#ifdef __HOSTBOOT_MODULE
if ( !areDramRepairsDisabled() )
{
uint8_t l_data[ROW_REPAIR::ROW_REPAIR_SIZE] = {0};
memset( l_data, 0, sizeof(l_data) );
MemRowRepair l_rowRepair( i_dimm, i_rank, l_data );
o_rc = setRowRepairData<T>( i_dimm, i_rank, l_rowRepair );
if ( SUCCESS != o_rc )
{
PRDF_ERR( PRDF_FUNC "setRowRepairData() failed" )
}
}
#endif // __HOSTBOOT_MODULE
return o_rc;
#undef PRDF_FUNC
}
template
uint32_t clearRowRepairData<TYPE_OCMB_CHIP>( TargetHandle_t i_dimm,
const MemRank & i_rank );
//------------------------------------------------------------------------------
} // end namespace PRDF
<|endoftext|> |
<commit_before>#include "Program.hpp"
Program::Program(std::vector<std::string> args)
{
if (!args.size())
{
throw std::runtime_error("Invalid number of arguments!");
}
csv_file = args[0];
}
Program::~Program()
{
}
int Program::run()
{
char path[FILENAME_MAX];
if (!GetCurrentDir(path, sizeof(path)))
{
throw std::runtime_error("Failed to get current directory path!");
}
std::string work_dir(path);
std::replace(work_dir.begin(), work_dir.end(), '\\', '/');
work_dir += '/';
std::ifstream file(work_dir + csv_file);
if (!file.is_open())
{
throw std::runtime_error("Failed to open CSV file!");
}
RouterCSVParser csv(file);
csv.readHeader("Hostname", "IP Address", "Patched?", "OS Version", "Notes");
std::vector<Router> routers;
Hostname hostname;
IPAddress ip_address;
bool patched;
std::string os_version;
std::string notes;
while (csv.readRow(hostname, ip_address, patched, os_version, notes))
{
if (!hostname.isValid() || !ip_address.isValid())
{
continue;
}
routers.emplace_back(hostname, ip_address, patched, os_version, notes);
}
auto iter_router = std::remove_if(routers.begin(), routers.end(),
[](const Router& router)
{
return router.getOSVersion() < 12.0 || router.getPatched() == true;
});
iter_router = routers.erase(iter_router, routers.end());
iter_router = std::remove_if(routers.begin(), routers.end(),
[&routers](const Router& router)
{
auto iter_router = std::find_if(routers.begin(), routers.end(),
[&](const Router& search_router)
{
return search_router.getIPAddress() == router.getIPAddress() && router != search_router;
});
if (iter_router != routers.end())
{
return true;
}
iter_router = std::find_if(routers.begin(), routers.end(),
[&](const Router& search_router)
{
return search_router.getHostname() == router.getHostname() && router != search_router;
});
if (iter_router != routers.end())
{
return true;
}
return false;
});
iter_router = routers.erase(iter_router, routers.end());
std::for_each(routers.begin(), routers.end(),
[](const Router& router)
{
std::cout << router << std::endl;
});
return 0;
}
<commit_msg>Add debug info for work dir.<commit_after>#include "Program.hpp"
Program::Program(std::vector<std::string> args)
{
if (!args.size())
{
throw std::runtime_error("Invalid number of arguments!");
}
csv_file = args[0];
}
Program::~Program()
{
}
int Program::run()
{
char path[FILENAME_MAX];
if (!GetCurrentDir(path, sizeof(path)))
{
throw std::runtime_error("Failed to get current directory path!");
}
std::string work_dir(path);
std::replace(work_dir.begin(), work_dir.end(), '\\', '/');
work_dir += '/';
std::cout << "Current working directory: " << work_dir << std::endl;
std::ifstream file(work_dir + csv_file);
if (!file.is_open())
{
throw std::runtime_error("Failed to open CSV file!");
}
RouterCSVParser csv(file);
csv.readHeader("Hostname", "IP Address", "Patched?", "OS Version", "Notes");
std::vector<Router> routers;
Hostname hostname;
IPAddress ip_address;
bool patched;
std::string os_version;
std::string notes;
while (csv.readRow(hostname, ip_address, patched, os_version, notes))
{
if (!hostname.isValid() || !ip_address.isValid())
{
continue;
}
routers.emplace_back(hostname, ip_address, patched, os_version, notes);
}
auto iter_router = std::remove_if(routers.begin(), routers.end(),
[](const Router& router)
{
return router.getOSVersion() < 12.0 || router.getPatched() == true;
});
iter_router = routers.erase(iter_router, routers.end());
iter_router = std::remove_if(routers.begin(), routers.end(),
[&routers](const Router& router)
{
auto iter_router = std::find_if(routers.begin(), routers.end(),
[&](const Router& search_router)
{
return search_router.getIPAddress() == router.getIPAddress() && router != search_router;
});
if (iter_router != routers.end())
{
return true;
}
iter_router = std::find_if(routers.begin(), routers.end(),
[&](const Router& search_router)
{
return search_router.getHostname() == router.getHostname() && router != search_router;
});
if (iter_router != routers.end())
{
return true;
}
return false;
});
iter_router = routers.erase(iter_router, routers.end());
std::for_each(routers.begin(), routers.end(),
[](const Router& router)
{
std::cout << router << std::endl;
});
return 0;
}
<|endoftext|> |
<commit_before>//===- PPC32RegisterInfo.cpp - PowerPC32 Register Information ---*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file was developed by the LLVM research group and is distributed under
// the University of Illinois Open Source License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file contains the PowerPC32 implementation of the MRegisterInfo class.
//
//===----------------------------------------------------------------------===//
#define DEBUG_TYPE "reginfo"
#include "PowerPC.h"
#include "PowerPCInstrBuilder.h"
#include "PPC32RegisterInfo.h"
#include "llvm/Constants.h"
#include "llvm/Type.h"
#include "llvm/CodeGen/ValueTypes.h"
#include "llvm/CodeGen/MachineInstrBuilder.h"
#include "llvm/CodeGen/MachineFunction.h"
#include "llvm/CodeGen/MachineFrameInfo.h"
#include "llvm/Target/TargetFrameInfo.h"
#include "llvm/Target/TargetMachine.h"
#include "llvm/Target/TargetOptions.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/Support/Debug.h"
#include "llvm/ADT/STLExtras.h"
#include <cstdlib>
#include <iostream>
using namespace llvm;
PPC32RegisterInfo::PPC32RegisterInfo()
: PPC32GenRegisterInfo(PPC::ADJCALLSTACKDOWN, PPC::ADJCALLSTACKUP) {
ImmToIdxMap[PPC::LD] = PPC::LDX; ImmToIdxMap[PPC::STD] = PPC::STDX;
ImmToIdxMap[PPC::LBZ] = PPC::LBZX; ImmToIdxMap[PPC::STB] = PPC::STBX;
ImmToIdxMap[PPC::LHZ] = PPC::LHZX; ImmToIdxMap[PPC::LHA] = PPC::LHAX;
ImmToIdxMap[PPC::LWZ] = PPC::LWZX; ImmToIdxMap[PPC::LWA] = PPC::LWAX;
ImmToIdxMap[PPC::LFS] = PPC::LFSX; ImmToIdxMap[PPC::LFD] = PPC::LFDX;
ImmToIdxMap[PPC::STH] = PPC::STHX; ImmToIdxMap[PPC::STW] = PPC::STWX;
ImmToIdxMap[PPC::STFS] = PPC::STFSX; ImmToIdxMap[PPC::STFD] = PPC::STFDX;
ImmToIdxMap[PPC::ADDI] = PPC::ADD;
}
static const TargetRegisterClass *getClass(unsigned SrcReg) {
if (PPC32::GPRCRegisterClass->contains(SrcReg))
return PPC32::GPRCRegisterClass;
if (PPC32::FPRCRegisterClass->contains(SrcReg))
return PPC32::FPRCRegisterClass;
assert(PPC32::CRRCRegisterClass->contains(SrcReg) &&"Reg not FPR, GPR, CRRC");
return PPC32::CRRCRegisterClass;
}
static unsigned getIdx(const TargetRegisterClass *RC) {
if (RC == PPC32::GPRCRegisterClass) {
switch (RC->getSize()) {
default: assert(0 && "Invalid data size!");
case 1: return 0;
case 2: return 1;
case 4: return 2;
}
} else if (RC == PPC32::FPRCRegisterClass) {
switch (RC->getSize()) {
default: assert(0 && "Invalid data size!");
case 4: return 3;
case 8: return 4;
}
} else if (RC == PPC32::CRRCRegisterClass) {
switch (RC->getSize()) {
default: assert(0 && "Invalid data size!");
case 4: return 2;
}
}
std::cerr << "Invalid register class to getIdx()!\n";
abort();
}
void
PPC32RegisterInfo::storeRegToStackSlot(MachineBasicBlock &MBB,
MachineBasicBlock::iterator MI,
unsigned SrcReg, int FrameIdx) const {
static const unsigned Opcode[] = {
PPC::STB, PPC::STH, PPC::STW, PPC::STFS, PPC::STFD
};
const TargetRegisterClass *RegClass = getClass(SrcReg);
unsigned OC = Opcode[getIdx(RegClass)];
if (SrcReg == PPC::LR) {
BuildMI(MBB, MI, PPC::MFLR, 1, PPC::R11);
addFrameReference(BuildMI(MBB, MI, OC, 3).addReg(PPC::R11),FrameIdx);
} else if (RegClass == PPC32::CRRCRegisterClass) {
BuildMI(MBB, MI, PPC::MFCR, 0, PPC::R11);
addFrameReference(BuildMI(MBB, MI, OC, 3).addReg(PPC::R11),FrameIdx);
} else {
addFrameReference(BuildMI(MBB, MI, OC, 3).addReg(SrcReg),FrameIdx);
}
}
void
PPC32RegisterInfo::loadRegFromStackSlot(MachineBasicBlock &MBB,
MachineBasicBlock::iterator MI,
unsigned DestReg, int FrameIdx) const {
static const unsigned Opcode[] = {
PPC::LBZ, PPC::LHZ, PPC::LWZ, PPC::LFS, PPC::LFD
};
const TargetRegisterClass *RegClass = getClass(DestReg);
unsigned OC = Opcode[getIdx(RegClass)];
if (DestReg == PPC::LR) {
addFrameReference(BuildMI(MBB, MI, OC, 2, PPC::R11), FrameIdx);
BuildMI(MBB, MI, PPC::MTLR, 1).addReg(PPC::R11);
} else if (RegClass == PPC32::CRRCRegisterClass) {
addFrameReference(BuildMI(MBB, MI, OC, 2, PPC::R11), FrameIdx);
BuildMI(MBB, MI, PPC::MTCRF, 1, DestReg).addReg(PPC::R11);
} else {
addFrameReference(BuildMI(MBB, MI, OC, 2, DestReg), FrameIdx);
}
}
void PPC32RegisterInfo::copyRegToReg(MachineBasicBlock &MBB,
MachineBasicBlock::iterator MI,
unsigned DestReg, unsigned SrcReg,
const TargetRegisterClass *RC) const {
MachineInstr *I;
if (RC == PPC32::GPRCRegisterClass) {
BuildMI(MBB, MI, PPC::OR, 2, DestReg).addReg(SrcReg).addReg(SrcReg);
} else if (RC == PPC32::FPRCRegisterClass) {
BuildMI(MBB, MI, PPC::FMR, 1, DestReg).addReg(SrcReg);
} else if (RC == PPC32::CRRCRegisterClass) {
BuildMI(MBB, MI, PPC::MCRF, 1, DestReg).addReg(SrcReg);
} else {
std::cerr << "Attempt to copy register that is not GPR or FPR";
abort();
}
}
//===----------------------------------------------------------------------===//
// Stack Frame Processing methods
//===----------------------------------------------------------------------===//
// hasFP - Return true if the specified function should have a dedicated frame
// pointer register. This is true if the function has variable sized allocas or
// if frame pointer elimination is disabled.
//
static bool hasFP(MachineFunction &MF) {
return NoFramePointerElim || MF.getFrameInfo()->hasVarSizedObjects();
}
void PPC32RegisterInfo::
eliminateCallFramePseudoInstr(MachineFunction &MF, MachineBasicBlock &MBB,
MachineBasicBlock::iterator I) const {
if (hasFP(MF)) {
// If we have a frame pointer, convert as follows:
// ADJCALLSTACKDOWN -> addi, r1, r1, -amount
// ADJCALLSTACKUP -> addi, r1, r1, amount
MachineInstr *Old = I;
unsigned Amount = Old->getOperand(0).getImmedValue();
if (Amount != 0) {
// We need to keep the stack aligned properly. To do this, we round the
// amount of space needed for the outgoing arguments up to the next
// alignment boundary.
unsigned Align = MF.getTarget().getFrameInfo()->getStackAlignment();
Amount = (Amount+Align-1)/Align*Align;
// Replace the pseudo instruction with a new instruction...
if (Old->getOpcode() == PPC::ADJCALLSTACKDOWN) {
MBB.insert(I, BuildMI(PPC::ADDI, 2, PPC::R1).addReg(PPC::R1)
.addSImm(-Amount));
} else {
assert(Old->getOpcode() == PPC::ADJCALLSTACKUP);
MBB.insert(I, BuildMI(PPC::ADDI, 2, PPC::R1).addReg(PPC::R1)
.addSImm(Amount));
}
}
}
MBB.erase(I);
}
void
PPC32RegisterInfo::eliminateFrameIndex(MachineBasicBlock::iterator II) const {
unsigned i = 0;
MachineInstr &MI = *II;
MachineBasicBlock &MBB = *MI.getParent();
MachineFunction &MF = *MBB.getParent();
while (!MI.getOperand(i).isFrameIndex()) {
++i;
assert(i < MI.getNumOperands() && "Instr doesn't have FrameIndex operand!");
}
int FrameIndex = MI.getOperand(i).getFrameIndex();
// Replace the FrameIndex with base register with GPR1 (SP) or GPR31 (FP).
MI.SetMachineOperandReg(i, hasFP(MF) ? PPC::R31 : PPC::R1);
// Take into account whether it's an add or mem instruction
unsigned OffIdx = (i == 2) ? 1 : 2;
// Now add the frame object offset to the offset from r1.
int Offset = MF.getFrameInfo()->getObjectOffset(FrameIndex) +
MI.getOperand(OffIdx).getImmedValue();
// If we're not using a Frame Pointer that has been set to the value of the
// SP before having the stack size subtracted from it, then add the stack size
// to Offset to get the correct offset.
Offset += MF.getFrameInfo()->getStackSize();
if (Offset > 32767 || Offset < -32768) {
// Insert a set of r0 with the full offset value before the ld, st, or add
MachineBasicBlock *MBB = MI.getParent();
MBB->insert(II, BuildMI(PPC::LIS, 1, PPC::R0).addSImm(Offset >> 16));
MBB->insert(II, BuildMI(PPC::ORI, 2, PPC::R0).addReg(PPC::R0)
.addImm(Offset));
// convert into indexed form of the instruction
// sth 0:rA, 1:imm 2:(rB) ==> sthx 0:rA, 2:rB, 1:r0
// addi 0:rA 1:rB, 2, imm ==> add 0:rA, 1:rB, 2:r0
unsigned NewOpcode = const_cast<std::map<unsigned, unsigned>& >(ImmToIdxMap)[MI.getOpcode()];
assert(NewOpcode && "No indexed form of load or store available!");
MI.setOpcode(NewOpcode);
MI.SetMachineOperandReg(1, MI.getOperand(i).getReg());
MI.SetMachineOperandReg(2, PPC::R0);
} else {
MI.SetMachineOperandConst(OffIdx,MachineOperand::MO_SignExtendedImmed,Offset);
}
}
void PPC32RegisterInfo::emitPrologue(MachineFunction &MF) const {
MachineBasicBlock &MBB = MF.front(); // Prolog goes in entry BB
MachineBasicBlock::iterator MBBI = MBB.begin();
MachineFrameInfo *MFI = MF.getFrameInfo();
MachineInstr *MI;
// Get the number of bytes to allocate from the FrameInfo
unsigned NumBytes = MFI->getStackSize();
// If we have calls, we cannot use the red zone to store callee save registers
// and we must set up a stack frame, so calculate the necessary size here.
if (MFI->hasCalls()) {
// We reserve argument space for call sites in the function immediately on
// entry to the current function. This eliminates the need for add/sub
// brackets around call sites.
NumBytes += MFI->getMaxCallFrameSize();
}
// If we are a leaf function, and use up to 224 bytes of stack space,
// and don't have a frame pointer, then we do not need to adjust the stack
// pointer (we fit in the Red Zone).
if ((NumBytes == 0) || (NumBytes <= 224 && !hasFP(MF) && !MFI->hasCalls())) {
MFI->setStackSize(0);
return;
}
// Add the size of R1 to NumBytes size for the store of R1 to the bottom
// of the stack and round the size to a multiple of the alignment.
unsigned Align = MF.getTarget().getFrameInfo()->getStackAlignment();
unsigned GPRSize = getSpillSize(PPC::R1)/8;
unsigned Size = hasFP(MF) ? GPRSize + GPRSize : GPRSize;
NumBytes = (NumBytes+Size+Align-1)/Align*Align;
// Update frame info to pretend that this is part of the stack...
MFI->setStackSize(NumBytes);
// Adjust stack pointer: r1 -= numbytes.
if (NumBytes <= 32768) {
MI=BuildMI(PPC::STWU,3).addReg(PPC::R1).addSImm(-NumBytes).addReg(PPC::R1);
MBB.insert(MBBI, MI);
} else {
int NegNumbytes = -NumBytes;
MI = BuildMI(PPC::LIS, 1, PPC::R0).addSImm(NegNumbytes >> 16);
MBB.insert(MBBI, MI);
MI = BuildMI(PPC::ORI, 2, PPC::R0).addReg(PPC::R0)
.addImm(NegNumbytes & 0xFFFF);
MBB.insert(MBBI, MI);
MI = BuildMI(PPC::STWUX, 3).addReg(PPC::R1).addReg(PPC::R1).addReg(PPC::R0);
MBB.insert(MBBI, MI);
}
if (hasFP(MF)) {
MI = BuildMI(PPC::STW, 3).addReg(PPC::R31).addSImm(GPRSize).addReg(PPC::R1);
MBB.insert(MBBI, MI);
MI = BuildMI(PPC::OR, 2, PPC::R31).addReg(PPC::R1).addReg(PPC::R1);
MBB.insert(MBBI, MI);
}
}
void PPC32RegisterInfo::emitEpilogue(MachineFunction &MF,
MachineBasicBlock &MBB) const {
const MachineFrameInfo *MFI = MF.getFrameInfo();
MachineBasicBlock::iterator MBBI = prior(MBB.end());
MachineInstr *MI;
assert(MBBI->getOpcode() == PPC::BLR &&
"Can only insert epilog into returning blocks");
// Get the number of bytes allocated from the FrameInfo...
unsigned NumBytes = MFI->getStackSize();
unsigned GPRSize = getSpillSize(PPC::R31)/8;
if (NumBytes != 0) {
if (hasFP(MF)) {
MI = BuildMI(PPC::LWZ, 2, PPC::R31).addSImm(GPRSize).addReg(PPC::R31);
MBB.insert(MBBI, MI);
}
MI = BuildMI(PPC::LWZ, 2, PPC::R1).addSImm(0).addReg(PPC::R1);
MBB.insert(MBBI, MI);
}
}
#include "PPC32GenRegisterInfo.inc"
<commit_msg>code cleanup<commit_after>//===- PPC32RegisterInfo.cpp - PowerPC32 Register Information ---*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file was developed by the LLVM research group and is distributed under
// the University of Illinois Open Source License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file contains the PowerPC32 implementation of the MRegisterInfo class.
//
//===----------------------------------------------------------------------===//
#define DEBUG_TYPE "reginfo"
#include "PowerPC.h"
#include "PowerPCInstrBuilder.h"
#include "PPC32RegisterInfo.h"
#include "llvm/Constants.h"
#include "llvm/Type.h"
#include "llvm/CodeGen/ValueTypes.h"
#include "llvm/CodeGen/MachineInstrBuilder.h"
#include "llvm/CodeGen/MachineFunction.h"
#include "llvm/CodeGen/MachineFrameInfo.h"
#include "llvm/Target/TargetFrameInfo.h"
#include "llvm/Target/TargetMachine.h"
#include "llvm/Target/TargetOptions.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/Support/Debug.h"
#include "llvm/ADT/STLExtras.h"
#include <cstdlib>
#include <iostream>
using namespace llvm;
PPC32RegisterInfo::PPC32RegisterInfo()
: PPC32GenRegisterInfo(PPC::ADJCALLSTACKDOWN, PPC::ADJCALLSTACKUP) {
ImmToIdxMap[PPC::LD] = PPC::LDX; ImmToIdxMap[PPC::STD] = PPC::STDX;
ImmToIdxMap[PPC::LBZ] = PPC::LBZX; ImmToIdxMap[PPC::STB] = PPC::STBX;
ImmToIdxMap[PPC::LHZ] = PPC::LHZX; ImmToIdxMap[PPC::LHA] = PPC::LHAX;
ImmToIdxMap[PPC::LWZ] = PPC::LWZX; ImmToIdxMap[PPC::LWA] = PPC::LWAX;
ImmToIdxMap[PPC::LFS] = PPC::LFSX; ImmToIdxMap[PPC::LFD] = PPC::LFDX;
ImmToIdxMap[PPC::STH] = PPC::STHX; ImmToIdxMap[PPC::STW] = PPC::STWX;
ImmToIdxMap[PPC::STFS] = PPC::STFSX; ImmToIdxMap[PPC::STFD] = PPC::STFDX;
ImmToIdxMap[PPC::ADDI] = PPC::ADD;
}
static const TargetRegisterClass *getClass(unsigned SrcReg) {
if (PPC32::GPRCRegisterClass->contains(SrcReg))
return PPC32::GPRCRegisterClass;
if (PPC32::FPRCRegisterClass->contains(SrcReg))
return PPC32::FPRCRegisterClass;
assert(PPC32::CRRCRegisterClass->contains(SrcReg) &&"Reg not FPR, GPR, CRRC");
return PPC32::CRRCRegisterClass;
}
static unsigned getIdx(const TargetRegisterClass *RC) {
if (RC == PPC32::GPRCRegisterClass) {
switch (RC->getSize()) {
default: assert(0 && "Invalid data size!");
case 1: return 0;
case 2: return 1;
case 4: return 2;
}
} else if (RC == PPC32::FPRCRegisterClass) {
switch (RC->getSize()) {
default: assert(0 && "Invalid data size!");
case 4: return 3;
case 8: return 4;
}
} else if (RC == PPC32::CRRCRegisterClass) {
switch (RC->getSize()) {
default: assert(0 && "Invalid data size!");
case 4: return 2;
}
}
std::cerr << "Invalid register class to getIdx()!\n";
abort();
}
void
PPC32RegisterInfo::storeRegToStackSlot(MachineBasicBlock &MBB,
MachineBasicBlock::iterator MI,
unsigned SrcReg, int FrameIdx) const {
static const unsigned Opcode[] = {
PPC::STB, PPC::STH, PPC::STW, PPC::STFS, PPC::STFD
};
const TargetRegisterClass *RegClass = getClass(SrcReg);
unsigned OC = Opcode[getIdx(RegClass)];
if (SrcReg == PPC::LR) {
BuildMI(MBB, MI, PPC::MFLR, 1, PPC::R11);
addFrameReference(BuildMI(MBB, MI, OC, 3).addReg(PPC::R11),FrameIdx);
} else if (RegClass == PPC32::CRRCRegisterClass) {
BuildMI(MBB, MI, PPC::MFCR, 0, PPC::R11);
addFrameReference(BuildMI(MBB, MI, OC, 3).addReg(PPC::R11),FrameIdx);
} else {
addFrameReference(BuildMI(MBB, MI, OC, 3).addReg(SrcReg),FrameIdx);
}
}
void
PPC32RegisterInfo::loadRegFromStackSlot(MachineBasicBlock &MBB,
MachineBasicBlock::iterator MI,
unsigned DestReg, int FrameIdx) const {
static const unsigned Opcode[] = {
PPC::LBZ, PPC::LHZ, PPC::LWZ, PPC::LFS, PPC::LFD
};
const TargetRegisterClass *RegClass = getClass(DestReg);
unsigned OC = Opcode[getIdx(RegClass)];
if (DestReg == PPC::LR) {
addFrameReference(BuildMI(MBB, MI, OC, 2, PPC::R11), FrameIdx);
BuildMI(MBB, MI, PPC::MTLR, 1).addReg(PPC::R11);
} else if (RegClass == PPC32::CRRCRegisterClass) {
addFrameReference(BuildMI(MBB, MI, OC, 2, PPC::R11), FrameIdx);
BuildMI(MBB, MI, PPC::MTCRF, 1, DestReg).addReg(PPC::R11);
} else {
addFrameReference(BuildMI(MBB, MI, OC, 2, DestReg), FrameIdx);
}
}
void PPC32RegisterInfo::copyRegToReg(MachineBasicBlock &MBB,
MachineBasicBlock::iterator MI,
unsigned DestReg, unsigned SrcReg,
const TargetRegisterClass *RC) const {
MachineInstr *I;
if (RC == PPC32::GPRCRegisterClass) {
BuildMI(MBB, MI, PPC::OR, 2, DestReg).addReg(SrcReg).addReg(SrcReg);
} else if (RC == PPC32::FPRCRegisterClass) {
BuildMI(MBB, MI, PPC::FMR, 1, DestReg).addReg(SrcReg);
} else if (RC == PPC32::CRRCRegisterClass) {
BuildMI(MBB, MI, PPC::MCRF, 1, DestReg).addReg(SrcReg);
} else {
std::cerr << "Attempt to copy register that is not GPR or FPR";
abort();
}
}
//===----------------------------------------------------------------------===//
// Stack Frame Processing methods
//===----------------------------------------------------------------------===//
// hasFP - Return true if the specified function should have a dedicated frame
// pointer register. This is true if the function has variable sized allocas or
// if frame pointer elimination is disabled.
//
static bool hasFP(MachineFunction &MF) {
return NoFramePointerElim || MF.getFrameInfo()->hasVarSizedObjects();
}
void PPC32RegisterInfo::
eliminateCallFramePseudoInstr(MachineFunction &MF, MachineBasicBlock &MBB,
MachineBasicBlock::iterator I) const {
if (hasFP(MF)) {
// If we have a frame pointer, convert as follows:
// ADJCALLSTACKDOWN -> addi, r1, r1, -amount
// ADJCALLSTACKUP -> addi, r1, r1, amount
MachineInstr *Old = I;
unsigned Amount = Old->getOperand(0).getImmedValue();
if (Amount != 0) {
// We need to keep the stack aligned properly. To do this, we round the
// amount of space needed for the outgoing arguments up to the next
// alignment boundary.
unsigned Align = MF.getTarget().getFrameInfo()->getStackAlignment();
Amount = (Amount+Align-1)/Align*Align;
// Replace the pseudo instruction with a new instruction...
if (Old->getOpcode() == PPC::ADJCALLSTACKDOWN) {
MBB.insert(I, BuildMI(PPC::ADDI, 2, PPC::R1).addReg(PPC::R1)
.addSImm(-Amount));
} else {
assert(Old->getOpcode() == PPC::ADJCALLSTACKUP);
MBB.insert(I, BuildMI(PPC::ADDI, 2, PPC::R1).addReg(PPC::R1)
.addSImm(Amount));
}
}
}
MBB.erase(I);
}
void
PPC32RegisterInfo::eliminateFrameIndex(MachineBasicBlock::iterator II) const {
unsigned i = 0;
MachineInstr &MI = *II;
MachineBasicBlock &MBB = *MI.getParent();
MachineFunction &MF = *MBB.getParent();
while (!MI.getOperand(i).isFrameIndex()) {
++i;
assert(i < MI.getNumOperands() && "Instr doesn't have FrameIndex operand!");
}
int FrameIndex = MI.getOperand(i).getFrameIndex();
// Replace the FrameIndex with base register with GPR1 (SP) or GPR31 (FP).
MI.SetMachineOperandReg(i, hasFP(MF) ? PPC::R31 : PPC::R1);
// Take into account whether it's an add or mem instruction
unsigned OffIdx = (i == 2) ? 1 : 2;
// Now add the frame object offset to the offset from r1.
int Offset = MF.getFrameInfo()->getObjectOffset(FrameIndex) +
MI.getOperand(OffIdx).getImmedValue();
// If we're not using a Frame Pointer that has been set to the value of the
// SP before having the stack size subtracted from it, then add the stack size
// to Offset to get the correct offset.
Offset += MF.getFrameInfo()->getStackSize();
if (Offset > 32767 || Offset < -32768) {
// Insert a set of r0 with the full offset value before the ld, st, or add
MachineBasicBlock *MBB = MI.getParent();
MBB->insert(II, BuildMI(PPC::LIS, 1, PPC::R0).addSImm(Offset >> 16));
MBB->insert(II, BuildMI(PPC::ORI, 2, PPC::R0).addReg(PPC::R0)
.addImm(Offset));
// convert into indexed form of the instruction
// sth 0:rA, 1:imm 2:(rB) ==> sthx 0:rA, 2:rB, 1:r0
// addi 0:rA 1:rB, 2, imm ==> add 0:rA, 1:rB, 2:r0
assert(ImmToIdxMap.count(MI.getOpcode()) &&
"No indexed form of load or store available!");
unsigned NewOpcode = ImmToIdxMap.find(MI.getOpcode())->second;
MI.setOpcode(NewOpcode);
MI.SetMachineOperandReg(1, MI.getOperand(i).getReg());
MI.SetMachineOperandReg(2, PPC::R0);
} else {
MI.SetMachineOperandConst(OffIdx,MachineOperand::MO_SignExtendedImmed,Offset);
}
}
void PPC32RegisterInfo::emitPrologue(MachineFunction &MF) const {
MachineBasicBlock &MBB = MF.front(); // Prolog goes in entry BB
MachineBasicBlock::iterator MBBI = MBB.begin();
MachineFrameInfo *MFI = MF.getFrameInfo();
MachineInstr *MI;
// Get the number of bytes to allocate from the FrameInfo
unsigned NumBytes = MFI->getStackSize();
// If we have calls, we cannot use the red zone to store callee save registers
// and we must set up a stack frame, so calculate the necessary size here.
if (MFI->hasCalls()) {
// We reserve argument space for call sites in the function immediately on
// entry to the current function. This eliminates the need for add/sub
// brackets around call sites.
NumBytes += MFI->getMaxCallFrameSize();
}
// If we are a leaf function, and use up to 224 bytes of stack space,
// and don't have a frame pointer, then we do not need to adjust the stack
// pointer (we fit in the Red Zone).
if ((NumBytes == 0) || (NumBytes <= 224 && !hasFP(MF) && !MFI->hasCalls())) {
MFI->setStackSize(0);
return;
}
// Add the size of R1 to NumBytes size for the store of R1 to the bottom
// of the stack and round the size to a multiple of the alignment.
unsigned Align = MF.getTarget().getFrameInfo()->getStackAlignment();
unsigned GPRSize = getSpillSize(PPC::R1)/8;
unsigned Size = hasFP(MF) ? GPRSize + GPRSize : GPRSize;
NumBytes = (NumBytes+Size+Align-1)/Align*Align;
// Update frame info to pretend that this is part of the stack...
MFI->setStackSize(NumBytes);
// Adjust stack pointer: r1 -= numbytes.
if (NumBytes <= 32768) {
MI=BuildMI(PPC::STWU,3).addReg(PPC::R1).addSImm(-NumBytes).addReg(PPC::R1);
MBB.insert(MBBI, MI);
} else {
int NegNumbytes = -NumBytes;
MI = BuildMI(PPC::LIS, 1, PPC::R0).addSImm(NegNumbytes >> 16);
MBB.insert(MBBI, MI);
MI = BuildMI(PPC::ORI, 2, PPC::R0).addReg(PPC::R0)
.addImm(NegNumbytes & 0xFFFF);
MBB.insert(MBBI, MI);
MI = BuildMI(PPC::STWUX, 3).addReg(PPC::R1).addReg(PPC::R1).addReg(PPC::R0);
MBB.insert(MBBI, MI);
}
if (hasFP(MF)) {
MI = BuildMI(PPC::STW, 3).addReg(PPC::R31).addSImm(GPRSize).addReg(PPC::R1);
MBB.insert(MBBI, MI);
MI = BuildMI(PPC::OR, 2, PPC::R31).addReg(PPC::R1).addReg(PPC::R1);
MBB.insert(MBBI, MI);
}
}
void PPC32RegisterInfo::emitEpilogue(MachineFunction &MF,
MachineBasicBlock &MBB) const {
const MachineFrameInfo *MFI = MF.getFrameInfo();
MachineBasicBlock::iterator MBBI = prior(MBB.end());
MachineInstr *MI;
assert(MBBI->getOpcode() == PPC::BLR &&
"Can only insert epilog into returning blocks");
// Get the number of bytes allocated from the FrameInfo...
unsigned NumBytes = MFI->getStackSize();
unsigned GPRSize = getSpillSize(PPC::R31)/8;
if (NumBytes != 0) {
if (hasFP(MF)) {
MI = BuildMI(PPC::LWZ, 2, PPC::R31).addSImm(GPRSize).addReg(PPC::R31);
MBB.insert(MBBI, MI);
}
MI = BuildMI(PPC::LWZ, 2, PPC::R1).addSImm(0).addReg(PPC::R1);
MBB.insert(MBBI, MI);
}
}
#include "PPC32GenRegisterInfo.inc"
<|endoftext|> |
<commit_before>#include <mpi.h>
#include <stdio.h>
#include <stdlib.h>
#include <algorithm>
#include <time.h>
#include "string.h"
#include "assert.h"
#include <iostream>
#include <vector>
#include "tau.h"
#define MAX_NAME_LENGTH 38
int main_argc=-1;
char ** main_argv;
MPI_Comm comm;
double excl_time;
double complete_time;
int set_contxt = 0;
class function_timer{
public:
char name[MAX_NAME_LENGTH];
double start_time;
double start_excl_time;
double acc_time;
double acc_excl_time;
int calls;
double total_time;
double total_excl_time;
int total_calls;
public:
function_timer(char const * name_,
double const start_time_,
double const start_excl_time_){
sprintf(name, "%s", name_);
start_time = start_time_;
start_excl_time = start_excl_time_;
if (strlen(name) > MAX_NAME_LENGTH) {
printf("function name must be fewer than %d characters\n",MAX_NAME_LENGTH);
assert(0);
}
acc_time = 0.0;
acc_excl_time = 0.0;
calls = 0;
}
void compute_totals(MPI_Comm comm){
MPI_Allreduce(&acc_time, &total_time, 1,
MPI_DOUBLE, MPI_SUM, comm);
MPI_Allreduce(&acc_excl_time, &total_excl_time, 1,
MPI_DOUBLE, MPI_SUM, comm);
MPI_Allreduce(&calls, &total_calls, 1,
MPI_INT, MPI_SUM, comm);
}
bool operator<(function_timer const & w) const {
return total_time > w.total_time;
}
void print(FILE * output,
MPI_Comm const comm,
int const rank,
int const np){
int i;
if (rank == 0){
fprintf(output, "%s", name);
char * space = (char*)malloc(MAX_NAME_LENGTH-strlen(name)+1);
for (i=0; i<MAX_NAME_LENGTH-(int)strlen(name); i++){
space[i] = ' ';
}
space[i] = '\0';
fprintf(output, "%s", space);
fprintf(output,"%5d %3d.%04d %3d.%02d %3d.%04d %3d.%02d\n",
total_calls/np,
(int)(total_time/np),
((int)(1000.*(total_time)/np))%1000,
(int)(100.*(total_time)/complete_time),
((int)(10000.*(total_time)/complete_time))%100,
(int)(total_excl_time/np),
((int)(1000.*(total_excl_time)/np))%1000,
(int)(100.*(total_excl_time)/complete_time),
((int)(10000.*(total_excl_time)/complete_time))%100);
}
}
};
bool comp_name(function_timer const & w1, function_timer const & w2) {
return strcmp(w1.name, w2.name)>0;
}
std::vector<function_timer> function_timers;
CTF_timer::CTF_timer(const char * name){
int i;
if (function_timers.size() == 0) {
original = 1;
index = 0;
excl_time = 0.0;
function_timers.push_back(function_timer(name, MPI_Wtime(), 0.0));
} else {
for (i=0; i<(int)function_timers.size(); i++){
if (strcmp(function_timers[i].name, name) == 0){
/*function_timers[i].start_time = MPI_Wtime();
function_timers[i].start_excl_time = excl_time;*/
break;
}
}
index = i;
original = (index==0);
}
if (index == (int)function_timers.size()) {
function_timers.push_back(function_timer(name, MPI_Wtime(), excl_time));
}
timer_name = name;
exited = 0;
}
void CTF_timer::start(){
function_timers[index].start_time = MPI_Wtime();
function_timers[index].start_excl_time = excl_time;
}
void CTF_timer::stop(){
double delta_time = MPI_Wtime() - function_timers[index].start_time;
function_timers[index].acc_time += delta_time;
function_timers[index].acc_excl_time += delta_time -
(excl_time- function_timers[index].start_excl_time);
excl_time = function_timers[index].start_excl_time + delta_time;
function_timers[index].calls++;
exit();
exited = 1;
}
CTF_timer::~CTF_timer(){ }
void CTF_timer::exit(){
if (set_contxt && original && !exited) {
int rank, np, i, j, p, len_symbols;
MPI_Comm_rank(comm, &rank);
MPI_Comm_size(comm, &np);
FILE * output;
char all_symbols[10000];
if (rank == 0){
char filename[300];
char part[300];
sprintf(filename, "profile.");
int off;
if (main_argc != -1){
for (off=strlen(main_argv[0]); off>=0; off--){
if (main_argv[0][off-1] == '/') break;
}
for (i=0; i<main_argc; i++){
if (i==0)
sprintf(filename+strlen(filename), "%s.", main_argv[0]+off);
else
sprintf(filename+strlen(filename), "%s.", main_argv[i]);
}
}
sprintf(filename+strlen(filename), "-p%d.out", np);
output = fopen(filename, "w");
char heading[MAX_NAME_LENGTH+200];
for (i=0; i<MAX_NAME_LENGTH; i++){
part[i] = ' ';
}
part[i] = '\0';
sprintf(heading,"%s",part);
//sprintf(part,"calls total sec exclusive sec\n");
sprintf(part," inclusive exclusive\n");
strcat(heading,part);
fprintf(output, "%s", heading);
for (i=0; i<MAX_NAME_LENGTH; i++){
part[i] = ' ';
}
part[i] = '\0';
sprintf(heading,"%s",part);
sprintf(part, "calls sec %%");
strcat(heading,part);
sprintf(part, " sec %%\n");
strcat(heading,part);
fprintf(output, "%s", heading);
len_symbols = 0;
for (i=0; i<(int)function_timers.size(); i++){
sprintf(all_symbols+len_symbols, "%s", function_timers[i].name);
len_symbols += strlen(function_timers[i].name)+1;
}
}
if (np > 1){
for (p=0; p<np; p++){
if (rank == p){
MPI_Send(&len_symbols, 1, MPI_INT, (p+1)%np, 1, comm);
MPI_Send(all_symbols, len_symbols, MPI_CHAR, (p+1)%np, 2, comm);
}
if (rank == (p+1)%np){
MPI_Status stat;
MPI_Recv(&len_symbols, 1, MPI_INT, p, 1, comm, &stat);
MPI_Recv(all_symbols, len_symbols, MPI_CHAR, p, 2, comm, &stat);
for (i=0; i<(int)function_timers.size(); i++){
j=0;
while (j<len_symbols && strcmp(all_symbols+j, function_timers[i].name) != 0){
j+=strlen(all_symbols+j)+1;
}
if (j>=len_symbols){
sprintf(all_symbols+len_symbols, "%s", function_timers[i].name);
len_symbols += strlen(function_timers[i].name)+1;
}
}
}
}
MPI_Bcast(all_symbols, len_symbols, MPI_CHAR, 0, comm);
j=0;
while (j<len_symbols){
CTF_timer t(all_symbols+j);
j+=strlen(all_symbols+j)+1;
}
}
std::sort(function_timers.begin(), function_timers.end(),comp_name);
for (i=0; i<(int)function_timers.size(); i++){
function_timers[i].compute_totals(comm);
}
std::sort(function_timers.begin(), function_timers.end());
complete_time = function_timers[0].total_time;
for (i=0; i<(int)function_timers.size(); i++){
function_timers[i].print(output,comm,rank,np);
}
if (rank == 0){
fclose(output);
}
}
}
void CTF_set_main_args(int argc, char ** argv){
main_argv = argv;
main_argc = argc;
}
void CTF_set_context(int const ctxt){
set_contxt = 1;
if (ctxt == 0) comm = MPI_COMM_WORLD;
else comm = ctxt;
}
<commit_msg>fixed offset in tau exe name<commit_after>#include <mpi.h>
#include <stdio.h>
#include <stdlib.h>
#include <algorithm>
#include <time.h>
#include "string.h"
#include "assert.h"
#include <iostream>
#include <vector>
#include "tau.h"
#define MAX_NAME_LENGTH 38
int main_argc=-1;
char ** main_argv;
MPI_Comm comm;
double excl_time;
double complete_time;
int set_contxt = 0;
class function_timer{
public:
char name[MAX_NAME_LENGTH];
double start_time;
double start_excl_time;
double acc_time;
double acc_excl_time;
int calls;
double total_time;
double total_excl_time;
int total_calls;
public:
function_timer(char const * name_,
double const start_time_,
double const start_excl_time_){
sprintf(name, "%s", name_);
start_time = start_time_;
start_excl_time = start_excl_time_;
if (strlen(name) > MAX_NAME_LENGTH) {
printf("function name must be fewer than %d characters\n",MAX_NAME_LENGTH);
assert(0);
}
acc_time = 0.0;
acc_excl_time = 0.0;
calls = 0;
}
void compute_totals(MPI_Comm comm){
MPI_Allreduce(&acc_time, &total_time, 1,
MPI_DOUBLE, MPI_SUM, comm);
MPI_Allreduce(&acc_excl_time, &total_excl_time, 1,
MPI_DOUBLE, MPI_SUM, comm);
MPI_Allreduce(&calls, &total_calls, 1,
MPI_INT, MPI_SUM, comm);
}
bool operator<(function_timer const & w) const {
return total_time > w.total_time;
}
void print(FILE * output,
MPI_Comm const comm,
int const rank,
int const np){
int i;
if (rank == 0){
fprintf(output, "%s", name);
char * space = (char*)malloc(MAX_NAME_LENGTH-strlen(name)+1);
for (i=0; i<MAX_NAME_LENGTH-(int)strlen(name); i++){
space[i] = ' ';
}
space[i] = '\0';
fprintf(output, "%s", space);
fprintf(output,"%5d %3d.%04d %3d.%02d %3d.%04d %3d.%02d\n",
total_calls/np,
(int)(total_time/np),
((int)(1000.*(total_time)/np))%1000,
(int)(100.*(total_time)/complete_time),
((int)(10000.*(total_time)/complete_time))%100,
(int)(total_excl_time/np),
((int)(1000.*(total_excl_time)/np))%1000,
(int)(100.*(total_excl_time)/complete_time),
((int)(10000.*(total_excl_time)/complete_time))%100);
}
}
};
bool comp_name(function_timer const & w1, function_timer const & w2) {
return strcmp(w1.name, w2.name)>0;
}
std::vector<function_timer> function_timers;
CTF_timer::CTF_timer(const char * name){
int i;
if (function_timers.size() == 0) {
original = 1;
index = 0;
excl_time = 0.0;
function_timers.push_back(function_timer(name, MPI_Wtime(), 0.0));
} else {
for (i=0; i<(int)function_timers.size(); i++){
if (strcmp(function_timers[i].name, name) == 0){
/*function_timers[i].start_time = MPI_Wtime();
function_timers[i].start_excl_time = excl_time;*/
break;
}
}
index = i;
original = (index==0);
}
if (index == (int)function_timers.size()) {
function_timers.push_back(function_timer(name, MPI_Wtime(), excl_time));
}
timer_name = name;
exited = 0;
}
void CTF_timer::start(){
function_timers[index].start_time = MPI_Wtime();
function_timers[index].start_excl_time = excl_time;
}
void CTF_timer::stop(){
double delta_time = MPI_Wtime() - function_timers[index].start_time;
function_timers[index].acc_time += delta_time;
function_timers[index].acc_excl_time += delta_time -
(excl_time- function_timers[index].start_excl_time);
excl_time = function_timers[index].start_excl_time + delta_time;
function_timers[index].calls++;
exit();
exited = 1;
}
CTF_timer::~CTF_timer(){ }
void CTF_timer::exit(){
if (set_contxt && original && !exited) {
int rank, np, i, j, p, len_symbols;
MPI_Comm_rank(comm, &rank);
MPI_Comm_size(comm, &np);
FILE * output;
char all_symbols[10000];
if (rank == 0){
char filename[300];
char part[300];
sprintf(filename, "profile.");
int off;
if (main_argc != -1){
for (off=strlen(main_argv[0]); off>=1; off--){
if (main_argv[0][off-1] == '/') break;
}
for (i=0; i<main_argc; i++){
if (i==0)
sprintf(filename+strlen(filename), "%s.", main_argv[0]+off);
else
sprintf(filename+strlen(filename), "%s.", main_argv[i]);
}
}
sprintf(filename+strlen(filename), "-p%d.out", np);
output = fopen(filename, "w");
char heading[MAX_NAME_LENGTH+200];
for (i=0; i<MAX_NAME_LENGTH; i++){
part[i] = ' ';
}
part[i] = '\0';
sprintf(heading,"%s",part);
//sprintf(part,"calls total sec exclusive sec\n");
sprintf(part," inclusive exclusive\n");
strcat(heading,part);
fprintf(output, "%s", heading);
for (i=0; i<MAX_NAME_LENGTH; i++){
part[i] = ' ';
}
part[i] = '\0';
sprintf(heading,"%s",part);
sprintf(part, "calls sec %%");
strcat(heading,part);
sprintf(part, " sec %%\n");
strcat(heading,part);
fprintf(output, "%s", heading);
len_symbols = 0;
for (i=0; i<(int)function_timers.size(); i++){
sprintf(all_symbols+len_symbols, "%s", function_timers[i].name);
len_symbols += strlen(function_timers[i].name)+1;
}
}
if (np > 1){
for (p=0; p<np; p++){
if (rank == p){
MPI_Send(&len_symbols, 1, MPI_INT, (p+1)%np, 1, comm);
MPI_Send(all_symbols, len_symbols, MPI_CHAR, (p+1)%np, 2, comm);
}
if (rank == (p+1)%np){
MPI_Status stat;
MPI_Recv(&len_symbols, 1, MPI_INT, p, 1, comm, &stat);
MPI_Recv(all_symbols, len_symbols, MPI_CHAR, p, 2, comm, &stat);
for (i=0; i<(int)function_timers.size(); i++){
j=0;
while (j<len_symbols && strcmp(all_symbols+j, function_timers[i].name) != 0){
j+=strlen(all_symbols+j)+1;
}
if (j>=len_symbols){
sprintf(all_symbols+len_symbols, "%s", function_timers[i].name);
len_symbols += strlen(function_timers[i].name)+1;
}
}
}
}
MPI_Bcast(all_symbols, len_symbols, MPI_CHAR, 0, comm);
j=0;
while (j<len_symbols){
CTF_timer t(all_symbols+j);
j+=strlen(all_symbols+j)+1;
}
}
std::sort(function_timers.begin(), function_timers.end(),comp_name);
for (i=0; i<(int)function_timers.size(); i++){
function_timers[i].compute_totals(comm);
}
std::sort(function_timers.begin(), function_timers.end());
complete_time = function_timers[0].total_time;
for (i=0; i<(int)function_timers.size(); i++){
function_timers[i].print(output,comm,rank,np);
}
if (rank == 0){
fclose(output);
}
}
}
void CTF_set_main_args(int argc, char ** argv){
main_argv = argv;
main_argc = argc;
}
void CTF_set_context(int const ctxt){
set_contxt = 1;
if (ctxt == 0) comm = MPI_COMM_WORLD;
else comm = ctxt;
}
<|endoftext|> |
<commit_before>//
// PCMTrack.cpp
// Clock Signal
//
// Created by Thomas Harte on 10/07/2016.
// Copyright 2016 Thomas Harte. All rights reserved.
//
#include "PCMTrack.hpp"
#include "../../../NumberTheory/Factors.hpp"
#include "../../../Outputs/Log.hpp"
using namespace Storage::Disk;
PCMTrack::PCMTrack() : segment_pointer_(0) {}
PCMTrack::PCMTrack(const std::vector<PCMSegment> &segments) : PCMTrack() {
// sum total length of all segments
Time total_length;
for(const auto &segment : segments) {
total_length += segment.length_of_a_bit * static_cast<unsigned int>(segment.data.size());
}
total_length.simplify();
// each segment is then some proportion of the total; for them all to sum to 1 they'll
// need to be adjusted to be
for(const auto &segment : segments) {
Time original_length_of_segment = segment.length_of_a_bit * static_cast<unsigned int>(segment.data.size());
Time proportion_of_whole = original_length_of_segment / total_length;
proportion_of_whole.simplify();
PCMSegment length_adjusted_segment = segment;
length_adjusted_segment.length_of_a_bit = proportion_of_whole / static_cast<unsigned int>(segment.data.size());
length_adjusted_segment.length_of_a_bit.simplify();
segment_event_sources_.emplace_back(length_adjusted_segment);
}
}
PCMTrack::PCMTrack(const PCMSegment &segment) : PCMTrack() {
// a single segment necessarily fills the track
PCMSegment length_adjusted_segment = segment;
length_adjusted_segment.length_of_a_bit.length = 1;
length_adjusted_segment.length_of_a_bit.clock_rate = static_cast<unsigned int>(segment.data.size());
segment_event_sources_.emplace_back(std::move(length_adjusted_segment));
}
PCMTrack::PCMTrack(const PCMTrack &original) : PCMTrack() {
segment_event_sources_ = original.segment_event_sources_;
}
PCMTrack::PCMTrack(unsigned int bits_per_track) : PCMTrack() {
PCMSegment segment;
segment.length_of_a_bit.length = 1;
segment.length_of_a_bit.clock_rate = bits_per_track;
segment.data.resize(bits_per_track);
segment_event_sources_.emplace_back(segment);
}
PCMTrack *PCMTrack::resampled_clone(Track *original, size_t bits_per_track) {
PCMTrack *pcm_original = dynamic_cast<PCMTrack *>(original);
if(pcm_original) {
return pcm_original->resampled_clone(bits_per_track);
}
ERROR("NOT IMPLEMENTED: resampling non-PCMTracks");
return nullptr;
}
bool PCMTrack::is_resampled_clone() {
return is_resampled_clone_;
}
Track *PCMTrack::clone() const {
return new PCMTrack(*this);
}
PCMTrack *PCMTrack::resampled_clone(size_t bits_per_track) {
// Create an empty track.
PCMTrack *const new_track = new PCMTrack(static_cast<unsigned int>(bits_per_track));
// Plot all segments from this track onto the destination.
Time start_time;
for(const auto &event_source: segment_event_sources_) {
const PCMSegment &source = event_source.segment();
new_track->add_segment(start_time, source, true);
start_time += source.length();
}
new_track->is_resampled_clone_ = true;
return new_track;
}
Track::Event PCMTrack::get_next_event() {
// ask the current segment for a new event
Track::Event event = segment_event_sources_[segment_pointer_].get_next_event();
// if it was a flux transition, that's code for end-of-segment, so dig deeper
if(event.type == Track::Event::IndexHole) {
// multiple segments may be crossed, so start summing lengths in case the net
// effect is an index hole
Time total_length = event.length;
// continue until somewhere no returning an index hole
while(event.type == Track::Event::IndexHole) {
// advance to the [start of] the next segment
segment_pointer_ = (segment_pointer_ + 1) % segment_event_sources_.size();
segment_event_sources_[segment_pointer_].reset();
// if this is all the way back to the start, that's a genuine index hole,
// so set the summed length and return
if(!segment_pointer_) {
return event;
}
// otherwise get the next event (if it's not another index hole, the loop will end momentarily),
// summing in any prior accumulated time
event = segment_event_sources_[segment_pointer_].get_next_event();
total_length += event.length;
event.length = total_length;
}
}
return event;
}
Storage::Time PCMTrack::seek_to(const Time &time_since_index_hole) {
// initial condition: no time yet accumulated, the whole thing requested yet to navigate
Storage::Time accumulated_time;
Storage::Time time_left_to_seek = time_since_index_hole;
// search from the first segment
segment_pointer_ = 0;
do {
// if this segment extends beyond the amount of time left to seek, trust it to complete
// the seek
Storage::Time segment_time = segment_event_sources_[segment_pointer_].get_length();
if(segment_time > time_left_to_seek) {
return accumulated_time + segment_event_sources_[segment_pointer_].seek_to(time_left_to_seek);
}
// otherwise swallow this segment, updating the time left to seek and time so far accumulated
time_left_to_seek -= segment_time;
accumulated_time += segment_time;
segment_pointer_ = (segment_pointer_ + 1) % segment_event_sources_.size();
} while(segment_pointer_);
// if all segments have now been swallowed, the closest we can get is the very end of
// the list of segments
return accumulated_time;
}
void PCMTrack::add_segment(const Time &start_time, const PCMSegment &segment, bool clamp_to_index_hole) {
// Get a reference to the destination.
PCMSegment &destination = segment_event_sources_.front().segment();
// Determine the range to fill on the target segment.
const Time end_time = start_time + segment.length();
const size_t start_bit = start_time.length * destination.data.size() / start_time.clock_rate;
const size_t end_bit = end_time.length * destination.data.size() / end_time.clock_rate;
const size_t target_width = end_bit - start_bit;
const size_t half_offset = target_width / (2 * segment.data.size());
if(clamp_to_index_hole || end_bit <= destination.data.size()) {
// If clamping is applied, just write a single segment, from the start_bit to whichever is
// closer of the end of track and the end_bit.
const size_t selected_end_bit = std::min(end_bit, destination.data.size());
// Reset the destination.
std::fill(destination.data.begin() + static_cast<off_t>(start_bit), destination.data.begin() + static_cast<off_t>(selected_end_bit), false);
// Step through the source data from start to finish, stopping early if it goes out of bounds.
for(size_t bit = 0; bit < segment.data.size(); ++bit) {
if(segment.data[bit]) {
const size_t output_bit = start_bit + half_offset + (bit * target_width) / segment.data.size();
if(output_bit >= destination.data.size()) return;
destination.data[output_bit] = true;
}
}
} else {
// Clamping is not enabled, so the supplied segment loops over the index hole, arbitrarily many times.
// So work backwards unless or until the original start position is reached, then stop.
// This definitely runs over the index hole; check whether the whole track needs clearing, or whether
// a centre segment is untouched.
if(target_width >= destination.data.size()) {
std::fill(destination.data.begin(), destination.data.end(), false);
} else {
std::fill(destination.data.begin(), destination.data.begin() + static_cast<off_t>(end_bit % destination.data.size()), false);
std::fill(destination.data.begin() + static_cast<off_t>(start_bit), destination.data.end(), false);
}
// Run backwards from final bit back to first, stopping early if overlapping the beginning.
for(off_t bit = static_cast<off_t>(segment.data.size()-1); bit >= 0; --bit) {
if(segment.data[static_cast<size_t>(bit)]) {
const size_t output_bit = start_bit + half_offset + (static_cast<size_t>(bit) * target_width) / segment.data.size();
if(output_bit <= end_bit - destination.data.size()) return;
destination.data[output_bit % destination.data.size()] = true;
}
}
}
}
<commit_msg>Slightly improves syntax.<commit_after>//
// PCMTrack.cpp
// Clock Signal
//
// Created by Thomas Harte on 10/07/2016.
// Copyright 2016 Thomas Harte. All rights reserved.
//
#include "PCMTrack.hpp"
#include "../../../NumberTheory/Factors.hpp"
#include "../../../Outputs/Log.hpp"
using namespace Storage::Disk;
PCMTrack::PCMTrack() : segment_pointer_(0) {}
PCMTrack::PCMTrack(const std::vector<PCMSegment> &segments) : PCMTrack() {
// sum total length of all segments
Time total_length;
for(const auto &segment : segments) {
total_length += segment.length_of_a_bit * static_cast<unsigned int>(segment.data.size());
}
total_length.simplify();
// each segment is then some proportion of the total; for them all to sum to 1 they'll
// need to be adjusted to be
for(const auto &segment : segments) {
Time original_length_of_segment = segment.length_of_a_bit * static_cast<unsigned int>(segment.data.size());
Time proportion_of_whole = original_length_of_segment / total_length;
proportion_of_whole.simplify();
PCMSegment length_adjusted_segment = segment;
length_adjusted_segment.length_of_a_bit = proportion_of_whole / static_cast<unsigned int>(segment.data.size());
length_adjusted_segment.length_of_a_bit.simplify();
segment_event_sources_.emplace_back(length_adjusted_segment);
}
}
PCMTrack::PCMTrack(const PCMSegment &segment) : PCMTrack() {
// a single segment necessarily fills the track
PCMSegment length_adjusted_segment = segment;
length_adjusted_segment.length_of_a_bit.length = 1;
length_adjusted_segment.length_of_a_bit.clock_rate = static_cast<unsigned int>(segment.data.size());
segment_event_sources_.emplace_back(std::move(length_adjusted_segment));
}
PCMTrack::PCMTrack(const PCMTrack &original) : PCMTrack() {
segment_event_sources_ = original.segment_event_sources_;
}
PCMTrack::PCMTrack(unsigned int bits_per_track) : PCMTrack() {
PCMSegment segment;
segment.length_of_a_bit.length = 1;
segment.length_of_a_bit.clock_rate = bits_per_track;
segment.data.resize(bits_per_track);
segment_event_sources_.emplace_back(segment);
}
PCMTrack *PCMTrack::resampled_clone(Track *original, size_t bits_per_track) {
PCMTrack *pcm_original = dynamic_cast<PCMTrack *>(original);
if(pcm_original) {
return pcm_original->resampled_clone(bits_per_track);
}
ERROR("NOT IMPLEMENTED: resampling non-PCMTracks");
return nullptr;
}
bool PCMTrack::is_resampled_clone() {
return is_resampled_clone_;
}
Track *PCMTrack::clone() const {
return new PCMTrack(*this);
}
PCMTrack *PCMTrack::resampled_clone(size_t bits_per_track) {
// Create an empty track.
PCMTrack *const new_track = new PCMTrack(static_cast<unsigned int>(bits_per_track));
// Plot all segments from this track onto the destination.
Time start_time;
for(const auto &event_source: segment_event_sources_) {
const PCMSegment &source = event_source.segment();
new_track->add_segment(start_time, source, true);
start_time += source.length();
}
new_track->is_resampled_clone_ = true;
return new_track;
}
Track::Event PCMTrack::get_next_event() {
// ask the current segment for a new event
Track::Event event = segment_event_sources_[segment_pointer_].get_next_event();
// if it was a flux transition, that's code for end-of-segment, so dig deeper
if(event.type == Track::Event::IndexHole) {
// multiple segments may be crossed, so start summing lengths in case the net
// effect is an index hole
Time total_length = event.length;
// continue until somewhere no returning an index hole
while(event.type == Track::Event::IndexHole) {
// advance to the [start of] the next segment
segment_pointer_ = (segment_pointer_ + 1) % segment_event_sources_.size();
segment_event_sources_[segment_pointer_].reset();
// if this is all the way back to the start, that's a genuine index hole,
// so set the summed length and return
if(!segment_pointer_) {
return event;
}
// otherwise get the next event (if it's not another index hole, the loop will end momentarily),
// summing in any prior accumulated time
event = segment_event_sources_[segment_pointer_].get_next_event();
total_length += event.length;
event.length = total_length;
}
}
return event;
}
Storage::Time PCMTrack::seek_to(const Time &time_since_index_hole) {
// initial condition: no time yet accumulated, the whole thing requested yet to navigate
Storage::Time accumulated_time;
Storage::Time time_left_to_seek = time_since_index_hole;
// search from the first segment
segment_pointer_ = 0;
do {
// if this segment extends beyond the amount of time left to seek, trust it to complete
// the seek
Storage::Time segment_time = segment_event_sources_[segment_pointer_].get_length();
if(segment_time > time_left_to_seek) {
return accumulated_time + segment_event_sources_[segment_pointer_].seek_to(time_left_to_seek);
}
// otherwise swallow this segment, updating the time left to seek and time so far accumulated
time_left_to_seek -= segment_time;
accumulated_time += segment_time;
segment_pointer_ = (segment_pointer_ + 1) % segment_event_sources_.size();
} while(segment_pointer_);
// if all segments have now been swallowed, the closest we can get is the very end of
// the list of segments
return accumulated_time;
}
void PCMTrack::add_segment(const Time &start_time, const PCMSegment &segment, bool clamp_to_index_hole) {
// Get a reference to the destination.
PCMSegment &destination = segment_event_sources_.front().segment();
// Determine the range to fill on the target segment.
const Time end_time = start_time + segment.length();
const size_t start_bit = start_time.length * destination.data.size() / start_time.clock_rate;
const size_t end_bit = end_time.length * destination.data.size() / end_time.clock_rate;
const size_t target_width = end_bit - start_bit;
const size_t half_offset = target_width / (2 * segment.data.size());
if(clamp_to_index_hole || end_bit <= destination.data.size()) {
// If clamping is applied, just write a single segment, from the start_bit to whichever is
// closer of the end of track and the end_bit.
const size_t selected_end_bit = std::min(end_bit, destination.data.size());
// Reset the destination.
std::fill(destination.data.begin() + off_t(start_bit), destination.data.begin() + off_t(selected_end_bit), false);
// Step through the source data from start to finish, stopping early if it goes out of bounds.
for(size_t bit = 0; bit < segment.data.size(); ++bit) {
if(segment.data[bit]) {
const size_t output_bit = start_bit + half_offset + (bit * target_width) / segment.data.size();
if(output_bit >= destination.data.size()) return;
destination.data[output_bit] = true;
}
}
} else {
// Clamping is not enabled, so the supplied segment loops over the index hole, arbitrarily many times.
// So work backwards unless or until the original start position is reached, then stop.
// This definitely runs over the index hole; check whether the whole track needs clearing, or whether
// a centre segment is untouched.
if(target_width >= destination.data.size()) {
std::fill(destination.data.begin(), destination.data.end(), false);
} else {
std::fill(destination.data.begin(), destination.data.begin() + off_t(end_bit % destination.data.size()), false);
std::fill(destination.data.begin() + off_t(start_bit), destination.data.end(), false);
}
// Run backwards from final bit back to first, stopping early if overlapping the beginning.
for(off_t bit = off_t(segment.data.size()-1); bit >= 0; --bit) {
// Store flux transitions only; non-transitions can be ignored.
if(segment.data[size_t(bit)]) {
// Map to the proper output destination; stop if now potentially overwriting where we began.
const size_t output_bit = start_bit + half_offset + (size_t(bit) * target_width) / segment.data.size();
if(output_bit < end_bit - destination.data.size()) return;
// Store.
destination.data[output_bit % destination.data.size()] = true;
}
}
}
}
<|endoftext|> |
<commit_before>/**
* Copyright (c) 2016-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*/
#include "matrix.h"
#include "vector.h"
#include "dictionary.h"
#include "model.h"
#include "utils.h"
#include "real.h"
#include "args.h"
#include <iostream>
#include <iomanip>
#include <thread>
#include <time.h>
#include <string>
#include <math.h>
#include <vector>
#include <atomic>
#include <algorithm>
#include <fenv.h>
Args args;
namespace info {
time_t startTime;
time_t nowTime;
clock_t start;
std::atomic<int64_t> allWords(0);
std::atomic<int64_t> allN(0);
double allLoss(0.0);
}
void saveVectors(Dictionary& dict, Matrix& input, Matrix& output) {
int32_t N = dict.getNumWords();
std::ofstream ofs(args.output + ".vec");
if (ofs.is_open()) {
ofs << N << ' ' << args.dim << std::endl;
for (int32_t i = 0; i < N; i++) {
ofs << dict.getWord(i) << ' ';
Vector vec(args.dim);
vec.zero();
const std::vector<int32_t>& ngrams = dict.getNgrams(i);
for (auto it = ngrams.begin(); it != ngrams.end(); ++it) {
vec.addRow(input, *it);
}
vec.mul(1.0 / ngrams.size());
vec.writeToStream(ofs);
ofs << std::endl;
}
ofs.close();
} else {
std::cout << "Error opening file for saving vectors." << std::endl;
}
}
void printVectors(Dictionary& dict, Matrix& input, Matrix& output) {
std::string ws;
while (std::cin >> ws) {
std::cout << ws << " ";
Vector vec(args.dim);
vec.zero();
const std::vector<int32_t> ngrams = dict.getNgrams(ws);
for (auto it = ngrams.begin(); it != ngrams.end(); ++it) {
vec.addRow(input, *it);
}
vec.mul(1.0 / ngrams.size());
vec.writeToStream(std::cout);
std::cout << std::endl;
}
}
void saveModel(Dictionary& dict, Matrix& input, Matrix& output) {
std::ofstream ofs(args.output + ".bin");
args.save(ofs);
dict.save(ofs);
input.save(ofs);
output.save(ofs);
ofs.close();
}
void loadModel(std::string filename, Dictionary& dict,
Matrix& input, Matrix& output) {
std::ifstream ifs(filename);
if (!ifs.is_open()) {
std::cerr << "Model file cannot be opened for loading!" << std::endl;
exit(EXIT_FAILURE);
}
args.load(ifs);
dict.load(ifs);
input.load(ifs);
output.load(ifs);
ifs.close();
}
void printInfo(Model& model, int64_t numTokens) {
real progress = real(info::allWords) / (args.epoch * numTokens);
real avLoss = info::allLoss / info::allN;
float time = float(clock() - info::start) / CLOCKS_PER_SEC;
float wst = float(info::allWords) / time;
int eta = int(time / progress * (1 - progress) / args.thread);
int etah = eta / 3600;
int etam = (eta - etah * 3600) / 60;
std::cout << std::fixed;
std::cout << "\rProgress: " << std::setprecision(1) << 100 * progress << "%";
std::cout << " words/sec/thread: " << std::setprecision(0) << wst;
std::cout << " lr: " << std::setprecision(6) << model.getLearningRate();
std::cout << " loss: " << std::setprecision(6) << avLoss;
std::cout << " eta: " << etah << "h" << etam << "m ";
std::cout << std::flush;
}
void supervised(Model& model,
const std::vector<int32_t>& line,
const std::vector<int32_t>& labels,
double& loss, int32_t& N) {
if (labels.size() == 0 || line.size() == 0) return;
std::uniform_int_distribution<> uniform(0, labels.size() - 1);
int32_t i = uniform(model.rng);
model.update(line, labels[i], loss, N);
}
void cbow(Dictionary& dict, Model& model,
const std::vector<int32_t>& line,
double& loss, int32_t& N) {
int32_t n = line.size();
std::vector<int32_t> bow;
std::uniform_int_distribution<> uniform(1, args.ws);
for (int32_t w = 0; w < n; w++) {
int32_t wb = uniform(model.rng);
bow.clear();
for (int32_t c = -wb; c <= wb; c++) {
if (c != 0 && w + c >= 0 && w + c < n) {
const std::vector<int32_t>& ngrams = dict.getNgrams(line[w + c]);
for (auto it = ngrams.cbegin(); it != ngrams.cend(); ++it) {
bow.push_back(*it);
}
}
}
model.update(bow, line[w], loss, N);
}
}
void skipGram(Dictionary& dict, Model& model,
const std::vector<int32_t>& line,
double& loss, int32_t& N) {
int32_t n = line.size();
std::uniform_int_distribution<> uniform(1, args.ws);
for (int32_t w = 0; w < n; w++) {
int32_t wb = uniform(model.rng);
const std::vector<int32_t>& ngrams = dict.getNgrams(line[w]);
for (int32_t c = -wb; c <= wb; c++) {
if (c != 0 && w + c >= 0 && w + c < n) {
int32_t target = line[w + c];
model.update(ngrams, target, loss, N);
}
}
}
}
void test(Dictionary& dict, Model& model, std::string filename) {
int32_t nexamples = 0;
double precision = 0.0;
std::vector<int32_t> line, labels;
std::ifstream ifs(filename);
if (!ifs.is_open()) {
std::cerr << "Test file cannot be opened!" << std::endl;
exit(EXIT_FAILURE);
}
while (ifs.peek() != EOF) {
dict.getLine(ifs, line, labels, model.rng);
dict.addNgrams(line, args.wordNgrams);
if (labels.size() > 0 && line.size() > 0) {
int32_t i = model.predict(line);
if (std::find(labels.begin(), labels.end(), i) != labels.end()) {
precision += 1.0;
}
nexamples++;
}
}
ifs.close();
std::cout << std::setprecision(3);
std::cout << "P@1: " << precision / nexamples << std::endl;
std::cout << "Number of examples: " << nexamples << std::endl;
}
void predict(Dictionary& dict, Model& model, std::string filename) {
int32_t nexamples = 0;
double precision = 0.0;
std::vector<int32_t> line, labels;
std::ifstream ifs(filename);
if (!ifs.is_open()) {
std::cerr << "Test file cannot be opened!" << std::endl;
exit(EXIT_FAILURE);
}
while (ifs.peek() != EOF) {
dict.getLine(ifs, line, labels, model.rng);
dict.addNgrams(line, args.wordNgrams);
if (line.size() > 0) {
int32_t i = model.predict(line);
std::cout << dict.getLabel(i) << std::endl;
} else {
std::cout << "n/a" << std::endl;
}
}
ifs.close();
}
void trainThread(Dictionary& dict, Matrix& input, Matrix& output,
int32_t threadId) {
std::ifstream ifs(args.input);
utils::seek(ifs, threadId * utils::size(ifs) / args.thread);
Model model(input, output, args.dim, args.lr, threadId);
if (args.model == model_name::sup) {
model.setLabelFreq(dict.getLabelFreq());
} else {
model.setLabelFreq(dict.getWordFreq());
}
const int64_t ntokens = dict.getNumTokens();
int64_t tokenCount = 0;
double loss = 0.0;
int32_t N = 0;
std::vector<int32_t> line, labels;
while (info::allWords < args.epoch * ntokens) {
tokenCount += dict.getLine(ifs, line, labels, model.rng);
if (args.model == model_name::sup) {
dict.addNgrams(line, args.wordNgrams);
supervised(model, line, labels, loss, N);
} else if (args.model == model_name::cbow) {
cbow(dict, model, line, loss, N);
} else if (args.model == model_name::sg) {
skipGram(dict, model, line, loss, N);
}
if (tokenCount > 10000) {
info::allWords += tokenCount;
info::allLoss += loss;
info::allN += N;
tokenCount = 0;
loss = 0.0;
N = 0;
real progress = real(info::allWords) / (args.epoch * ntokens);
model.setLearningRate(args.lr * (1.0 - progress));
if (threadId == 0) printInfo(model, ntokens);
}
}
if (threadId == 0) {
printInfo(model, ntokens);
std::cout << std::endl;
}
if (args.model == model_name::sup && threadId == 0) {
test(dict, model, args.test);
}
ifs.close();
}
void printUsage() {
std::cout
<< "usage: fasttext <command> <args>\n\n"
<< "The commands supported by fasttext are:\n\n"
<< " supervised train a supervised classifier\n"
<< " test evaluate a supervised classifier\n"
<< " predict predict most likely label\n"
<< " skipgram train a skipgram model\n"
<< " cbow train a cbow model\n"
<< " print-vectors print vectors given a trained model\n"
<< std::endl;
}
void printTestUsage() {
std::cout
<< "usage: fasttext test <model> <test-data>\n\n"
<< " <model> model filename\n"
<< " <test-data> test data filename\n"
<< std::endl;
}
void printPredictUsage() {
std::cout
<< "usage: fasttext predict <model> <test-data>\n\n"
<< " <model> model filename\n"
<< " <test-data> test data filename\n"
<< std::endl;
}
void printPrintVectorsUsage() {
std::cout
<< "usage: fasttext print-vectors <model>\n\n"
<< " <model> model filename\n"
<< std::endl;
}
void test(int argc, char** argv) {
if (argc != 4) {
printTestUsage();
exit(EXIT_FAILURE);
}
Dictionary dict;
Matrix input, output;
loadModel(std::string(argv[2]), dict, input, output);
Model model(input, output, args.dim, args.lr, 1);
model.setLabelFreq(dict.getLabelFreq());
test(dict, model, std::string(argv[3]));
exit(0);
}
void predict(int argc, char** argv) {
if (argc != 4) {
printPredictUsage();
exit(EXIT_FAILURE);
}
Dictionary dict;
Matrix input, output;
loadModel(std::string(argv[2]), dict, input, output);
Model model(input, output, args.dim, args.lr, 1);
model.setLabelFreq(dict.getLabelFreq());
predict(dict, model, std::string(argv[3]));
exit(0);
}
void printVectors(int argc, char** argv) {
if (argc != 3) {
printPrintVectorsUsage();
exit(EXIT_FAILURE);
}
Dictionary dict;
Matrix input, output;
loadModel(std::string(argv[2]), dict, input, output);
printVectors(dict, input, output);
exit(0);
}
void train(int argc, char** argv) {
args.parseArgs(argc, argv);
Dictionary dict;
std::ifstream ifs(args.input);
if (!ifs.is_open()) {
std::cerr << "Input file cannot be opened!" << std::endl;
exit(EXIT_FAILURE);
}
dict.readFromFile(ifs);
ifs.close();
Matrix input(dict.getNumWords() + args.bucket, args.dim);
Matrix output;
if (args.model == model_name::sup) {
output = Matrix(dict.getNumLabels(), args.dim);
} else {
output = Matrix(dict.getNumWords(), args.dim);
}
input.uniform(1.0 / args.dim);
output.zero();
info::start = clock();
time(&info::startTime);
std::vector<std::thread> threads;
for (int32_t i = 0; i < args.thread; i++) {
threads.push_back(std::thread(&trainThread, std::ref(dict),
std::ref(input), std::ref(output), i));
}
for (auto it = threads.begin(); it != threads.end(); ++it) {
it->join();
}
time(&info::nowTime);
double trainTime = difftime(info::nowTime, info::startTime);
std::cout << "training took: " << trainTime << " sec" << std::endl;
if (args.output.size() != 0) {
saveModel(dict, input, output);
saveVectors(dict, input, output);
}
}
int main(int argc, char** argv) {
std::locale::global(std::locale(""));
utils::initTables();
if (argc < 2) {
printUsage();
exit(EXIT_FAILURE);
}
std::string command(argv[1]);
if (command == "skipgram" || command == "cbow" || command == "supervised") {
train(argc, argv);
} else if (command == "test") {
test(argc, argv);
} else if (command == "print-vectors") {
printVectors(argc, argv);
} else if (command == "predict") {
predict(argc, argv);
} else {
printUsage();
exit(EXIT_FAILURE);
}
utils::freeTables();
return 0;
}
<commit_msg>Created a method in fasttext for computing vector for a word.<commit_after>/**
* Copyright (c) 2016-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*/
#include "matrix.h"
#include "vector.h"
#include "dictionary.h"
#include "model.h"
#include "utils.h"
#include "real.h"
#include "args.h"
#include <iostream>
#include <iomanip>
#include <thread>
#include <time.h>
#include <string>
#include <math.h>
#include <vector>
#include <atomic>
#include <algorithm>
#include <fenv.h>
Args args;
namespace info {
time_t startTime;
time_t nowTime;
clock_t start;
std::atomic<int64_t> allWords(0);
std::atomic<int64_t> allN(0);
double allLoss(0.0);
}
void getVector(Dictionary& dict, Matrix& input, Vector& vec, std::string ws) {
vec.zero();
const std::vector<int32_t>& ngrams = dict.getNgrams(ws);
for (auto it = ngrams.begin(); it != ngrams.end(); ++it) {
vec.addRow(input, *it);
}
vec.mul(1.0 / ngrams.size());
}
void saveVectors(Dictionary& dict, Matrix& input, Matrix& output) {
int32_t N = dict.getNumWords();
std::ofstream ofs(args.output + ".vec");
std::string ws;
if (ofs.is_open()) {
ofs << N << ' ' << args.dim << std::endl;
Vector vec(args.dim);
for (int32_t i = 0; i < N; i++) {
ws = dict.getWord(i);
ofs << ws << ' ';
getVector(dict, input, vec, ws);
vec.writeToStream(ofs);
ofs << std::endl;
}
ofs.close();
} else {
std::cout << "Error opening file for saving vectors." << std::endl;
}
}
void printVectors(Dictionary& dict, Matrix& input) {
std::string ws;
Vector vec(args.dim);
while (std::cin >> ws) {
std::cout << ws << " ";
getVector(dict, input, vec, ws);
vec.writeToStream(std::cout);
std::cout << std::endl;
}
}
void saveModel(Dictionary& dict, Matrix& input, Matrix& output) {
std::ofstream ofs(args.output + ".bin");
args.save(ofs);
dict.save(ofs);
input.save(ofs);
output.save(ofs);
ofs.close();
}
void loadModel(std::string filename, Dictionary& dict,
Matrix& input, Matrix& output) {
std::ifstream ifs(filename);
if (!ifs.is_open()) {
std::cerr << "Model file cannot be opened for loading!" << std::endl;
exit(EXIT_FAILURE);
}
args.load(ifs);
dict.load(ifs);
input.load(ifs);
output.load(ifs);
ifs.close();
}
void printInfo(Model& model, int64_t numTokens) {
real progress = real(info::allWords) / (args.epoch * numTokens);
real avLoss = info::allLoss / info::allN;
float time = float(clock() - info::start) / CLOCKS_PER_SEC;
float wst = float(info::allWords) / time;
int eta = int(time / progress * (1 - progress) / args.thread);
int etah = eta / 3600;
int etam = (eta - etah * 3600) / 60;
std::cout << std::fixed;
std::cout << "\rProgress: " << std::setprecision(1) << 100 * progress << "%";
std::cout << " words/sec/thread: " << std::setprecision(0) << wst;
std::cout << " lr: " << std::setprecision(6) << model.getLearningRate();
std::cout << " loss: " << std::setprecision(6) << avLoss;
std::cout << " eta: " << etah << "h" << etam << "m ";
std::cout << std::flush;
}
void supervised(Model& model,
const std::vector<int32_t>& line,
const std::vector<int32_t>& labels,
double& loss, int32_t& N) {
if (labels.size() == 0 || line.size() == 0) return;
std::uniform_int_distribution<> uniform(0, labels.size() - 1);
int32_t i = uniform(model.rng);
model.update(line, labels[i], loss, N);
}
void cbow(Dictionary& dict, Model& model,
const std::vector<int32_t>& line,
double& loss, int32_t& N) {
int32_t n = line.size();
std::vector<int32_t> bow;
std::uniform_int_distribution<> uniform(1, args.ws);
for (int32_t w = 0; w < n; w++) {
int32_t wb = uniform(model.rng);
bow.clear();
for (int32_t c = -wb; c <= wb; c++) {
if (c != 0 && w + c >= 0 && w + c < n) {
const std::vector<int32_t>& ngrams = dict.getNgrams(line[w + c]);
for (auto it = ngrams.cbegin(); it != ngrams.cend(); ++it) {
bow.push_back(*it);
}
}
}
model.update(bow, line[w], loss, N);
}
}
void skipGram(Dictionary& dict, Model& model,
const std::vector<int32_t>& line,
double& loss, int32_t& N) {
int32_t n = line.size();
std::uniform_int_distribution<> uniform(1, args.ws);
for (int32_t w = 0; w < n; w++) {
int32_t wb = uniform(model.rng);
const std::vector<int32_t>& ngrams = dict.getNgrams(line[w]);
for (int32_t c = -wb; c <= wb; c++) {
if (c != 0 && w + c >= 0 && w + c < n) {
int32_t target = line[w + c];
model.update(ngrams, target, loss, N);
}
}
}
}
void test(Dictionary& dict, Model& model, std::string filename) {
int32_t nexamples = 0;
double precision = 0.0;
std::vector<int32_t> line, labels;
std::ifstream ifs(filename);
if (!ifs.is_open()) {
std::cerr << "Test file cannot be opened!" << std::endl;
exit(EXIT_FAILURE);
}
while (ifs.peek() != EOF) {
dict.getLine(ifs, line, labels, model.rng);
dict.addNgrams(line, args.wordNgrams);
if (labels.size() > 0 && line.size() > 0) {
int32_t i = model.predict(line);
if (std::find(labels.begin(), labels.end(), i) != labels.end()) {
precision += 1.0;
}
nexamples++;
}
}
ifs.close();
std::cout << std::setprecision(3);
std::cout << "P@1: " << precision / nexamples << std::endl;
std::cout << "Number of examples: " << nexamples << std::endl;
}
void predict(Dictionary& dict, Model& model, std::string filename) {
int32_t nexamples = 0;
double precision = 0.0;
std::vector<int32_t> line, labels;
std::ifstream ifs(filename);
if (!ifs.is_open()) {
std::cerr << "Test file cannot be opened!" << std::endl;
exit(EXIT_FAILURE);
}
while (ifs.peek() != EOF) {
dict.getLine(ifs, line, labels, model.rng);
dict.addNgrams(line, args.wordNgrams);
if (line.size() > 0) {
int32_t i = model.predict(line);
std::cout << dict.getLabel(i) << std::endl;
} else {
std::cout << "n/a" << std::endl;
}
}
ifs.close();
}
void trainThread(Dictionary& dict, Matrix& input, Matrix& output,
int32_t threadId) {
std::ifstream ifs(args.input);
utils::seek(ifs, threadId * utils::size(ifs) / args.thread);
Model model(input, output, args.dim, args.lr, threadId);
if (args.model == model_name::sup) {
model.setLabelFreq(dict.getLabelFreq());
} else {
model.setLabelFreq(dict.getWordFreq());
}
const int64_t ntokens = dict.getNumTokens();
int64_t tokenCount = 0;
double loss = 0.0;
int32_t N = 0;
std::vector<int32_t> line, labels;
while (info::allWords < args.epoch * ntokens) {
tokenCount += dict.getLine(ifs, line, labels, model.rng);
if (args.model == model_name::sup) {
dict.addNgrams(line, args.wordNgrams);
supervised(model, line, labels, loss, N);
} else if (args.model == model_name::cbow) {
cbow(dict, model, line, loss, N);
} else if (args.model == model_name::sg) {
skipGram(dict, model, line, loss, N);
}
if (tokenCount > 10000) {
info::allWords += tokenCount;
info::allLoss += loss;
info::allN += N;
tokenCount = 0;
loss = 0.0;
N = 0;
real progress = real(info::allWords) / (args.epoch * ntokens);
model.setLearningRate(args.lr * (1.0 - progress));
if (threadId == 0) printInfo(model, ntokens);
}
}
if (threadId == 0) {
printInfo(model, ntokens);
std::cout << std::endl;
}
if (args.model == model_name::sup && threadId == 0) {
test(dict, model, args.test);
}
ifs.close();
}
void printUsage() {
std::cout
<< "usage: fasttext <command> <args>\n\n"
<< "The commands supported by fasttext are:\n\n"
<< " supervised train a supervised classifier\n"
<< " test evaluate a supervised classifier\n"
<< " predict predict most likely label\n"
<< " skipgram train a skipgram model\n"
<< " cbow train a cbow model\n"
<< " print-vectors print vectors given a trained model\n"
<< std::endl;
}
void printTestUsage() {
std::cout
<< "usage: fasttext test <model> <test-data>\n\n"
<< " <model> model filename\n"
<< " <test-data> test data filename\n"
<< std::endl;
}
void printPredictUsage() {
std::cout
<< "usage: fasttext predict <model> <test-data>\n\n"
<< " <model> model filename\n"
<< " <test-data> test data filename\n"
<< std::endl;
}
void printPrintVectorsUsage() {
std::cout
<< "usage: fasttext print-vectors <model>\n\n"
<< " <model> model filename\n"
<< std::endl;
}
void test(int argc, char** argv) {
if (argc != 4) {
printTestUsage();
exit(EXIT_FAILURE);
}
Dictionary dict;
Matrix input, output;
loadModel(std::string(argv[2]), dict, input, output);
Model model(input, output, args.dim, args.lr, 1);
model.setLabelFreq(dict.getLabelFreq());
test(dict, model, std::string(argv[3]));
exit(0);
}
void predict(int argc, char** argv) {
if (argc != 4) {
printPredictUsage();
exit(EXIT_FAILURE);
}
Dictionary dict;
Matrix input, output;
loadModel(std::string(argv[2]), dict, input, output);
Model model(input, output, args.dim, args.lr, 1);
model.setLabelFreq(dict.getLabelFreq());
predict(dict, model, std::string(argv[3]));
exit(0);
}
void printVectors(int argc, char** argv) {
if (argc != 3) {
printPrintVectorsUsage();
exit(EXIT_FAILURE);
}
Dictionary dict;
Matrix input, output;
loadModel(std::string(argv[2]), dict, input, output);
printVectors(dict, input);
exit(0);
}
void train(int argc, char** argv) {
args.parseArgs(argc, argv);
Dictionary dict;
std::ifstream ifs(args.input);
if (!ifs.is_open()) {
std::cerr << "Input file cannot be opened!" << std::endl;
exit(EXIT_FAILURE);
}
dict.readFromFile(ifs);
ifs.close();
Matrix input(dict.getNumWords() + args.bucket, args.dim);
Matrix output;
if (args.model == model_name::sup) {
output = Matrix(dict.getNumLabels(), args.dim);
} else {
output = Matrix(dict.getNumWords(), args.dim);
}
input.uniform(1.0 / args.dim);
output.zero();
info::start = clock();
time(&info::startTime);
std::vector<std::thread> threads;
for (int32_t i = 0; i < args.thread; i++) {
threads.push_back(std::thread(&trainThread, std::ref(dict),
std::ref(input), std::ref(output), i));
}
for (auto it = threads.begin(); it != threads.end(); ++it) {
it->join();
}
time(&info::nowTime);
double trainTime = difftime(info::nowTime, info::startTime);
std::cout << "training took: " << trainTime << " sec" << std::endl;
if (args.output.size() != 0) {
saveModel(dict, input, output);
saveVectors(dict, input, output);
}
}
int main(int argc, char** argv) {
std::locale::global(std::locale(""));
utils::initTables();
if (argc < 2) {
printUsage();
exit(EXIT_FAILURE);
}
std::string command(argv[1]);
if (command == "skipgram" || command == "cbow" || command == "supervised") {
train(argc, argv);
} else if (command == "test") {
test(argc, argv);
} else if (command == "print-vectors") {
printVectors(argc, argv);
} else if (command == "predict") {
predict(argc, argv);
} else {
printUsage();
exit(EXIT_FAILURE);
}
utils::freeTables();
return 0;
}
<|endoftext|> |
<commit_before>/*
* Copyright (C) 2005 Ryan Nickell <p0z3r @ earthlink . net>
*
* This file is part of SuperKaramba.
*
* SuperKaramba is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* SuperKaramba 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 SuperKaramba; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
****************************************************************************/
#include <kapplication.h>
#include <kdebug.h>
#include <kfilemetainfo.h>
#include <kio/netaccess.h>
#include <kmimetype.h>
#include <kstandarddirs.h>
#include <ktar.h>
#include <kurl.h>
#include <qdir.h>
#include <qfileinfo.h>
#include "karambaapp.h"
#include "themesdlg.h"
#ifdef KDE_3_3
#include "sknewstuff.h"
SKNewStuff::SKNewStuff( ThemesDlg *dlg ) :
KNewStuff( "superkaramba/themes", dlg ),
mDlg( dlg )
{
}
void SKNewStuff::addThemes(const KArchiveDirectory *archiveDir,
const QString& destDir)
{
QStringList entries = archiveDir->entries();
QStringList::Iterator end( entries.end() );
for(QStringList::Iterator it = entries.begin(); it != end; ++it)
{
if(archiveDir->entry(*it)->isDirectory())
{
addThemes(static_cast<const KArchiveDirectory*>(archiveDir->entry(*it)),
destDir + *it + "/");
}
else
{
QFileInfo fi(*it);
if(fi.extension() == "theme")
{
mDlg->addThemeToList(destDir + *it);
}
}
}
}
bool SKNewStuff::install( const QString &fileName )
{
kdDebug() << "SKNewStuff::install(): " << fileName << endl;
KMimeType::Ptr result = KMimeType::findByURL(fileName);
KStandardDirs myStdDir;
const QString destDir =myStdDir.saveLocation("data", kapp->instanceName() + "/themes/", true);
KStandardDirs::makeDir( destDir );
kdDebug() << "SKNewStuff::install() mimetype: " << result->name() << endl;
if( result->name() == "application/x-gzip" ||
result->name() == "application/x-tgz" ||
result->name() == "application/x-bzip" ||
result->name() == "application/x-bzip2" ||
result->name() == "application/x-tbz" ||
result->name() == "application/x-tbz2" ||
result->name() == "application/x-tar" ||
result->name() == "application/x-tarz")
{
kdDebug() << "SKNewStuff::install() gzip/bzip2 mimetype encountered" <<
endl;
KTar archive( fileName );
if ( !archive.open( IO_ReadOnly ) )
return false;
const KArchiveDirectory *archiveDir = archive.directory();
archiveDir->copyTo(destDir);
addThemes(archiveDir, destDir);
archive.close();
}
else if(result->name() == "application/x-zip" ||
result->name() == "application/x-superkaramba")
{
kdDebug() << "SKNewStuff::install() zip mimetype encountered" << endl;
//TODO: write a routine to check if this is a valid .skz file
//otherwise we need to unpack it like it is an old theme that was packaged
//as a .zip instead of .bz2 or .tar.gz
KURL sourceFile(fileName);
KURL destFile( destDir + sourceFile.fileName() );
if(!KIO::NetAccess::file_copy( sourceFile, destFile ))
{
return false;
}
KIO::NetAccess::removeTempFile( sourceFile.url() );
mDlg->newSkzTheme(destFile.path());
}
else if(result->name() == "plaint/text")
{
kdDebug() << "SKNewStuff::install() plain text" << endl;
}
else
{
kdDebug() << "SKNewStuff::install() Error no compatible mimetype encountered to install"
<< endl;
return false;
}
return true;
}
bool SKNewStuff::createUploadFile( const QString &fileName )
{
kdDebug() << "SKNewStuff::createUploadFile(): " << fileName << endl;
return true;
}
QString SKNewStuff::downloadDestination( KNS::Entry *entry )
{
KURL source = entry->payload();
kdDebug() << "SKNewStuff::downloadDestination() fileName: "
<< source.fileName() << endl;
return KGlobal::dirs()->saveLocation( "tmp" ) + source.fileName();
}
#endif //KDE_3_3
<commit_msg>Themes in which the download link is a url to the theme authors website will now open in konqueror instead of getting an uninformative error message.<commit_after>/*
* Copyright (C) 2005 Ryan Nickell <p0z3r @ earthlink . net>
*
* This file is part of SuperKaramba.
*
* SuperKaramba is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* SuperKaramba 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 SuperKaramba; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
****************************************************************************/
#include <kapplication.h>
#include <kdebug.h>
#include <kfilemetainfo.h>
#include <kio/netaccess.h>
#include <kmimetype.h>
#include <krun.h>
#include <kstandarddirs.h>
#include <ktar.h>
#include <kurl.h>
#include <qdir.h>
#include <qfileinfo.h>
#include "karambaapp.h"
#include "themesdlg.h"
#ifdef KDE_3_3
#include "sknewstuff.h"
SKNewStuff::SKNewStuff( ThemesDlg *dlg ) :
KNewStuff( "superkaramba/themes", dlg ),
mDlg( dlg )
{
}
void SKNewStuff::addThemes(const KArchiveDirectory *archiveDir,
const QString& destDir)
{
QStringList entries = archiveDir->entries();
QStringList::Iterator end( entries.end() );
for(QStringList::Iterator it = entries.begin(); it != end; ++it)
{
if(archiveDir->entry(*it)->isDirectory())
{
addThemes(static_cast<const KArchiveDirectory*>(archiveDir->entry(*it)),
destDir + *it + "/");
}
else
{
QFileInfo fi(*it);
if(fi.extension() == "theme")
{
mDlg->addThemeToList(destDir + *it);
}
}
}
}
bool SKNewStuff::install( const QString &fileName )
{
kdDebug() << "SKNewStuff::install(): " << fileName << endl;
KMimeType::Ptr result = KMimeType::findByURL(fileName);
KStandardDirs myStdDir;
const QString destDir =myStdDir.saveLocation("data", kapp->instanceName() + "/themes/", true);
KStandardDirs::makeDir( destDir );
kdDebug() << "SKNewStuff::install() mimetype: " << result->name() << endl;
if( result->name() == "application/x-gzip" ||
result->name() == "application/x-tgz" ||
result->name() == "application/x-bzip" ||
result->name() == "application/x-bzip2" ||
result->name() == "application/x-tbz" ||
result->name() == "application/x-tbz2" ||
result->name() == "application/x-tar" ||
result->name() == "application/x-tarz")
{
kdDebug() << "SKNewStuff::install() gzip/bzip2 mimetype encountered" <<
endl;
KTar archive( fileName );
if ( !archive.open( IO_ReadOnly ) )
return false;
const KArchiveDirectory *archiveDir = archive.directory();
archiveDir->copyTo(destDir);
addThemes(archiveDir, destDir);
archive.close();
}
else if(result->name() == "application/x-zip" ||
result->name() == "application/x-superkaramba")
{
kdDebug() << "SKNewStuff::install() zip mimetype encountered" << endl;
//TODO: write a routine to check if this is a valid .skz file
//otherwise we need to unpack it like it is an old theme that was packaged
//as a .zip instead of .bz2 or .tar.gz
KURL sourceFile(fileName);
KURL destFile( destDir + sourceFile.fileName() );
if(!KIO::NetAccess::file_copy( sourceFile, destFile ))
{
return false;
}
KIO::NetAccess::removeTempFile( sourceFile.url() );
mDlg->newSkzTheme(destFile.path());
}
else if(result->name() == "plaint/text")
{
kdDebug() << "SKNewStuff::install() plain text" << endl;
}
else
{
kdDebug() << "SKNewStuff::install() Error no compatible mimetype encountered to install"
<< endl;
return false;
}
return true;
}
bool SKNewStuff::createUploadFile( const QString &fileName )
{
kdDebug() << "SKNewStuff::createUploadFile(): " << fileName << endl;
return true;
}
QString SKNewStuff::downloadDestination( KNS::Entry *entry )
{
KURL source = entry->payload();
kdDebug() << "SKNewStuff::downloadDestination() url: "
<< source.url() << " fileName: " << source.fileName() << endl;
QString file(source.fileName());
if ( file.isEmpty() )
{
kdDebug() << "the file was empty, this must be a direct URL" << endl;
KRun::runURL( source, "text/html");
return file;
}
return KGlobal::dirs()->saveLocation( "tmp" ) + source.fileName();
}
#endif //KDE_3_3
<|endoftext|> |
<commit_before>/*
* Copyright (C) 2008-2013 The Communi Project
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*/
#include "textdocument.h"
#include "messageformatter.h"
#include "syntaxhighlighter.h"
#include <QAbstractTextDocumentLayout>
#include <QTextDocumentFragment>
#include <QApplication>
#include <QTextCursor>
#include <QTextBlock>
#include <IrcBuffer>
#include <QPalette>
#include <QPainter>
#include <qmath.h>
static int delay = 1000;
TextDocument::TextDocument(IrcBuffer* buffer) : QTextDocument(buffer)
{
qRegisterMetaType<TextDocument*>();
d.ub = -1;
d.dirty = -1;
d.lowlight = -1;
d.clone = false;
d.buffer = buffer;
d.visible = false;
// TODO: stylesheet
d.markerColor = Qt::darkGray;
d.lowlightColor = qApp->palette().color(QPalette::AlternateBase);
d.highlightColor = QColor("#ffd6d6");
d.highlighter = new SyntaxHighlighter(this);
d.formatter = new MessageFormatter(this);
d.formatter->setBuffer(buffer);
setUndoRedoEnabled(false);
setMaximumBlockCount(1000);
connect(buffer, SIGNAL(messageReceived(IrcMessage*)), this, SLOT(receiveMessage(IrcMessage*)));
}
TextDocument* TextDocument::clone()
{
if (d.dirty > 0)
flushLines();
TextDocument* doc = new TextDocument(d.buffer);
QTextCursor(doc).insertFragment(QTextDocumentFragment(this));
doc->rootFrame()->setFrameFormat(rootFrame()->frameFormat());
// TODO:
doc->d.ub = d.ub;
doc->d.lowlight = d.lowlight;
doc->d.buffer = d.buffer;
doc->d.highlights = d.highlights;
doc->d.lowlights = d.lowlights;
doc->d.clone = true;
return doc;
}
bool TextDocument::isClone() const
{
return d.clone;
}
IrcBuffer* TextDocument::buffer() const
{
return d.buffer;
}
SyntaxHighlighter* TextDocument::highlighter() const
{
return d.highlighter;
}
int TextDocument::totalCount() const
{
int count = d.lines.count();
if (!isEmpty())
count += blockCount();
return count;
}
QColor TextDocument::markerColor() const
{
return d.markerColor;
}
void TextDocument::setMarkerColor(const QColor& color)
{
if (d.markerColor != color) {
d.markerColor = color;
// TODO: update();
}
}
QColor TextDocument::lowlightColor() const
{
return d.lowlightColor;
}
void TextDocument::setLowlightColor(const QColor& color)
{
if (d.lowlightColor != color) {
d.lowlightColor = color;
// TODO: update();
}
}
QColor TextDocument::highlightColor() const
{
return d.highlightColor;
}
void TextDocument::setHighlightColor(const QColor& color)
{
if (d.highlightColor != color) {
d.highlightColor = color;
// TODO: update();
}
}
bool TextDocument::isVisible() const
{
return d.visible;
}
void TextDocument::setVisible(bool visible)
{
if (d.visible != visible) {
if (visible) {
if (d.dirty > 0)
flushLines();
} else {
d.ub = -1;
}
d.visible = visible;
}
}
void TextDocument::beginLowlight()
{
d.lowlight = totalCount();
d.lowlights.insert(d.lowlight, -1);
}
void TextDocument::endLowlight()
{
d.lowlights.insert(d.lowlight, totalCount());
d.lowlight = -1;
}
void TextDocument::addHighlight(int block)
{
const int max = totalCount() - 1;
if (block == -1)
block = max;
if (block >= 0 && block <= max) {
QList<int>::iterator it = qLowerBound(d.highlights.begin(), d.highlights.end(), block);
d.highlights.insert(it, block);
updateBlock(block);
}
}
void TextDocument::removeHighlight(int block)
{
if (d.highlights.removeOne(block) && block >= 0 && block < totalCount())
updateBlock(block);
}
void TextDocument::append(const QString& text)
{
if (!text.isEmpty()) {
if (d.dirty == 0 || d.visible) {
QTextCursor cursor(this);
cursor.beginEditBlock();
appendLine(cursor, text);
cursor.endEditBlock();
} else {
if (d.dirty <= 0) {
d.dirty = startTimer(delay);
delay += 1000;
}
d.lines += text;
}
}
}
void TextDocument::drawForeground(QPainter* painter, const QRect& bounds)
{
if (d.lowlights.isEmpty() && d.ub <= 1)
return;
const QPen oldPen = painter->pen();
const QBrush oldBrush = painter->brush();
painter->setBrush(Qt::NoBrush);
bool drawUb = d.ub > 1;
if (!d.lowlights.isEmpty()) {
const qreal oldOpacity = painter->opacity();
const QAbstractTextDocumentLayout* layout = documentLayout();
const int margin = qCeil(documentMargin());
QMap<int, int>::const_iterator it;
for (it = d.lowlights.begin(); it != d.lowlights.end(); ++it) {
const QTextBlock from = findBlockByNumber(it.key());
const QTextBlock to = findBlockByNumber(it.value());
if (from.isValid() && to.isValid()) {
const QRect fr = layout->blockBoundingRect(from).toAlignedRect();
const QRect tr = layout->blockBoundingRect(to).toAlignedRect();
QRect br = fr.united(tr);
if (bounds.intersects(br)) {
bool atBottom = false;
if (to == lastBlock()) {
if (qAbs(bounds.bottom() - br.bottom()) < qMin(fr.height(), tr.height()))
atBottom = true;
}
if (atBottom)
br.setBottom(bounds.bottom());
br = br.adjusted(-margin, 0, margin, 1);
painter->setOpacity(0.2);
painter->fillRect(br, d.lowlightColor);
painter->setPen(d.markerColor);
painter->setOpacity(0.5);
painter->drawLine(br.topLeft(), br.topRight());
if (!atBottom)
painter->drawLine(br.bottomLeft(), br.bottomRight());
if (drawUb && d.ub - 1 >= it.key() && (it.value() == -1 || d.ub - 1 <= it.value()))
drawUb = false;
}
}
}
painter->setOpacity(oldOpacity);
}
if (drawUb) {
painter->setPen(QPen(d.markerColor, 1, Qt::DashLine));
QTextBlock block = findBlockByNumber(d.ub);
if (block.isValid()) {
QRect br = documentLayout()->blockBoundingRect(block).toAlignedRect();
if (bounds.intersects(br))
painter->drawLine(br.topLeft(), br.topRight());
}
}
painter->setPen(oldPen);
painter->setBrush(oldBrush);
}
void TextDocument::drawBackground(QPainter* painter, const QRect& bounds)
{
if (d.highlights.isEmpty())
return;
const QPen oldPen = painter->pen();
const QBrush oldBrush = painter->brush();
const qreal oldOpacity = painter->opacity();
const int margin = qCeil(documentMargin());
const QAbstractTextDocumentLayout* layout = documentLayout();
painter->setPen(QColor("#ffb6b6")); // TODO
painter->setBrush(d.highlightColor);
foreach (int highlight, d.highlights) {
QTextBlock block = findBlockByNumber(highlight);
if (block.isValid()) {
QRect br = layout->blockBoundingRect(block).toAlignedRect();
if (bounds.intersects(br))
painter->drawRect(br.adjusted(-margin - 1, 0, margin + 1, 0));
}
}
painter->setPen(oldPen);
painter->setBrush(oldBrush);
painter->setOpacity(oldOpacity);
}
void TextDocument::updateBlock(int number)
{
if (d.visible) {
QTextBlock block = findBlockByNumber(number);
if (block.isValid())
QMetaObject::invokeMethod(documentLayout(), "updateBlock", Q_ARG(QTextBlock, block));
}
}
void TextDocument::timerEvent(QTimerEvent* event)
{
QTextDocument::timerEvent(event);
if (event->timerId() == d.dirty) {
delay -= 1000;
flushLines();
}
}
void TextDocument::flushLines()
{
if (!d.lines.isEmpty()) {
QTextCursor cursor(this);
cursor.beginEditBlock();
foreach (const QString& line, d.lines)
appendLine(cursor, line);
cursor.endEditBlock();
d.lines.clear();
}
if (d.dirty > 0) {
killTimer(d.dirty);
d.dirty = 0;
}
}
void TextDocument::receiveMessage(IrcMessage* message)
{
append(d.formatter->formatMessage(message));
emit messageReceived(message);
}
void TextDocument::appendLine(QTextCursor& cursor, const QString& line)
{
const int count = blockCount();
cursor.movePosition(QTextCursor::End);
if (!isEmpty()) {
const int max = maximumBlockCount();
cursor.insertBlock();
if (count >= max) {
const int diff = max - count + 1;
if (d.ub > 0)
d.ub -= diff;
QList<int>::iterator i;
for (i = d.highlights.begin(); i != d.highlights.end(); ++i) {
*i -= diff;
if (*i < 0)
i = d.highlights.erase(i);
}
QMap<int, int> ll;
QMap<int, int>::const_iterator j;
for (j = d.lowlights.begin(); j != d.lowlights.end(); ++j) {
int from = j.key() - diff;
int to = j.value() - diff;
if (to > 0)
ll.insert(qMax(0, from), to);
}
d.lowlights = ll;
}
}
#if QT_VERSION >= 0x040800
QTextBlockFormat format = cursor.blockFormat();
format.setLineHeight(120, QTextBlockFormat::ProportionalHeight);
cursor.setBlockFormat(format);
#endif // QT_VERSION
cursor.insertHtml(line);
if (d.ub == -1 && !d.visible)
d.ub = count;
}
<commit_msg>Fix TextDocument::clone() - copy the default style sheet as well<commit_after>/*
* Copyright (C) 2008-2013 The Communi Project
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*/
#include "textdocument.h"
#include "messageformatter.h"
#include "syntaxhighlighter.h"
#include <QAbstractTextDocumentLayout>
#include <QTextDocumentFragment>
#include <QApplication>
#include <QTextCursor>
#include <QTextBlock>
#include <IrcBuffer>
#include <QPalette>
#include <QPainter>
#include <qmath.h>
static int delay = 1000;
TextDocument::TextDocument(IrcBuffer* buffer) : QTextDocument(buffer)
{
qRegisterMetaType<TextDocument*>();
d.ub = -1;
d.dirty = -1;
d.lowlight = -1;
d.clone = false;
d.buffer = buffer;
d.visible = false;
// TODO: stylesheet
d.markerColor = Qt::darkGray;
d.lowlightColor = qApp->palette().color(QPalette::AlternateBase);
d.highlightColor = QColor("#ffd6d6");
d.highlighter = new SyntaxHighlighter(this);
d.formatter = new MessageFormatter(this);
d.formatter->setBuffer(buffer);
setUndoRedoEnabled(false);
setMaximumBlockCount(1000);
connect(buffer, SIGNAL(messageReceived(IrcMessage*)), this, SLOT(receiveMessage(IrcMessage*)));
}
TextDocument* TextDocument::clone()
{
if (d.dirty > 0)
flushLines();
TextDocument* doc = new TextDocument(d.buffer);
doc->setDefaultStyleSheet(defaultStyleSheet());
QTextCursor(doc).insertFragment(QTextDocumentFragment(this));
doc->rootFrame()->setFrameFormat(rootFrame()->frameFormat());
// TODO:
doc->d.ub = d.ub;
doc->d.lowlight = d.lowlight;
doc->d.buffer = d.buffer;
doc->d.highlights = d.highlights;
doc->d.lowlights = d.lowlights;
doc->d.clone = true;
return doc;
}
bool TextDocument::isClone() const
{
return d.clone;
}
IrcBuffer* TextDocument::buffer() const
{
return d.buffer;
}
SyntaxHighlighter* TextDocument::highlighter() const
{
return d.highlighter;
}
int TextDocument::totalCount() const
{
int count = d.lines.count();
if (!isEmpty())
count += blockCount();
return count;
}
QColor TextDocument::markerColor() const
{
return d.markerColor;
}
void TextDocument::setMarkerColor(const QColor& color)
{
if (d.markerColor != color) {
d.markerColor = color;
// TODO: update();
}
}
QColor TextDocument::lowlightColor() const
{
return d.lowlightColor;
}
void TextDocument::setLowlightColor(const QColor& color)
{
if (d.lowlightColor != color) {
d.lowlightColor = color;
// TODO: update();
}
}
QColor TextDocument::highlightColor() const
{
return d.highlightColor;
}
void TextDocument::setHighlightColor(const QColor& color)
{
if (d.highlightColor != color) {
d.highlightColor = color;
// TODO: update();
}
}
bool TextDocument::isVisible() const
{
return d.visible;
}
void TextDocument::setVisible(bool visible)
{
if (d.visible != visible) {
if (visible) {
if (d.dirty > 0)
flushLines();
} else {
d.ub = -1;
}
d.visible = visible;
}
}
void TextDocument::beginLowlight()
{
d.lowlight = totalCount();
d.lowlights.insert(d.lowlight, -1);
}
void TextDocument::endLowlight()
{
d.lowlights.insert(d.lowlight, totalCount());
d.lowlight = -1;
}
void TextDocument::addHighlight(int block)
{
const int max = totalCount() - 1;
if (block == -1)
block = max;
if (block >= 0 && block <= max) {
QList<int>::iterator it = qLowerBound(d.highlights.begin(), d.highlights.end(), block);
d.highlights.insert(it, block);
updateBlock(block);
}
}
void TextDocument::removeHighlight(int block)
{
if (d.highlights.removeOne(block) && block >= 0 && block < totalCount())
updateBlock(block);
}
void TextDocument::append(const QString& text)
{
if (!text.isEmpty()) {
if (d.dirty == 0 || d.visible) {
QTextCursor cursor(this);
cursor.beginEditBlock();
appendLine(cursor, text);
cursor.endEditBlock();
} else {
if (d.dirty <= 0) {
d.dirty = startTimer(delay);
delay += 1000;
}
d.lines += text;
}
}
}
void TextDocument::drawForeground(QPainter* painter, const QRect& bounds)
{
if (d.lowlights.isEmpty() && d.ub <= 1)
return;
const QPen oldPen = painter->pen();
const QBrush oldBrush = painter->brush();
painter->setBrush(Qt::NoBrush);
bool drawUb = d.ub > 1;
if (!d.lowlights.isEmpty()) {
const qreal oldOpacity = painter->opacity();
const QAbstractTextDocumentLayout* layout = documentLayout();
const int margin = qCeil(documentMargin());
QMap<int, int>::const_iterator it;
for (it = d.lowlights.begin(); it != d.lowlights.end(); ++it) {
const QTextBlock from = findBlockByNumber(it.key());
const QTextBlock to = findBlockByNumber(it.value());
if (from.isValid() && to.isValid()) {
const QRect fr = layout->blockBoundingRect(from).toAlignedRect();
const QRect tr = layout->blockBoundingRect(to).toAlignedRect();
QRect br = fr.united(tr);
if (bounds.intersects(br)) {
bool atBottom = false;
if (to == lastBlock()) {
if (qAbs(bounds.bottom() - br.bottom()) < qMin(fr.height(), tr.height()))
atBottom = true;
}
if (atBottom)
br.setBottom(bounds.bottom());
br = br.adjusted(-margin, 0, margin, 1);
painter->setOpacity(0.2);
painter->fillRect(br, d.lowlightColor);
painter->setPen(d.markerColor);
painter->setOpacity(0.5);
painter->drawLine(br.topLeft(), br.topRight());
if (!atBottom)
painter->drawLine(br.bottomLeft(), br.bottomRight());
if (drawUb && d.ub - 1 >= it.key() && (it.value() == -1 || d.ub - 1 <= it.value()))
drawUb = false;
}
}
}
painter->setOpacity(oldOpacity);
}
if (drawUb) {
painter->setPen(QPen(d.markerColor, 1, Qt::DashLine));
QTextBlock block = findBlockByNumber(d.ub);
if (block.isValid()) {
QRect br = documentLayout()->blockBoundingRect(block).toAlignedRect();
if (bounds.intersects(br))
painter->drawLine(br.topLeft(), br.topRight());
}
}
painter->setPen(oldPen);
painter->setBrush(oldBrush);
}
void TextDocument::drawBackground(QPainter* painter, const QRect& bounds)
{
if (d.highlights.isEmpty())
return;
const QPen oldPen = painter->pen();
const QBrush oldBrush = painter->brush();
const qreal oldOpacity = painter->opacity();
const int margin = qCeil(documentMargin());
const QAbstractTextDocumentLayout* layout = documentLayout();
painter->setPen(QColor("#ffb6b6")); // TODO
painter->setBrush(d.highlightColor);
foreach (int highlight, d.highlights) {
QTextBlock block = findBlockByNumber(highlight);
if (block.isValid()) {
QRect br = layout->blockBoundingRect(block).toAlignedRect();
if (bounds.intersects(br))
painter->drawRect(br.adjusted(-margin - 1, 0, margin + 1, 0));
}
}
painter->setPen(oldPen);
painter->setBrush(oldBrush);
painter->setOpacity(oldOpacity);
}
void TextDocument::updateBlock(int number)
{
if (d.visible) {
QTextBlock block = findBlockByNumber(number);
if (block.isValid())
QMetaObject::invokeMethod(documentLayout(), "updateBlock", Q_ARG(QTextBlock, block));
}
}
void TextDocument::timerEvent(QTimerEvent* event)
{
QTextDocument::timerEvent(event);
if (event->timerId() == d.dirty) {
delay -= 1000;
flushLines();
}
}
void TextDocument::flushLines()
{
if (!d.lines.isEmpty()) {
QTextCursor cursor(this);
cursor.beginEditBlock();
foreach (const QString& line, d.lines)
appendLine(cursor, line);
cursor.endEditBlock();
d.lines.clear();
}
if (d.dirty > 0) {
killTimer(d.dirty);
d.dirty = 0;
}
}
void TextDocument::receiveMessage(IrcMessage* message)
{
append(d.formatter->formatMessage(message));
emit messageReceived(message);
}
void TextDocument::appendLine(QTextCursor& cursor, const QString& line)
{
const int count = blockCount();
cursor.movePosition(QTextCursor::End);
if (!isEmpty()) {
const int max = maximumBlockCount();
cursor.insertBlock();
if (count >= max) {
const int diff = max - count + 1;
if (d.ub > 0)
d.ub -= diff;
QList<int>::iterator i;
for (i = d.highlights.begin(); i != d.highlights.end(); ++i) {
*i -= diff;
if (*i < 0)
i = d.highlights.erase(i);
}
QMap<int, int> ll;
QMap<int, int>::const_iterator j;
for (j = d.lowlights.begin(); j != d.lowlights.end(); ++j) {
int from = j.key() - diff;
int to = j.value() - diff;
if (to > 0)
ll.insert(qMax(0, from), to);
}
d.lowlights = ll;
}
}
#if QT_VERSION >= 0x040800
QTextBlockFormat format = cursor.blockFormat();
format.setLineHeight(120, QTextBlockFormat::ProportionalHeight);
cursor.setBlockFormat(format);
#endif // QT_VERSION
cursor.insertHtml(line);
if (d.ub == -1 && !d.visible)
d.ub = count;
}
<|endoftext|> |
<commit_before>/*************************************************************************
*
* $RCSfile: breakit.hxx,v $
*
* $Revision: 1.6 $
*
* last change: $Author: jp $ $Date: 2001-09-28 16:54:37 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the "License"); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#ifndef _BREAKIT_HXX
#define _BREAKIT_HXX
#ifndef _SOLAR_H
#include <tools/solar.h>
#endif
#ifndef _LANG_HXX //autogen
#include <tools/lang.hxx>
#endif
/*************************************************************************
* class SwBreakIt
*************************************************************************/
#ifndef _COM_SUN_STAR_UNO_REFERENCE_H_
#include <com/sun/star/uno/Reference.h>
#endif
#ifndef _COM_SUN_STAR_I18N_XBREAKITERATOR_HPP_
#include <com/sun/star/i18n/XBreakIterator.hpp>
#endif
#ifndef _COM_SUN_STAR_I18N_FORBIDDENCHARACTERS_HDL_
#include <com/sun/star/i18n/ForbiddenCharacters.hdl>
#endif
class String;
class SwBreakIt
{
public:
com::sun::star::uno::Reference < com::sun::star::i18n::XBreakIterator > xBreak;
private:
com::sun::star::lang::Locale* pLocale;
com::sun::star::i18n::ForbiddenCharacters* pForbidden;
LanguageType aLast; // language of the current locale
LanguageType aForbiddenLang; // language of the current forbiddenChar struct
void _GetLocale( const LanguageType aLang );
void _GetForbidden( const LanguageType aLang );
public:
SwBreakIt();
~SwBreakIt() { delete pLocale; delete pForbidden; }
com::sun::star::lang::Locale& GetLocale( const LanguageType aLang )
{
if( aLast != aLang )
_GetLocale( aLang );
return *pLocale;
}
com::sun::star::i18n::ForbiddenCharacters& GetForbidden( const LanguageType aLang )
{
if( !pForbidden || aForbiddenLang != aLang )
_GetForbidden( aLang );
return *pForbidden;
}
USHORT GetRealScriptOfText( const String& rTxt, xub_StrLen nPos ) const;
USHORT GetAllScriptsOfText( const String& rTxt ) const;
};
extern SwBreakIt* pBreakIt;
#endif
<commit_msg>INTEGRATION: CWS dialogdiet01 (1.6.606); FILE MERGED 2004/03/26 09:11:50 mwu 1.6.606.1: sw model converted. 20040326<commit_after>/*************************************************************************
*
* $RCSfile: breakit.hxx,v $
*
* $Revision: 1.7 $
*
* last change: $Author: hr $ $Date: 2004-05-10 16:11:54 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the "License"); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#ifndef _BREAKIT_HXX
#define _BREAKIT_HXX
#ifndef _SOLAR_H
#include <tools/solar.h>
#endif
#ifndef _LANG_HXX //autogen
#include <tools/lang.hxx>
#endif
/*************************************************************************
* class SwBreakIt
*************************************************************************/
#ifndef _COM_SUN_STAR_UNO_REFERENCE_H_
#include <com/sun/star/uno/Reference.h>
#endif
#ifndef _COM_SUN_STAR_I18N_XBREAKITERATOR_HPP_
#include <com/sun/star/i18n/XBreakIterator.hpp>
#endif
#ifndef _COM_SUN_STAR_I18N_FORBIDDENCHARACTERS_HDL_
#include <com/sun/star/i18n/ForbiddenCharacters.hdl>
#endif
class String;
class SwBreakIt
{
public:
com::sun::star::uno::Reference < com::sun::star::i18n::XBreakIterator > xBreak;
private:
com::sun::star::lang::Locale* pLocale;
com::sun::star::i18n::ForbiddenCharacters* pForbidden;
LanguageType aLast; // language of the current locale
LanguageType aForbiddenLang; // language of the current forbiddenChar struct
void _GetLocale( const LanguageType aLang );
void _GetForbidden( const LanguageType aLang );
public:
SwBreakIt();
~SwBreakIt() { delete pLocale; delete pForbidden; }
com::sun::star::lang::Locale& GetLocale( const LanguageType aLang )
{
if( aLast != aLang )
_GetLocale( aLang );
return *pLocale;
}
com::sun::star::i18n::ForbiddenCharacters& GetForbidden( const LanguageType aLang )
{
if( !pForbidden || aForbiddenLang != aLang )
_GetForbidden( aLang );
return *pForbidden;
}
USHORT GetRealScriptOfText( const String& rTxt, xub_StrLen nPos ) const;
USHORT GetAllScriptsOfText( const String& rTxt ) const;
};
extern SwBreakIt* pBreakIt;
SwBreakIt* GetBreakIt(); //CHINA001 add for swui
#endif
<|endoftext|> |
<commit_before>/* bzflag
* Copyright (c) 1993 - 2008 Tim Riker
*
* This package is free software; you can redistribute it and/or
* modify it under the terms of the license found in the file
* named COPYING that should have accompanied this file.
*
* THIS PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
*/
// interface headers
#include "HUDuiServerInfo.h"
#include "playing.h"
#include "ServerList.h"
#include "FontManager.h"
#include "FontSizer.h"
#include "LocalFontFace.h"
#include "HUDuiLabel.h"
#include "OpenGLUtils.h"
//
// HUDuiServerInfo
//
HUDuiServerInfo::HUDuiServerInfo() : HUDuiControl()
{
readouts.push_back(new HUDuiLabel); // 0
readouts.push_back(new HUDuiLabel); // 1
readouts.push_back(new HUDuiLabel); // 2
readouts.push_back(new HUDuiLabel); // 3
readouts.push_back(new HUDuiLabel); // 4
readouts.push_back(new HUDuiLabel); // 5
readouts.push_back(new HUDuiLabel); // 6
readouts.push_back(new HUDuiLabel); // 7 max shots
readouts.push_back(new HUDuiLabel); // 8 capture-the-flag/free-style/rabbit chase
readouts.push_back(new HUDuiLabel); // 9 super-flags
readouts.push_back(new HUDuiLabel); // 10 antidote-flag
readouts.push_back(new HUDuiLabel); // 11 shaking time
readouts.push_back(new HUDuiLabel); // 12 shaking wins
readouts.push_back(new HUDuiLabel); // 13 jumping
readouts.push_back(new HUDuiLabel); // 14 ricochet
readouts.push_back(new HUDuiLabel); // 15 inertia
readouts.push_back(new HUDuiLabel); // 16 time limit
readouts.push_back(new HUDuiLabel); // 17 max team score
readouts.push_back(new HUDuiLabel); // 18 max player score
readouts.push_back(new HUDuiLabel); // 19 ping time
readouts.push_back(new HUDuiLabel); // 20 cached status
readouts.push_back(new HUDuiLabel); // 21 cached age
HUDuiLabel* allPlayers = new HUDuiLabel;
allPlayers->setString("Players");
playerLabels.push_back(allPlayers);
HUDuiLabel* rogue = new HUDuiLabel;
rogue->setString("Rogue");
playerLabels.push_back(rogue);
HUDuiLabel* red = new HUDuiLabel;
red->setString("Red");
playerLabels.push_back(red);
HUDuiLabel* green = new HUDuiLabel;
green->setString("Green");
playerLabels.push_back(green);
HUDuiLabel* blue = new HUDuiLabel;
blue->setString("Blue");
playerLabels.push_back(blue);
HUDuiLabel* purple = new HUDuiLabel;
purple->setString("Purple");
playerLabels.push_back(purple);
HUDuiLabel* observers = new HUDuiLabel;
observers->setString("Observers");
playerLabels.push_back(observers);
}
HUDuiServerInfo::~HUDuiServerInfo()
{
// Do nothing
}
void HUDuiServerInfo::setServerItem(ServerItem* item)
{
if (item == NULL)
serverKey = "";
else
serverKey = item->getServerKey();
}
void HUDuiServerInfo::setSize(float width, float height)
{
HUDuiControl::setSize(width, height);
resize();
}
void HUDuiServerInfo::setFontSize(float size)
{
HUDuiControl::setFontSize(size);
resize();
}
void HUDuiServerInfo::setFontFace(const LocalFontFace* face)
{
HUDuiControl::setFontFace(face);
resize();
}
void HUDuiServerInfo::setPosition(float x, float y)
{
HUDuiControl::setPosition(x, y);
resize();
}
void HUDuiServerInfo::resize()
{
FontManager &fm = FontManager::instance();
FontSizer fs = FontSizer(getWidth(), getHeight());
// reposition server readouts
float fontSize = fs.getFontSize(getFontFace()->getFMFace(), "alertFontSize");
float itemHeight = fm.getStringHeight(getFontFace()->getFMFace(), fontSize);
const float y0 = getY() + getHeight() - itemHeight - itemHeight/2;
float y = y0;
float x = getX() + itemHeight;
fs.setMin(10, 10);
for (size_t i=0; i<readouts.size(); i++) {
if ((i + 1) % 7 == 1) {
x = (0.125f + 0.25f * (float)(i / 7)) * (float)getWidth();
y = y0;
}
HUDuiLabel* readout = readouts[i];
readout->setFontSize(fontSize);
readout->setFontFace(getFontFace());
y -= 1.0f * itemHeight;
readout->setPosition(x, y);
}
// Was this supposed to be used somewhere?
// float spacer = fm.getStringWidth(getFontFace()->getFMFace(), fontSize, "X");
x = (0.125f + 0.25f * (float)(1 / 7)) * (float)getWidth();
y = y0;
for (size_t i=0; i<playerLabels.size(); i++) {
HUDuiLabel* _label = playerLabels[i];
_label->setFontSize(fontSize);
_label->setFontFace(getFontFace());
y -= 1.0f * itemHeight;
_label->setPosition(x, y);
}
}
void HUDuiServerInfo::fillReadouts()
{
ServerItem* itemPointer = ServerList::instance().lookupServer(serverKey);
if (itemPointer == NULL)
return;
const ServerItem& item = *itemPointer;
const PingPacket& ping = item.ping;
// update server readouts
char buf[60];
std::vector<HUDuiLabel*>& listHUD = readouts;
//const uint8_t maxes [] = { ping.maxPlayers, ping.rogueMax, ping.redMax, ping.greenMax,
// ping.blueMax, ping.purpleMax, ping.observerMax };
// if this is a cached item set the player counts to "?/max count"
if (item.cached && item.getPlayerCount() == 0) {
//for (int i = 1; i <=7; i ++) {
// sprintf(buf, "?/%d", maxes[i-1]);
// (listHUD[i])->setLabel(buf);
//}
} else { // not an old item, set players #s to info we have
sprintf(buf, "%d/%d", ping.rogueCount + ping.redCount + ping.greenCount +
ping.blueCount + ping.purpleCount, ping.maxPlayers);
(listHUD[0])->setLabel(buf);
if (ping.rogueMax == 0)
buf[0]=0;
else if (ping.rogueMax >= ping.maxPlayers)
sprintf(buf, "%d", ping.rogueCount);
else
sprintf(buf, "%d/%d", ping.rogueCount, ping.rogueMax);
(listHUD[1])->setLabel(buf);
if (ping.redMax == 0)
buf[0]=0;
else if (ping.redMax >= ping.maxPlayers)
sprintf(buf, "%d", ping.redCount);
else
sprintf(buf, "%d/%d", ping.redCount, ping.redMax);
(listHUD[2])->setLabel(buf);
if (ping.greenMax == 0)
buf[0]=0;
else if (ping.greenMax >= ping.maxPlayers)
sprintf(buf, "%d", ping.greenCount);
else
sprintf(buf, "%d/%d", ping.greenCount, ping.greenMax);
(listHUD[3])->setLabel(buf);
if (ping.blueMax == 0)
buf[0]=0;
else if (ping.blueMax >= ping.maxPlayers)
sprintf(buf, "%d", ping.blueCount);
else
sprintf(buf, "%d/%d", ping.blueCount, ping.blueMax);
(listHUD[4])->setLabel(buf);
if (ping.purpleMax == 0)
buf[0]=0;
else if (ping.purpleMax >= ping.maxPlayers)
sprintf(buf, "%d", ping.purpleCount);
else
sprintf(buf, "%d/%d", ping.purpleCount, ping.purpleMax);
(listHUD[5])->setLabel(buf);
if (ping.observerMax == 0)
buf[0]=0;
else if (ping.observerMax >= ping.maxPlayers)
sprintf(buf, "%d", ping.observerCount);
else
sprintf(buf, "%d/%d", ping.observerCount, ping.observerMax);
(listHUD[6])->setLabel(buf);
}
std::vector<std::string> args;
sprintf(buf, "%d", ping.maxShots);
args.push_back(buf);
if (ping.maxShots == 1)
(listHUD[7])->setString("{1} Shot", &args );
else
(listHUD[7])->setString("{1} Shots", &args );
if (ping.gameType == ClassicCTF)
(listHUD[8])->setString("Classic Capture-the-Flag");
else if (ping.gameType == RabbitChase)
(listHUD[8])->setString("Rabbit Chase");
else if (ping.gameType == OpenFFA)
(listHUD[8])->setString("Open (Teamless) Free-For-All");
else
(listHUD[8])->setString("Team Free-For-All");
if (ping.gameOptions & SuperFlagGameStyle)
(listHUD[9])->setString("Super Flags");
else
(listHUD[9])->setString("");
if (ping.gameOptions & AntidoteGameStyle)
(listHUD[10])->setString("Antidote Flags");
else
(listHUD[10])->setString("");
if ((ping.gameOptions & ShakableGameStyle) && ping.shakeTimeout != 0) {
std::vector<std::string> dropArgs;
sprintf(buf, "%.1f", 0.1f * float(ping.shakeTimeout));
dropArgs.push_back(buf);
if (ping.shakeWins == 1)
(listHUD[11])->setString("{1} sec To Drop Bad Flag",
&dropArgs);
else
(listHUD[11])->setString("{1} secs To Drop Bad Flag",
&dropArgs);
} else {
(listHUD[11])->setString("");
}
if ((ping.gameOptions & ShakableGameStyle) && ping.shakeWins != 0) {
std::vector<std::string> dropArgs;
sprintf(buf, "%d", ping.shakeWins);
dropArgs.push_back(buf);
dropArgs.push_back(ping.shakeWins == 1 ? "" : "s");
if (ping.shakeWins == 1)
(listHUD[12])->setString("{1} Win Drops Bad Flag",
&dropArgs);
else
(listHUD[12])->setString("{1} Wins Drops Bad Flag",
&dropArgs);
} else {
(listHUD[12])->setString("");
}
if (ping.gameOptions & JumpingGameStyle)
(listHUD[13])->setString("Jumping");
else
(listHUD[13])->setString("");
if (ping.gameOptions & RicochetGameStyle)
(listHUD[14])->setString("Ricochet");
else
(listHUD[14])->setString("");
if (ping.gameOptions & HandicapGameStyle)
(listHUD[15])->setString("Handicap");
else
(listHUD[15])->setString("");
if (ping.maxTime != 0) {
std::vector<std::string> pingArgs;
if (ping.maxTime >= 3600)
sprintf(buf, "%d:%02d:%02d", ping.maxTime / 3600, (ping.maxTime / 60) % 60, ping.maxTime % 60);
else if (ping.maxTime >= 60)
sprintf(buf, "%d:%02d", ping.maxTime / 60, ping.maxTime % 60);
else
sprintf(buf, "0:%02d", ping.maxTime);
pingArgs.push_back(buf);
(listHUD[16])->setString("Time limit: {1}", &pingArgs);
} else {
(listHUD[16])->setString("");
}
if (ping.maxTeamScore != 0) {
std::vector<std::string> scoreArgs;
sprintf(buf, "%d", ping.maxTeamScore);
scoreArgs.push_back(buf);
(listHUD[17])->setString("Max team score: {1}", &scoreArgs);
} else {
(listHUD[17])->setString("");
}
if (ping.maxPlayerScore != 0) {
std::vector<std::string> scoreArgs;
sprintf(buf, "%d", ping.maxPlayerScore);
scoreArgs.push_back(buf);
(listHUD[18])->setString("Max player score: {1}", &scoreArgs);
} else {
(listHUD[18])->setString("");
}
if (ping.pingTime > 0) {
std::vector<std::string> pingArgs;
if (ping.pingTime == INT_MAX)
strcpy(buf, " Not responding");
else
sprintf(buf, "%dms", ping.pingTime);
pingArgs.push_back(buf);
((HUDuiLabel*)listHUD[19])->setString("Ping: {1}", &pingArgs);
} else {
((HUDuiLabel*)listHUD[19])->setString("");
}
if (item.cached) {
(listHUD[20])->setString("Cached");
(listHUD[21])->setString(item.getAgeString());
} else {
(listHUD[20])->setString("");
(listHUD[21])->setString("");
}
}
void HUDuiServerInfo::doRender()
{
if (getFontFace() < 0) {
return;
}
FontManager &fm = FontManager::instance();
FontSizer fs = FontSizer(getWidth(), getHeight());
float fontSize = fs.getFontSize(getFontFace()->getFMFace(), "alertFontSize");
float itemHeight = fm.getStringHeight(getFontFace()->getFMFace(), fontSize);
float titleWidth = fm.getStringWidth(getFontFace()->getFMFace(), fontSize, "Server Information");
fm.drawString(getX() + (getWidth()/2) - (titleWidth/2), getY() + getHeight() - itemHeight, 0, getFontFace()->getFMFace(), fontSize, "Server Information");
float color[4] = {1.0f, 1.0f, 1.0f, 1.0f};
glColor4fv(color);
glOutlineBoxHV(1.0f, getX(), getY(), getX() + getWidth(), getY() + getHeight(), -0.5f);
glOutlineBoxHV(1.0f, getX(), getY(), getX() + getWidth(), getY() + getHeight() - itemHeight - itemHeight/2, -0.5f);
if (serverKey == "")
return;
fillReadouts();
for (std::vector<HUDuiLabel*>::iterator itr = readouts.begin(); itr != readouts.end(); ++itr)
(*itr)->render();
for (std::vector<HUDuiLabel*>::iterator itr = playerLabels.begin(); itr != playerLabels.end(); ++itr)
(*itr)->render();
}
// Local Variables: ***
// mode: C++ ***
// tab-width: 8 ***
// c-basic-offset: 2 ***
// indent-tabs-mode: t ***
// End: ***
// ex: shiftwidth=2 tabstop=8
<commit_msg>dead code<commit_after>/* bzflag
* Copyright (c) 1993 - 2008 Tim Riker
*
* This package is free software; you can redistribute it and/or
* modify it under the terms of the license found in the file
* named COPYING that should have accompanied this file.
*
* THIS PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
*/
// interface headers
#include "HUDuiServerInfo.h"
#include "playing.h"
#include "ServerList.h"
#include "FontManager.h"
#include "FontSizer.h"
#include "LocalFontFace.h"
#include "HUDuiLabel.h"
#include "OpenGLUtils.h"
//
// HUDuiServerInfo
//
HUDuiServerInfo::HUDuiServerInfo() : HUDuiControl()
{
readouts.push_back(new HUDuiLabel); // 0
readouts.push_back(new HUDuiLabel); // 1
readouts.push_back(new HUDuiLabel); // 2
readouts.push_back(new HUDuiLabel); // 3
readouts.push_back(new HUDuiLabel); // 4
readouts.push_back(new HUDuiLabel); // 5
readouts.push_back(new HUDuiLabel); // 6
readouts.push_back(new HUDuiLabel); // 7 max shots
readouts.push_back(new HUDuiLabel); // 8 capture-the-flag/free-style/rabbit chase
readouts.push_back(new HUDuiLabel); // 9 super-flags
readouts.push_back(new HUDuiLabel); // 10 antidote-flag
readouts.push_back(new HUDuiLabel); // 11 shaking time
readouts.push_back(new HUDuiLabel); // 12 shaking wins
readouts.push_back(new HUDuiLabel); // 13 jumping
readouts.push_back(new HUDuiLabel); // 14 ricochet
readouts.push_back(new HUDuiLabel); // 15 inertia
readouts.push_back(new HUDuiLabel); // 16 time limit
readouts.push_back(new HUDuiLabel); // 17 max team score
readouts.push_back(new HUDuiLabel); // 18 max player score
readouts.push_back(new HUDuiLabel); // 19 ping time
readouts.push_back(new HUDuiLabel); // 20 cached status
readouts.push_back(new HUDuiLabel); // 21 cached age
HUDuiLabel* allPlayers = new HUDuiLabel;
allPlayers->setString("Players");
playerLabels.push_back(allPlayers);
HUDuiLabel* rogue = new HUDuiLabel;
rogue->setString("Rogue");
playerLabels.push_back(rogue);
HUDuiLabel* red = new HUDuiLabel;
red->setString("Red");
playerLabels.push_back(red);
HUDuiLabel* green = new HUDuiLabel;
green->setString("Green");
playerLabels.push_back(green);
HUDuiLabel* blue = new HUDuiLabel;
blue->setString("Blue");
playerLabels.push_back(blue);
HUDuiLabel* purple = new HUDuiLabel;
purple->setString("Purple");
playerLabels.push_back(purple);
HUDuiLabel* observers = new HUDuiLabel;
observers->setString("Observers");
playerLabels.push_back(observers);
}
HUDuiServerInfo::~HUDuiServerInfo()
{
// Do nothing
}
void HUDuiServerInfo::setServerItem(ServerItem* item)
{
if (item == NULL)
serverKey = "";
else
serverKey = item->getServerKey();
}
void HUDuiServerInfo::setSize(float width, float height)
{
HUDuiControl::setSize(width, height);
resize();
}
void HUDuiServerInfo::setFontSize(float size)
{
HUDuiControl::setFontSize(size);
resize();
}
void HUDuiServerInfo::setFontFace(const LocalFontFace* face)
{
HUDuiControl::setFontFace(face);
resize();
}
void HUDuiServerInfo::setPosition(float x, float y)
{
HUDuiControl::setPosition(x, y);
resize();
}
void HUDuiServerInfo::resize()
{
FontManager &fm = FontManager::instance();
FontSizer fs = FontSizer(getWidth(), getHeight());
// reposition server readouts
float fontSize = fs.getFontSize(getFontFace()->getFMFace(), "alertFontSize");
float itemHeight = fm.getStringHeight(getFontFace()->getFMFace(), fontSize);
const float y0 = getY() + getHeight() - itemHeight - itemHeight/2;
float y = y0;
float x = getX() + itemHeight;
fs.setMin(10, 10);
for (size_t i=0; i<readouts.size(); i++) {
if ((i + 1) % 7 == 1) {
x = (0.125f + 0.25f * (float)(i / 7)) * (float)getWidth();
y = y0;
}
HUDuiLabel* readout = readouts[i];
readout->setFontSize(fontSize);
readout->setFontFace(getFontFace());
y -= 1.0f * itemHeight;
readout->setPosition(x, y);
}
x = (0.125f + 0.25f * (float)(1 / 7)) * (float)getWidth();
y = y0;
for (size_t i=0; i<playerLabels.size(); i++) {
HUDuiLabel* _label = playerLabels[i];
_label->setFontSize(fontSize);
_label->setFontFace(getFontFace());
y -= 1.0f * itemHeight;
_label->setPosition(x, y);
}
}
void HUDuiServerInfo::fillReadouts()
{
ServerItem* itemPointer = ServerList::instance().lookupServer(serverKey);
if (itemPointer == NULL)
return;
const ServerItem& item = *itemPointer;
const PingPacket& ping = item.ping;
// update server readouts
char buf[60];
std::vector<HUDuiLabel*>& listHUD = readouts;
//const uint8_t maxes [] = { ping.maxPlayers, ping.rogueMax, ping.redMax, ping.greenMax,
// ping.blueMax, ping.purpleMax, ping.observerMax };
// if this is a cached item set the player counts to "?/max count"
if (item.cached && item.getPlayerCount() == 0) {
//for (int i = 1; i <=7; i ++) {
// sprintf(buf, "?/%d", maxes[i-1]);
// (listHUD[i])->setLabel(buf);
//}
} else { // not an old item, set players #s to info we have
sprintf(buf, "%d/%d", ping.rogueCount + ping.redCount + ping.greenCount +
ping.blueCount + ping.purpleCount, ping.maxPlayers);
(listHUD[0])->setLabel(buf);
if (ping.rogueMax == 0)
buf[0]=0;
else if (ping.rogueMax >= ping.maxPlayers)
sprintf(buf, "%d", ping.rogueCount);
else
sprintf(buf, "%d/%d", ping.rogueCount, ping.rogueMax);
(listHUD[1])->setLabel(buf);
if (ping.redMax == 0)
buf[0]=0;
else if (ping.redMax >= ping.maxPlayers)
sprintf(buf, "%d", ping.redCount);
else
sprintf(buf, "%d/%d", ping.redCount, ping.redMax);
(listHUD[2])->setLabel(buf);
if (ping.greenMax == 0)
buf[0]=0;
else if (ping.greenMax >= ping.maxPlayers)
sprintf(buf, "%d", ping.greenCount);
else
sprintf(buf, "%d/%d", ping.greenCount, ping.greenMax);
(listHUD[3])->setLabel(buf);
if (ping.blueMax == 0)
buf[0]=0;
else if (ping.blueMax >= ping.maxPlayers)
sprintf(buf, "%d", ping.blueCount);
else
sprintf(buf, "%d/%d", ping.blueCount, ping.blueMax);
(listHUD[4])->setLabel(buf);
if (ping.purpleMax == 0)
buf[0]=0;
else if (ping.purpleMax >= ping.maxPlayers)
sprintf(buf, "%d", ping.purpleCount);
else
sprintf(buf, "%d/%d", ping.purpleCount, ping.purpleMax);
(listHUD[5])->setLabel(buf);
if (ping.observerMax == 0)
buf[0]=0;
else if (ping.observerMax >= ping.maxPlayers)
sprintf(buf, "%d", ping.observerCount);
else
sprintf(buf, "%d/%d", ping.observerCount, ping.observerMax);
(listHUD[6])->setLabel(buf);
}
std::vector<std::string> args;
sprintf(buf, "%d", ping.maxShots);
args.push_back(buf);
if (ping.maxShots == 1)
(listHUD[7])->setString("{1} Shot", &args );
else
(listHUD[7])->setString("{1} Shots", &args );
if (ping.gameType == ClassicCTF)
(listHUD[8])->setString("Classic Capture-the-Flag");
else if (ping.gameType == RabbitChase)
(listHUD[8])->setString("Rabbit Chase");
else if (ping.gameType == OpenFFA)
(listHUD[8])->setString("Open (Teamless) Free-For-All");
else
(listHUD[8])->setString("Team Free-For-All");
if (ping.gameOptions & SuperFlagGameStyle)
(listHUD[9])->setString("Super Flags");
else
(listHUD[9])->setString("");
if (ping.gameOptions & AntidoteGameStyle)
(listHUD[10])->setString("Antidote Flags");
else
(listHUD[10])->setString("");
if ((ping.gameOptions & ShakableGameStyle) && ping.shakeTimeout != 0) {
std::vector<std::string> dropArgs;
sprintf(buf, "%.1f", 0.1f * float(ping.shakeTimeout));
dropArgs.push_back(buf);
if (ping.shakeWins == 1)
(listHUD[11])->setString("{1} sec To Drop Bad Flag",
&dropArgs);
else
(listHUD[11])->setString("{1} secs To Drop Bad Flag",
&dropArgs);
} else {
(listHUD[11])->setString("");
}
if ((ping.gameOptions & ShakableGameStyle) && ping.shakeWins != 0) {
std::vector<std::string> dropArgs;
sprintf(buf, "%d", ping.shakeWins);
dropArgs.push_back(buf);
dropArgs.push_back(ping.shakeWins == 1 ? "" : "s");
if (ping.shakeWins == 1)
(listHUD[12])->setString("{1} Win Drops Bad Flag",
&dropArgs);
else
(listHUD[12])->setString("{1} Wins Drops Bad Flag",
&dropArgs);
} else {
(listHUD[12])->setString("");
}
if (ping.gameOptions & JumpingGameStyle)
(listHUD[13])->setString("Jumping");
else
(listHUD[13])->setString("");
if (ping.gameOptions & RicochetGameStyle)
(listHUD[14])->setString("Ricochet");
else
(listHUD[14])->setString("");
if (ping.gameOptions & HandicapGameStyle)
(listHUD[15])->setString("Handicap");
else
(listHUD[15])->setString("");
if (ping.maxTime != 0) {
std::vector<std::string> pingArgs;
if (ping.maxTime >= 3600)
sprintf(buf, "%d:%02d:%02d", ping.maxTime / 3600, (ping.maxTime / 60) % 60, ping.maxTime % 60);
else if (ping.maxTime >= 60)
sprintf(buf, "%d:%02d", ping.maxTime / 60, ping.maxTime % 60);
else
sprintf(buf, "0:%02d", ping.maxTime);
pingArgs.push_back(buf);
(listHUD[16])->setString("Time limit: {1}", &pingArgs);
} else {
(listHUD[16])->setString("");
}
if (ping.maxTeamScore != 0) {
std::vector<std::string> scoreArgs;
sprintf(buf, "%d", ping.maxTeamScore);
scoreArgs.push_back(buf);
(listHUD[17])->setString("Max team score: {1}", &scoreArgs);
} else {
(listHUD[17])->setString("");
}
if (ping.maxPlayerScore != 0) {
std::vector<std::string> scoreArgs;
sprintf(buf, "%d", ping.maxPlayerScore);
scoreArgs.push_back(buf);
(listHUD[18])->setString("Max player score: {1}", &scoreArgs);
} else {
(listHUD[18])->setString("");
}
if (ping.pingTime > 0) {
std::vector<std::string> pingArgs;
if (ping.pingTime == INT_MAX)
strcpy(buf, " Not responding");
else
sprintf(buf, "%dms", ping.pingTime);
pingArgs.push_back(buf);
((HUDuiLabel*)listHUD[19])->setString("Ping: {1}", &pingArgs);
} else {
((HUDuiLabel*)listHUD[19])->setString("");
}
if (item.cached) {
(listHUD[20])->setString("Cached");
(listHUD[21])->setString(item.getAgeString());
} else {
(listHUD[20])->setString("");
(listHUD[21])->setString("");
}
}
void HUDuiServerInfo::doRender()
{
if (getFontFace() < 0) {
return;
}
FontManager &fm = FontManager::instance();
FontSizer fs = FontSizer(getWidth(), getHeight());
float fontSize = fs.getFontSize(getFontFace()->getFMFace(), "alertFontSize");
float itemHeight = fm.getStringHeight(getFontFace()->getFMFace(), fontSize);
float titleWidth = fm.getStringWidth(getFontFace()->getFMFace(), fontSize, "Server Information");
fm.drawString(getX() + (getWidth()/2) - (titleWidth/2), getY() + getHeight() - itemHeight, 0, getFontFace()->getFMFace(), fontSize, "Server Information");
float color[4] = {1.0f, 1.0f, 1.0f, 1.0f};
glColor4fv(color);
glOutlineBoxHV(1.0f, getX(), getY(), getX() + getWidth(), getY() + getHeight(), -0.5f);
glOutlineBoxHV(1.0f, getX(), getY(), getX() + getWidth(), getY() + getHeight() - itemHeight - itemHeight/2, -0.5f);
if (serverKey == "")
return;
fillReadouts();
for (std::vector<HUDuiLabel*>::iterator itr = readouts.begin(); itr != readouts.end(); ++itr)
(*itr)->render();
for (std::vector<HUDuiLabel*>::iterator itr = playerLabels.begin(); itr != playerLabels.end(); ++itr)
(*itr)->render();
}
// Local Variables: ***
// mode: C++ ***
// tab-width: 8 ***
// c-basic-offset: 2 ***
// indent-tabs-mode: t ***
// End: ***
// ex: shiftwidth=2 tabstop=8
<|endoftext|> |
<commit_before>//
// File: crosscorrelate.cc
// Author: ruehle
//
// Created on May 22, 2007, 5:42 PM
//
#include <fftw3.h>
#include "crosscorrelate.h"
/**
\todo clean implementation!!!
*/
void CrossCorrelate::AutoCorrelate(DataCollection<double>::selection *data, bool average)
{
size_t N = (*data)[0].size();
_corrfunc.resize(N);
fftw_complex *tmp;
fftw_plan fft, ifft;
tmp = (fftw_complex*) fftw_malloc(sizeof(fftw_complex) * (N/2+1));
fft = fftw_plan_dft_r2c_1d(N, &(*data)[0][0], tmp,
FFTW_ESTIMATE);
ifft = fftw_plan_dft_c2r_1d(N, tmp, &_corrfunc[0],
FFTW_ESTIMATE);
fftw_execute(fft);
tmp[0][0] = tmp[0][1] = 0;
for(int i=1; i<N/2+1; i++) {
tmp[i][0] = tmp[i][0]*tmp[i][0] + tmp[i][1]*tmp[i][1];
tmp[i][1] = 0;
}
fftw_execute(ifft);
/*double m=0;
for(int i=0; i<N; i++) {
_corrfunc[i] = 0;
m+=(*data)[0][i];
}
m=m/(double)N;
for(int i=0;i<N; i++)
for(int j=0; j<N-i-1; j++)
_corrfunc[i]+=((*data)[0][j]-m)*((*data)[0][(i+j)]-m);
*/
double d = _corrfunc[0];
for(int i=0; i<N; i++)
_corrfunc[i] = _corrfunc[i]/d;
//cout << *data << endl;
fftw_destroy_plan(fft);
fftw_destroy_plan(ifft);
fftw_free(tmp);
}
void CrossCorrelate::AutoFourier(vector <double>& ivec){
size_t N = ivec.size();
_corrfunc.resize(N);
fftw_complex *tmp;
fftw_plan fft;
tmp = (fftw_complex*) fftw_malloc(sizeof(fftw_complex) * (N/2+1));
fft = fftw_plan_dft_r2c_1d(N, &ivec[0], tmp, FFTW_ESTIMATE);
fftw_execute(fft);
tmp[0][0] = tmp[0][1] = 0;
for(int i=1; i<N/2+1; i++) {
tmp[i][0] = tmp[i][0]*tmp[i][0] + tmp[i][1]*tmp[i][1];
tmp[i][1] = 0;
}
// copy the real component of temp to the _corrfunc vector
for(int i=0; i<N; i++){
_corrfunc[i] = tmp[i][0];
}
fftw_destroy_plan(fft);
fftw_free(tmp);
}
void CrossCorrelate::AutoCosine(vector <double>& ivec){
size_t N = ivec.size();
_corrfunc.resize(N);
vector <double> tmp;
tmp.resize(N);
fftw_plan fft;
// do real to real discrete cosine trafo
fft = fftw_plan_r2r_1d(N, &ivec[0], &tmp[0], FFTW_REDFT10, FFTW_ESTIMATE);
fftw_execute(fft);
// compute autocorrelation
tmp[0] = 0;
for(int i=1; i<N; i++) {
tmp[i] = tmp[i]*tmp[i];
}
// store results
for(int i=0; i<N; i++){
_corrfunc[i] = tmp[i];
}
fftw_destroy_plan(fft);
}
void CrossCorrelate::AutoCorr(vector <double>& ivec){
size_t N = ivec.size();
_corrfunc.resize(N);
fftw_complex *tmp;
fftw_plan fft, ifft;
tmp = (fftw_complex*) fftw_malloc(sizeof(fftw_complex) * (N/2+1));
fft = fftw_plan_dft_r2c_1d(N, &ivec[0], tmp, FFTW_ESTIMATE);
ifft = fftw_plan_dft_c2r_1d(N, tmp, &_corrfunc[0], FFTW_ESTIMATE);
fftw_execute(fft);
tmp[0][0] = tmp[0][1] = 0;
for(int i=1; i<N/2+1; i++) {
tmp[i][0] = tmp[i][0]*tmp[i][0] + tmp[i][1]*tmp[i][1];
tmp[i][1] = 0;
}
fftw_execute(ifft);
double d = _corrfunc[0];
for(int i=0; i<N; i++)
_corrfunc[i] = _corrfunc[i]/d;
fftw_destroy_plan(fft);
fftw_destroy_plan(ifft);
fftw_free(tmp);
}<commit_msg>now contains fcts doing solely Fourier trafo or Discrete Cosine trafo for testing<commit_after>//
// File: crosscorrelate.cc
// Author: ruehle
//
// Created on May 22, 2007, 5:42 PM
//
#include <fftw3.h>
#include "crosscorrelate.h"
/**
\todo clean implementation!!!
*/
void CrossCorrelate::AutoCorrelate(DataCollection<double>::selection *data, bool average)
{
size_t N = (*data)[0].size();
_corrfunc.resize(N);
fftw_complex *tmp;
fftw_plan fft, ifft;
tmp = (fftw_complex*) fftw_malloc(sizeof(fftw_complex) * (N/2+1));
fft = fftw_plan_dft_r2c_1d(N, &(*data)[0][0], tmp,
FFTW_ESTIMATE);
ifft = fftw_plan_dft_c2r_1d(N, tmp, &_corrfunc[0],
FFTW_ESTIMATE);
fftw_execute(fft);
tmp[0][0] = tmp[0][1] = 0;
for(int i=1; i<N/2+1; i++) {
tmp[i][0] = tmp[i][0]*tmp[i][0] + tmp[i][1]*tmp[i][1];
tmp[i][1] = 0;
}
fftw_execute(ifft);
/*double m=0;
for(int i=0; i<N; i++) {
_corrfunc[i] = 0;
m+=(*data)[0][i];
}
m=m/(double)N;
for(int i=0;i<N; i++)
for(int j=0; j<N-i-1; j++)
_corrfunc[i]+=((*data)[0][j]-m)*((*data)[0][(i+j)]-m);
*/
double d = _corrfunc[0];
for(int i=0; i<N; i++)
_corrfunc[i] = _corrfunc[i]/d;
//cout << *data << endl;
fftw_destroy_plan(fft);
fftw_destroy_plan(ifft);
fftw_free(tmp);
}
void CrossCorrelate::AutoFourier(vector <double>& ivec){
size_t N = ivec.size();
_corrfunc.resize(N);
fftw_complex *tmp;
fftw_plan fft;
tmp = (fftw_complex*) fftw_malloc(sizeof(fftw_complex) * (N/2+1));
fft = fftw_plan_dft_r2c_1d(N, &ivec[0], tmp, FFTW_ESTIMATE);
fftw_execute(fft);
tmp[0][0] = tmp[0][1] = 0;
for(int i=1; i<N/2+1; i++) {
tmp[i][0] = tmp[i][0]*tmp[i][0] + tmp[i][1]*tmp[i][1];
tmp[i][1] = 0;
}
// copy the real component of temp to the _corrfunc vector
for(int i=0; i<N; i++){
_corrfunc[i] = tmp[i][0];
}
fftw_destroy_plan(fft);
fftw_free(tmp);
}
void CrossCorrelate::FFTOnly(vector <double>& ivec){
size_t N = ivec.size();
_corrfunc.resize(N);
fftw_complex *tmp;
fftw_plan fft;
tmp = (fftw_complex*) fftw_malloc(sizeof(fftw_complex) * (N/2+1));
fft = fftw_plan_dft_r2c_1d(N, &ivec[0], tmp, FFTW_ESTIMATE);
fftw_execute(fft);
// copy the real component of temp to the _corrfunc vector
for(int i=0; i<N/2+1; i++){
_corrfunc[i] = tmp[i][0];
}
fftw_destroy_plan(fft);
fftw_free(tmp);
}
void CrossCorrelate::DCTOnly(vector <double>& ivec){
size_t N = ivec.size();
_corrfunc.resize(N);
vector <double> tmp;
tmp.resize(N);
fftw_plan fft;
// do real to real discrete cosine trafo
fft = fftw_plan_r2r_1d(N, &ivec[0], &tmp[0], FFTW_REDFT10, FFTW_ESTIMATE);
fftw_execute(fft);
// store results
for(int i=0; i<N; i++){
_corrfunc[i] = tmp[i];
}
fftw_destroy_plan(fft);
}
void CrossCorrelate::AutoCosine(vector <double>& ivec){
size_t N = ivec.size();
_corrfunc.resize(N);
vector <double> tmp;
tmp.resize(N);
fftw_plan fft;
// do real to real discrete cosine trafo
fft = fftw_plan_r2r_1d(N, &ivec[0], &tmp[0], FFTW_REDFT10, FFTW_ESTIMATE);
fftw_execute(fft);
// compute autocorrelation
tmp[0] = 0;
for(int i=1; i<N; i++) {
tmp[i] = tmp[i]*tmp[i];
}
// store results
for(int i=0; i<N; i++){
_corrfunc[i] = tmp[i];
}
fftw_destroy_plan(fft);
}
void CrossCorrelate::AutoCorr(vector <double>& ivec){
size_t N = ivec.size();
_corrfunc.resize(N);
fftw_complex *tmp;
fftw_plan fft, ifft;
tmp = (fftw_complex*) fftw_malloc(sizeof(fftw_complex) * (N/2+1));
fft = fftw_plan_dft_r2c_1d(N, &ivec[0], tmp, FFTW_ESTIMATE);
ifft = fftw_plan_dft_c2r_1d(N, tmp, &_corrfunc[0], FFTW_ESTIMATE);
fftw_execute(fft);
tmp[0][0] = tmp[0][1] = 0;
for(int i=1; i<N/2+1; i++) {
tmp[i][0] = tmp[i][0]*tmp[i][0] + tmp[i][1]*tmp[i][1];
tmp[i][1] = 0;
}
fftw_execute(ifft);
double d = _corrfunc[0];
for(int i=0; i<N; i++)
_corrfunc[i] = _corrfunc[i]/d;
fftw_destroy_plan(fft);
fftw_destroy_plan(ifft);
fftw_free(tmp);
}<|endoftext|> |
<commit_before>/*
* Copyright (C) 2003-2006 Funambol
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#include "base/fscapi.h"
#include "base/util/utils.h"
#include "base/Log.h"
#include "spdm/spdmutils.h"
#include "spdm/ManagementNode.h"
#include "spdm/DeviceManagementNode.h"
#include "spdm/DMTree.h"
/*
* Basic implementation of DMTree, can be re-defined if platform specific
* variant is needed.
*/
/*
* Constructor
*/
DMTree::DMTree(const BCHAR *rootContext) {
root = stringdup(rootContext);
}
/*
* Destructor
*/
DMTree::~DMTree() {
if (root)
delete [] root;
}
bool DMTree::isLeaf(const BCHAR *node) {
DeviceManagementNode dmn(node);
return (dmn.getChildrenMaxCount() == 0);
}
/*
* Returns the management node identified by the given node pathname
* (relative to the root management node). If the node is not found
* NULL is returned; additional info on the error condition can be
* retrieved calling getLastError() and getLastErrorMessage()
*
* The ManagementNode is created with the new operator and must be
* discarded by the caller with the operator delete.
*/
ManagementNode* DMTree::getManagementNode(const BCHAR* node) {
//LOG.debug(node);
ManagementNode *n = new DeviceManagementNode(node);
int childrenCount = n->getChildrenMaxCount();
if (childrenCount) {
BCHAR** childrenNames = n->getChildrenNames();
if (!childrenNames){
LOG.error(T("Error in getChildrenNames"));
return NULL;
}
for (int i = 0; i < childrenCount; i++) {
DeviceManagementNode s(node, childrenNames[i]);
n->addChild(s);
}
}
return n;
}
/*
void DMTree::setManagementNode(ManagementNode& n) {
DeviceManagementNode dmn;
LOG.info(T("in setManagementNode"));
BCHAR nodeName [DIM_MANAGEMENT_PATH];
BCHAR context [DIM_MANAGEMENT_PATH];
BCHAR leafName [DIM_MANAGEMENT_PATH];
wmemset(context, 0, DIM_MANAGEMENT_PATH);
wmemset(leafName, 0, DIM_MANAGEMENT_PATH);
n.getFullName(nodeName, DIM_MANAGEMENT_PATH-1);
getNodeName(nodeName, leafName, DIM_MANAGEMENT_PATH);
getNodeConT(nodeName, context, DIM_MANAGEMENT_PATH);
resetError();
if (wcscmp(leafName, SYNCML) == 0) {
dmn.setAccessManagementNode((AccessManagementNode&)n);
} else {
dmn.setSourceManagementNode((SourceManagementNode&)n);
}
}
*/
<commit_msg>memory leak<commit_after>/*
* Copyright (C) 2003-2006 Funambol
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#include "base/fscapi.h"
#include "base/util/utils.h"
#include "base/Log.h"
#include "spdm/spdmutils.h"
#include "spdm/ManagementNode.h"
#include "spdm/DeviceManagementNode.h"
#include "spdm/DMTree.h"
/*
* Basic implementation of DMTree, can be re-defined if platform specific
* variant is needed.
*/
/*
* Constructor
*/
DMTree::DMTree(const BCHAR *rootContext) {
root = stringdup(rootContext);
}
/*
* Destructor
*/
DMTree::~DMTree() {
if (root)
delete [] root;
}
bool DMTree::isLeaf(const BCHAR *node) {
DeviceManagementNode dmn(node);
return (dmn.getChildrenMaxCount() == 0);
}
/*
* Returns the management node identified by the given node pathname
* (relative to the root management node). If the node is not found
* NULL is returned; additional info on the error condition can be
* retrieved calling getLastError() and getLastErrorMessage()
*
* The ManagementNode is created with the new operator and must be
* discarded by the caller with the operator delete.
*/
ManagementNode* DMTree::getManagementNode(const BCHAR* node) {
//LOG.debug(node);
ManagementNode *n = new DeviceManagementNode(node);
int childrenCount = n->getChildrenMaxCount();
if (childrenCount) {
BCHAR** childrenNames = n->getChildrenNames();
if (!childrenNames){
LOG.error(T("Error in getChildrenNames"));
return NULL;
}
for (int i = 0; i < childrenCount; i++) {
DeviceManagementNode s(node, childrenNames[i]);
n->addChild(s);
}
delete [] childrenNames;
}
return n;
}
/*
void DMTree::setManagementNode(ManagementNode& n) {
DeviceManagementNode dmn;
LOG.info(T("in setManagementNode"));
BCHAR nodeName [DIM_MANAGEMENT_PATH];
BCHAR context [DIM_MANAGEMENT_PATH];
BCHAR leafName [DIM_MANAGEMENT_PATH];
wmemset(context, 0, DIM_MANAGEMENT_PATH);
wmemset(leafName, 0, DIM_MANAGEMENT_PATH);
n.getFullName(nodeName, DIM_MANAGEMENT_PATH-1);
getNodeName(nodeName, leafName, DIM_MANAGEMENT_PATH);
getNodeConT(nodeName, context, DIM_MANAGEMENT_PATH);
resetError();
if (wcscmp(leafName, SYNCML) == 0) {
dmn.setAccessManagementNode((AccessManagementNode&)n);
} else {
dmn.setSourceManagementNode((SourceManagementNode&)n);
}
}
*/
<|endoftext|> |
<commit_before><commit_msg>toxinit.hxx included by nothing<commit_after><|endoftext|> |
<commit_before>#include "machineInteractionTask.h"
machineInteractionTask::machineInteractionTask():
setMachineStateChannel (this, "set_Machine_State_Channel"),
clock (this, 500 MS, "MIT_clock"),
Uart(),
listeners(),
currentState(),
setState()
{}
void machineInteractionTask::addMachineStateListener(
machineStateListener& listener)
{
listeners.push_back(listener);
}
void machineInteractionTask::notifyListeners()
{
std::vector<machineStateListener>::iterator listen =
this->listeners.begin();
for(;listen != this->listeners.end(); ++listen)
{
*listen.stateChanged(currentState);
}
}
void machineInteractionTask::main()
{
for(;;)
{
RTOS::event ev = RTOS::wait(this->clock + this->SetMachineStateChannel);
if(ev == SetMachineStateChannel)
{
ResponseStruct rs = readChannel();
switch(rs.request.request)
{
case HEATING_UNIT_REQ:
currentState.heatingUnit = rs.value;
break;
case WATER_VALVE_REQ:
currentState.waterValve = rs.value;
break;
case DOOR_LOCK_REQ:
currentState.doorLock = rs.value;
break;
case PUMP_REQ:
currentState.pump = rs.value;
break;
}
}
else if(ev == clock)
{
update();
}
}
}
void machineInteractionTask::update()
{
if(currentState.waterLevel >= setState.waterLevel)
{
if(currentState.waterValve == 1){setWaterValve(0);}
}
else if(currentState.waterLevel == 0)
{
if(currentState.pump == 1) {setPump(0);}
if(currentState.doorLock == 1){setDoorLock(0);}
}
else if(setState.waterLevel == 0)
{
if(currentState.pump == 0){setPump(1);}
}
if(currentState.temperature > setState.temperature)
{if(currentState.heatingUnit == 1) {setHeater(0);}}
if(currentState.temperature < setState.temperature)
{if(currentState.heatingUnit == 0) {setHeater(1);}}
getTemperature(); getWaterLevel();
//Update all the listeners.
notifyListeners()
}
ResponseStruct machineInteractionTask::readChannel()
{
//read the request in words.
RequestStruct request = SetMachineStateChannel.read();
//{"HEATING_UNIT_REQ", "ON_CMD"}
//Translate the request to bytes.
std::vector<std::uint8_t> TranslatedRequest = requestTranslate(request);
//Write the request in bytes to the uart/washing machine.
uart.write(TranslatedRequest);
RTOS::wait(10);
//Read the response of the request.
std::uint8_t responseByte = uart.read();
//Translate the response from bytes to words.
return responseTranslate(responseByte, request);
}
void machineInteractionTask::setTemperature(unsigned int temperature)
{
setState.temperature = temperature;
if(currentState.temperature < temperature)
{if(currentState.heatingUnit == 0) {setHeater(1);}}
}
void machineInteractionTask::setWaterLevel(unsigned int waterLevel)
{
setDoorLock(1);
setState.waterLevel = waterLevel;
if(currentState.waterLevel < waterLevel)
{if(currentState.waterValve == 0) {setWaterValve(1);}}
}
void machineInteractionTask::setRPM(bool clockwise, unsigned int rpm)
{
setState.drumRPM = rpm;
RequestStruct reqS;
reqS.request = SET_RPM_REQ;
if(clockwise){reqS.command = RPM_Clockwise;}
else{reqS.command = RPM_counterClockwise;}
this-> SetMachineStateChannel.write(reqS);
getRPM();
}
void machineInteractionTask::setDetergent(bool add)
{
//?
}
void machineInteractionTask::flush()
{
setState.waterLevel = 0;
if(currentState.waterLevel > 0)
{if(currentState.pump = 0){setPump(1);}}
}
void machineInteractionTask::setMachineState(bool start)
{
RequestStruct reqS;
reqS.request = MACHINE_REQ;
if(start){ reqS.command = START_CMD; }
else { reqS.command = STOP_CMD; }
this-> SetMachineStateChannel.write(reqS);
}
void machineInteractionTask::setDoorLock(bool lock)
{
RequestStruct reqS;
reqS.request = DOOR_LOCK_REQ;
if(lock){ reqS.command = LOCK_CMD; }
else { reqS.command = UNLOCK_CMD; }
this-> SetMachineStateChannel.write(reqS);
}
void machineInteractionTask::getState(std::string request)
{
RequestStruct reqS;
reqS.request = request;
reqS.command = STATUS_CMD;
this-> SetMachineStateChannel.write(reqS);
}
void machineInteractionTask::getWaterLevel()
{
RequestStruct reqS;
reqS.request = WATER_LEVEL_REQ;
this-> SetMachineStateChannel.write(reqS);
}
void machineInteractionTask::setWaterValve(bool open)
{
RequestStruct reqS;
reqS.request = WATER_VALVE_REQ;
if(open){ reqS.command = OPEN_CMD; }
else { reqS.command = CLOSE_CMD; }
this-> SetMachineStateChannel.write(reqS);
}
void machineInteractionTask::setSoapDispenser(bool open)
{
RequestStruct reqS;
reqS.request = SOAP_DISPENSER_REQ;
if(open){ reqS.command = OPEN_CMD; }
else { reqS.command = CLOSE_CMD; }
this-> SetMachineStateChannel.write(reqS);
}
void machineInteractionTask::setPump(bool on)
{
RequestStruct reqS;
reqS.request = PUMP_REQ;
if(on){ reqS.command = ON_CMD; }
else { reqS.command = OFF_CMD; }
this-> SetMachineStateChannel.write(reqS);
}
int machineInteractionTask::getTemperature()
{
RequestStruct reqS;
reqS.request = TEMPERATURE_REQ;
this-> SetMachineStateChannel.write(reqS);
}
void machineInteractionTask::setHeater(bool on)
{
RequestStruct reqS;
reqS.request = HEATING_UNIT_REQ;
if(on){ reqS.command = ON_CMD; }
else { reqS.command = OFF_CMD; }
this-> SetMachineStateChannel.write(reqS);
}
void machineInteractionTask::getRPM()
{
RequestStruct reqS;
reqS.request = GET_RPM_REQ;
this-> SetMachineStateChannel.write(reqS);
}
void machineInteractionTask::setSignalLed(bool on)
{
RequestStruct reqS;
reqS.request = SIGNAL_LED_REQ;
if(on){ reqS.command = ON_CMD; }
else { reqS.command = OFF_CMD; }
this-> SetMachineStateChannel.write(reqS);
}
std::vector<std::uint8_t> machineInteractionTask::requestTranslate(
RequestStruct reqS)
{
std::vector<std::uint8_t> bytes;
switch(reqS.request)
{
case MACHINE_REQ: bytes[0] = 0x01; break;
case DOOR_LOCK_REQ: bytes[0] = 0x02; break;
case WATER_VALVE_REQ: bytes[0] = 0x03; break;
case SOAP_DISPENSER_REQ: bytes[0] = 0x04; break;
case PUMP_REQ: bytes[0] = 0x05; break;
case WATER_LEVEL_REQ: bytes[0] = 0x06; break;
case HEATING_UNIT_REQ: bytes[0] = 0x07; break;
case TEMPERATURE_REQ: bytes[0] = 0x08; break;
case SET_RPM_REQ: bytes[0] = 0x0A; break;
case GET_RPM_REQ: bytes[0] = 0x09; break;
case SIGNAL_LED_REQ: bytes[0] = 0x0B; break;
default: return -1; break;
}
switch(reqS.command)
{
case STATUS_CMD: bytes[1] = 0x01; break;
case LOCK_CMD: bytes[1] = 0x40; break;
case UNLOCK_CMD: bytes[1] = 0x80; break;
case START_CMD: case OPEN_CMD: case ON_CMD: bytes[1] = 0x10; break;
case STOP_CMD: case CLOSE_CMD: case OFF_CMD: bytes[1] = 0x20; break;
case RPM_Clockwise: bytes[1] = setState.drumRPM | 0x80; break;
case RPM_counterClockwise: bytes[1] = setState.drumRPM; break;
//default: break;
}
return bytes;
}
ResponseStruct machineInteractionTask::responseTranslate(
std::uint8_t responseByte,
RequestStruct reqS)
{
ResponseStruct resS;
resS.request = reqS;
resS.value = responseByte;
switch(reqS.request)
{
case MACHINE_REQ:
switch(responseByte)
{
case 0x01: resS.response = "HALTED"; break;
case 0x02: resS.response = "IDLE"; break;
case 0x04: resS.response = "RUNNING"; break;
case 0x08: resS.response = "STOPPED"; break;
}
break;
case DOOR_LOCK_REQ: case WATER_VALVE_REQ: case SOAP_DISPENSER_REQ:
switch(responseByte)
{
case 0x01: resS.response = "OPENED"; resS.value = 1; break;
case 0x02: resS.response = "CLOSED"; resS.value = 0; break;
case 0x04: if(reqS.request == "DOOR_LOCK_REQ")
{resS.response = "LOCKED";} break;
}
break;
case PUMP_REQ: case HEATING_UNIT_REQ: case SIGNAL_LED_REQ:
switch(responseByte)
{
case 0x08: resS.response = "ON"; resS.value = 1; break;
case 0x10: resS.response = "OFF"; resS.value = 0; break;
}
break;
case WATER_LEVEL_REQ:
currentState.waterLevel = responseByte;
resS.response = "Niveau in %";
break;
case TEMPERATURE_REQ:
currentState.temperature = responseByte;
resS.response = "Temp in Graden Celcius";
break;
case SET_RPM_REQ: case GET_RPM_REQ:
currentState.drumRPM = responseByte;
resS.response = "RPM";
break;
default:
resS.response = "NO VALID REQUEST"
break;
}
return resS;
}
<commit_msg>fixed getRPM function<commit_after>#include "machineInteractionTask.h"
machineInteractionTask::machineInteractionTask():
setMachineStateChannel (this, "set_Machine_State_Channel"),
clock (this, 500 MS, "MIT_clock"),
Uart(),
listeners(),
currentState(),
setState()
{}
void machineInteractionTask::addMachineStateListener(
machineStateListener& listener)
{
listeners.push_back(listener);
}
void machineInteractionTask::notifyListeners()
{
std::vector<machineStateListener>::iterator listen =
this->listeners.begin();
for(;listen != this->listeners.end(); ++listen)
{
*listen.stateChanged(currentState);
}
}
void machineInteractionTask::main()
{
for(;;)
{
RTOS::event ev = RTOS::wait(this->clock + this->SetMachineStateChannel);
if(ev == SetMachineStateChannel)
{
ResponseStruct rs = readChannel();
switch(rs.request.request)
{
case HEATING_UNIT_REQ:
currentState.heatingUnit = rs.value;
break;
case WATER_VALVE_REQ:
currentState.waterValve = rs.value;
break;
case DOOR_LOCK_REQ:
currentState.doorLock = rs.value;
break;
case PUMP_REQ:
currentState.pump = rs.value;
break;
}
}
else if(ev == clock)
{
update();
}
}
}
void machineInteractionTask::update()
{
if(currentState.waterLevel >= setState.waterLevel)
{
if(currentState.waterValve == 1){setWaterValve(0);}
}
else if(currentState.waterLevel == 0)
{
if(currentState.pump == 1) {setPump(0);}
if(currentState.doorLock == 1){setDoorLock(0);}
}
else if(setState.waterLevel == 0)
{
if(currentState.pump == 0){setPump(1);}
}
if(currentState.temperature > setState.temperature)
{if(currentState.heatingUnit == 1) {setHeater(0);}}
if(currentState.temperature < setState.temperature)
{if(currentState.heatingUnit == 0) {setHeater(1);}}
getTemperature(); getWaterLevel();
//Update all the listeners.
notifyListeners()
}
ResponseStruct machineInteractionTask::readChannel()
{
//read the request in words.
RequestStruct request = SetMachineStateChannel.read();
//{"HEATING_UNIT_REQ", "ON_CMD"}
//Translate the request to bytes.
std::vector<std::uint8_t> TranslatedRequest = requestTranslate(request);
//Write the request in bytes to the uart/washing machine.
uart.write(TranslatedRequest);
RTOS::wait(10);
//Read the response of the request.
std::uint8_t responseByte = uart.read();
//Translate the response from bytes to words.
return responseTranslate(responseByte, request);
}
void machineInteractionTask::setTemperature(unsigned int temperature)
{
setState.temperature = temperature;
if(currentState.temperature < temperature)
{if(currentState.heatingUnit == 0) {setHeater(1);}}
}
void machineInteractionTask::setWaterLevel(unsigned int waterLevel)
{
setDoorLock(1);
setState.waterLevel = waterLevel;
if(currentState.waterLevel < waterLevel)
{if(currentState.waterValve == 0) {setWaterValve(1);}}
}
void machineInteractionTask::setRPM(bool clockwise, unsigned int rpm)
{
setState.drumRPM = rpm;
RequestStruct reqS;
reqS.request = SET_RPM_REQ;
if(clockwise){reqS.command = RPM_Clockwise;}
else{reqS.command = RPM_counterClockwise;}
this-> SetMachineStateChannel.write(reqS);
getRPM();
}
void machineInteractionTask::setDetergent(bool add)
{
//?
}
void machineInteractionTask::flush()
{
setState.waterLevel = 0;
if(currentState.waterLevel > 0)
{if(currentState.pump = 0){setPump(1);}}
}
void machineInteractionTask::setMachineState(bool start)
{
RequestStruct reqS;
reqS.request = MACHINE_REQ;
if(start){ reqS.command = START_CMD; }
else { reqS.command = STOP_CMD; }
this-> SetMachineStateChannel.write(reqS);
}
void machineInteractionTask::setDoorLock(bool lock)
{
RequestStruct reqS;
reqS.request = DOOR_LOCK_REQ;
if(lock){ reqS.command = LOCK_CMD; }
else { reqS.command = UNLOCK_CMD; }
this-> SetMachineStateChannel.write(reqS);
}
void machineInteractionTask::getState(std::string request)
{
RequestStruct reqS;
reqS.request = request;
reqS.command = STATUS_CMD;
this-> SetMachineStateChannel.write(reqS);
}
void machineInteractionTask::getWaterLevel()
{
RequestStruct reqS;
reqS.request = WATER_LEVEL_REQ;
this-> SetMachineStateChannel.write(reqS);
}
void machineInteractionTask::setWaterValve(bool open)
{
RequestStruct reqS;
reqS.request = WATER_VALVE_REQ;
if(open){ reqS.command = OPEN_CMD; }
else { reqS.command = CLOSE_CMD; }
this-> SetMachineStateChannel.write(reqS);
}
void machineInteractionTask::setSoapDispenser(bool open)
{
RequestStruct reqS;
reqS.request = SOAP_DISPENSER_REQ;
if(open){ reqS.command = OPEN_CMD; }
else { reqS.command = CLOSE_CMD; }
this-> SetMachineStateChannel.write(reqS);
}
void machineInteractionTask::setPump(bool on)
{
RequestStruct reqS;
reqS.request = PUMP_REQ;
if(on){ reqS.command = ON_CMD; }
else { reqS.command = OFF_CMD; }
this-> SetMachineStateChannel.write(reqS);
}
int machineInteractionTask::getTemperature()
{
RequestStruct reqS;
reqS.request = TEMPERATURE_REQ;
this-> SetMachineStateChannel.write(reqS);
}
void machineInteractionTask::setHeater(bool on)
{
RequestStruct reqS;
reqS.request = HEATING_UNIT_REQ;
if(on){ reqS.command = ON_CMD; }
else { reqS.command = OFF_CMD; }
this-> SetMachineStateChannel.write(reqS);
}
void machineInteractionTask::getRPM()
{
RequestStruct reqS;
reqS.request = GET_RPM_REQ;
this-> SetMachineStateChannel.write(reqS);
}
void machineInteractionTask::setSignalLed(bool on)
{
RequestStruct reqS;
reqS.request = SIGNAL_LED_REQ;
if(on){ reqS.command = ON_CMD; }
else { reqS.command = OFF_CMD; }
this-> SetMachineStateChannel.write(reqS);
}
std::vector<std::uint8_t> machineInteractionTask::requestTranslate(
RequestStruct reqS)
{
std::vector<std::uint8_t> bytes;
switch(reqS.request)
{
case MACHINE_REQ: bytes[0] = 0x01; break;
case DOOR_LOCK_REQ: bytes[0] = 0x02; break;
case WATER_VALVE_REQ: bytes[0] = 0x03; break;
case SOAP_DISPENSER_REQ: bytes[0] = 0x04; break;
case PUMP_REQ: bytes[0] = 0x05; break;
case WATER_LEVEL_REQ: bytes[0] = 0x06; break;
case HEATING_UNIT_REQ: bytes[0] = 0x07; break;
case TEMPERATURE_REQ: bytes[0] = 0x08; break;
case SET_RPM_REQ: bytes[0] = 0x0A; break;
case GET_RPM_REQ: bytes[0] = 0x09; break;
case SIGNAL_LED_REQ: bytes[0] = 0x0B; break;
default: return -1; break;
}
switch(reqS.command)
{
case STATUS_CMD: bytes[1] = 0x01; break;
case LOCK_CMD: bytes[1] = 0x40; break;
case UNLOCK_CMD: bytes[1] = 0x80; break;
case START_CMD: case OPEN_CMD: case ON_CMD: bytes[1] = 0x10; break;
case STOP_CMD: case CLOSE_CMD: case OFF_CMD: bytes[1] = 0x20; break;
case RPM_Clockwise: bytes[1] = setState.drumRPM | 0x80; break;
case RPM_counterClockwise: bytes[1] = setState.drumRPM; break;
//default: break;
}
return bytes;
}
ResponseStruct machineInteractionTask::responseTranslate(
std::uint8_t responseByte,
RequestStruct reqS)
{
ResponseStruct resS;
resS.request = reqS;
resS.value = responseByte;
switch(reqS.request)
{
case MACHINE_REQ:
switch(responseByte)
{
case 0x01: resS.response = "HALTED"; break;
case 0x02: resS.response = "IDLE"; break;
case 0x04: resS.response = "RUNNING"; break;
case 0x08: resS.response = "STOPPED"; break;
}
break;
case DOOR_LOCK_REQ: case WATER_VALVE_REQ: case SOAP_DISPENSER_REQ:
switch(responseByte)
{
case 0x01: resS.response = "OPENED"; resS.value = 1; break;
case 0x02: resS.response = "CLOSED"; resS.value = 0; break;
case 0x04: if(reqS.request == "DOOR_LOCK_REQ")
{resS.response = "LOCKED";} break;
}
break;
case PUMP_REQ: case HEATING_UNIT_REQ: case SIGNAL_LED_REQ:
switch(responseByte)
{
case 0x08: resS.response = "ON"; resS.value = 1; break;
case 0x10: resS.response = "OFF"; resS.value = 0; break;
}
break;
case WATER_LEVEL_REQ:
currentState.waterLevel = responseByte;
resS.response = "Niveau in %";
break;
case TEMPERATURE_REQ:
currentState.temperature = responseByte;
resS.response = "Temp in Graden Celcius";
break;
case SET_RPM_REQ: case GET_RPM_REQ:
if(responseByte >= 0x00|0x80 && responseByte <= 0x40|0x80)
{
currentState.drumRPM = responseByte|0x80;
resS.response = "RPM_Clockwise";
}
else if(responseByte >= 0x00 && responseByte <= 0x40)
{
currentState.drumRPM = responseByte;
resS.response = "RPM_counterClockwise";
}
break;
default:
resS.response = "NO VALID REQUEST"
break;
}
return resS;
}
<|endoftext|> |
<commit_before>//---------------------------------------------------------- -*- Mode: C++ -*-
// $Id$
//
// Created 2008/11/01
// Author: Mike Ovsiannikov
//
// Copyright 2008-2011,2016 Quantcast Corporation. All rights reserved.
//
// This file is part of Kosmos File System (KFS).
//
// 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.
//
// IO buffer pool implementation.
//
//----------------------------------------------------------------------------
#include "QCIoBufferPool.h"
#include "QCUtils.h"
#include "qcdebug.h"
#include "qcstutils.h"
#include "QCDLList.h"
#include <sys/mman.h>
#include <errno.h>
#include <unistd.h>
class QCIoBufferPool::Partition
{
public:
Partition()
: mAllocPtr(0),
mAllocSize(0),
mStartPtr(0),
mFreeListPtr(0),
mTotalCnt(0),
mFreeCnt(0),
mBufSizeShift(0)
{ List::Init(*this); }
~Partition()
{ Partition::Destroy(); }
int Create(
int inNumBuffers,
int inBufferSize,
bool inLockMemoryFlag)
{
int theBufSizeShift = -1;
for (int i = inBufferSize; i > 0; i >>= 1, theBufSizeShift++)
{}
if (theBufSizeShift < 0 || inBufferSize != (1 << theBufSizeShift)) {
return EINVAL;
}
Destroy();
mBufSizeShift = theBufSizeShift;
if (inNumBuffers <= 0) {
return 0;
}
mFreeListPtr = new BufferIndex[inNumBuffers + 1];
size_t const kPageSize = sysconf(_SC_PAGESIZE);
size_t const kAlign = kPageSize > size_t(inBufferSize) ?
kPageSize : size_t(inBufferSize);
mAllocSize = size_t(inNumBuffers) * inBufferSize + kAlign;
mAllocSize = (mAllocSize + kPageSize - 1) / kPageSize * kPageSize;
mAllocPtr = mmap(0, mAllocSize,
PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANON, -1, 0);
if (mAllocPtr == MAP_FAILED) {
const int theRet = errno;
mAllocPtr = 0;
return (theRet == 0 ? -1 : theRet);
}
if (inLockMemoryFlag && mlock(mAllocPtr, mAllocSize) != 0) {
const int theRet = errno;
Destroy();
return (theRet == 0 ? -1 : theRet);
}
mStartPtr = 0;
mStartPtr += (((char*)mAllocPtr - (char*)0) + kAlign - 1) /
kAlign * kAlign;
mTotalCnt = inNumBuffers;
mFreeCnt = 0;
*mFreeListPtr = 0;
while (mFreeCnt < mTotalCnt) {
mFreeListPtr[mFreeCnt] = mFreeCnt + 1;
mFreeCnt++;
}
mFreeListPtr[mFreeCnt] = 0;
return 0;
}
void Destroy()
{
delete [] mFreeListPtr;
mFreeListPtr = 0;
if (mAllocPtr && munmap(mAllocPtr, mAllocSize) != 0) {
QCUtils::FatalError("munmap", errno);
}
mAllocPtr = 0;
mAllocSize = 0;
mStartPtr = 0;
mTotalCnt = 0;
mFreeCnt = 0;
mBufSizeShift = 0;
}
char* Get()
{
if (mFreeCnt <= 0) {
QCASSERT(*mFreeListPtr == 0 && mFreeCnt == 0);
return 0;
}
const BufferIndex theIdx = *mFreeListPtr;
QCASSERT(theIdx > 0);
mFreeCnt--;
*mFreeListPtr = mFreeListPtr[theIdx];
return (mStartPtr + ((theIdx - 1) << mBufSizeShift));
}
bool Put(char* inPtr)
{
if (inPtr < mStartPtr) {
return false;
}
const size_t theOffset = inPtr - mStartPtr;
const size_t theIdx = (theOffset >> mBufSizeShift) + 1;
if (theIdx > size_t(mTotalCnt)) {
return false;
}
QCRTASSERT(mTotalCnt > mFreeCnt &&
(theOffset & ((size_t(1) << mBufSizeShift) - 1)) == 0);
mFreeListPtr[theIdx] = *mFreeListPtr;
*mFreeListPtr = BufferIndex(theIdx);
mFreeCnt++;
return true;
}
int GetFreeCount() const
{ return mFreeCnt; }
int GetTotalCount() const
{ return mTotalCnt; }
bool IsEmpty() const
{ return (mFreeCnt <= 0); }
bool IsFull() const
{ return (mFreeCnt >= mTotalCnt); }
typedef QCDLList<Partition, 0> List;
private:
friend class QCDLListOp<Partition, 0>;
friend class QCDLListOp<const Partition, 0>;
typedef unsigned int BufferIndex;
void* mAllocPtr;
size_t mAllocSize;
char* mStartPtr;
BufferIndex* mFreeListPtr;
int mTotalCnt;
int mFreeCnt;
int mBufSizeShift;
Partition* mPrevPtr[1];
Partition* mNextPtr[1];
};
typedef QCDLList<QCIoBufferPool::Client, 0> QCIoBufferPoolClientList;
QCIoBufferPool::Client::Client()
: mPoolPtr(0)
{
QCIoBufferPoolClientList::Init(*this);
}
bool
QCIoBufferPool::Client::Unregister()
{
return (mPoolPtr && mPoolPtr->UnRegister(*this));
}
QCIoBufferPool::QCIoBufferPool()
: mMutex(),
mBufferSize(0),
mFreeCnt(0),
mTotalCnt(0)
{
QCIoBufferPoolClientList::Init(mClientListPtr);
Partition::List::Init(mPartitionListPtr);
}
QCIoBufferPool::~QCIoBufferPool()
{
QCStMutexLocker theLock(mMutex);
QCIoBufferPool::Destroy();
Client* thePtr;
while ((thePtr = QCIoBufferPoolClientList::PopBack(mClientListPtr))) {
Client& theClient = *thePtr;
QCASSERT(theClient.mPoolPtr == this);
theClient.mPoolPtr = 0;
}
}
int
QCIoBufferPool::Create(
int inPartitionCount,
int inPartitionBufferCount,
int inBufferSize,
bool inLockMemoryFlag)
{
QCStMutexLocker theLock(mMutex);
Destroy();
mBufferSize = inBufferSize;
int theErr = 0;
for (int i = 0; i < inPartitionCount; i++) {
Partition& thePart = *(new Partition());
Partition::List::PushBack(mPartitionListPtr, thePart);
theErr = thePart.Create(
inPartitionBufferCount, inBufferSize, inLockMemoryFlag);
if (theErr) {
Destroy();
break;
}
mFreeCnt += thePart.GetFreeCount();
mTotalCnt += thePart.GetTotalCount();
}
return theErr;
}
void
QCIoBufferPool::Destroy()
{
QCStMutexLocker theLock(mMutex);
Partition* thePtr;
while ((thePtr = Partition::List::PopBack(mPartitionListPtr))) {
delete thePtr;
}
mBufferSize = 0;
mFreeCnt = 0;
}
char*
QCIoBufferPool::Get(
QCIoBufferPool::RefillReqId inRefillReqId /* = kRefillReqIdUndefined */)
{
QCStMutexLocker theLock(mMutex);
if (mFreeCnt <= 0 && ! TryToRefill(inRefillReqId, 1)) {
return 0;
}
QCASSERT(mFreeCnt >= 1);
// Always start from the first partition, to try to keep next
// partitions full, and be able to reclaim these if needed.
Partition::List::Iterator theItr(mPartitionListPtr);
Partition* thePtr;
while ((thePtr = theItr.Next()) && thePtr->IsEmpty())
{}
char* const theBufPtr = thePtr ? thePtr->Get() : 0;
QCASSERT(theBufPtr && mFreeCnt > 0);
mFreeCnt--;
return theBufPtr;
}
bool
QCIoBufferPool::Get(
QCIoBufferPool::OutputIterator& inIt,
int inBufCnt,
QCIoBufferPool::RefillReqId inRefillReqId /* = kRefillReqIdUndefined */)
{
if (inBufCnt <= 0) {
return true;
}
QCStMutexLocker theLock(mMutex);
if (mFreeCnt < inBufCnt && ! TryToRefill(inRefillReqId, inBufCnt)) {
return false;
}
QCASSERT(mFreeCnt >= inBufCnt);
Partition::List::Iterator theItr(mPartitionListPtr);
for (int i = 0; i < inBufCnt; ) {
Partition* thePPtr;
while ((thePPtr = theItr.Next()) && thePPtr->IsEmpty())
{}
QCASSERT(thePPtr);
for (char* theBPtr; i < inBufCnt && (theBPtr = thePPtr->Get()); i++) {
mFreeCnt--;
inIt.Put(theBPtr);
}
}
return true;
}
void
QCIoBufferPool::Put(
char* inBufPtr)
{
if (! inBufPtr) {
return;
}
QCStMutexLocker theLock(mMutex);
PutSelf(inBufPtr);
}
void
QCIoBufferPool::Put(
QCIoBufferPool::InputIterator& inIt,
int inBufCnt)
{
if (inBufCnt < 0) {
return;
}
QCStMutexLocker theLock(mMutex);
for (int i = 0; i < inBufCnt; i++) {
char* const theBufPtr = inIt.Get();
if (! theBufPtr) {
break;
}
PutSelf(theBufPtr);
}
}
bool
QCIoBufferPool::Register(
QCIoBufferPool::Client& inClient)
{
QCStMutexLocker theLock(mMutex);
if (inClient.mPoolPtr) {
return (inClient.mPoolPtr == this);
}
QCIoBufferPoolClientList::PushBack(mClientListPtr, inClient);
inClient.mPoolPtr = this;
return true;
}
bool
QCIoBufferPool::UnRegister(
QCIoBufferPool::Client& inClient)
{
QCStMutexLocker theLock(mMutex);
if (inClient.mPoolPtr != this) {
return false;
}
QCIoBufferPoolClientList::Remove(mClientListPtr, inClient);
inClient.mPoolPtr = 0;
return true;
}
void
QCIoBufferPool::PutSelf(
char* inBufPtr)
{
QCASSERT(mMutex.IsOwned());
if (! inBufPtr) {
return;
}
Partition::List::Iterator theItr(mPartitionListPtr);
Partition* thePtr;
while ((thePtr = theItr.Next()) && ! thePtr->Put(inBufPtr))
{}
QCRTASSERT(thePtr);
mFreeCnt++;
}
bool
QCIoBufferPool::TryToRefill(
QCIoBufferPool::RefillReqId inReqId,
int inBufCnt)
{
QCASSERT(mMutex.IsOwned());
if (inReqId == kRefillReqIdUndefined) {
return false;
}
QCIoBufferPoolClientList::Iterator theItr(mClientListPtr);
Client* thePtr;
while ((thePtr = theItr.Next()) && mFreeCnt < inBufCnt) {
QCASSERT(thePtr->mPoolPtr == this);
{
// QCStMutexUnlocker theUnlock(mMutex);
thePtr->Release(inReqId, inBufCnt - mFreeCnt);
}
}
return (mFreeCnt >= inBufCnt);
}
int
QCIoBufferPool::GetFreeBufferCount()
{
QCStMutexLocker theLock(mMutex);
return mFreeCnt;
}
int
QCIoBufferPool::GetTotalBufferCount()
{
QCStMutexLocker theLock(mMutex);
return mTotalCnt;
}
int
QCIoBufferPool::GetUsedBufferCount()
{
QCStMutexLocker theLock(mMutex);
return (mTotalCnt - mFreeCnt);
}
<commit_msg>Disk IO library: implement IO buffer pool put (buffer free) verification to catch double put.<commit_after>//---------------------------------------------------------- -*- Mode: C++ -*-
// $Id$
//
// Created 2008/11/01
// Author: Mike Ovsiannikov
//
// Copyright 2008-2011,2016 Quantcast Corporation. All rights reserved.
//
// This file is part of Kosmos File System (KFS).
//
// 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.
//
// IO buffer pool implementation.
//
//----------------------------------------------------------------------------
#include "QCIoBufferPool.h"
#include "QCUtils.h"
#include "qcdebug.h"
#include "qcstutils.h"
#include "QCDLList.h"
#include <sys/mman.h>
#include <errno.h>
#include <unistd.h>
class QCIoBufferPool::Partition
{
public:
Partition()
: mAllocPtr(0),
mAllocSize(0),
mStartPtr(0),
mFreeListPtr(0),
mTotalCnt(0),
mFreeCnt(0),
mBufSizeShift(0)
{ List::Init(*this); }
~Partition()
{ Partition::Destroy(); }
int Create(
int inNumBuffers,
int inBufferSize,
bool inLockMemoryFlag)
{
int theBufSizeShift = -1;
for (int i = inBufferSize; i > 0; i >>= 1, theBufSizeShift++)
{}
if (theBufSizeShift < 0 || inBufferSize != (1 << theBufSizeShift)) {
return EINVAL;
}
Destroy();
mBufSizeShift = theBufSizeShift;
if (inNumBuffers <= 0) {
return 0;
}
mFreeListPtr = new BufferIndex[inNumBuffers + 1];
size_t const kPageSize = sysconf(_SC_PAGESIZE);
size_t const kAlign = kPageSize > size_t(inBufferSize) ?
kPageSize : size_t(inBufferSize);
mAllocSize = size_t(inNumBuffers) * inBufferSize + kAlign;
mAllocSize = (mAllocSize + kPageSize - 1) / kPageSize * kPageSize;
mAllocPtr = mmap(0, mAllocSize,
PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANON, -1, 0);
if (mAllocPtr == MAP_FAILED) {
const int theRet = errno;
mAllocPtr = 0;
return (theRet == 0 ? -1 : theRet);
}
if (inLockMemoryFlag && mlock(mAllocPtr, mAllocSize) != 0) {
const int theRet = errno;
Destroy();
return (theRet == 0 ? -1 : theRet);
}
mStartPtr = 0;
mStartPtr += (((char*)mAllocPtr - (char*)0) + kAlign - 1) /
kAlign * kAlign;
mTotalCnt = inNumBuffers;
mFreeCnt = 0;
*mFreeListPtr = 0;
while (mFreeCnt < mTotalCnt) {
mFreeListPtr[mFreeCnt] = mFreeCnt + 1;
mFreeCnt++;
}
mFreeListPtr[mFreeCnt] = 0;
return 0;
}
void Destroy()
{
delete [] mFreeListPtr;
mFreeListPtr = 0;
if (mAllocPtr && munmap(mAllocPtr, mAllocSize) != 0) {
QCUtils::FatalError("munmap", errno);
}
mAllocPtr = 0;
mAllocSize = 0;
mStartPtr = 0;
mTotalCnt = 0;
mFreeCnt = 0;
mBufSizeShift = 0;
}
char* Get()
{
if (mFreeCnt <= 0) {
QCASSERT(*mFreeListPtr == 0 && mFreeCnt == 0);
return 0;
}
const BufferIndex theIdx = *mFreeListPtr;
QCASSERT(theIdx > 0);
mFreeCnt--;
*mFreeListPtr = mFreeListPtr[theIdx];
mFreeListPtr[theIdx] = 0;
return (mStartPtr + ((theIdx - 1) << mBufSizeShift));
}
bool Put(char* inPtr)
{
if (inPtr < mStartPtr) {
return false;
}
const size_t theOffset = inPtr - mStartPtr;
const size_t theIdx = (theOffset >> mBufSizeShift) + 1;
if (size_t(mTotalCnt) < theIdx) {
return false;
}
const BufferIndex theNext = *mFreeListPtr;
QCRTASSERT(
mFreeCnt < mTotalCnt &&
(theOffset & ((size_t(1) << mBufSizeShift) - 1)) == 0 &&
theIdx != theNext &&
0 == mFreeListPtr[theIdx]
);
mFreeListPtr[theIdx] = theNext;
*mFreeListPtr = BufferIndex(theIdx);
mFreeCnt++;
return true;
}
int GetFreeCount() const
{ return mFreeCnt; }
int GetTotalCount() const
{ return mTotalCnt; }
bool IsEmpty() const
{ return (mFreeCnt <= 0); }
bool IsFull() const
{ return (mFreeCnt >= mTotalCnt); }
typedef QCDLList<Partition, 0> List;
private:
friend class QCDLListOp<Partition, 0>;
friend class QCDLListOp<const Partition, 0>;
typedef unsigned int BufferIndex;
void* mAllocPtr;
size_t mAllocSize;
char* mStartPtr;
BufferIndex* mFreeListPtr;
int mTotalCnt;
int mFreeCnt;
int mBufSizeShift;
Partition* mPrevPtr[1];
Partition* mNextPtr[1];
};
typedef QCDLList<QCIoBufferPool::Client, 0> QCIoBufferPoolClientList;
QCIoBufferPool::Client::Client()
: mPoolPtr(0)
{
QCIoBufferPoolClientList::Init(*this);
}
bool
QCIoBufferPool::Client::Unregister()
{
return (mPoolPtr && mPoolPtr->UnRegister(*this));
}
QCIoBufferPool::QCIoBufferPool()
: mMutex(),
mBufferSize(0),
mFreeCnt(0),
mTotalCnt(0)
{
QCIoBufferPoolClientList::Init(mClientListPtr);
Partition::List::Init(mPartitionListPtr);
}
QCIoBufferPool::~QCIoBufferPool()
{
QCStMutexLocker theLock(mMutex);
QCIoBufferPool::Destroy();
Client* thePtr;
while ((thePtr = QCIoBufferPoolClientList::PopBack(mClientListPtr))) {
Client& theClient = *thePtr;
QCASSERT(theClient.mPoolPtr == this);
theClient.mPoolPtr = 0;
}
}
int
QCIoBufferPool::Create(
int inPartitionCount,
int inPartitionBufferCount,
int inBufferSize,
bool inLockMemoryFlag)
{
QCStMutexLocker theLock(mMutex);
Destroy();
mBufferSize = inBufferSize;
int theErr = 0;
for (int i = 0; i < inPartitionCount; i++) {
Partition& thePart = *(new Partition());
Partition::List::PushBack(mPartitionListPtr, thePart);
theErr = thePart.Create(
inPartitionBufferCount, inBufferSize, inLockMemoryFlag);
if (theErr) {
Destroy();
break;
}
mFreeCnt += thePart.GetFreeCount();
mTotalCnt += thePart.GetTotalCount();
}
return theErr;
}
void
QCIoBufferPool::Destroy()
{
QCStMutexLocker theLock(mMutex);
Partition* thePtr;
while ((thePtr = Partition::List::PopBack(mPartitionListPtr))) {
delete thePtr;
}
mBufferSize = 0;
mFreeCnt = 0;
}
char*
QCIoBufferPool::Get(
QCIoBufferPool::RefillReqId inRefillReqId /* = kRefillReqIdUndefined */)
{
QCStMutexLocker theLock(mMutex);
if (mFreeCnt <= 0 && ! TryToRefill(inRefillReqId, 1)) {
return 0;
}
QCASSERT(mFreeCnt >= 1);
// Always start from the first partition, to try to keep next
// partitions full, and be able to reclaim these if needed.
Partition::List::Iterator theItr(mPartitionListPtr);
Partition* thePtr;
while ((thePtr = theItr.Next()) && thePtr->IsEmpty())
{}
char* const theBufPtr = thePtr ? thePtr->Get() : 0;
QCASSERT(theBufPtr && mFreeCnt > 0);
mFreeCnt--;
return theBufPtr;
}
bool
QCIoBufferPool::Get(
QCIoBufferPool::OutputIterator& inIt,
int inBufCnt,
QCIoBufferPool::RefillReqId inRefillReqId /* = kRefillReqIdUndefined */)
{
if (inBufCnt <= 0) {
return true;
}
QCStMutexLocker theLock(mMutex);
if (mFreeCnt < inBufCnt && ! TryToRefill(inRefillReqId, inBufCnt)) {
return false;
}
QCASSERT(mFreeCnt >= inBufCnt);
Partition::List::Iterator theItr(mPartitionListPtr);
for (int i = 0; i < inBufCnt; ) {
Partition* thePPtr;
while ((thePPtr = theItr.Next()) && thePPtr->IsEmpty())
{}
QCASSERT(thePPtr);
for (char* theBPtr; i < inBufCnt && (theBPtr = thePPtr->Get()); i++) {
mFreeCnt--;
inIt.Put(theBPtr);
}
}
return true;
}
void
QCIoBufferPool::Put(
char* inBufPtr)
{
if (! inBufPtr) {
return;
}
QCStMutexLocker theLock(mMutex);
PutSelf(inBufPtr);
}
void
QCIoBufferPool::Put(
QCIoBufferPool::InputIterator& inIt,
int inBufCnt)
{
if (inBufCnt < 0) {
return;
}
QCStMutexLocker theLock(mMutex);
for (int i = 0; i < inBufCnt; i++) {
char* const theBufPtr = inIt.Get();
if (! theBufPtr) {
break;
}
PutSelf(theBufPtr);
}
}
bool
QCIoBufferPool::Register(
QCIoBufferPool::Client& inClient)
{
QCStMutexLocker theLock(mMutex);
if (inClient.mPoolPtr) {
return (inClient.mPoolPtr == this);
}
QCIoBufferPoolClientList::PushBack(mClientListPtr, inClient);
inClient.mPoolPtr = this;
return true;
}
bool
QCIoBufferPool::UnRegister(
QCIoBufferPool::Client& inClient)
{
QCStMutexLocker theLock(mMutex);
if (inClient.mPoolPtr != this) {
return false;
}
QCIoBufferPoolClientList::Remove(mClientListPtr, inClient);
inClient.mPoolPtr = 0;
return true;
}
void
QCIoBufferPool::PutSelf(
char* inBufPtr)
{
QCASSERT(mMutex.IsOwned());
if (! inBufPtr) {
return;
}
Partition::List::Iterator theItr(mPartitionListPtr);
Partition* thePtr;
while ((thePtr = theItr.Next()) && ! thePtr->Put(inBufPtr))
{}
QCRTASSERT(thePtr);
mFreeCnt++;
}
bool
QCIoBufferPool::TryToRefill(
QCIoBufferPool::RefillReqId inReqId,
int inBufCnt)
{
QCASSERT(mMutex.IsOwned());
if (inReqId == kRefillReqIdUndefined) {
return false;
}
QCIoBufferPoolClientList::Iterator theItr(mClientListPtr);
Client* thePtr;
while ((thePtr = theItr.Next()) && mFreeCnt < inBufCnt) {
QCASSERT(thePtr->mPoolPtr == this);
{
// QCStMutexUnlocker theUnlock(mMutex);
thePtr->Release(inReqId, inBufCnt - mFreeCnt);
}
}
return (mFreeCnt >= inBufCnt);
}
int
QCIoBufferPool::GetFreeBufferCount()
{
QCStMutexLocker theLock(mMutex);
return mFreeCnt;
}
int
QCIoBufferPool::GetTotalBufferCount()
{
QCStMutexLocker theLock(mMutex);
return mTotalCnt;
}
int
QCIoBufferPool::GetUsedBufferCount()
{
QCStMutexLocker theLock(mMutex);
return (mTotalCnt - mFreeCnt);
}
<|endoftext|> |
<commit_before>/*
* SimpleRenderEngine (https://github.com/mortennobel/SimpleRenderEngine)
*
* Created by Morten Nobel-Jørgensen ( http://www.nobel-joergensen.com/ )
* License: MIT
*/
#include "sre/Camera.hpp"
#include "sre/impl/GL.hpp"
#include "sre/Renderer.hpp"
#include <glm/gtc/matrix_transform.hpp>
#include <glm/gtx/transform.hpp>
#include <sre/Camera.hpp>
#include <glm/gtx/matrix_decompose.hpp>
#include <glm/gtc/type_ptr.hpp>
#include <glm/gtx/string_cast.hpp>
#include <glm/gtx/euler_angles.hpp>
#include "sre/Log.hpp"
namespace sre {
Camera::Camera()
: viewTransform{1.0f}
{
projectionValue.orthographic.orthographicSize = 1;
projectionValue.orthographic.nearPlane = -1;
projectionValue.orthographic.farPlane = 1;
}
void Camera::setPerspectiveProjection(float fieldOfViewY, float nearPlane, float farPlane) {
projectionValue.perspective.fieldOfViewY = glm::radians( fieldOfViewY);
projectionValue.perspective.nearPlane = nearPlane;
projectionValue.perspective.farPlane = farPlane;
projectionType = ProjectionType::Perspective;
}
void Camera::setOrthographicProjection(float orthographicSize, float nearPlane, float farPlane) {
projectionValue.orthographic.orthographicSize = orthographicSize;
projectionValue.orthographic.nearPlane = nearPlane;
projectionValue.orthographic.farPlane = farPlane;
projectionType = ProjectionType::Orthographic;
}
void Camera::setWindowCoordinates(){
projectionType = ProjectionType::OrthographicWindow;
}
void Camera::lookAt(glm::vec3 eye, glm::vec3 at, glm::vec3 up) {
if (glm::length(eye-at)<std::numeric_limits<float>::epsilon()){
auto eyeStr = glm::to_string(eye);
auto atStr = glm::to_string(at);
LOG_WARNING("Camera::lookAt() invalid parameters. eye (%s) must be different from at (%s)",eyeStr.c_str(),atStr.c_str());
}
setViewTransform(glm::lookAt<float>(eye, at, up));
}
glm::mat4 Camera::getViewTransform() {
return viewTransform;
}
glm::mat4 Camera::getProjectionTransform(glm::uvec2 viewportSize) {
switch (projectionType){
case ProjectionType::Custom:
return glm::make_mat4(projectionValue.customProjectionMatrix);
case ProjectionType::Orthographic:
{
float aspect = viewportSize.x/(float)viewportSize.y;
float sizeX = aspect * projectionValue.orthographic.orthographicSize;
return glm::ortho<float> (-sizeX, sizeX, -projectionValue.orthographic.orthographicSize, projectionValue.orthographic.orthographicSize, projectionValue.orthographic.nearPlane, projectionValue.orthographic.farPlane);
}
case ProjectionType::OrthographicWindow:
return glm::ortho<float> (0, float(viewportSize.x), 0, float(viewportSize.y), 1.0f,-1.0f);
case ProjectionType::Perspective:
return glm::perspectiveFov<float>(projectionValue.perspective.fieldOfViewY,
float(viewportSize.x),
float(viewportSize.y),
projectionValue.perspective.nearPlane,
projectionValue.perspective.farPlane);
default:
return glm::mat4(1);
}
}
glm::mat4 Camera::getInfiniteProjectionTransform(glm::uvec2 viewportSize) {
switch (projectionType){
case ProjectionType::Custom:
LOG_WARNING("getInfiniteProjectionTransform not supported for custom projection");
return glm::mat4(1);
case ProjectionType::Orthographic:
{
LOG_WARNING("getInfiniteProjectionTransform not supported for Orthographic projection");
return glm::mat4(1);
}
case ProjectionType::OrthographicWindow:
LOG_WARNING("getInfiniteProjectionTransform not supported for OrthographicWindow projection");
return glm::mat4(1);
case ProjectionType::Perspective:
return glm::tweakedInfinitePerspective(projectionValue.perspective.fieldOfViewY,float(viewportSize.x)/float(viewportSize.y),projectionValue.perspective.nearPlane);
default:
return glm::mat4(1);
}
}
void Camera::setViewTransform(const glm::mat4 &viewTransform) {
Camera::viewTransform = viewTransform;
}
void Camera::setProjectionTransform(const glm::mat4 &projectionTransform) {
memcpy(projectionValue.customProjectionMatrix, glm::value_ptr(projectionTransform), sizeof(glm::mat4));
projectionType = ProjectionType::Custom;
}
void Camera::setViewport(glm::vec2 offset, glm::vec2 size) {
viewportOffset = offset;
viewportSize = size;
}
void Camera::setPositionAndRotation(glm::vec3 position, glm::vec3 rotationEulersDegrees) {
auto rotationEulersRadians = glm::radians(rotationEulersDegrees);
auto viewTransform = glm::translate(position) * glm::eulerAngleXYZ(rotationEulersRadians.x, rotationEulersRadians.y, rotationEulersRadians.z);
setViewTransform(glm::inverse(viewTransform));
}
glm::vec3 Camera::getPosition() {
glm::vec3 scale;
glm::quat orientation;
glm::vec3 translation;
glm::vec3 skew;
glm::vec4 perspective;
glm::decompose(glm::inverse(viewTransform),
scale,
orientation,
translation,
skew,
perspective);
return translation;
}
glm::vec3 Camera::getRotationEuler() {
glm::vec3 scale;
glm::quat orientation;
glm::vec3 translation;
glm::vec3 skew;
glm::vec4 perspective;
glm::decompose(glm::inverse(viewTransform),
scale,
orientation,
translation,
skew,
perspective);
return glm::degrees( -glm::eulerAngles(orientation));
}
std::array<glm::vec3, 2> Camera::screenPointToRay(glm::vec2 position) {
glm::vec2 viewportSize = (glm::vec2)Renderer::instance->getWindowSize() * this->viewportSize;
position = (position / viewportSize)*2.0f-glm::vec2(1.0f);
auto viewProjection = getProjectionTransform(viewportSize) * viewTransform;
auto invViewProjection = glm::inverse(viewProjection);
glm::vec4 originClipSpace{position,-1,1};
glm::vec4 destClipSpace{position,1,1};
glm::vec4 originClipSpaceWS = invViewProjection * originClipSpace;
glm::vec4 destClipSpaceWS = invViewProjection * destClipSpace;
glm::vec3 originClipSpaceWS3 = glm::vec3(originClipSpaceWS)/originClipSpaceWS.w;
glm::vec3 destClipSpaceWS3 = glm::vec3(destClipSpaceWS)/destClipSpaceWS.w;
return {originClipSpaceWS3, glm::normalize(destClipSpaceWS3-originClipSpaceWS3)};
}
}
<commit_msg>getInfiniteProjectionTransform defaults to getProjectionTransform<commit_after>/*
* SimpleRenderEngine (https://github.com/mortennobel/SimpleRenderEngine)
*
* Created by Morten Nobel-Jørgensen ( http://www.nobel-joergensen.com/ )
* License: MIT
*/
#include "sre/Camera.hpp"
#include "sre/impl/GL.hpp"
#include "sre/Renderer.hpp"
#include <glm/gtc/matrix_transform.hpp>
#include <glm/gtx/transform.hpp>
#include <sre/Camera.hpp>
#include <glm/gtx/matrix_decompose.hpp>
#include <glm/gtc/type_ptr.hpp>
#include <glm/gtx/string_cast.hpp>
#include <glm/gtx/euler_angles.hpp>
#include "sre/Log.hpp"
namespace sre {
Camera::Camera()
: viewTransform{1.0f}
{
projectionValue.orthographic.orthographicSize = 1;
projectionValue.orthographic.nearPlane = -1;
projectionValue.orthographic.farPlane = 1;
}
void Camera::setPerspectiveProjection(float fieldOfViewY, float nearPlane, float farPlane) {
projectionValue.perspective.fieldOfViewY = glm::radians( fieldOfViewY);
projectionValue.perspective.nearPlane = nearPlane;
projectionValue.perspective.farPlane = farPlane;
projectionType = ProjectionType::Perspective;
}
void Camera::setOrthographicProjection(float orthographicSize, float nearPlane, float farPlane) {
projectionValue.orthographic.orthographicSize = orthographicSize;
projectionValue.orthographic.nearPlane = nearPlane;
projectionValue.orthographic.farPlane = farPlane;
projectionType = ProjectionType::Orthographic;
}
void Camera::setWindowCoordinates(){
projectionType = ProjectionType::OrthographicWindow;
}
void Camera::lookAt(glm::vec3 eye, glm::vec3 at, glm::vec3 up) {
if (glm::length(eye-at)<std::numeric_limits<float>::epsilon()){
auto eyeStr = glm::to_string(eye);
auto atStr = glm::to_string(at);
LOG_WARNING("Camera::lookAt() invalid parameters. eye (%s) must be different from at (%s)",eyeStr.c_str(),atStr.c_str());
}
setViewTransform(glm::lookAt<float>(eye, at, up));
}
glm::mat4 Camera::getViewTransform() {
return viewTransform;
}
glm::mat4 Camera::getProjectionTransform(glm::uvec2 viewportSize) {
switch (projectionType){
case ProjectionType::Custom:
return glm::make_mat4(projectionValue.customProjectionMatrix);
case ProjectionType::Orthographic:
{
float aspect = viewportSize.x/(float)viewportSize.y;
float sizeX = aspect * projectionValue.orthographic.orthographicSize;
return glm::ortho<float> (-sizeX, sizeX, -projectionValue.orthographic.orthographicSize, projectionValue.orthographic.orthographicSize, projectionValue.orthographic.nearPlane, projectionValue.orthographic.farPlane);
}
case ProjectionType::OrthographicWindow:
return glm::ortho<float> (0, float(viewportSize.x), 0, float(viewportSize.y), 1.0f,-1.0f);
case ProjectionType::Perspective:
return glm::perspectiveFov<float>(projectionValue.perspective.fieldOfViewY,
float(viewportSize.x),
float(viewportSize.y),
projectionValue.perspective.nearPlane,
projectionValue.perspective.farPlane);
default:
return glm::mat4(1);
}
}
glm::mat4 Camera::getInfiniteProjectionTransform(glm::uvec2 viewportSize) {
switch (projectionType){
case ProjectionType::Perspective:
return glm::tweakedInfinitePerspective(projectionValue.perspective.fieldOfViewY,float(viewportSize.x)/float(viewportSize.y),projectionValue.perspective.nearPlane);
default:
return getProjectionTransform(viewportSize);
}
}
void Camera::setViewTransform(const glm::mat4 &viewTransform) {
Camera::viewTransform = viewTransform;
}
void Camera::setProjectionTransform(const glm::mat4 &projectionTransform) {
memcpy(projectionValue.customProjectionMatrix, glm::value_ptr(projectionTransform), sizeof(glm::mat4));
projectionType = ProjectionType::Custom;
}
void Camera::setViewport(glm::vec2 offset, glm::vec2 size) {
viewportOffset = offset;
viewportSize = size;
}
void Camera::setPositionAndRotation(glm::vec3 position, glm::vec3 rotationEulersDegrees) {
auto rotationEulersRadians = glm::radians(rotationEulersDegrees);
auto viewTransform = glm::translate(position) * glm::eulerAngleXYZ(rotationEulersRadians.x, rotationEulersRadians.y, rotationEulersRadians.z);
setViewTransform(glm::inverse(viewTransform));
}
glm::vec3 Camera::getPosition() {
glm::vec3 scale;
glm::quat orientation;
glm::vec3 translation;
glm::vec3 skew;
glm::vec4 perspective;
glm::decompose(glm::inverse(viewTransform),
scale,
orientation,
translation,
skew,
perspective);
return translation;
}
glm::vec3 Camera::getRotationEuler() {
glm::vec3 scale;
glm::quat orientation;
glm::vec3 translation;
glm::vec3 skew;
glm::vec4 perspective;
glm::decompose(glm::inverse(viewTransform),
scale,
orientation,
translation,
skew,
perspective);
return glm::degrees( -glm::eulerAngles(orientation));
}
std::array<glm::vec3, 2> Camera::screenPointToRay(glm::vec2 position) {
glm::vec2 viewportSize = (glm::vec2)Renderer::instance->getWindowSize() * this->viewportSize;
position = (position / viewportSize)*2.0f-glm::vec2(1.0f);
auto viewProjection = getProjectionTransform(viewportSize) * viewTransform;
auto invViewProjection = glm::inverse(viewProjection);
glm::vec4 originClipSpace{position,-1,1};
glm::vec4 destClipSpace{position,1,1};
glm::vec4 originClipSpaceWS = invViewProjection * originClipSpace;
glm::vec4 destClipSpaceWS = invViewProjection * destClipSpace;
glm::vec3 originClipSpaceWS3 = glm::vec3(originClipSpaceWS)/originClipSpaceWS.w;
glm::vec3 destClipSpaceWS3 = glm::vec3(destClipSpaceWS)/destClipSpaceWS.w;
return {originClipSpaceWS3, glm::normalize(destClipSpaceWS3-originClipSpaceWS3)};
}
}
<|endoftext|> |
<commit_before>#include "machineInteractionTask.h"
#include <iostream>
machineInteractionTask::machineInteractionTask():
RTOS::task(5,"machine interaction"),
machineInstructionChannel (this,"machineInstructionChannel"),
clock (this, 500 MS, "MIT_clock"),
currentState(),
setState(),
Uart(),
listeners()
{}
void machineInteractionTask::
addMachineStateListener(machineStateListener* listener)
{
this->listeners.push_back(listener);
}
void machineInteractionTask::notifyListeners()
{
std::vector<machineStateListener*>::iterator listen =
this->listeners.begin();
for(;listen != this->listeners.end(); ++listen)
{
(*listen)->stateChanged(currentState);
}
}
void machineInteractionTask::main()
{
#ifdef DEBUG
std::cout << "MIT started."<< std::endl;
#endif
for(;;)
{
//Wait for clock.
#ifdef DEBUG
std::cout << "MIT running..."<< std::endl;
#endif
this->wait(this->machineInstructionChannel);
update();
//Read the pool and execute request through the uart,
//returns the response in the ResponseStruct.
ResponseStruct rs = doRequest(this->machineInstructionChannel.read());
//Updates the currentState of the machine with the new read value
//from the ResponseStruct.
switch(rs.request.request)
{
case requestEnum::DOOR_LOCK_REQ:
currentState.doorLock = rs.value;
break;
case requestEnum::WATER_VALVE_REQ:
currentState.waterValve = rs.value;
break;
case requestEnum::SOAP_DISPENSER_REQ:
currentState.soapDispenser = rs.value;
break;
case requestEnum::PUMP_REQ:
currentState.pump = rs.value;
break;
case requestEnum::HEATING_UNIT_REQ:
currentState.heatingUnit = rs.value;
break;
default:
break;
}
}
}
void machineInteractionTask::update()
{
//Close water valve and stop soap dispenser when
//the wanted water level is reached.
if(currentState.waterLevel >= setState.waterLevel)
{
if(currentState.waterValve == 1){setWaterValve(0);}
if(currentState.soapDispenser == 1){setSoapDispenser(0);}
setState.waterValve = 0; setState.soapDispenser = 0;
}
//Stop the pump and unlock the door when there is
//no water in the washing machine.
else if(currentState.waterLevel == 0)
{
if(currentState.pump == 1) {setPump(0);}
if(currentState.doorLock == 1){setDoorLock(0);}
setState.pump = 0; setState.doorLock = 0;
}
//Turn on the pump if the wanted water level is 0/empty.
else if(setState.waterLevel == 0)
{
if(currentState.pump == 0){setPump(1);}
setState.pump = 1;
}
//Turn heater on or off depending on current temperature
//compared to wanted temperature
if(currentState.temperature > setState.temperature)
{if(currentState.heatingUnit == 1) {setHeater(0);}}
if(currentState.temperature < setState.temperature)
{if(currentState.heatingUnit == 0) {setHeater(1);}}
//Update the current state of the washing machine
//for temperature and waterLevel.
getTemperature(); getWaterLevel();
//Update all the listeners.
notifyListeners();
}
ResponseStruct machineInteractionTask::doRequest(const RequestStruct& req)
{
//Translate the request to bytes.
std::uint16_t TranslatedRequest = requestTranslate(req);
//Write the request in bytes to the uart/washing machine.
Uart.write(TranslatedRequest);
this->sleep(10);
//Read the response byte of the request.
std::uint16_t responseByte = Uart.read_16();
#ifdef DEBUG
std::cout << "request:" << std::hex << TranslatedRequest <<
std::endl <<"response:" << responseByte << std::dec << std::endl;
#endif
//Translate the response from byte to words and return it.
return responseTranslate(responseByte, req);
}
void machineInteractionTask::setTemperature(unsigned int temperature)
{
setState.temperature = temperature;
}
void machineInteractionTask::setWaterLevel(unsigned int waterLevel)
{
setState.waterLevel = waterLevel;
setState.doorLock = true;
setDoorLock(1); //Locks the door
if(currentState.waterLevel < waterLevel)
{if(currentState.waterValve == 0) {setWaterValve(1);}}
}
void machineInteractionTask::setRPM(bool clockwise, unsigned int rpm)
{
setState.drumRPM = rpm;
setState.drumClockwise = clockwise;
RequestStruct reqS;
reqS.request = requestEnum::SET_RPM_REQ;
if(clockwise){reqS.command = commandEnum::RPM_Clockwise;}
else{reqS.command = commandEnum::RPM_counterClockwise;}
this-> machineInstructionChannel.write(reqS);
}
void machineInteractionTask::setDetergent(bool add)
{
setState.soapDispenser = add;
if(currentState.soapDispenser != add){setSoapDispenser(add);}
}
void machineInteractionTask::flush()
{
setState.temperature = 20; //Reset to standby temperature
setState.waterLevel = 0;
if(currentState.waterLevel > 0){
if(!currentState.pump){
setPump(1);
}
}
}
void machineInteractionTask::setMachineState(bool start)
{
RequestStruct reqS;
reqS.request = requestEnum::MACHINE_REQ;
if(start){ reqS.command = commandEnum::START_CMD; }
else { reqS.command = commandEnum::STOP_CMD; }
this-> machineInstructionChannel.write(reqS);
}
void machineInteractionTask::setDoorLock(bool lock)
{
RequestStruct reqS;
reqS.request = requestEnum::DOOR_LOCK_REQ;
if(lock){ reqS.command = commandEnum::LOCK_CMD; }
else { reqS.command = commandEnum::UNLOCK_CMD; }
this-> machineInstructionChannel.write(reqS);
}
//Function marked private, and doesn't get called at all. Still needed?
void machineInteractionTask::getState(requestEnum request)
{
RequestStruct reqS;
reqS.request = request;
reqS.command = commandEnum::STATUS_CMD;
this-> machineInstructionChannel.write(reqS);
}
void machineInteractionTask::getWaterLevel()
{
RequestStruct reqS;
reqS.request = requestEnum::WATER_LEVEL_REQ;
this-> machineInstructionChannel.write(reqS);
}
void machineInteractionTask::setWaterValve(bool open)
{
RequestStruct reqS;
reqS.request = requestEnum::WATER_VALVE_REQ;
if(open){ reqS.command = commandEnum::OPEN_CMD; }
else { reqS.command = commandEnum::CLOSE_CMD; }
this-> machineInstructionChannel.write(reqS);
}
void machineInteractionTask::setSoapDispenser(bool open)
{
RequestStruct reqS;
reqS.request = requestEnum::SOAP_DISPENSER_REQ;
if(open){ reqS.command = commandEnum::OPEN_CMD; }
else { reqS.command = commandEnum::CLOSE_CMD; }
this-> machineInstructionChannel.write(reqS);
}
void machineInteractionTask::setPump(bool on)
{
RequestStruct reqS;
reqS.request = requestEnum::PUMP_REQ;
if(on){ reqS.command = commandEnum::ON_CMD; }
else { reqS.command = commandEnum::OFF_CMD; }
this-> machineInstructionChannel.write(reqS);
}
void machineInteractionTask::getTemperature()
{
RequestStruct reqS;
reqS.request = requestEnum::TEMPERATURE_REQ;
this-> machineInstructionChannel.write(reqS);
}
void machineInteractionTask::setHeater(bool on)
{
RequestStruct reqS;
reqS.request = requestEnum::HEATING_UNIT_REQ;
if(on){ reqS.command = commandEnum::ON_CMD; }
else { reqS.command = commandEnum::OFF_CMD; }
this-> machineInstructionChannel.write(reqS);
}
void machineInteractionTask::getRPM()
{
RequestStruct reqS;
reqS.request = requestEnum::GET_RPM_REQ;
this-> machineInstructionChannel.write(reqS);
}
void machineInteractionTask::setSignalLed(bool on)
{
RequestStruct reqS;
reqS.request = requestEnum::SIGNAL_LED_REQ;
if(on){ reqS.command = commandEnum::ON_CMD; }
else { reqS.command = commandEnum::OFF_CMD; }
this-> machineInstructionChannel.write(reqS);
}
std::uint16_t machineInteractionTask::requestTranslate(RequestStruct reqS){
std::uint16_t retval = 0;
//Check which request byte should be send
switch(reqS.request){
case requestEnum::MACHINE_REQ: retval |= 0x01; break;
case requestEnum::DOOR_LOCK_REQ: retval |= 0x02; break;
case requestEnum::WATER_VALVE_REQ: retval |= 0x03; break;
case requestEnum::SOAP_DISPENSER_REQ: retval |= 0x04; break;
case requestEnum::PUMP_REQ: retval |= 0x05; break;
case requestEnum::WATER_LEVEL_REQ: retval |= 0x06; break;
case requestEnum::HEATING_UNIT_REQ: retval |= 0x07; break;
case requestEnum::TEMPERATURE_REQ: retval |= 0x08; break;
case requestEnum::SET_RPM_REQ: retval |= 0x0A; break;
case requestEnum::GET_RPM_REQ: retval |= 0x09; break;
case requestEnum::SIGNAL_LED_REQ: retval |= 0x0B; break;
default: retval |= 0x00; break;
}
//Check which command byte should be send.
switch(reqS.command){
case commandEnum::STATUS_CMD: retval |= (0x01) << 8; break;
case commandEnum::LOCK_CMD: retval |= (0x40) << 8; break;
case commandEnum::UNLOCK_CMD: retval |= (0x80) << 8; break;
case commandEnum::START_CMD:
case commandEnum::OPEN_CMD:
case commandEnum::ON_CMD: retval |= (0x10) << 8; break;
case commandEnum::STOP_CMD:
case commandEnum::CLOSE_CMD:
case commandEnum::OFF_CMD: retval |= (0x20) << 8; break;
case commandEnum::RPM_Clockwise:
retval |= (setState.drumRPM | 0x80) << 8; break;
case commandEnum::RPM_counterClockwise:
retval |= (setState.drumRPM) << 8; break;
default:
break;
}
return retval;
}
ResponseStruct machineInteractionTask::responseTranslate(
std::uint16_t response, const RequestStruct& reqS)
{
//ResponseStruct that will contain the response that will be returned.
ResponseStruct resS;
resS.request = reqS; //The request that was send and caused the response.
resS.value = (std::uint8_t) ((response>>8)&0xff);
//Check to which request this response came from and what the returned byte means.
switch(reqS.request)
{
case requestEnum::MACHINE_REQ:
switch(response)
{
case 0x01: resS.response = "HALTED"; break;
case 0x02: resS.response = "IDLE"; break;
case 0x04: resS.response = "RUNNING"; break;
case 0x08: resS.response = "STOPPED"; break;
}
break;
case requestEnum::DOOR_LOCK_REQ:
case requestEnum::WATER_VALVE_REQ:
case requestEnum::SOAP_DISPENSER_REQ:
switch(response)
{
case 0x01: resS.response = "OPENED"; resS.value = 1; break;
case 0x02: resS.response = "CLOSED"; resS.value = 0; break;
case 0x04: if(reqS.request == requestEnum::DOOR_LOCK_REQ)
{resS.response = "LOCKED";} break;
}
break;
case requestEnum::PUMP_REQ:
case requestEnum::HEATING_UNIT_REQ:
case requestEnum::SIGNAL_LED_REQ:
switch(response)
{
case 0x08: resS.response = "ON"; resS.value = 1; break;
case 0x10: resS.response = "OFF"; resS.value = 0; break;
}
break;
case requestEnum::WATER_LEVEL_REQ:
currentState.waterLevel = response; //Save read waterLevel value
resS.response = "Niveau in %";
break;
case requestEnum::TEMPERATURE_REQ:
currentState.temperature = response; //Save read temperature value
resS.response = "Temp in Graden Celcius";
break;
case requestEnum::SET_RPM_REQ:
case requestEnum::GET_RPM_REQ:
//What do these values mean? (COMMENT_ME)
if(response >= (0x00|0x80) && response <= (0x40|0x80))
{
currentState.drumRPM = response|0x80; //Save read RPM value
currentState.drumClockwise = true; //Save RPM is going clockwise
resS.response = "RPM_Clockwise";
}
else if(response >= 0x00 && response <= 0x40)
{
currentState.drumRPM = response; //Save read RPM value
currentState.drumClockwise = false; //Save RPM is going counterclockwise
resS.response = "RPM_counterClockwise";
}
break;
default:
resS.response = "NO VALID REQUEST";
break;
}
return resS;
}
<commit_msg>trying a different flavour of debugging.<commit_after>#include "machineInteractionTask.h"
#include <iostream>
machineInteractionTask::machineInteractionTask():
RTOS::task(5,"machine interaction"),
machineInstructionChannel (this,"machineInstructionChannel"),
clock (this, 500 MS, "MIT_clock"),
currentState(),
setState(),
Uart(),
listeners()
{}
void machineInteractionTask::
addMachineStateListener(machineStateListener* listener)
{
this->listeners.push_back(listener);
}
void machineInteractionTask::notifyListeners()
{
std::vector<machineStateListener*>::iterator listen =
this->listeners.begin();
for(;listen != this->listeners.end(); ++listen)
{
(*listen)->stateChanged(currentState);
}
}
void machineInteractionTask::main()
{
trace;
for(;;)
{
//Wait for clock.
trace;
this->wait(this->machineInstructionChannel);
update();
//Read the pool and execute request through the uart,
//returns the response in the ResponseStruct.
ResponseStruct rs = doRequest(this->machineInstructionChannel.read());
//Updates the currentState of the machine with the new read value
//from the ResponseStruct.
switch(rs.request.request)
{
case requestEnum::DOOR_LOCK_REQ:
currentState.doorLock = rs.value;
break;
case requestEnum::WATER_VALVE_REQ:
currentState.waterValve = rs.value;
break;
case requestEnum::SOAP_DISPENSER_REQ:
currentState.soapDispenser = rs.value;
break;
case requestEnum::PUMP_REQ:
currentState.pump = rs.value;
break;
case requestEnum::HEATING_UNIT_REQ:
currentState.heatingUnit = rs.value;
break;
default:
break;
}
}
}
void machineInteractionTask::update()
{
//Close water valve and stop soap dispenser when
//the wanted water level is reached.
if(currentState.waterLevel >= setState.waterLevel)
{
if(currentState.waterValve == 1){setWaterValve(0);}
if(currentState.soapDispenser == 1){setSoapDispenser(0);}
setState.waterValve = 0; setState.soapDispenser = 0;
}
//Stop the pump and unlock the door when there is
//no water in the washing machine.
else if(currentState.waterLevel == 0)
{
if(currentState.pump == 1) {setPump(0);}
if(currentState.doorLock == 1){setDoorLock(0);}
setState.pump = 0; setState.doorLock = 0;
}
//Turn on the pump if the wanted water level is 0/empty.
else if(setState.waterLevel == 0)
{
if(currentState.pump == 0){setPump(1);}
setState.pump = 1;
}
//Turn heater on or off depending on current temperature
//compared to wanted temperature
if(currentState.temperature > setState.temperature)
{if(currentState.heatingUnit == 1) {setHeater(0);}}
if(currentState.temperature < setState.temperature)
{if(currentState.heatingUnit == 0) {setHeater(1);}}
//Update the current state of the washing machine
//for temperature and waterLevel.
getTemperature(); getWaterLevel();
//Update all the listeners.
notifyListeners();
}
ResponseStruct machineInteractionTask::doRequest(const RequestStruct& req)
{
//Translate the request to bytes.
std::uint16_t TranslatedRequest = requestTranslate(req);
//Write the request in bytes to the uart/washing machine.
Uart.write(TranslatedRequest);
this->sleep(10);
//Read the response byte of the request.
std::uint16_t responseByte = Uart.read_16();
#ifdef DEBUG
std::cout << "request:" << std::hex << TranslatedRequest <<
std::endl <<"response:" << responseByte << std::dec << std::endl;
#endif
//Translate the response from byte to words and return it.
return responseTranslate(responseByte, req);
}
void machineInteractionTask::setTemperature(unsigned int temperature)
{
setState.temperature = temperature;
}
void machineInteractionTask::setWaterLevel(unsigned int waterLevel)
{
setState.waterLevel = waterLevel;
setState.doorLock = true;
setDoorLock(1); //Locks the door
if(currentState.waterLevel < waterLevel)
{if(currentState.waterValve == 0) {setWaterValve(1);}}
}
void machineInteractionTask::setRPM(bool clockwise, unsigned int rpm)
{
setState.drumRPM = rpm;
setState.drumClockwise = clockwise;
RequestStruct reqS;
reqS.request = requestEnum::SET_RPM_REQ;
if(clockwise){reqS.command = commandEnum::RPM_Clockwise;}
else{reqS.command = commandEnum::RPM_counterClockwise;}
this-> machineInstructionChannel.write(reqS);
}
void machineInteractionTask::setDetergent(bool add)
{
setState.soapDispenser = add;
if(currentState.soapDispenser != add){setSoapDispenser(add);}
}
void machineInteractionTask::flush()
{
setState.temperature = 20; //Reset to standby temperature
setState.waterLevel = 0;
if(currentState.waterLevel > 0){
if(!currentState.pump){
setPump(1);
}
}
}
void machineInteractionTask::setMachineState(bool start)
{
RequestStruct reqS;
reqS.request = requestEnum::MACHINE_REQ;
if(start){ reqS.command = commandEnum::START_CMD; }
else { reqS.command = commandEnum::STOP_CMD; }
this-> machineInstructionChannel.write(reqS);
}
void machineInteractionTask::setDoorLock(bool lock)
{
RequestStruct reqS;
reqS.request = requestEnum::DOOR_LOCK_REQ;
if(lock){ reqS.command = commandEnum::LOCK_CMD; }
else { reqS.command = commandEnum::UNLOCK_CMD; }
this-> machineInstructionChannel.write(reqS);
}
//Function marked private, and doesn't get called at all. Still needed?
void machineInteractionTask::getState(requestEnum request)
{
RequestStruct reqS;
reqS.request = request;
reqS.command = commandEnum::STATUS_CMD;
this-> machineInstructionChannel.write(reqS);
}
void machineInteractionTask::getWaterLevel()
{
RequestStruct reqS;
reqS.request = requestEnum::WATER_LEVEL_REQ;
this-> machineInstructionChannel.write(reqS);
}
void machineInteractionTask::setWaterValve(bool open)
{
RequestStruct reqS;
reqS.request = requestEnum::WATER_VALVE_REQ;
if(open){ reqS.command = commandEnum::OPEN_CMD; }
else { reqS.command = commandEnum::CLOSE_CMD; }
this-> machineInstructionChannel.write(reqS);
}
void machineInteractionTask::setSoapDispenser(bool open)
{
RequestStruct reqS;
reqS.request = requestEnum::SOAP_DISPENSER_REQ;
if(open){ reqS.command = commandEnum::OPEN_CMD; }
else { reqS.command = commandEnum::CLOSE_CMD; }
this-> machineInstructionChannel.write(reqS);
}
void machineInteractionTask::setPump(bool on)
{
RequestStruct reqS;
reqS.request = requestEnum::PUMP_REQ;
if(on){ reqS.command = commandEnum::ON_CMD; }
else { reqS.command = commandEnum::OFF_CMD; }
this-> machineInstructionChannel.write(reqS);
}
void machineInteractionTask::getTemperature()
{
RequestStruct reqS;
reqS.request = requestEnum::TEMPERATURE_REQ;
this-> machineInstructionChannel.write(reqS);
}
void machineInteractionTask::setHeater(bool on)
{
RequestStruct reqS;
reqS.request = requestEnum::HEATING_UNIT_REQ;
if(on){ reqS.command = commandEnum::ON_CMD; }
else { reqS.command = commandEnum::OFF_CMD; }
this-> machineInstructionChannel.write(reqS);
}
void machineInteractionTask::getRPM()
{
RequestStruct reqS;
reqS.request = requestEnum::GET_RPM_REQ;
this-> machineInstructionChannel.write(reqS);
}
void machineInteractionTask::setSignalLed(bool on)
{
RequestStruct reqS;
reqS.request = requestEnum::SIGNAL_LED_REQ;
if(on){ reqS.command = commandEnum::ON_CMD; }
else { reqS.command = commandEnum::OFF_CMD; }
this-> machineInstructionChannel.write(reqS);
}
std::uint16_t machineInteractionTask::requestTranslate(RequestStruct reqS){
std::uint16_t retval = 0;
//Check which request byte should be send
switch(reqS.request){
case requestEnum::MACHINE_REQ: retval |= 0x01; break;
case requestEnum::DOOR_LOCK_REQ: retval |= 0x02; break;
case requestEnum::WATER_VALVE_REQ: retval |= 0x03; break;
case requestEnum::SOAP_DISPENSER_REQ: retval |= 0x04; break;
case requestEnum::PUMP_REQ: retval |= 0x05; break;
case requestEnum::WATER_LEVEL_REQ: retval |= 0x06; break;
case requestEnum::HEATING_UNIT_REQ: retval |= 0x07; break;
case requestEnum::TEMPERATURE_REQ: retval |= 0x08; break;
case requestEnum::SET_RPM_REQ: retval |= 0x0A; break;
case requestEnum::GET_RPM_REQ: retval |= 0x09; break;
case requestEnum::SIGNAL_LED_REQ: retval |= 0x0B; break;
default: retval |= 0x00; break;
}
//Check which command byte should be send.
switch(reqS.command){
case commandEnum::STATUS_CMD: retval |= (0x01) << 8; break;
case commandEnum::LOCK_CMD: retval |= (0x40) << 8; break;
case commandEnum::UNLOCK_CMD: retval |= (0x80) << 8; break;
case commandEnum::START_CMD:
case commandEnum::OPEN_CMD:
case commandEnum::ON_CMD: retval |= (0x10) << 8; break;
case commandEnum::STOP_CMD:
case commandEnum::CLOSE_CMD:
case commandEnum::OFF_CMD: retval |= (0x20) << 8; break;
case commandEnum::RPM_Clockwise:
retval |= (setState.drumRPM | 0x80) << 8; break;
case commandEnum::RPM_counterClockwise:
retval |= (setState.drumRPM) << 8; break;
default:
break;
}
return retval;
}
ResponseStruct machineInteractionTask::responseTranslate(
std::uint16_t response, const RequestStruct& reqS)
{
//ResponseStruct that will contain the response that will be returned.
ResponseStruct resS;
resS.request = reqS; //The request that was send and caused the response.
resS.value = (std::uint8_t) ((response>>8)&0xff);
//Check to which request this response came from and what the returned byte means.
switch(reqS.request)
{
case requestEnum::MACHINE_REQ:
switch(response)
{
case 0x01: resS.response = "HALTED"; break;
case 0x02: resS.response = "IDLE"; break;
case 0x04: resS.response = "RUNNING"; break;
case 0x08: resS.response = "STOPPED"; break;
}
break;
case requestEnum::DOOR_LOCK_REQ:
case requestEnum::WATER_VALVE_REQ:
case requestEnum::SOAP_DISPENSER_REQ:
switch(response)
{
case 0x01: resS.response = "OPENED"; resS.value = 1; break;
case 0x02: resS.response = "CLOSED"; resS.value = 0; break;
case 0x04: if(reqS.request == requestEnum::DOOR_LOCK_REQ)
{resS.response = "LOCKED";} break;
}
break;
case requestEnum::PUMP_REQ:
case requestEnum::HEATING_UNIT_REQ:
case requestEnum::SIGNAL_LED_REQ:
switch(response)
{
case 0x08: resS.response = "ON"; resS.value = 1; break;
case 0x10: resS.response = "OFF"; resS.value = 0; break;
}
break;
case requestEnum::WATER_LEVEL_REQ:
currentState.waterLevel = response; //Save read waterLevel value
resS.response = "Niveau in %";
break;
case requestEnum::TEMPERATURE_REQ:
currentState.temperature = response; //Save read temperature value
resS.response = "Temp in Graden Celcius";
break;
case requestEnum::SET_RPM_REQ:
case requestEnum::GET_RPM_REQ:
//What do these values mean? (COMMENT_ME)
if(response >= (0x00|0x80) && response <= (0x40|0x80))
{
currentState.drumRPM = response|0x80; //Save read RPM value
currentState.drumClockwise = true; //Save RPM is going clockwise
resS.response = "RPM_Clockwise";
}
else if(response >= 0x00 && response <= 0x40)
{
currentState.drumRPM = response; //Save read RPM value
currentState.drumClockwise = false; //Save RPM is going counterclockwise
resS.response = "RPM_counterClockwise";
}
break;
default:
resS.response = "NO VALID REQUEST";
break;
}
return resS;
}
<|endoftext|> |
<commit_before>
#include <gnutls/gnutls.h>
#include <gnutls/x509.h>
#include "utils_p.h"
#include "keybuilder.h"
QT_BEGIN_NAMESPACE_CERTIFICATE
/*!
\class KeyBuilder
\brief The KeyBuilder class is a tool for creating QSslKeys.
The KeyBuilder class provides an easy way to generate a new private
key for an X.509 certificate.
*/
/*!
Generates a new key using the specified algorithm and strength. The algorithm
will generally be RSA. The various strengths allow you to specify the trade-off
between the security of the key and the time involved in creating it.
Note that this method can take a considerable length of time to execute, so in
gui applications it should be run in a worker thread.
*/
QSslKey KeyBuilder::generate( QSsl::KeyAlgorithm algo, KeyStrength strength )
{
ensure_gnutls_init();
gnutls_sec_param_t sec;
switch(strength) {
case StrengthLow:
sec = GNUTLS_SEC_PARAM_LOW;
break;
case StrengthNormal:
sec = GNUTLS_SEC_PARAM_NORMAL;
break;
case StrengthHigh:
sec = GNUTLS_SEC_PARAM_HIGH;
break;
case StrengthUltra:
sec = GNUTLS_SEC_PARAM_ULTRA;
break;
default:
qWarning("Unhandled strength %d passed to generate", uint(strength));
sec = GNUTLS_SEC_PARAM_NORMAL;
}
uint bits = gnutls_sec_param_to_pk_bits((algo == QSsl::Rsa) ? GNUTLS_PK_RSA : GNUTLS_PK_DSA, sec);
gnutls_x509_privkey_t key;
gnutls_x509_privkey_init(&key);
int errno = gnutls_x509_privkey_generate(key, (algo == QSsl::Rsa) ? GNUTLS_PK_RSA : GNUTLS_PK_DSA, bits, 0);
if (GNUTLS_E_SUCCESS != errno) {
qWarning("Failed to generate key %s", gnutls_strerror(errno));
gnutls_x509_privkey_deinit(key);
return QSslKey();
}
QSslKey qkey = key_to_qsslkey(key, algo, &errno);
if (GNUTLS_E_SUCCESS != errno) {
qWarning("Failed to convert key to bytearray %s", gnutls_strerror(errno));
return QSslKey();
}
return qkey;
}
QT_END_NAMESPACE_CERTIFICATE
<commit_msg>Fix leak,<commit_after>
#include <gnutls/gnutls.h>
#include <gnutls/x509.h>
#include "utils_p.h"
#include "keybuilder.h"
QT_BEGIN_NAMESPACE_CERTIFICATE
/*!
\class KeyBuilder
\brief The KeyBuilder class is a tool for creating QSslKeys.
The KeyBuilder class provides an easy way to generate a new private
key for an X.509 certificate.
*/
/*!
Generates a new key using the specified algorithm and strength. The algorithm
will generally be RSA. The various strengths allow you to specify the trade-off
between the security of the key and the time involved in creating it.
Note that this method can take a considerable length of time to execute, so in
gui applications it should be run in a worker thread.
*/
QSslKey KeyBuilder::generate( QSsl::KeyAlgorithm algo, KeyStrength strength )
{
ensure_gnutls_init();
gnutls_sec_param_t sec;
switch(strength) {
case StrengthLow:
sec = GNUTLS_SEC_PARAM_LOW;
break;
case StrengthNormal:
sec = GNUTLS_SEC_PARAM_NORMAL;
break;
case StrengthHigh:
sec = GNUTLS_SEC_PARAM_HIGH;
break;
case StrengthUltra:
sec = GNUTLS_SEC_PARAM_ULTRA;
break;
default:
qWarning("Unhandled strength %d passed to generate", uint(strength));
sec = GNUTLS_SEC_PARAM_NORMAL;
}
uint bits = gnutls_sec_param_to_pk_bits((algo == QSsl::Rsa) ? GNUTLS_PK_RSA : GNUTLS_PK_DSA, sec);
gnutls_x509_privkey_t key;
gnutls_x509_privkey_init(&key);
int errno = gnutls_x509_privkey_generate(key, (algo == QSsl::Rsa) ? GNUTLS_PK_RSA : GNUTLS_PK_DSA, bits, 0);
if (GNUTLS_E_SUCCESS != errno) {
qWarning("Failed to generate key %s", gnutls_strerror(errno));
gnutls_x509_privkey_deinit(key);
return QSslKey();
}
QSslKey qkey = key_to_qsslkey(key, algo, &errno);
if (GNUTLS_E_SUCCESS != errno) {
qWarning("Failed to convert key to bytearray %s", gnutls_strerror(errno));
gnutls_x509_privkey_deinit(key);
return QSslKey();
}
return qkey;
}
QT_END_NAMESPACE_CERTIFICATE
<|endoftext|> |
<commit_before>/*************************************************************************
*
* $RCSfile: AccessibleShapeTreeInfo.cxx,v $
*
* $Revision: 1.3 $
*
* last change: $Author: af $ $Date: 2002-05-06 13:13:45 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the "License"); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#include "AccessibleShapeTreeInfo.hxx"
using namespace ::com::sun::star;
using namespace ::drafts::com::sun::star::accessibility;
using ::com::sun::star::uno::Reference;
namespace accessibility {
AccessibleShapeTreeInfo::AccessibleShapeTreeInfo (
const Reference<XAccessibleComponent>& rxDocumentWindow,
const Reference<document::XEventBroadcaster>& rxModelBroadcaster)
: mxDocumentWindow (rxDocumentWindow),
mxModelBroadcaster (rxModelBroadcaster),
mpView (NULL),
mpWindow (NULL)
{
}
AccessibleShapeTreeInfo::AccessibleShapeTreeInfo (void)
: mpView (NULL),
mpWindow (NULL)
{
//empty
}
AccessibleShapeTreeInfo::~AccessibleShapeTreeInfo (void)
{
//empty
}
void AccessibleShapeTreeInfo::SetDocumentWindow (
const Reference<XAccessibleComponent>& rxDocumentWindow)
{
if (mxDocumentWindow != rxDocumentWindow)
mxDocumentWindow = rxDocumentWindow;
}
uno::Reference<XAccessibleComponent>
AccessibleShapeTreeInfo::GetDocumentWindow (void) const
{
return mxDocumentWindow;
}
void AccessibleShapeTreeInfo::SetControllerBroadcaster (
const uno::Reference<document::XEventBroadcaster>& rxControllerBroadcaster)
{
mxModelBroadcaster = rxControllerBroadcaster;
}
uno::Reference<document::XEventBroadcaster>
AccessibleShapeTreeInfo::GetControllerBroadcaster (void) const
{
return mxModelBroadcaster;
}
void AccessibleShapeTreeInfo::SetModelBroadcaster (
const Reference<document::XEventBroadcaster>& rxModelBroadcaster)
{
mxModelBroadcaster = rxModelBroadcaster;
}
Reference<document::XEventBroadcaster>
AccessibleShapeTreeInfo::GetModelBroadcaster (void) const
{
return mxModelBroadcaster;
}
void AccessibleShapeTreeInfo::SetSdrView (SdrView* pView)
{
mpView = pView;
}
SdrView* AccessibleShapeTreeInfo::GetSdrView (void) const
{
return mpView;
}
void AccessibleShapeTreeInfo::SetWindow (Window* pWindow)
{
mpWindow = pWindow;
}
const Window* AccessibleShapeTreeInfo::GetWindow (void) const
{
return mpWindow;
}
void AccessibleShapeTreeInfo::SetViewForwarder (const IAccessibleViewForwarder* pViewForwarder)
{
mpViewForwarder = pViewForwarder;
}
const IAccessibleViewForwarder* AccessibleShapeTreeInfo::GetViewForwarder (void) const
{
return mpViewForwarder;
}
} // end of namespace accessibility
<commit_msg>#95585# Added copy constructor and assignment operator.<commit_after>/*************************************************************************
*
* $RCSfile: AccessibleShapeTreeInfo.cxx,v $
*
* $Revision: 1.4 $
*
* last change: $Author: af $ $Date: 2002-05-08 09:45:28 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the "License"); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#include "AccessibleShapeTreeInfo.hxx"
using namespace ::com::sun::star;
using namespace ::drafts::com::sun::star::accessibility;
using ::com::sun::star::uno::Reference;
namespace accessibility {
AccessibleShapeTreeInfo::AccessibleShapeTreeInfo (
const Reference<XAccessibleComponent>& rxDocumentWindow,
const Reference<document::XEventBroadcaster>& rxModelBroadcaster)
: mxDocumentWindow (rxDocumentWindow),
mxModelBroadcaster (rxModelBroadcaster),
mpView (NULL),
mpWindow (NULL),
mpViewForwarder (NULL)
{
// Empty.
}
AccessibleShapeTreeInfo::AccessibleShapeTreeInfo (void)
: mpView (NULL),
mpWindow (NULL),
mpViewForwarder (NULL)
{
// Empty.
}
AccessibleShapeTreeInfo::AccessibleShapeTreeInfo (const AccessibleShapeTreeInfo& rInfo)
: mxDocumentWindow (rInfo.mxDocumentWindow),
mxModelBroadcaster (rInfo.mxModelBroadcaster),
mpView (rInfo.mpView),
mpWindow (rInfo.mpWindow),
mpViewForwarder (rInfo.mpViewForwarder)
{
// Empty.
}
AccessibleShapeTreeInfo& AccessibleShapeTreeInfo::operator= (const AccessibleShapeTreeInfo& rInfo)
{
mxDocumentWindow = rInfo.mxDocumentWindow;
mxModelBroadcaster = rInfo.mxModelBroadcaster;
mpView = rInfo.mpView;
mpWindow = rInfo.mpWindow;
mpViewForwarder = rInfo.mpViewForwarder;
return *this;
}
AccessibleShapeTreeInfo::~AccessibleShapeTreeInfo (void)
{
//empty
}
void AccessibleShapeTreeInfo::SetDocumentWindow (
const Reference<XAccessibleComponent>& rxDocumentWindow)
{
if (mxDocumentWindow != rxDocumentWindow)
mxDocumentWindow = rxDocumentWindow;
}
uno::Reference<XAccessibleComponent>
AccessibleShapeTreeInfo::GetDocumentWindow (void) const
{
return mxDocumentWindow;
}
void AccessibleShapeTreeInfo::SetControllerBroadcaster (
const uno::Reference<document::XEventBroadcaster>& rxControllerBroadcaster)
{
mxModelBroadcaster = rxControllerBroadcaster;
}
uno::Reference<document::XEventBroadcaster>
AccessibleShapeTreeInfo::GetControllerBroadcaster (void) const
{
return mxModelBroadcaster;
}
void AccessibleShapeTreeInfo::SetModelBroadcaster (
const Reference<document::XEventBroadcaster>& rxModelBroadcaster)
{
mxModelBroadcaster = rxModelBroadcaster;
}
Reference<document::XEventBroadcaster>
AccessibleShapeTreeInfo::GetModelBroadcaster (void) const
{
return mxModelBroadcaster;
}
void AccessibleShapeTreeInfo::SetSdrView (SdrView* pView)
{
mpView = pView;
}
SdrView* AccessibleShapeTreeInfo::GetSdrView (void) const
{
return mpView;
}
void AccessibleShapeTreeInfo::SetWindow (Window* pWindow)
{
mpWindow = pWindow;
}
const Window* AccessibleShapeTreeInfo::GetWindow (void) const
{
return mpWindow;
}
void AccessibleShapeTreeInfo::SetViewForwarder (const IAccessibleViewForwarder* pViewForwarder)
{
mpViewForwarder = pViewForwarder;
}
const IAccessibleViewForwarder* AccessibleShapeTreeInfo::GetViewForwarder (void) const
{
return mpViewForwarder;
}
} // end of namespace accessibility
<|endoftext|> |
<commit_before>/*!
* @file File stateTitle.cpp
* @brief Implementation of the class StateTitle
*
* Auxiliary documentation
* @sa stateTitle.hpp
*/
#include <stateTitle.hpp>
#include <camera.hpp>
#include <complib.hpp>
#include <game.hpp>
#include <inputManager.hpp>
#include <stateStage.hpp>
#include <stateEditor.hpp>
#include <assert.h>
#define BACKGROUND "img/tela-inicio2.png"
#define INSTRUCTION_TEXT "IDJ-Projeto\n\nPress [Space] to continue\n[E] Level Editor\n"
/*!
@class StateTitle
@brief This class provides the title states
*/
//! A constructor.
/*!
* This is a constructor method of StateTitle
*/
StateTitle::StateTitle():State::State(), bg{Sprite(BACKGROUND)},
bt1{"img/botao-editor.png", 2},
bt2{"img/botao-inicio.png", 2}{
LOG_METHOD_START("StateTitle::StateTitle");
LoadAssets();
bg.StretchToFit(WINSIZE);
LOG_METHOD_CLOSE("StateTitle::StateTitle","constructor");
}
//! A destructor.
/*!
This is a destructor method of StateTitle class
*/
StateTitle::~StateTitle() {
LOG_METHOD_START("StateTitle::~StateTitle");
LOG_METHOD_CLOSE("StateTitle::~StateTitle","destructor");
}
/*!
@fn void StateTitle::LoadAssets()
@brief Virtual method that loads assets
@return The execution of this method returns no value
*/
void StateTitle::LoadAssets() {
LOG_METHOD_START("StateTitle::LoadAssets");
LOG_METHOD_CLOSE("StateTitle::LoadAssets","void");
}
/*!
@fn void StateTitle::LoadGUI()
@brief Virtual method that loads GUI
@return The execution of this method returns no value
*/
void StateTitle::LoadGUI() {
LOG_METHOD_START("StateTitle::LoadGUI()");
LOG_METHOD_CLOSE("StateTitle::LoadGUI()","void");
}
/*!
@fn void StateTitle::Begin()
@brief Virtual method that represents the Begin title state
@return The execution of this method returns no value
*/
void StateTitle::Begin() {
LOG_METHOD_START("StateTitle::Begin");
//! Defines the GameObject
//! @var text
GameObject* text = new GameObject{Rect{(WINSIZE.x / 2), (WINSIZE.y / 2), 0,
0}};//!< A GameObject with the informations of the game
assert(text != NULL);
text->AddComponent(new CompText{INSTRUCTION_TEXT, 36, SDL_COLOR_WHITE,
Hotspot::CENTER});
AddObject(text->uid);
LOG_METHOD_CLOSE("StateTitle::Begin","void");
}
/*!
@fn void StateTitle::Update(float time)
@brief Virtual method that updates the title state
@param time
@brief a positive float, the represents the game time
@return The execution of this method returns no value
*/
void StateTitle::update(float time) {
LOG_METHOD_START("StateTitle::update");
assert(time >= 0);
LOG_VARIABLE("time",time);
//! Checks if the user tried to quit
if (INPUT.get_quit_requested() || INPUT.key_pressed(KEY_ESC)){
quit_requested = true;
}
//! Checks if the user pressed the space key
if (INPUT.key_pressed(KEY_SPACE)) {
bt2.set_frame(1);
GAMEINST.Push(new StateStage{"level_0"});
}
//! Checks if the user pressed the 'e' key
if (INPUT.key_pressed(KEY(e))) {
bt1.set_frame(1);
GAMEINST.Push(new StateEditor{});
}
UpdateArray(time);
LOG_METHOD_CLOSE("StateTitle::update","void");
}
/*!
@fn void StateTitle::render()
@brief Virtual method that renders the title images
@return The execution of this method returns no value
*/
void StateTitle::render() {
LOG_METHOD_START("StateTitle::render");
bg.render(0,0);
bt1.render(500,300);
bt2.render(100,300);
// RenderArray();
LOG_METHOD_CLOSE("StateTitle::render","void");
}
/*!
@fn void StateTitle::Pause()
@brief Virtual method that represents the Pause title state
@return The execution of this method returns no value
*/
void StateTitle::Pause() {
LOG_METHOD_START("StateTitle::Pause");
LOG_METHOD_CLOSE("StateTitle::Pause","void");
}
/*!
@fn void StateTitle::Resume()
@brief Virtual method that represents the Resume title state
@return The execution of this method returns no value
*/
void StateTitle::Resume() {
LOG_METHOD_START("StateTitle::Resume");
CAMERA.x=CAMERA.y=0;
LOG_METHOD_CLOSE("StateTitle::Resume","void");
}
<commit_msg>Applies elses technique<commit_after>/*!
* @file File stateTitle.cpp
* @brief Implementation of the class StateTitle
*
* Auxiliary documentation
* @sa stateTitle.hpp
*/
#include <stateTitle.hpp>
#include <camera.hpp>
#include <complib.hpp>
#include <game.hpp>
#include <inputManager.hpp>
#include <stateStage.hpp>
#include <stateEditor.hpp>
#include <assert.h>
#define BACKGROUND "img/tela-inicio2.png"
#define INSTRUCTION_TEXT "IDJ-Projeto\n\nPress [Space]" +
" to continue\n[E] Level Editor\n"
/*!
@class StateTitle
@brief This class provides the title states
*/
//! A constructor.
/*!
* This is a constructor method of StateTitle
*/
StateTitle::StateTitle():State::State(), bg{Sprite(BACKGROUND)},
bt1{"img/botao-editor.png", 2},
bt2{"img/botao-inicio.png", 2}{
LOG_METHOD_START("StateTitle::StateTitle");
LoadAssets();
bg.StretchToFit(WINSIZE);
LOG_METHOD_CLOSE("StateTitle::StateTitle","constructor");
}
//! A destructor.
/*!
This is a destructor method of StateTitle class
*/
StateTitle::~StateTitle() {
LOG_METHOD_START("StateTitle::~StateTitle");
LOG_METHOD_CLOSE("StateTitle::~StateTitle","destructor");
}
/*!
@fn void StateTitle::LoadAssets()
@brief Virtual method that loads assets
@return The execution of this method returns no value
*/
void StateTitle::LoadAssets() {
LOG_METHOD_START("StateTitle::LoadAssets");
LOG_METHOD_CLOSE("StateTitle::LoadAssets","void");
}
/*!
@fn void StateTitle::LoadGUI()
@brief Virtual method that loads GUI
@return The execution of this method returns no value
*/
void StateTitle::LoadGUI() {
LOG_METHOD_START("StateTitle::LoadGUI()");
LOG_METHOD_CLOSE("StateTitle::LoadGUI()","void");
}
/*!
@fn void StateTitle::Begin()
@brief Virtual method that represents the Begin title state
@return The execution of this method returns no value
*/
void StateTitle::Begin() {
LOG_METHOD_START("StateTitle::Begin");
//! Defines the GameObject
//! @var text
//!< A GameObject with the informations of the game
GameObject* text = new GameObject{Rect{(WINSIZE.x / 2), (WINSIZE.y / 2), 0,
0}};//!< A GameObject with the informations of the game
assert(text != NULL);
text->AddComponent(new CompText{INSTRUCTION_TEXT, 36, SDL_COLOR_WHITE,
Hotspot::CENTER});
AddObject(text->uid);
LOG_METHOD_CLOSE("StateTitle::Begin","void");
}
/*!
@fn void StateTitle::Update(float time)
@brief Virtual method that updates the title state
@param time
@brief a positive float, the represents the game time
@return The execution of this method returns no value
*/
void StateTitle::update(float time) {
LOG_METHOD_START("StateTitle::update");
assert(time >= 0);
LOG_VARIABLE("time",time);
//! Checks if the user tried to quit
if (INPUT.get_quit_requested() || INPUT.key_pressed(KEY_ESC)){
quit_requested = true;
}
else{
// do nothing
}
//! Checks if the user pressed the space key
if (INPUT.key_pressed(KEY_SPACE)) {
bt2.set_frame(1);
GAMEINST.Push(new StateStage{"level_0"});
}
else{
// do nothing
}
//! Checks if the user pressed the 'e' key
if (INPUT.key_pressed(KEY(e))) {
bt1.set_frame(1);
GAMEINST.Push(new StateEditor{});
}
else{
// do nothing
}
UpdateArray(time);
LOG_METHOD_CLOSE("StateTitle::update","void");
}
/*!
@fn void StateTitle::render()
@brief Virtual method that renders the title images
@return The execution of this method returns no value
*/
void StateTitle::render() {
LOG_METHOD_START("StateTitle::render");
bg.render(0,0);
bt1.render(500,300);
bt2.render(100,300);
// RenderArray();
LOG_METHOD_CLOSE("StateTitle::render","void");
}
/*!
@fn void StateTitle::Pause()
@brief Virtual method that represents the Pause title state
@return The execution of this method returns no value
*/
void StateTitle::Pause() {
LOG_METHOD_START("StateTitle::Pause");
LOG_METHOD_CLOSE("StateTitle::Pause","void");
}
/*!
@fn void StateTitle::Resume()
@brief Virtual method that represents the Resume title state
@return The execution of this method returns no value
*/
void StateTitle::Resume() {
LOG_METHOD_START("StateTitle::Resume");
CAMERA.x=CAMERA.y=0;
LOG_METHOD_CLOSE("StateTitle::Resume","void");
}
<|endoftext|> |
<commit_before>// -*- mode: c++; coding: utf-8; -*-
// state_space.hh - State space
// Copyright (C) 2013 Seiji Kumagai
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the "Software"),
// to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following conditions:
// The above copyright notice and this permission notice (including the next
// paragraph) shall be included in all copies or substantial portions of the
// Software.
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
#ifndef STATE_SPACE_HH
#define STATE_SPACE_HH
#include <vector>
#include "typedef.hh"
namespace esf {
class StateSpace {
public:
static Index StateToIndex(Init, State);
static State IndexToState(Init, Index);
static StateList Neighbors(Init, Index);
static Init StateToInit(State);
static State InitToState(Init);
};
}
#endif // STATE_SPACE_HH
<commit_msg>Convert StateSpace to namespace.<commit_after>// -*- mode: c++; coding: utf-8; -*-
// state_space.hh - State space
// Copyright (C) 2013 Seiji Kumagai
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the "Software"),
// to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following conditions:
// The above copyright notice and this permission notice (including the next
// paragraph) shall be included in all copies or substantial portions of the
// Software.
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
#ifndef STATE_SPACE_HH
#define STATE_SPACE_HH
#include <vector>
#include "typedef.hh"
namespace esf {
namespace StateSpace {
Index StateToIndex(Init, State);
State IndexToState(Init, Index);
StateList Neighbors(Init, Index);
Init StateToInit(State);
State InitToState(Init);
};
}
#endif // STATE_SPACE_HH
<|endoftext|> |
<commit_before>// ---------------------------------------------------------------------------
//
// This file is part of the <kortex> library suite
//
// Copyright (C) 2017 Engin Tola
//
// See LICENSE file for license information.
//
// author: Engin Tola
// e-mail: [email protected]
// web : http://www.engintola.com
// web : http://www.aurvis.com
//
// ---------------------------------------------------------------------------
#ifndef KORTEX_GEOMETRY_CC
#define KORTEX_GEOMETRY_CC
#include <kortex/geometry.h>
#include <kortex/math.h>
#include <kortex/svd.h>
namespace kortex {
void compute_mean( const vector<const double*> pnts, double mean[3] ) {
assert_statement( pnts.size() > 0, "invalid number of points" );
memset( mean, 0, sizeof(*mean)*3 );
int n_pnts = (int)pnts.size();
for( int p=0; p<n_pnts; p++ ) {
const double* X = pnts[p];
assert_pointer( X );
mean[0] += X[0];
mean[1] += X[1];
mean[2] += X[2];
}
mean[0] /= n_pnts;
mean[1] /= n_pnts;
mean[2] /= n_pnts;
}
void compute_mean( const vector<const float*> pnts, float mean[3] ) {
assert_statement( pnts.size() > 0, "invalid number of points" );
memset( mean, 0, sizeof(*mean)*3 );
int n_pnts = (int)pnts.size();
for( int p=0; p<n_pnts; p++ ) {
const float* X = pnts[p];
assert_pointer( X );
mean[0] += X[0];
mean[1] += X[1];
mean[2] += X[2];
}
mean[0] /= static_cast<float>(n_pnts);
mean[1] /= static_cast<float>(n_pnts);
mean[2] /= static_cast<float>(n_pnts);
}
/// computes the plane equation fitting to the points. returning value is
/// the curvature estimate for the points.
double compute_plane( const vector<const double*> pnts, double plane[4] ) {
int n_pnts = (int)pnts.size();
if( n_pnts < 4 ) {
plane[0] = plane[1] = plane[2] = plane[3] = 0.0;
logman_warning_g( "not enough points [%d] to estimate a plane", n_pnts );
return -1.0;
}
double mu[3];
compute_mean( pnts, mu );
double Cov[9];
mat_zero( Cov, 3, 3 );
double nX[3];
double ppt[9];
for( int p=0; p<n_pnts; p++ ) {
const double* X = pnts[p];
nX[0] = X[0]-mu[0];
nX[1] = X[1]-mu[1];
nX[2] = X[2]-mu[2];
mat_mat_trans( nX, 3, 1, nX, 3, 1, ppt, 9 );
mat_add_3( ppt, Cov );
}
// need to divide by number of samples to compute the actual covariance
// but it is not necessary here as we divide singular values to each
// other and the n_pnts will just cancel each oher.
SVD svd;
svd.decompose( Cov, 3, 3, true, true );
const double* components = svd.Vt();
memcpy( plane, components+6, sizeof(*plane)*3 );
plane[3] = -dot3(plane, mu);
const double* sd = svd.Sd();
double l0 = fabs(sd[0]);
double l1 = fabs(sd[1]);
double l2 = fabs(sd[2]);
return l2 / (l0+l1+l2);
}
float compute_plane( const vector< Vec3f >& pnts, float plane[4] ) {
int n_pnts = (int)pnts.size();
if( n_pnts < 4 ) {
plane[0] = plane[1] = plane[2] = plane[3] = 0.0f;
logman_warning_g( "not enough points [%d] to estimate a plane", n_pnts );
return -1.0;
}
Vec3f mu;
compute_mean( pnts, mu );
double Cov[9];
mat_zero( Cov, 3, 3 );
double ppt[9];
double nX[3];
for( int p=0; p<n_pnts; p++ ) {
const Vec3f& X = pnts[p];
nX[0] = X[0]-mu[0];
nX[1] = X[1]-mu[1];
nX[2] = X[2]-mu[2];
mat_mat_trans( nX, 3, 1, nX, 3, 1, ppt, 9 );
mat_add_3( ppt, Cov );
}
SVD svd;
svd.decompose( Cov, 3, 3, true, true );
const double* components = svd.Vt();
plane[0] = (float)components[6];
plane[1] = (float)components[7];
plane[2] = (float)components[8];
plane[3] = -dot3(plane, mu());
const double* sd = svd.Sd();
double l0 = fabs(sd[0]);
double l1 = fabs(sd[1]);
double l2 = fabs(sd[2]);
return float( l2 / (l0+l1+l2) );
}
/// computes the plane equation fitting to the points. returning value is
/// the curvature estimate for the points.
float compute_plane( const vector<const float*> pnts, float plane[4] ) {
int n_pnts = (int)pnts.size();
if( n_pnts < 4 ) {
plane[0] = plane[1] = plane[2] = plane[3] = 0.0f;
logman_warning_g( "not enough points [%d] to estimate a plane", n_pnts );
return -1.0;
}
float mu[3];
compute_mean( pnts, mu );
double Cov[9];
mat_zero( Cov, 3, 3 );
double nX[3];
double ppt[9];
for( int p=0; p<n_pnts; p++ ) {
const float* X = pnts[p];
assert_pointer(X);
nX[0] = X[0]-mu[0];
nX[1] = X[1]-mu[1];
nX[2] = X[2]-mu[2];
mat_mat_trans( nX, 3, 1, nX, 3, 1, ppt, 9 );
mat_add_3( ppt, Cov );
}
SVD svd;
svd.decompose( Cov, 3, 3, true, true );
const double* components = svd.Vt();
plane[0] = (float)components[6];
plane[1] = (float)components[7];
plane[2] = (float)components[8];
plane[3] = -dot3(plane, mu);
const double* sd = svd.Sd();
double l0 = fabs(sd[0]);
double l1 = fabs(sd[1]);
double l2 = fabs(sd[2]);
return float( l2 / (l0+l1+l2) );
}
double point_to_plane_distance( const double X[3], const double plane[4] ) {
assert_statement( is_unit_norm_3( plane ), "plane normal is not normalized" );
return dot3(plane, X) + plane[3];
}
float point_to_plane_distance( const float X[3], const float plane[4] ) {
assert_statement( is_unit_norm_3( plane ), "plane normal is not normalized" );
return dot3(plane, X) + plane[3];
}
/// finds the closest point on the given plane and returns its distance
float closest_point_on_plane( const float point[3], const float plane[4], float q[3] ) {
float d = point_to_plane_distance( point, plane );
q[0] = point[0] - d*plane[0];
q[1] = point[1] - d*plane[1];
q[2] = point[2] - d*plane[2];
return d;
}
}
#endif
<commit_msg>[geometry] assertion prints info<commit_after>// ---------------------------------------------------------------------------
//
// This file is part of the <kortex> library suite
//
// Copyright (C) 2017 Engin Tola
//
// See LICENSE file for license information.
//
// author: Engin Tola
// e-mail: [email protected]
// web : http://www.engintola.com
// web : http://www.aurvis.com
//
// ---------------------------------------------------------------------------
#ifndef KORTEX_GEOMETRY_CC
#define KORTEX_GEOMETRY_CC
#include <kortex/geometry.h>
#include <kortex/math.h>
#include <kortex/svd.h>
namespace kortex {
void compute_mean( const vector<const double*> pnts, double mean[3] ) {
assert_statement( pnts.size() > 0, "invalid number of points" );
memset( mean, 0, sizeof(*mean)*3 );
int n_pnts = (int)pnts.size();
for( int p=0; p<n_pnts; p++ ) {
const double* X = pnts[p];
assert_pointer( X );
mean[0] += X[0];
mean[1] += X[1];
mean[2] += X[2];
}
mean[0] /= n_pnts;
mean[1] /= n_pnts;
mean[2] /= n_pnts;
}
void compute_mean( const vector<const float*> pnts, float mean[3] ) {
assert_statement( pnts.size() > 0, "invalid number of points" );
memset( mean, 0, sizeof(*mean)*3 );
int n_pnts = (int)pnts.size();
for( int p=0; p<n_pnts; p++ ) {
const float* X = pnts[p];
assert_pointer( X );
mean[0] += X[0];
mean[1] += X[1];
mean[2] += X[2];
}
mean[0] /= static_cast<float>(n_pnts);
mean[1] /= static_cast<float>(n_pnts);
mean[2] /= static_cast<float>(n_pnts);
}
/// computes the plane equation fitting to the points. returning value is
/// the curvature estimate for the points.
double compute_plane( const vector<const double*> pnts, double plane[4] ) {
int n_pnts = (int)pnts.size();
if( n_pnts < 4 ) {
plane[0] = plane[1] = plane[2] = plane[3] = 0.0;
logman_warning_g( "not enough points [%d] to estimate a plane", n_pnts );
return -1.0;
}
double mu[3];
compute_mean( pnts, mu );
double Cov[9];
mat_zero( Cov, 3, 3 );
double nX[3];
double ppt[9];
for( int p=0; p<n_pnts; p++ ) {
const double* X = pnts[p];
nX[0] = X[0]-mu[0];
nX[1] = X[1]-mu[1];
nX[2] = X[2]-mu[2];
mat_mat_trans( nX, 3, 1, nX, 3, 1, ppt, 9 );
mat_add_3( ppt, Cov );
}
// need to divide by number of samples to compute the actual covariance
// but it is not necessary here as we divide singular values to each
// other and the n_pnts will just cancel each oher.
SVD svd;
svd.decompose( Cov, 3, 3, true, true );
const double* components = svd.Vt();
memcpy( plane, components+6, sizeof(*plane)*3 );
plane[3] = -dot3(plane, mu);
const double* sd = svd.Sd();
double l0 = fabs(sd[0]);
double l1 = fabs(sd[1]);
double l2 = fabs(sd[2]);
return l2 / (l0+l1+l2);
}
float compute_plane( const vector< Vec3f >& pnts, float plane[4] ) {
int n_pnts = (int)pnts.size();
if( n_pnts < 4 ) {
plane[0] = plane[1] = plane[2] = plane[3] = 0.0f;
logman_warning_g( "not enough points [%d] to estimate a plane", n_pnts );
return -1.0;
}
Vec3f mu;
compute_mean( pnts, mu );
double Cov[9];
mat_zero( Cov, 3, 3 );
double ppt[9];
double nX[3];
for( int p=0; p<n_pnts; p++ ) {
const Vec3f& X = pnts[p];
nX[0] = X[0]-mu[0];
nX[1] = X[1]-mu[1];
nX[2] = X[2]-mu[2];
mat_mat_trans( nX, 3, 1, nX, 3, 1, ppt, 9 );
mat_add_3( ppt, Cov );
}
SVD svd;
svd.decompose( Cov, 3, 3, true, true );
const double* components = svd.Vt();
plane[0] = (float)components[6];
plane[1] = (float)components[7];
plane[2] = (float)components[8];
plane[3] = -dot3(plane, mu());
const double* sd = svd.Sd();
double l0 = fabs(sd[0]);
double l1 = fabs(sd[1]);
double l2 = fabs(sd[2]);
return float( l2 / (l0+l1+l2) );
}
/// computes the plane equation fitting to the points. returning value is
/// the curvature estimate for the points.
float compute_plane( const vector<const float*> pnts, float plane[4] ) {
int n_pnts = (int)pnts.size();
if( n_pnts < 4 ) {
plane[0] = plane[1] = plane[2] = plane[3] = 0.0f;
logman_warning_g( "not enough points [%d] to estimate a plane", n_pnts );
return -1.0;
}
float mu[3];
compute_mean( pnts, mu );
double Cov[9];
mat_zero( Cov, 3, 3 );
double nX[3];
double ppt[9];
for( int p=0; p<n_pnts; p++ ) {
const float* X = pnts[p];
assert_pointer(X);
nX[0] = X[0]-mu[0];
nX[1] = X[1]-mu[1];
nX[2] = X[2]-mu[2];
mat_mat_trans( nX, 3, 1, nX, 3, 1, ppt, 9 );
mat_add_3( ppt, Cov );
}
SVD svd;
svd.decompose( Cov, 3, 3, true, true );
const double* components = svd.Vt();
plane[0] = (float)components[6];
plane[1] = (float)components[7];
plane[2] = (float)components[8];
plane[3] = -dot3(plane, mu);
const double* sd = svd.Sd();
double l0 = fabs(sd[0]);
double l1 = fabs(sd[1]);
double l2 = fabs(sd[2]);
return float( l2 / (l0+l1+l2) );
}
double point_to_plane_distance( const double X[3], const double plane[4] ) {
assert_statement_g( is_unit_norm_3( plane ), "plane normal is not normalized [%f]", dot3(plane,plane) );
return dot3(plane, X) + plane[3];
}
float point_to_plane_distance( const float X[3], const float plane[4] ) {
assert_statement_g( is_unit_norm_3( plane ), "plane normal is not normalized [%f]", dot3(plane,plane) );
return dot3(plane, X) + plane[3];
}
/// finds the closest point on the given plane and returns its distance
float closest_point_on_plane( const float point[3], const float plane[4], float q[3] ) {
float d = point_to_plane_distance( point, plane );
q[0] = point[0] - d*plane[0];
q[1] = point[1] - d*plane[1];
q[2] = point[2] - d*plane[2];
return d;
}
}
#endif
<|endoftext|> |
<commit_before>// This file is part of SWGANH which is released under the MIT license.
// See file LICENSE or go to http://swganh.com/LICENSE
#include <exception>
#include <iostream>
#include <string>
#include <boost/thread.hpp>
#include <boost/python.hpp>
#include "anh/logger.h"
#include "swganh/app/swganh_app.h"
#include "swganh/scripting/utilities.h"
#include "version.h"
using namespace boost;
using namespace swganh;
using namespace std;
int main(int argc, char* argv[])
{
Py_Initialize();
PyEval_InitThreads();
// Step 2: Release the GIL from the main thread so that other threads can use it
PyEval_ReleaseThread(PyGILState_GetThisThreadState());
try {
app::SwganhApp app(argc, argv);
for (;;) {
string cmd;
cin >> cmd;
if (cmd.compare("exit") == 0 || cmd.compare("quit") == 0 || cmd.compare("q") == 0) {
LOG(info) << "Exit command received from command line. Shutting down.";
break;
} else if(cmd.compare("console") == 0 || cmd.compare("~") == 0) {
swganh::scripting::ScopedGilLock lock;
anh::Logger::getInstance().DisableConsoleLogging();
#ifdef WIN32
std::system("cls");
#else
if (std::system("clear") != 0)
{
LOG(error) << "Error clearing screen, ignoring console mode";
continue;
}
#endif
std::cout << "swgpy console " << VERSION_MAJOR << "." << VERSION_MINOR << "." << VERSION_PATCH << std::endl;
boost::python::object main = boost::python::object (boost::python::handle<>(boost::python::borrowed(
PyImport_AddModule("__main__")
)));
auto global_dict = main.attr("__dict__");
global_dict["kernel"] = boost::python::ptr(app.GetAppKernel());
PyRun_InteractiveLoop(stdin, "<stdin>");
anh::Logger::getInstance().EnableConsoleLogging();
} else {
LOG(warning) << "Invalid command received: " << cmd;
std::cout << "Type exit or (q)uit to quit" << std::endl;
}
}
} catch(std::exception& e) {
LOG(fatal) << "Unhandled application exception occurred: " << e.what();
}
// Step 4: Lock the GIL before calling finalize
PyGILState_Ensure();
Py_Finalize();
return 0;
}
<commit_msg>Made bringing up the interactive console more responsive and inline with how many games work (hit ` to bring down the console)<commit_after>// This file is part of SWGANH which is released under the MIT license.
// See file LICENSE or go to http://swganh.com/LICENSE
#include <exception>
#include <iostream>
#include <string>
#include <boost/thread.hpp>
#include <boost/python.hpp>
#include "anh/logger.h"
#include "anh/utilities.h"
#include "swganh/app/swganh_app.h"
#include "swganh/scripting/utilities.h"
using namespace boost;
using namespace swganh;
using namespace std;
int main(int argc, char* argv[])
{
Py_Initialize();
PyEval_InitThreads();
// Step 2: Release the GIL from the main thread so that other threads can use it
PyEval_ReleaseThread(PyGILState_GetThisThreadState());
try {
app::SwganhApp app(argc, argv);
for (;;) {
if (anh::KeyboardHit())
{
char input = anh::GetHitKey();
if (input == '`')
{
app.StartInteractiveConsole();
}
else
{
// Echo out the input that was given and add it back to the input stream to read in.
std::cout << input;
cin.putback(input);
string cmd;
cin >> cmd;
if (cmd.compare("exit") == 0 || cmd.compare("quit") == 0 || cmd.compare("q") == 0) {
LOG(info) << "Exit command received from command line. Shutting down.";
break;
} else {
LOG(warning) << "Invalid command received: " << cmd;
std::cout << "Type exit or (q)uit to quit" << std::endl;
}
}
}
}
} catch(std::exception& e) {
LOG(fatal) << "Unhandled application exception occurred: " << e.what();
}
// Step 4: Lock the GIL before calling finalize
PyGILState_Ensure();
Py_Finalize();
return 0;
}
<|endoftext|> |
<commit_before>#include "taskqueuer.h"
WARNINGS_DISABLE
#include <QCoreApplication>
#include <QEventLoop>
#include <QVariant>
WARNINGS_ENABLE
#include "cmdlinetask.h"
/*! Track info about tasks. */
struct TaskMeta
{
/*! Actual task. */
CmdlineTask *task;
/*! Does this task need to be the only one happening? */
bool isExclusive;
/*! This is a "create archive" task? */
bool isBackup;
};
TaskQueuer::TaskQueuer() : _threadPool(QThreadPool::globalInstance())
{
#ifdef QT_TESTLIB_LIB
_fakeNextTask = false;
#endif
}
TaskQueuer::~TaskQueuer()
{
// Wait up to 1 second to finish any background tasks
_threadPool->waitForDone(1000);
// Wait up to 1 second to delete objects scheduled with ->deleteLater()
QCoreApplication::processEvents(QEventLoop::AllEvents, 1000);
}
void TaskQueuer::stopTasks(bool interrupt, bool running, bool queued)
{
// Clear the queue first, to avoid starting a queued task
// after already clearing the running task(s).
if(queued)
{
while(!_taskQueue.isEmpty())
{
TaskMeta * tm = _taskQueue.dequeue();
CmdlineTask *task = tm->task;
if(task)
{
task->emitCanceled();
task->deleteLater();
}
}
emit message("Cleared queued tasks.");
}
// Deal with a running backup.
if(interrupt)
{
// Sending a SIGQUIT will cause the tarsnap binary to
// create a checkpoint. Non-tarsnap binaries should be
// receive a CmdlineTask::stop() instead of a SIGQUIT.
if(!_runningTasks.isEmpty())
{
TaskMeta *tm = _runningTasks.first();
Q_ASSERT(tm->isBackup == true);
CmdlineTask *backupTask = tm->task;
backupTask->sigquit();
}
emit message("Interrupting current backup.");
}
// Stop running tasks.
if(running)
{
for(TaskMeta *tm : _runningTasks)
{
CmdlineTask *task = tm->task;
if(task)
task->stop();
}
emit message("Stopped running tasks.");
}
}
void TaskQueuer::queueTask(CmdlineTask *task, bool exclusive, bool isBackup)
{
// Sanity check.
Q_ASSERT(task != nullptr);
// Create & initialize the TaskMeta object.
TaskMeta *tm = new TaskMeta;
tm->task = task;
tm->isExclusive = exclusive;
tm->isBackup = isBackup;
// Add to the queue and trigger starting a new task.
_taskQueue.enqueue(tm);
startTasks();
}
void TaskQueuer::startTasks()
{
while(!_taskQueue.isEmpty() && !isExclusiveTaskRunning())
{
// Bail from loop if the next task requires exclusive running.
if(!_runningTasks.isEmpty() && _taskQueue.head()->isExclusive)
break;
// Bail from loop if we've reached the maximum number of threads.
if(_runningTasks.count() >= _threadPool->maxThreadCount())
break;
startTask();
}
// Send the updated task numbers.
updateTaskNumbers();
}
void TaskQueuer::startTask()
{
// Bail if there's nothing to do.
if(_taskQueue.isEmpty())
return;
// Check for exclusive.
if(isExclusiveTaskRunning())
return;
// Get a new task.
TaskMeta *tm = _taskQueue.dequeue();
// Set up the task ending.
CmdlineTask *task = tm->task;
connect(task, &CmdlineTask::dequeue, this, &TaskQueuer::dequeueTask);
task->setAutoDelete(false);
// Record this thread as "running", even though it hasn't actually
// started yet. QThreadPool::start() is non-blocking, and in fact
// explicitly states that a QRunnable can be added to an internal
// run queue if it's exceeded QThreadPoll::maxThreadCount().
//
// However, for the purpose of this TaskQueuer, the task should not
// be recorded in our _taskQueue (because we've just dequeued()'d it).
// The "strictly correct" solution would be to add a
// _waitingForStart queue, and move items out of that queue when the
// relevant CmdlineTask::started signal was emitted. At the moment,
// I don't think that step is necessary, but I might need to revisit
// that decision later.
_runningTasks.append(tm);
// Start the task.
#ifdef QT_TESTLIB_LIB
if(_fakeNextTask)
task->fake();
#endif
_threadPool->start(task);
}
void TaskQueuer::dequeueTask()
{
// Get the task.
CmdlineTask *task = qobject_cast<CmdlineTask *>(sender());
// Sanity check.
if(task == nullptr)
return;
// Clean up task.
for(TaskMeta *tm : _runningTasks)
{
if(tm->task == task)
{
_runningTasks.removeOne(tm);
delete tm;
break;
}
}
task->deleteLater();
// Start another task(s) if applicable.
startTasks();
}
bool TaskQueuer::isExclusiveTaskRunning()
{
for(TaskMeta *tm : _runningTasks)
{
if(tm->isExclusive)
return true;
}
return false;
}
bool TaskQueuer::isBackupTaskRunning()
{
for(TaskMeta *tm : _runningTasks)
{
if(tm->isBackup)
return true;
}
return false;
}
void TaskQueuer::updateTaskNumbers()
{
bool backupTaskRunning = isBackupTaskRunning();
emit numTasks(backupTaskRunning, _runningTasks.count(), _taskQueue.count());
}
#ifdef QT_TESTLIB_LIB
void TaskQueuer::fakeNextTask()
{
_fakeNextTask = true;
}
void TaskQueuer::waitUntilIdle()
{
while(!(_taskQueue.isEmpty() && _runningTasks.isEmpty()))
QCoreApplication::processEvents(QEventLoop::AllEvents, 100);
}
#endif
<commit_msg>TaskQueuer: invoke task->canceled() directly<commit_after>#include "taskqueuer.h"
WARNINGS_DISABLE
#include <QCoreApplication>
#include <QEventLoop>
#include <QVariant>
WARNINGS_ENABLE
#include "cmdlinetask.h"
/*! Track info about tasks. */
struct TaskMeta
{
/*! Actual task. */
CmdlineTask *task;
/*! Does this task need to be the only one happening? */
bool isExclusive;
/*! This is a "create archive" task? */
bool isBackup;
};
TaskQueuer::TaskQueuer() : _threadPool(QThreadPool::globalInstance())
{
#ifdef QT_TESTLIB_LIB
_fakeNextTask = false;
#endif
}
TaskQueuer::~TaskQueuer()
{
// Wait up to 1 second to finish any background tasks
_threadPool->waitForDone(1000);
// Wait up to 1 second to delete objects scheduled with ->deleteLater()
QCoreApplication::processEvents(QEventLoop::AllEvents, 1000);
}
void TaskQueuer::stopTasks(bool interrupt, bool running, bool queued)
{
// Clear the queue first, to avoid starting a queued task
// after already clearing the running task(s).
if(queued)
{
while(!_taskQueue.isEmpty())
{
TaskMeta * tm = _taskQueue.dequeue();
CmdlineTask *task = tm->task;
if(task)
{
task->canceled();
task->deleteLater();
}
}
emit message("Cleared queued tasks.");
}
// Deal with a running backup.
if(interrupt)
{
// Sending a SIGQUIT will cause the tarsnap binary to
// create a checkpoint. Non-tarsnap binaries should be
// receive a CmdlineTask::stop() instead of a SIGQUIT.
if(!_runningTasks.isEmpty())
{
TaskMeta *tm = _runningTasks.first();
Q_ASSERT(tm->isBackup == true);
CmdlineTask *backupTask = tm->task;
backupTask->sigquit();
}
emit message("Interrupting current backup.");
}
// Stop running tasks.
if(running)
{
for(TaskMeta *tm : _runningTasks)
{
CmdlineTask *task = tm->task;
if(task)
task->stop();
}
emit message("Stopped running tasks.");
}
}
void TaskQueuer::queueTask(CmdlineTask *task, bool exclusive, bool isBackup)
{
// Sanity check.
Q_ASSERT(task != nullptr);
// Create & initialize the TaskMeta object.
TaskMeta *tm = new TaskMeta;
tm->task = task;
tm->isExclusive = exclusive;
tm->isBackup = isBackup;
// Add to the queue and trigger starting a new task.
_taskQueue.enqueue(tm);
startTasks();
}
void TaskQueuer::startTasks()
{
while(!_taskQueue.isEmpty() && !isExclusiveTaskRunning())
{
// Bail from loop if the next task requires exclusive running.
if(!_runningTasks.isEmpty() && _taskQueue.head()->isExclusive)
break;
// Bail from loop if we've reached the maximum number of threads.
if(_runningTasks.count() >= _threadPool->maxThreadCount())
break;
startTask();
}
// Send the updated task numbers.
updateTaskNumbers();
}
void TaskQueuer::startTask()
{
// Bail if there's nothing to do.
if(_taskQueue.isEmpty())
return;
// Check for exclusive.
if(isExclusiveTaskRunning())
return;
// Get a new task.
TaskMeta *tm = _taskQueue.dequeue();
// Set up the task ending.
CmdlineTask *task = tm->task;
connect(task, &CmdlineTask::dequeue, this, &TaskQueuer::dequeueTask);
task->setAutoDelete(false);
// Record this thread as "running", even though it hasn't actually
// started yet. QThreadPool::start() is non-blocking, and in fact
// explicitly states that a QRunnable can be added to an internal
// run queue if it's exceeded QThreadPoll::maxThreadCount().
//
// However, for the purpose of this TaskQueuer, the task should not
// be recorded in our _taskQueue (because we've just dequeued()'d it).
// The "strictly correct" solution would be to add a
// _waitingForStart queue, and move items out of that queue when the
// relevant CmdlineTask::started signal was emitted. At the moment,
// I don't think that step is necessary, but I might need to revisit
// that decision later.
_runningTasks.append(tm);
// Start the task.
#ifdef QT_TESTLIB_LIB
if(_fakeNextTask)
task->fake();
#endif
_threadPool->start(task);
}
void TaskQueuer::dequeueTask()
{
// Get the task.
CmdlineTask *task = qobject_cast<CmdlineTask *>(sender());
// Sanity check.
if(task == nullptr)
return;
// Clean up task.
for(TaskMeta *tm : _runningTasks)
{
if(tm->task == task)
{
_runningTasks.removeOne(tm);
delete tm;
break;
}
}
task->deleteLater();
// Start another task(s) if applicable.
startTasks();
}
bool TaskQueuer::isExclusiveTaskRunning()
{
for(TaskMeta *tm : _runningTasks)
{
if(tm->isExclusive)
return true;
}
return false;
}
bool TaskQueuer::isBackupTaskRunning()
{
for(TaskMeta *tm : _runningTasks)
{
if(tm->isBackup)
return true;
}
return false;
}
void TaskQueuer::updateTaskNumbers()
{
bool backupTaskRunning = isBackupTaskRunning();
emit numTasks(backupTaskRunning, _runningTasks.count(), _taskQueue.count());
}
#ifdef QT_TESTLIB_LIB
void TaskQueuer::fakeNextTask()
{
_fakeNextTask = true;
}
void TaskQueuer::waitUntilIdle()
{
while(!(_taskQueue.isEmpty() && _runningTasks.isEmpty()))
QCoreApplication::processEvents(QEventLoop::AllEvents, 100);
}
#endif
<|endoftext|> |
<commit_before>/*
* Copyright (c) 1999-2008 Mark D. Hill and David A. Wood
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met: redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer;
* redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution;
* neither the name of the copyright holders 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 "mem/ruby/common/Address.hh"
#include "base/bitfield.hh"
#include "mem/ruby/system/RubySystem.hh"
Addr
bitSelect(Addr addr, unsigned int small, unsigned int big)
{
assert(big >= small);
return bits<Addr>(addr, big, small);
}
Addr
maskLowOrderBits(Addr addr, unsigned int number)
{
return mbits<Addr>(addr, 63, number);
}
Addr
getOffset(Addr addr)
{
return bitSelect(addr, 0, RubySystem::getBlockSizeBits() - 1);
}
Addr
makeLineAddress(Addr addr)
{
return mbits<Addr>(addr, 63, RubySystem::getBlockSizeBits());
}
Addr
makeLineAddress(Addr addr, int cacheLineBits)
{
return maskLowOrderBits(addr, cacheLineBits);
}
// returns the next stride address based on line address
Addr
makeNextStrideAddress(Addr addr, int stride)
{
return makeLineAddress(addr) + RubySystem::getBlockSizeBytes() * stride;
}
std::string
printAddress(Addr addr)
{
std::stringstream out;
out << "[" << std::hex << "0x" << addr << "," << " line 0x"
<< makeLineAddress(addr) << std::dec << "]";
return out.str();
}
<commit_msg>mem-ruby: Fix type casting in makeNextStrideAddress<commit_after>/*
* Copyright (c) 1999-2008 Mark D. Hill and David A. Wood
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met: redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer;
* redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution;
* neither the name of the copyright holders 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 "mem/ruby/common/Address.hh"
#include "base/bitfield.hh"
#include "mem/ruby/system/RubySystem.hh"
Addr
bitSelect(Addr addr, unsigned int small, unsigned int big)
{
assert(big >= small);
return bits<Addr>(addr, big, small);
}
Addr
maskLowOrderBits(Addr addr, unsigned int number)
{
return mbits<Addr>(addr, 63, number);
}
Addr
getOffset(Addr addr)
{
return bitSelect(addr, 0, RubySystem::getBlockSizeBits() - 1);
}
Addr
makeLineAddress(Addr addr)
{
return mbits<Addr>(addr, 63, RubySystem::getBlockSizeBits());
}
Addr
makeLineAddress(Addr addr, int cacheLineBits)
{
return maskLowOrderBits(addr, cacheLineBits);
}
// returns the next stride address based on line address
Addr
makeNextStrideAddress(Addr addr, int stride)
{
return makeLineAddress(addr) +
static_cast<int>(RubySystem::getBlockSizeBytes()) * stride;
}
std::string
printAddress(Addr addr)
{
std::stringstream out;
out << "[" << std::hex << "0x" << addr << "," << " line 0x"
<< makeLineAddress(addr) << std::dec << "]";
return out.str();
}
<|endoftext|> |
<commit_before>// (C) Copyright Ullrich Koethe 2001, Gennadiy Rozental 2001-2002.
// Permission to copy, use, modify, sell and distribute this software
// is granted provided this copyright notice appears in all copies.
// This software is provided "as is" without express or implied warranty,
// and with no claim as to its suitability for any purpose.
// See http://www.boost.org for updates, documentation, and revision history.
//
// File : $RCSfile$
//
// Version : $Id$
//
// Description : supplies offline implemtation for the Test Tools
// ***************************************************************************
// LOCAL
#include <boost/test/test_tools.hpp>
#include <boost/test/unit_test_result.hpp>
// BOOST
#include <boost/config.hpp>
// STL
#include <fstream>
#include <iostream>
#include <algorithm>
#include <cstring>
#include <string>
# ifdef BOOST_NO_STDC_NAMESPACE
namespace std { using ::strcmp; using ::strncmp; using ::strlen; }
# endif
namespace boost {
using namespace unit_test_framework;
namespace test_toolbox {
namespace detail {
// ************************************************************************** //
// ************** wrapstrstream ************** //
// ************************************************************************** //
std::string&
wrapstrstream::str() const {
#ifdef BOOST_NO_STRINGSTREAM
m_str.assign( m_buf.str(), m_buf.pcount() );
m_buf.freeze( false );
#else
m_str = m_buf.str();
#endif
return m_str;
}
//____________________________________________________________________________//
// ************************************************************************** //
// ************** TOOL BOX Implementation ************** //
// ************************************************************************** //
void
checkpoint_impl( wrapstrstream const& message, char const* file_name, int line_num )
{
BOOST_UT_LOG_BEGIN( file_name, line_num, report_test_suites )
checkpoint( message.str() )
BOOST_UT_LOG_END
}
//____________________________________________________________________________//
void
message_impl( wrapstrstream const& message, char const* file_name, int line_num )
{
BOOST_UT_LOG_BEGIN( file_name, line_num, report_messages )
message.str()
BOOST_UT_LOG_END
}
//____________________________________________________________________________//
void
warn_and_continue_impl( bool predicate, wrapstrstream const& message,
char const* file_name, int line_num, bool add_fail_pass )
{
if( !predicate ) {
BOOST_UT_LOG_BEGIN( file_name, line_num, report_warnings )
(add_fail_pass ? "condition " : "") << message.str() << (add_fail_pass ? " is not satisfied" : "" )
BOOST_UT_LOG_END
}
else {
BOOST_UT_LOG_BEGIN( file_name, line_num, report_successful_tests )
"condition " << message.str() << " is satisfied"
BOOST_UT_LOG_END
}
}
//____________________________________________________________________________//
void
warn_and_continue_impl( extended_predicate_value const& v, wrapstrstream const& message, char const* file_name, int line_num,
bool add_fail_pass )
{
warn_and_continue_impl( !!v,
message << (add_fail_pass && !v ? " is not satisfied" : "" ) << *(v.p_message),
file_name, line_num, false );
}
//____________________________________________________________________________//
bool
test_and_continue_impl( bool predicate, wrapstrstream const& message,
char const* file_name, int line_num,
bool add_fail_pass, report_level loglevel )
{
if( !predicate ) {
unit_test_result::instance().inc_failed_assertions();
BOOST_UT_LOG_BEGIN( file_name, line_num, loglevel )
(add_fail_pass ? "test " : "") << message.str() << (add_fail_pass ? " failed" : "")
BOOST_UT_LOG_END
return true;
}
else {
unit_test_result::instance().inc_passed_assertions();
BOOST_UT_LOG_BEGIN( file_name, line_num, report_successful_tests )
(add_fail_pass ? "test " : "") << message.str() << (add_fail_pass ? " passed" : "")
BOOST_UT_LOG_END
return false;
}
}
//____________________________________________________________________________//
bool
test_and_continue_impl( extended_predicate_value const& v, wrapstrstream const& message,
char const* file_name, int line_num,
bool add_fail_pass, report_level loglevel )
{
return test_and_continue_impl( !!v,
message << (add_fail_pass ? (!v ? " failed" : " passed") : "") << *(v.p_message),
file_name, line_num, false, loglevel );
}
//____________________________________________________________________________//
void
test_and_throw_impl( bool predicate, wrapstrstream const& message,
char const* file_name, int line_num,
bool add_fail_pass, report_level loglevel )
{
if( test_and_continue_impl( predicate, message, file_name, line_num, add_fail_pass, loglevel ) ) {
throw test_tool_failed( "" ); // error already reported by test_and_continue_impl
}
}
//____________________________________________________________________________//
void
test_and_throw_impl( extended_predicate_value const& v, wrapstrstream const& message,
char const* file_name, int line_num,
bool add_fail_pass, report_level loglevel )
{
if( test_and_continue_impl( v, message, file_name, line_num, add_fail_pass, loglevel ) ) {
throw test_tool_failed( "" ); // error already reported by test_and_continue_impl
}
}
//____________________________________________________________________________//
bool
equal_and_continue_impl( char const* left, char const* right, wrapstrstream const& message,
char const* file_name, int line_num,
report_level loglevel )
{
bool predicate = std::strcmp( left, right ) == 0;
if( !predicate ) {
return test_and_continue_impl( predicate,
wrapstrstream() << "test " << message.str() << " failed [" << left << " != " << right << "]",
file_name, line_num, false, loglevel );
}
return test_and_continue_impl( predicate, message, file_name, line_num, true, loglevel );
}
//____________________________________________________________________________//
bool
is_defined_impl( char const* symbol_name, char const* symbol_value )
{
return std::strcmp( symbol_name, symbol_value+1 ) != 0;
}
//____________________________________________________________________________//
} // namespace detail
// ************************************************************************** //
// ************** output_test_stream ************** //
// ************************************************************************** //
struct output_test_stream::Impl
{
std::fstream m_pattern_to_match_or_save;
bool m_match_or_save;
std::string m_synced_string;
void check_and_fill( detail::extended_predicate_value& res )
{
if( !res.p_predicate_value.get() )
*(res.p_message) << ". Output content: \"" << m_synced_string << '\"';
}
};
//____________________________________________________________________________//
output_test_stream::output_test_stream( char const* pattern_file, bool match_or_save )
: m_pimpl( new Impl )
{
if( pattern_file != NULL && pattern_file[0] != '\0' )
m_pimpl->m_pattern_to_match_or_save.open( pattern_file, match_or_save ? std::ios::in : std::ios::out );
m_pimpl->m_match_or_save = match_or_save;
}
//____________________________________________________________________________//
output_test_stream::~output_test_stream()
{
}
//____________________________________________________________________________//
detail::extended_predicate_value
output_test_stream::is_empty( bool flush_stream )
{
sync();
result_type res( m_pimpl->m_synced_string.empty() );
m_pimpl->check_and_fill( res );
if( flush_stream )
flush();
return res;
}
//____________________________________________________________________________//
detail::extended_predicate_value
output_test_stream::check_length( std::size_t length_, bool flush_stream )
{
sync();
result_type res( m_pimpl->m_synced_string.length() == length_ );
m_pimpl->check_and_fill( res );
if( flush_stream )
flush();
return res;
}
//____________________________________________________________________________//
detail::extended_predicate_value
output_test_stream::is_equal( char const* arg, bool flush_stream )
{
sync();
result_type res( m_pimpl->m_synced_string == arg );
m_pimpl->check_and_fill( res );
if( flush_stream )
flush();
return res;
}
//____________________________________________________________________________//
detail::extended_predicate_value
output_test_stream::is_equal( std::string const& arg, bool flush_stream )
{
sync();
result_type res( m_pimpl->m_synced_string == arg );
m_pimpl->check_and_fill( res );
if( flush_stream )
flush();
return res;
}
//____________________________________________________________________________//
detail::extended_predicate_value
output_test_stream::is_equal( char const* arg, std::size_t n, bool flush_stream )
{
sync();
result_type res( m_pimpl->m_synced_string == std::string( arg, n ) );
m_pimpl->check_and_fill( res );
if( flush_stream )
flush();
return res;
}
//____________________________________________________________________________//
bool
output_test_stream::match_pattern( bool flush_stream )
{
sync();
bool result = true;
if( !m_pimpl->m_pattern_to_match_or_save.is_open() )
result = false;
else {
if( m_pimpl->m_match_or_save ) {
char const* ptr = m_pimpl->m_synced_string.c_str();
for( std::size_t i = 0; i != m_pimpl->m_synced_string.length(); i++, ptr++ ) {
char c;
m_pimpl->m_pattern_to_match_or_save.get( c );
if( m_pimpl->m_pattern_to_match_or_save.fail() ||
m_pimpl->m_pattern_to_match_or_save.eof() )
{
result = false;
break;
}
if( *ptr != c ) {
result = false;
}
}
}
else {
m_pimpl->m_pattern_to_match_or_save.write( m_pimpl->m_synced_string.c_str(), m_pimpl->m_synced_string.length() );
m_pimpl->m_pattern_to_match_or_save.flush();
}
}
if( flush_stream )
flush();
return result;
}
//____________________________________________________________________________//
void
output_test_stream::flush()
{
m_pimpl->m_synced_string.erase();
seekp( 0, std::ios::beg );
#ifndef BOOST_NO_STRINGSTREAM
str( std::string() );
#endif
}
//____________________________________________________________________________//
std::size_t
output_test_stream::length()
{
sync();
return m_pimpl->m_synced_string.length();
}
//____________________________________________________________________________//
void
output_test_stream::sync()
{
#ifdef BOOST_NO_STRINGSTREAM
m_pimpl->m_synced_string.assign( str(), pcount() );
freeze( false );
#else
m_pimpl->m_synced_string = str();
#endif
}
//____________________________________________________________________________//
} // namespace test_toolbox
} // namespace boost
// ***************************************************************************
// Revision History :
//
// $Log$
// Revision 1.7 2002/08/20 22:10:30 rogeeff
// slightly modified failures report
//
// Revision 1.6 2002/08/20 08:24:13 rogeeff
// cvs keywords added
//
// 5 Oct 01 Reworked version (Gennadiy Rozental)
// ? ??? 01 Initial version (Ullrich Koethe)
// ***************************************************************************
// EOF
<commit_msg>Exclude using namespace for included use flush bud for new stringstream fixed<commit_after>// (C) Copyright Ullrich Koethe 2001, Gennadiy Rozental 2001-2002.
// Permission to copy, use, modify, sell and distribute this software
// is granted provided this copyright notice appears in all copies.
// This software is provided "as is" without express or implied warranty,
// and with no claim as to its suitability for any purpose.
// See http://www.boost.org for updates, documentation, and revision history.
//
// File : $RCSfile$
//
// Version : $Id$
//
// Description : supplies offline implemtation for the Test Tools
// ***************************************************************************
// LOCAL
#include <boost/test/test_tools.hpp>
#include <boost/test/unit_test_result.hpp>
// BOOST
#include <boost/config.hpp>
// STL
#include <fstream>
#include <iostream>
#include <algorithm>
#include <cstring>
#include <string>
# ifdef BOOST_NO_STDC_NAMESPACE
namespace std { using ::strcmp; using ::strncmp; using ::strlen; }
# endif
namespace boost {
namespace test_toolbox {
namespace detail {
// ************************************************************************** //
// ************** wrapstrstream ************** //
// ************************************************************************** //
std::string&
wrapstrstream::str() const {
#ifdef BOOST_NO_STRINGSTREAM
m_str.assign( m_buf.str(), m_buf.pcount() );
m_buf.freeze( false );
#else
m_str = m_buf.str();
#endif
return m_str;
}
//____________________________________________________________________________//
// ************************************************************************** //
// ************** TOOL BOX Implementation ************** //
// ************************************************************************** //
void
checkpoint_impl( wrapstrstream const& message, char const* file_name, int line_num )
{
BOOST_UT_LOG_BEGIN( file_name, line_num, unit_test_framework::report_test_suites )
unit_test_framework::checkpoint( message.str() )
BOOST_UT_LOG_END
}
//____________________________________________________________________________//
void
message_impl( wrapstrstream const& message, char const* file_name, int line_num )
{
BOOST_UT_LOG_BEGIN( file_name, line_num, unit_test_framework::report_messages )
message.str()
BOOST_UT_LOG_END
}
//____________________________________________________________________________//
void
warn_and_continue_impl( bool predicate, wrapstrstream const& message,
char const* file_name, int line_num, bool add_fail_pass )
{
if( !predicate ) {
BOOST_UT_LOG_BEGIN( file_name, line_num, unit_test_framework::report_warnings )
(add_fail_pass ? "condition " : "") << message.str() << (add_fail_pass ? " is not satisfied" : "" )
BOOST_UT_LOG_END
}
else {
BOOST_UT_LOG_BEGIN( file_name, line_num, unit_test_framework::report_successful_tests )
"condition " << message.str() << " is satisfied"
BOOST_UT_LOG_END
}
}
//____________________________________________________________________________//
void
warn_and_continue_impl( extended_predicate_value const& v, wrapstrstream const& message, char const* file_name, int line_num,
bool add_fail_pass )
{
warn_and_continue_impl( !!v,
message << (add_fail_pass && !v ? " is not satisfied" : "" ) << *(v.p_message),
file_name, line_num, false );
}
//____________________________________________________________________________//
bool
test_and_continue_impl( bool predicate, wrapstrstream const& message,
char const* file_name, int line_num,
bool add_fail_pass, unit_test_framework::report_level loglevel )
{
if( !predicate ) {
unit_test_framework::unit_test_result::instance().inc_failed_assertions();
BOOST_UT_LOG_BEGIN( file_name, line_num, loglevel )
(add_fail_pass ? "test " : "") << message.str() << (add_fail_pass ? " failed" : "")
BOOST_UT_LOG_END
return true;
}
else {
unit_test_framework::unit_test_result::instance().inc_passed_assertions();
BOOST_UT_LOG_BEGIN( file_name, line_num, unit_test_framework::report_successful_tests )
(add_fail_pass ? "test " : "") << message.str() << (add_fail_pass ? " passed" : "")
BOOST_UT_LOG_END
return false;
}
}
//____________________________________________________________________________//
bool
test_and_continue_impl( extended_predicate_value const& v, wrapstrstream const& message,
char const* file_name, int line_num,
bool add_fail_pass, unit_test_framework::report_level loglevel )
{
return test_and_continue_impl( !!v,
message << (add_fail_pass ? (!v ? " failed" : " passed") : "") << *(v.p_message),
file_name, line_num, false, loglevel );
}
//____________________________________________________________________________//
void
test_and_throw_impl( bool predicate, wrapstrstream const& message,
char const* file_name, int line_num,
bool add_fail_pass, unit_test_framework::report_level loglevel )
{
if( test_and_continue_impl( predicate, message, file_name, line_num, add_fail_pass, loglevel ) ) {
throw test_tool_failed( "" ); // error already reported by test_and_continue_impl
}
}
//____________________________________________________________________________//
void
test_and_throw_impl( extended_predicate_value const& v, wrapstrstream const& message,
char const* file_name, int line_num,
bool add_fail_pass, unit_test_framework::report_level loglevel )
{
if( test_and_continue_impl( v, message, file_name, line_num, add_fail_pass, loglevel ) ) {
throw test_tool_failed( "" ); // error already reported by test_and_continue_impl
}
}
//____________________________________________________________________________//
bool
equal_and_continue_impl( char const* left, char const* right, wrapstrstream const& message,
char const* file_name, int line_num,
unit_test_framework::report_level loglevel )
{
bool predicate = std::strcmp( left, right ) == 0;
if( !predicate ) {
return test_and_continue_impl( predicate,
wrapstrstream() << "test " << message.str() << " failed [" << left << " != " << right << "]",
file_name, line_num, false, loglevel );
}
return test_and_continue_impl( predicate, message, file_name, line_num, true, loglevel );
}
//____________________________________________________________________________//
bool
is_defined_impl( char const* symbol_name, char const* symbol_value )
{
return std::strcmp( symbol_name, symbol_value+1 ) != 0;
}
//____________________________________________________________________________//
} // namespace detail
// ************************************************************************** //
// ************** output_test_stream ************** //
// ************************************************************************** //
struct output_test_stream::Impl
{
std::fstream m_pattern_to_match_or_save;
bool m_match_or_save;
std::string m_synced_string;
void check_and_fill( detail::extended_predicate_value& res )
{
if( !res.p_predicate_value.get() )
*(res.p_message) << ". Output content: \"" << m_synced_string << '\"';
}
};
//____________________________________________________________________________//
output_test_stream::output_test_stream( char const* pattern_file, bool match_or_save )
: m_pimpl( new Impl )
{
if( pattern_file != NULL && pattern_file[0] != '\0' )
m_pimpl->m_pattern_to_match_or_save.open( pattern_file, match_or_save ? std::ios::in : std::ios::out );
m_pimpl->m_match_or_save = match_or_save;
}
//____________________________________________________________________________//
output_test_stream::~output_test_stream()
{
}
//____________________________________________________________________________//
detail::extended_predicate_value
output_test_stream::is_empty( bool flush_stream )
{
sync();
result_type res( m_pimpl->m_synced_string.empty() );
m_pimpl->check_and_fill( res );
if( flush_stream )
flush();
return res;
}
//____________________________________________________________________________//
detail::extended_predicate_value
output_test_stream::check_length( std::size_t length_, bool flush_stream )
{
sync();
result_type res( m_pimpl->m_synced_string.length() == length_ );
m_pimpl->check_and_fill( res );
if( flush_stream )
flush();
return res;
}
//____________________________________________________________________________//
detail::extended_predicate_value
output_test_stream::is_equal( char const* arg, bool flush_stream )
{
sync();
result_type res( m_pimpl->m_synced_string == arg );
m_pimpl->check_and_fill( res );
if( flush_stream )
flush();
return res;
}
//____________________________________________________________________________//
detail::extended_predicate_value
output_test_stream::is_equal( std::string const& arg, bool flush_stream )
{
sync();
result_type res( m_pimpl->m_synced_string == arg );
m_pimpl->check_and_fill( res );
if( flush_stream )
flush();
return res;
}
//____________________________________________________________________________//
detail::extended_predicate_value
output_test_stream::is_equal( char const* arg, std::size_t n, bool flush_stream )
{
sync();
result_type res( m_pimpl->m_synced_string == std::string( arg, n ) );
m_pimpl->check_and_fill( res );
if( flush_stream )
flush();
return res;
}
//____________________________________________________________________________//
bool
output_test_stream::match_pattern( bool flush_stream )
{
sync();
bool result = true;
if( !m_pimpl->m_pattern_to_match_or_save.is_open() )
result = false;
else {
if( m_pimpl->m_match_or_save ) {
char const* ptr = m_pimpl->m_synced_string.c_str();
for( std::size_t i = 0; i != m_pimpl->m_synced_string.length(); i++, ptr++ ) {
char c;
m_pimpl->m_pattern_to_match_or_save.get( c );
if( m_pimpl->m_pattern_to_match_or_save.fail() ||
m_pimpl->m_pattern_to_match_or_save.eof() )
{
result = false;
break;
}
if( *ptr != c ) {
result = false;
}
}
}
else {
m_pimpl->m_pattern_to_match_or_save.write( m_pimpl->m_synced_string.c_str(), m_pimpl->m_synced_string.length() );
m_pimpl->m_pattern_to_match_or_save.flush();
}
}
if( flush_stream )
flush();
return result;
}
//____________________________________________________________________________//
void
output_test_stream::flush()
{
m_pimpl->m_synced_string.erase();
#ifndef BOOST_NO_STRINGSTREAM
str( std::string() );
#else
seekp( 0, std::ios::beg );
#endif
}
//____________________________________________________________________________//
std::size_t
output_test_stream::length()
{
sync();
return m_pimpl->m_synced_string.length();
}
//____________________________________________________________________________//
void
output_test_stream::sync()
{
#ifdef BOOST_NO_STRINGSTREAM
m_pimpl->m_synced_string.assign( str(), pcount() );
freeze( false );
#else
m_pimpl->m_synced_string = str();
#endif
}
//____________________________________________________________________________//
} // namespace test_toolbox
} // namespace boost
// ***************************************************************************
// Revision History :
//
// $Log$
// Revision 1.8 2002/08/26 08:28:31 rogeeff
// Exclude using namespace for included use
// flush bud for new stringstream fixed
//
// Revision 1.7 2002/08/20 22:10:30 rogeeff
// slightly modified failures report
//
// Revision 1.6 2002/08/20 08:24:13 rogeeff
// cvs keywords added
//
// 5 Oct 01 Reworked version (Gennadiy Rozental)
// ? ??? 01 Initial version (Ullrich Koethe)
// ***************************************************************************
// EOF
<|endoftext|> |
<commit_before>#include <puppet/runtime/string_interpolator.hpp>
#include <puppet/parser/parser.hpp>
#include <boost/format.hpp>
#include <codecvt>
#include <cctype>
#include <sstream>
using namespace std;
using namespace puppet::lexer;
using namespace puppet::parser;
using namespace puppet::runtime::values;
namespace puppet { namespace runtime {
template <typename Value>
struct hex_to
{
operator Value() const
{
return value;
}
friend istream& operator>>(istream& in, hex_to& out)
{
in >> std::hex >> out.value;
return in;
}
private:
Value value;
};
static bool tokenize_interpolation(
string& result,
expression_evaluator& evaluator,
lexer_string_iterator begin,
lexer_string_iterator const& end,
function<token_position(token_position const&)> const& calculate_position)
{
bool bracket = begin != end && *begin == '{';
string_static_lexer lexer;
// Check for keyword or name
value const* val = nullptr;
try {
auto token_begin = lexer.begin(begin, end);
auto token_end = lexer.end();
// Check for the following forms:
// {keyword}, {name/bare_word}, {decimal}
// name, decimal
// Skip past the opening bracket
if (bracket && token_begin != token_end && token_begin->id() == '{') {
++token_begin;
}
if (token_begin != token_end &&
(
is_keyword(static_cast<token_id>(token_begin->id())) ||
token_begin->id() == static_cast<size_t>(token_id::name) ||
token_begin->id() == static_cast<size_t>(token_id::bare_word)
)) {
auto token = get<boost::iterator_range<lexer_string_iterator>>(&token_begin->value());
if (!token) {
return false;
}
val = evaluator.context().lookup(string(token->begin(), token->end()));
++token_begin;
} else if (token_begin != token_end && token_begin->id() == static_cast<size_t>(token_id::number)) {
auto token = get<number_token>(&token_begin->value());
if (!token) {
return false;
}
if (token->base() != numeric_base::decimal || token->value().which() != 0) {
throw evaluation_exception(calculate_position(token->position()), (boost::format("'%1%' is not a valid match variable name.") % *token).str());
}
val = evaluator.context().current().get(get<int64_t>(token->value()));
++token_begin;
} else {
return false;
}
// Check for not parsed or missing a closing } token
if (bracket && (token_begin == token_end || token_begin->id() != '}')) {
return false;
}
} catch (lexer_exception<lexer_string_iterator> const& ex) {
throw evaluation_exception(calculate_position(ex.location().position()), ex.what());
}
// Output the variable
if (val) {
ostringstream ss;
ss << *val;
result += ss.str();
}
return true;
}
static boost::optional<value> transform_expression(expression_evaluator& evaluator, ast::expression const& expression)
{
// Check for a postfix expression
auto postfix = boost::get<ast::postfix_expression>(&expression.primary());
if (!postfix || postfix->subexpressions().empty()) {
return boost::none;
}
// Check for access or method call
auto& subexpression = postfix->subexpressions().front();
if (!boost::get<ast::access_expression>(&subexpression) &&
!boost::get<ast::method_call_expression>(&subexpression)) {
return boost::none;
}
// If the expression is a name followed by an access operation or method call, treat as a variable
auto basic = boost::get<ast::basic_expression>(&postfix->primary());
if (!basic) {
return boost::none;
}
token_position variable_position;
string variable_name;
// Check for name
auto name = boost::get<ast::name>(basic);
if (name) {
variable_position = name->position();
variable_name = name->value();
} else {
// Also check for bare word
auto word = boost::get<ast::bare_word>(basic);
if (word) {
variable_position = word->position();
variable_name = word->value();
}
}
if (variable_name.empty()) {
return boost::none;
}
return evaluator.evaluate(ast::expression(ast::postfix_expression(ast::basic_expression(ast::variable(std::move(variable_name), std::move(variable_position))), postfix->subexpressions()), expression.binary()));
}
string_interpolator::string_interpolator(expression_evaluator& evaluator) :
_evaluator(evaluator)
{
}
string string_interpolator::interpolate(token_position const& position, string const& text, string const& escapes, char quote, bool full, int margin, bool remove_break)
{
// Helper function for calculating a position inside the string being interpolated
function<token_position(token_position const&)> calculate_position = [&](token_position const& other) {
return make_tuple(get<0>(position) + get<0>(other) + (quote ? 1 : 0), get<1>(position) + get<1>(other) - 1);
};
lexer_string_iterator begin(text.begin());
lexer_string_iterator end(text.end());
string result;
result.reserve(text.size());
int current_margin = margin;
while (begin != end) {
// This logic handles heredocs with margin specifiers (margin > 0)
for (; current_margin > 0 && begin != end; ++begin) {
// If we've found a non-whitespace character, we're done
if (*begin != ' ' && *begin != '\t') {
break;
}
// If we've found a tab, decrement by the tab width
if (*begin == '\t') {
current_margin -= (current_margin > LEXER_TAB_WIDTH ? LEXER_TAB_WIDTH : current_margin);
} else {
current_margin -= 1;
}
}
if (begin == end) {
break;
}
// No more margin for this line
current_margin = 0;
// Perform escape replacements
if (*begin == '\\' && !escapes.empty()) {
auto next = begin;
++next;
if (next != end && *next == '\r') {
++next;
}
if (next != end && escapes.find(*next) != string::npos) {
bool success = true;
switch (*next) {
case 'r':
result += '\r';
break;
case 'n':
result += '\n';
break;
case 't':
result += '\t';
break;
case 's':
result += ' ';
break;
case 'u':
success = write_unicode_escape_sequence(calculate_position(begin.position()), ++next, end, result);
break;
case '\n':
// Treat as new line, so reset the margin
current_margin = margin;
break;
case '$':
result += '$';
break;
default:
result += *next;
break;
}
if (success) {
begin = ++next;
continue;
}
} else if (next != end) {
// Emit a warning for invalid escape sequence (unless single quoted string)
if (quote != '\'') {
_evaluator.context().warn(calculate_position(begin.position()), (boost::format("invalid escape sequence '\\%1%'.") % *next).str());
}
}
} else if (*begin == '\n') {
// Reset the margin
current_margin = margin;
} else if (full && *begin == '$') {
auto next = begin;
++next;
if (next != end && !isspace(*next)) {
// First attempt to interpolate using the lexer
if (tokenize_interpolation(result, _evaluator, next, end, calculate_position)) {
// Success, update the iterator
if (*next == '{') {
// Move to closing }
for (begin = next; begin != end && *begin != '}'; ++begin);
} else {
// Move to first whitespace character
for (begin = next; begin != end && !isspace(*begin); ++begin);
}
if (begin != end) {
++begin;
}
continue;
}
// Otherwise, check for expression form
if (*next == '{') {
try {
// Parse the rest of the string as a manifest
// The parsing will stop at the first unmatched } token
auto manifest = parser::parser::parse(next, end, true);
if (manifest.body()) {
// Evaluate the body and add the result to the string
value val;
bool first = true;
for (auto& expression : *manifest.body()) {
// For the first expression, transform certain constructs to their "variable" forms
if (first) {
first = false;
auto result = transform_expression(_evaluator, expression);
if (result) {
val = *result;
continue;
}
}
val = _evaluator.evaluate(expression);
}
ostringstream ss;
ss << val;
result += ss.str();
}
// Move past where parsing stopped (must have been at the closing })
begin = lexer_string_iterator(text.begin() + get<0>(manifest.end()));
begin.position(manifest.end());
++begin;
continue;
} catch (parser::parse_exception const& ex) {
throw evaluation_exception(calculate_position(ex.position()), ex.what());
} catch (evaluation_exception const& ex) {
throw evaluation_exception(calculate_position(ex.position()), ex.what());
}
}
}
}
result += *begin++;
}
// Remove the trailing line break if instructed to do so
if (remove_break) {
if (boost::ends_with(text, "\n")) {
result.pop_back();
}
if (boost::ends_with(text, "\r")) {
result.pop_back();
}
}
return result;
}
bool string_interpolator::write_unicode_escape_sequence(token_position const& position, lexer_string_iterator& begin, lexer_string_iterator const& end, string& result, bool four_characters)
{
size_t count = four_characters ? 4 : 8;
// Use a buffer that can store up to 8 characters (nnnn or nnnnnnnn)
char buffer[9] = {};
size_t read = 0;
for (; begin != end; ++begin) {
if (!isxdigit(*begin)) {
break;
}
buffer[read] = *begin;
if (++read == 4) {
break;
}
}
if (read != count) {
_evaluator.context().warn(position, (boost::format("expected %1% hexadecimal digits but found %2% for unicode escape sequence.") % count % read).str());
return false;
}
// Convert the input to a utf32 character (supports both four or eight hex characters)
char32_t from;
try {
from = static_cast<char32_t>(boost::lexical_cast<hex_to<uint32_t>>(buffer));
} catch (boost::bad_lexical_cast const&) {
_evaluator.context().warn(position, "invalid unicode escape sequence.");
return false;
}
// Convert the utf32 character to utf8 bytes (maximum is 4 bytes)
codecvt_utf8<char32_t> converter;
char32_t const* next_from = nullptr;
char* next_to = nullptr;
auto state = mbstate_t();
converter.out(state, &from, &from + 1, next_from, buffer, &buffer[0] + 4, next_to);
// Ensure all characters were converted (there was only one)
if (next_from != &from + 1) {
_evaluator.context().warn(position, "invalid unicode code point.");
return false;
}
// Output the number of bytes converted
for (size_t i = 0; (&buffer[0] + i) < next_to; ++i) {
result += buffer[i];
}
return true;
}
}} // namespace puppet::runtime<commit_msg>Fix simple string interpolation not ending at the right position.<commit_after>#include <puppet/runtime/string_interpolator.hpp>
#include <puppet/parser/parser.hpp>
#include <boost/format.hpp>
#include <codecvt>
#include <cctype>
#include <sstream>
using namespace std;
using namespace puppet::lexer;
using namespace puppet::parser;
using namespace puppet::runtime::values;
namespace puppet { namespace runtime {
template <typename Value>
struct hex_to
{
operator Value() const
{
return value;
}
friend istream& operator>>(istream& in, hex_to& out)
{
in >> std::hex >> out.value;
return in;
}
private:
Value value;
};
static bool tokenize_interpolation(
string& result,
expression_evaluator& evaluator,
lexer_string_iterator& begin,
lexer_string_iterator const& end,
function<token_position(token_position const&)> const& calculate_position)
{
try {
bool bracket = begin != end && *begin == '{';
string_static_lexer lexer;
// Check for keyword or name
value const* val = nullptr;
auto current = begin;
auto token_begin = lexer.begin(current, end);
auto token_end = lexer.end();
// Check for the following forms:
// {keyword}, {name/bare_word}, {decimal}
// name, decimal
// Skip past the opening bracket
if (bracket && token_begin != token_end && token_begin->id() == '{') {
++token_begin;
}
if (token_begin != token_end &&
(
is_keyword(static_cast<token_id>(token_begin->id())) ||
token_begin->id() == static_cast<size_t>(token_id::name) ||
token_begin->id() == static_cast<size_t>(token_id::bare_word)
)) {
auto token = get<boost::iterator_range<lexer_string_iterator>>(&token_begin->value());
if (!token) {
return false;
}
val = evaluator.context().lookup(string(token->begin(), token->end()));
} else if (token_begin != token_end && token_begin->id() == static_cast<size_t>(token_id::number)) {
auto token = get<number_token>(&token_begin->value());
if (!token) {
return false;
}
if (token->base() != numeric_base::decimal || token->value().which() != 0) {
throw evaluation_exception(calculate_position(token->position()), (boost::format("'%1%' is not a valid match variable name.") % *token).str());
}
val = evaluator.context().current().get(get<int64_t>(token->value()));
} else {
return false;
}
// If bracketed, look for the closing bracket
if (bracket) {
++token_begin;
// Check for not parsed or missing a closing } token
if (bracket && (token_begin == token_end || token_begin->id() != '}')) {
return false;
}
}
// Output the variable
if (val) {
ostringstream ss;
ss << *val;
result += ss.str();
}
// Update to where we stopped lexing
begin = current;
return true;
} catch (lexer_exception<lexer_string_iterator> const& ex) {
throw evaluation_exception(calculate_position(ex.location().position()), ex.what());
}
}
static boost::optional<value> transform_expression(expression_evaluator& evaluator, ast::expression const& expression)
{
// Check for a postfix expression
auto postfix = boost::get<ast::postfix_expression>(&expression.primary());
if (!postfix || postfix->subexpressions().empty()) {
return boost::none;
}
// Check for access or method call
auto& subexpression = postfix->subexpressions().front();
if (!boost::get<ast::access_expression>(&subexpression) &&
!boost::get<ast::method_call_expression>(&subexpression)) {
return boost::none;
}
// If the expression is a name followed by an access operation or method call, treat as a variable
auto basic = boost::get<ast::basic_expression>(&postfix->primary());
if (!basic) {
return boost::none;
}
token_position variable_position;
string variable_name;
// Check for name
auto name = boost::get<ast::name>(basic);
if (name) {
variable_position = name->position();
variable_name = name->value();
} else {
// Also check for bare word
auto word = boost::get<ast::bare_word>(basic);
if (word) {
variable_position = word->position();
variable_name = word->value();
}
}
if (variable_name.empty()) {
return boost::none;
}
return evaluator.evaluate(ast::expression(ast::postfix_expression(ast::basic_expression(ast::variable(std::move(variable_name), std::move(variable_position))), postfix->subexpressions()), expression.binary()));
}
string_interpolator::string_interpolator(expression_evaluator& evaluator) :
_evaluator(evaluator)
{
}
string string_interpolator::interpolate(token_position const& position, string const& text, string const& escapes, char quote, bool full, int margin, bool remove_break)
{
// Helper function for calculating a position inside the string being interpolated
function<token_position(token_position const&)> calculate_position = [&](token_position const& other) {
return make_tuple(get<0>(position) + get<0>(other) + (quote ? 1 : 0), get<1>(position) + get<1>(other) - 1);
};
lexer_string_iterator begin(text.begin());
lexer_string_iterator end(text.end());
string result;
result.reserve(text.size());
int current_margin = margin;
while (begin != end) {
// This logic handles heredocs with margin specifiers (margin > 0)
for (; current_margin > 0 && begin != end; ++begin) {
// If we've found a non-whitespace character, we're done
if (*begin != ' ' && *begin != '\t') {
break;
}
// If we've found a tab, decrement by the tab width
if (*begin == '\t') {
current_margin -= (current_margin > LEXER_TAB_WIDTH ? LEXER_TAB_WIDTH : current_margin);
} else {
current_margin -= 1;
}
}
if (begin == end) {
break;
}
// No more margin for this line
current_margin = 0;
// Perform escape replacements
if (*begin == '\\' && !escapes.empty()) {
auto next = begin;
++next;
if (next != end && *next == '\r') {
++next;
}
if (next != end && escapes.find(*next) != string::npos) {
bool success = true;
switch (*next) {
case 'r':
result += '\r';
break;
case 'n':
result += '\n';
break;
case 't':
result += '\t';
break;
case 's':
result += ' ';
break;
case 'u':
success = write_unicode_escape_sequence(calculate_position(begin.position()), ++next, end, result);
break;
case '\n':
// Treat as new line, so reset the margin
current_margin = margin;
break;
case '$':
result += '$';
break;
default:
result += *next;
break;
}
if (success) {
begin = ++next;
continue;
}
} else if (next != end) {
// Emit a warning for invalid escape sequence (unless single quoted string)
if (quote != '\'') {
_evaluator.context().warn(calculate_position(begin.position()), (boost::format("invalid escape sequence '\\%1%'.") % *next).str());
}
}
} else if (*begin == '\n') {
// Reset the margin
current_margin = margin;
} else if (full && *begin == '$') {
auto next = begin;
++next;
if (next != end && !isspace(*next)) {
// First attempt to interpolate using the lexer
if (tokenize_interpolation(result, _evaluator, next, end, calculate_position)) {
begin = next;
continue;
}
// Otherwise, check for expression form
if (*next == '{') {
try {
// Parse the rest of the string as a manifest
// The parsing will stop at the first unmatched } token
auto manifest = parser::parser::parse(next, end, true);
if (manifest.body()) {
// Evaluate the body and add the result to the string
value val;
bool first = true;
for (auto& expression : *manifest.body()) {
// For the first expression, transform certain constructs to their "variable" forms
if (first) {
first = false;
auto result = transform_expression(_evaluator, expression);
if (result) {
val = *result;
continue;
}
}
val = _evaluator.evaluate(expression);
}
ostringstream ss;
ss << val;
result += ss.str();
}
// Move past where parsing stopped (must have been at the closing })
begin = lexer_string_iterator(text.begin() + get<0>(manifest.end()));
begin.position(manifest.end());
++begin;
continue;
} catch (parser::parse_exception const& ex) {
throw evaluation_exception(calculate_position(ex.position()), ex.what());
} catch (evaluation_exception const& ex) {
throw evaluation_exception(calculate_position(ex.position()), ex.what());
}
}
}
}
result += *begin++;
}
// Remove the trailing line break if instructed to do so
if (remove_break) {
if (boost::ends_with(text, "\n")) {
result.pop_back();
}
if (boost::ends_with(text, "\r")) {
result.pop_back();
}
}
return result;
}
bool string_interpolator::write_unicode_escape_sequence(token_position const& position, lexer_string_iterator& begin, lexer_string_iterator const& end, string& result, bool four_characters)
{
size_t count = four_characters ? 4 : 8;
// Use a buffer that can store up to 8 characters (nnnn or nnnnnnnn)
char buffer[9] = {};
size_t read = 0;
for (; begin != end; ++begin) {
if (!isxdigit(*begin)) {
break;
}
buffer[read] = *begin;
if (++read == 4) {
break;
}
}
if (read != count) {
_evaluator.context().warn(position, (boost::format("expected %1% hexadecimal digits but found %2% for unicode escape sequence.") % count % read).str());
return false;
}
// Convert the input to a utf32 character (supports both four or eight hex characters)
char32_t from;
try {
from = static_cast<char32_t>(boost::lexical_cast<hex_to<uint32_t>>(buffer));
} catch (boost::bad_lexical_cast const&) {
_evaluator.context().warn(position, "invalid unicode escape sequence.");
return false;
}
// Convert the utf32 character to utf8 bytes (maximum is 4 bytes)
codecvt_utf8<char32_t> converter;
char32_t const* next_from = nullptr;
char* next_to = nullptr;
auto state = mbstate_t();
converter.out(state, &from, &from + 1, next_from, buffer, &buffer[0] + 4, next_to);
// Ensure all characters were converted (there was only one)
if (next_from != &from + 1) {
_evaluator.context().warn(position, "invalid unicode code point.");
return false;
}
// Output the number of bytes converted
for (size_t i = 0; (&buffer[0] + i) < next_to; ++i) {
result += buffer[i];
}
return true;
}
}} // namespace puppet::runtime<|endoftext|> |
<commit_before>/***************************Copyright-DO-NOT-REMOVE-THIS-LINE**
* CONDOR Copyright Notice
*
* See LICENSE.TXT for additional notices and disclaimers.
*
* Copyright (c)1990-1998 CONDOR Team, Computer Sciences Department,
* University of Wisconsin-Madison, Madison, WI. All Rights Reserved.
* No use of the CONDOR Software Program Source Code is authorized
* without the express consent of the CONDOR Team. For more information
* contact: CONDOR Team, Attention: Professor Miron Livny,
* 7367 Computer Sciences, 1210 W. Dayton St., Madison, WI 53706-1685,
* (608) 262-0856 or [email protected].
*
* U.S. Government Rights Restrictions: Use, duplication, or disclosure
* by the U.S. Government is subject to restrictions as set forth in
* subparagraph (c)(1)(ii) of The Rights in Technical Data and Computer
* Software clause at DFARS 252.227-7013 or subparagraphs (c)(1) and
* (2) of Commercial Computer Software-Restricted Rights at 48 CFR
* 52.227-19, as applicable, CONDOR Team, Attention: Professor Miron
* Livny, 7367 Computer Sciences, 1210 W. Dayton St., Madison,
* WI 53706-1685, (608) 262-0856 or [email protected].
****************************Copyright-DO-NOT-REMOVE-THIS-LINE**/
#include "condor_common.h"
#include "condor_debug.h"
#include "condor_q.h"
#include "condor_attributes.h"
#include "condor_adtypes.h"
#include "condor_qmgr.h"
#include "format_time.h"
#include "condor_classad.h"
// specify keyword lists; N.B. The order should follow from the category
// enumerations in the .h file
static const char *intKeywords[] =
{
ATTR_CLUSTER_ID,
ATTR_PROC_ID,
ATTR_JOB_STATUS,
ATTR_JOB_UNIVERSE
};
static const char *strKeywords[] =
{
ATTR_OWNER
};
static const char *fltKeywords[] =
{
"" // add one string to avoid compiler error
};
// need this global variable to hold information reqd by the scan function
// 30-Dec-2001: These no longer seem needed--nothing refers to them, there
// doesn't seem to be a scan function.
//static ClassAdList *__list;
//static ClassAd *__query;
CondorQ::
CondorQ ()
{
query.setNumIntegerCats (CQ_INT_THRESHOLD);
query.setNumStringCats (CQ_STR_THRESHOLD);
query.setNumFloatCats (CQ_FLT_THRESHOLD);
query.setIntegerKwList ((char **) intKeywords);
query.setStringKwList ((char **) strKeywords);
query.setFloatKwList ((char **) fltKeywords);
}
CondorQ::
~CondorQ ()
{
}
int CondorQ::
add (CondorQIntCategories cat, int value)
{
return query.addInteger (cat, value);
}
int CondorQ::
add (CondorQStrCategories cat, char *value)
{
return query.addString (cat, value);
}
int CondorQ::
add (CondorQFltCategories cat, float value)
{
return query.addFloat (cat, value);
}
int CondorQ::
addOR (char *value)
{
return query.addCustomOR (value);
}
int CondorQ::
addAND (char *value)
{
return query.addCustomAND (value);
}
int CondorQ::
fetchQueue (ClassAdList &list, ClassAd *ad)
{
Qmgr_connection *qmgr;
ClassAd filterAd;
int result;
char scheddString [32];
// make the query ad
if ((result = query.makeQuery (filterAd)) != Q_OK)
return result;
// insert types into the query ad ###
// filterAd.SetMyTypeName ("Query");
// filterAd.SetTargetTypeName ("Job");
filterAd.InsertAttr( ATTR_MY_TYPE, (string)QUERY_ADTYPE ); // NAC
filterAd.InsertAttr( ATTR_TARGET_TYPE, (string)JOB_ADTYPE ); // NAC
// connect to the Q manager
if (ad == 0)
{
// local case
if (!(qmgr = ConnectQ (0,20,true)))
return Q_SCHEDD_COMMUNICATION_ERROR;
}
else
{
// remote case to handle condor_globalq
// if (!ad->LookupString (ATTR_SCHEDD_IP_ADDR, scheddString))
if ( !ad->EvaluateAttrString( ATTR_SCHEDD_IP_ADDR, scheddString, 32 ) ) { // NAC
return Q_NO_SCHEDD_IP_ADDR;
}
if (!(qmgr = ConnectQ (scheddString,20,true))) {
return Q_SCHEDD_COMMUNICATION_ERROR;
}
}
// get the ads and filter them
getAndFilterAds (filterAd, list);
DisconnectQ (qmgr);
return Q_OK;
}
int CondorQ::
fetchQueueFromHost (ClassAdList &list, char *host)
{
Qmgr_connection *qmgr;
ClassAd filterAd;
int result;
// make the query ad
if ((result = query.makeQuery (filterAd)) != Q_OK)
return result;
// insert types into the query ad ###
// filterAd.SetMyTypeName ("Query");
// filterAd.SetTargetTypeName ("Job");
filterAd.InsertAttr( ATTR_MY_TYPE, (string)QUERY_ADTYPE ); // NAC
filterAd.InsertAttr( ATTR_TARGET_TYPE, (string)JOB_ADTYPE ); // NAC
/*
connect to the Q manager.
use a timeout of 20 seconds, and a read-only connection.
why 20 seconds? because careful research by Derek has shown
that whenever one needs a periodic time value, 20 is always
optimal. :^).
*/
if (!(qmgr = ConnectQ (host,20,true))) {
return Q_SCHEDD_COMMUNICATION_ERROR;
}
// get the ads and filter them
result = getAndFilterAds (filterAd, list);
DisconnectQ (qmgr);
return result;
}
int CondorQ::
fetchQueueFromHostAndProcess ( char *host, process_function process_func )
{
// DEBUG NAC
// printf("entered fetchQueueFromHostAndProcess\n"); // NAC
Qmgr_connection *qmgr;
ClassAd filterAd;
int result;
// make the query ad
if ((result = query.makeQuery (filterAd)) != Q_OK)
return result;
// insert types into the query ad ###
// filterAd.SetMyTypeName ("Query");
// filterAd.SetTargetTypeName ("Job");
filterAd.InsertAttr( ATTR_MY_TYPE, (string)QUERY_ADTYPE ); // NAC
filterAd.InsertAttr( ATTR_TARGET_TYPE, (string)JOB_ADTYPE ); // NAC
/*
connect to the Q manager.
use a timeout of 20 seconds, and a read-only connection.
why 20 seconds? because careful research by Derek has shown
that whenever one needs a periodic time value, 20 is always
optimal. :^).
*/
if (!(qmgr = ConnectQ (host,20,true)))
return Q_SCHEDD_COMMUNICATION_ERROR;
// get the ads and filter them
result = getFilterAndProcessAds (filterAd, process_func);
result = Q_OK; // NAC
DisconnectQ (qmgr);
// DEBUG NAC
// printf("exiting fetchQueueFromHostAndProcess\n"); // NAC
return result;
}
int CondorQ::
getFilterAndProcessAds( ClassAd &queryad, process_function process_func )
{
// DEBUG NAC
// printf("entered getFilterAndProcessAds\n"); // NAC
// char constraint[ATTRLIST_MAX_EXPRESSION]; /* yuk! */
char constraint[10240]; // NAC
string constraint_string; // NAC
ExprTree *tree;
ClassAd *ad;
ClassAdUnParser unp; // NAC
// constraint[0] = '\0';
tree = queryad.Lookup(ATTR_REQUIREMENTS);
// if (!tree) {
// return Q_INVALID_QUERY;
// }
// tree->RArg()->PrintToStr(constraint);
unp.Unparse( constraint_string, tree ); // NAC
// DEBUG NAC
// cout << "constraints_string = " << constraint_string << endl; // NAC
strncpy( constraint, constraint_string.c_str( ), 10240 ); // NAC
// DEBUG NAC
// cout << "constraint = " << constraint << endl; // NAC
if ((ad = GetNextJobByConstraint(constraint, 1)) != NULL) {
// Process the data and insert it into the list
if ( ( *process_func )( ad ) ) {
delete(ad);
}
while((ad = GetNextJobByConstraint(constraint, 0)) != NULL) {
// Process the data and insert it into the list
// DEBUG NAC
// cout << "about to call process_func" << endl;
if ( ( *process_func )( ad ) ) {
delete(ad);
}
// cout << "done process_func" << endl;
}
}
// DEBUG NAC
// cout << "done GetNextJobByConstraint" << endl;
// here GetNextJobByConstraint returned NULL. check if it was
// because of the network or not. if qmgmt had a problem with
// the net, then errno is set to ETIMEDOUT, and we should fail.
if ( errno == ETIMEDOUT ) {
return Q_SCHEDD_COMMUNICATION_ERROR;
}
// DEBUG NAC
// printf("exiting getFilterAndProcessAds\n"); // NAC
return Q_OK;
}
int CondorQ::
getAndFilterAds (ClassAd &queryad, ClassAdList &list)
{
// char constraint[ATTRLIST_MAX_EXPRESSION]; /* yuk! */
char constraint[10240]; // NAC
string constraint_string; // NAC
ExprTree *tree;
ClassAd *ad;
ClassAdUnParser unp; // NAC
// constraint[0] = '\0';
tree = queryad.Lookup( ATTR_REQUIREMENTS );
// if (!tree) {
// return Q_INVALID_QUERY;
// }
// tree->RArg()->PrintToStr(constraint);
unp.Unparse( constraint_string, tree ); // NAC
strncpy( constraint, constraint_string.c_str( ), 10240 ); // NAC
if ((ad = GetNextJobByConstraint(constraint, 1)) != NULL) {
list.Insert(ad);
while((ad = GetNextJobByConstraint(constraint, 0)) != NULL) {
list.Insert(ad);
}
}
// here GetNextJobByConstraint returned NULL. check if it was
// because of the network or not. if qmgmt had a problem with
// the net, then errno is set to ETIMEDOUT, and we should fail.
if ( errno == ETIMEDOUT ) {
return Q_SCHEDD_COMMUNICATION_ERROR;
}
return Q_OK;
}
int JobSort(ClassAd *job1, ClassAd *job2, void *data)
{
int cluster1=0, cluster2=0, proc1=0, proc2=0;
// job1->LookupInteger(ATTR_CLUSTER_ID, cluster1);
// job2->LookupInteger(ATTR_CLUSTER_ID, cluster2);
job1->EvaluateAttrInt( ATTR_CLUSTER_ID, cluster1 ); // NAC
job2->EvaluateAttrInt( ATTR_CLUSTER_ID, cluster2 ); // NAC
if (cluster1 < cluster2) return 1;
if (cluster1 > cluster2) return 0;
// job1->LookupInteger(ATTR_PROC_ID, proc1);
// job2->LookupInteger(ATTR_PROC_ID, proc2);
job1->EvaluateAttrInt( ATTR_PROC_ID, proc1 ); // NAC
job2->EvaluateAttrInt( ATTR_PROC_ID, proc2 ); // NAC
if (proc1 < proc2) return 1;
else return 0;
}
/*
Encode a status from a PROC structure as a single letter suited for
printing.
*/
const char
encode_status( int status )
{
switch( status ) {
case UNEXPANDED:
return 'U';
case IDLE:
return 'I';
case RUNNING:
return 'R';
case COMPLETED:
return 'C';
case REMOVED:
return 'X';
case HELD:
return 'H';
case SUBMISSION_ERR:
return 'E';
default:
return ' ';
}
}
/*
Print a line of data for the "short" display of a PROC structure. The
"short" display is the one used by "condor_q". N.B. the columns used
by this routine must match those defined by the short_header routine
defined above.
*/
void
short_print(
int cluster,
int proc,
const char *owner,
int date,
int time,
int status,
int prio,
int image_size,
const char *cmd
) {
printf( "%4d.%-3d %-14s %-11s %-12s %-2c %-3d %-4.1f %-18.18s\n",
cluster,
proc,
owner,
format_date((time_t)date),
format_time(time),
encode_status(status),
prio,
image_size/1024.0,
cmd
);
}
<commit_msg>changed variable name, "list" to ca_list, since "list" clashes with some other identifier on Windows in the same namespace.<commit_after>/***************************Copyright-DO-NOT-REMOVE-THIS-LINE**
* CONDOR Copyright Notice
*
* See LICENSE.TXT for additional notices and disclaimers.
*
* Copyright (c)1990-1998 CONDOR Team, Computer Sciences Department,
* University of Wisconsin-Madison, Madison, WI. All Rights Reserved.
* No use of the CONDOR Software Program Source Code is authorized
* without the express consent of the CONDOR Team. For more information
* contact: CONDOR Team, Attention: Professor Miron Livny,
* 7367 Computer Sciences, 1210 W. Dayton St., Madison, WI 53706-1685,
* (608) 262-0856 or [email protected].
*
* U.S. Government Rights Restrictions: Use, duplication, or disclosure
* by the U.S. Government is subject to restrictions as set forth in
* subparagraph (c)(1)(ii) of The Rights in Technical Data and Computer
* Software clause at DFARS 252.227-7013 or subparagraphs (c)(1) and
* (2) of Commercial Computer Software-Restricted Rights at 48 CFR
* 52.227-19, as applicable, CONDOR Team, Attention: Professor Miron
* Livny, 7367 Computer Sciences, 1210 W. Dayton St., Madison,
* WI 53706-1685, (608) 262-0856 or [email protected].
****************************Copyright-DO-NOT-REMOVE-THIS-LINE**/
#include "condor_common.h"
#include "condor_debug.h"
#include "condor_q.h"
#include "condor_attributes.h"
#include "condor_adtypes.h"
#include "condor_qmgr.h"
#include "format_time.h"
#include "condor_classad.h"
// specify keyword lists; N.B. The order should follow from the category
// enumerations in the .h file
static const char *intKeywords[] =
{
ATTR_CLUSTER_ID,
ATTR_PROC_ID,
ATTR_JOB_STATUS,
ATTR_JOB_UNIVERSE
};
static const char *strKeywords[] =
{
ATTR_OWNER
};
static const char *fltKeywords[] =
{
"" // add one string to avoid compiler error
};
// need this global variable to hold information reqd by the scan function
// 30-Dec-2001: These no longer seem needed--nothing refers to them, there
// doesn't seem to be a scan function.
//static ClassAdList *__list;
//static ClassAd *__query;
CondorQ::
CondorQ ()
{
query.setNumIntegerCats (CQ_INT_THRESHOLD);
query.setNumStringCats (CQ_STR_THRESHOLD);
query.setNumFloatCats (CQ_FLT_THRESHOLD);
query.setIntegerKwList ((char **) intKeywords);
query.setStringKwList ((char **) strKeywords);
query.setFloatKwList ((char **) fltKeywords);
}
CondorQ::
~CondorQ ()
{
}
int CondorQ::
add (CondorQIntCategories cat, int value)
{
return query.addInteger (cat, value);
}
int CondorQ::
add (CondorQStrCategories cat, char *value)
{
return query.addString (cat, value);
}
int CondorQ::
add (CondorQFltCategories cat, float value)
{
return query.addFloat (cat, value);
}
int CondorQ::
addOR (char *value)
{
return query.addCustomOR (value);
}
int CondorQ::
addAND (char *value)
{
return query.addCustomAND (value);
}
int CondorQ::
fetchQueue (ClassAdList &ca_list, ClassAd *ad)
{
Qmgr_connection *qmgr;
ClassAd filterAd;
int result;
char scheddString [32];
// make the query ad
if ((result = query.makeQuery (filterAd)) != Q_OK)
return result;
// insert types into the query ad ###
// filterAd.SetMyTypeName ("Query");
// filterAd.SetTargetTypeName ("Job");
filterAd.InsertAttr( ATTR_MY_TYPE, (string)QUERY_ADTYPE ); // NAC
filterAd.InsertAttr( ATTR_TARGET_TYPE, (string)JOB_ADTYPE ); // NAC
// connect to the Q manager
if (ad == 0)
{
// local case
if (!(qmgr = ConnectQ (0,20,true)))
return Q_SCHEDD_COMMUNICATION_ERROR;
}
else
{
// remote case to handle condor_globalq
// if (!ad->LookupString (ATTR_SCHEDD_IP_ADDR, scheddString))
if ( !ad->EvaluateAttrString( ATTR_SCHEDD_IP_ADDR, scheddString, 32 ) ) { // NAC
return Q_NO_SCHEDD_IP_ADDR;
}
if (!(qmgr = ConnectQ (scheddString,20,true))) {
return Q_SCHEDD_COMMUNICATION_ERROR;
}
}
// get the ads and filter them
getAndFilterAds (filterAd, ca_list);
DisconnectQ (qmgr);
return Q_OK;
}
int CondorQ::
fetchQueueFromHost (ClassAdList &ca_list, char *host)
{
Qmgr_connection *qmgr;
ClassAd filterAd;
int result;
// make the query ad
if ((result = query.makeQuery (filterAd)) != Q_OK)
return result;
// insert types into the query ad ###
// filterAd.SetMyTypeName ("Query");
// filterAd.SetTargetTypeName ("Job");
filterAd.InsertAttr( ATTR_MY_TYPE, (string)QUERY_ADTYPE ); // NAC
filterAd.InsertAttr( ATTR_TARGET_TYPE, (string)JOB_ADTYPE ); // NAC
/*
connect to the Q manager.
use a timeout of 20 seconds, and a read-only connection.
why 20 seconds? because careful research by Derek has shown
that whenever one needs a periodic time value, 20 is always
optimal. :^).
*/
if (!(qmgr = ConnectQ (host,20,true))) {
return Q_SCHEDD_COMMUNICATION_ERROR;
}
// get the ads and filter them
result = getAndFilterAds (filterAd, ca_list);
DisconnectQ (qmgr);
return result;
}
int CondorQ::
fetchQueueFromHostAndProcess ( char *host, process_function process_func )
{
// DEBUG NAC
// printf("entered fetchQueueFromHostAndProcess\n"); // NAC
Qmgr_connection *qmgr;
ClassAd filterAd;
int result;
// make the query ad
if ((result = query.makeQuery (filterAd)) != Q_OK)
return result;
// insert types into the query ad ###
// filterAd.SetMyTypeName ("Query");
// filterAd.SetTargetTypeName ("Job");
filterAd.InsertAttr( ATTR_MY_TYPE, (string)QUERY_ADTYPE ); // NAC
filterAd.InsertAttr( ATTR_TARGET_TYPE, (string)JOB_ADTYPE ); // NAC
/*
connect to the Q manager.
use a timeout of 20 seconds, and a read-only connection.
why 20 seconds? because careful research by Derek has shown
that whenever one needs a periodic time value, 20 is always
optimal. :^).
*/
if (!(qmgr = ConnectQ (host,20,true)))
return Q_SCHEDD_COMMUNICATION_ERROR;
// get the ads and filter them
result = getFilterAndProcessAds (filterAd, process_func);
result = Q_OK; // NAC
DisconnectQ (qmgr);
// DEBUG NAC
// printf("exiting fetchQueueFromHostAndProcess\n"); // NAC
return result;
}
int CondorQ::
getFilterAndProcessAds( ClassAd &queryad, process_function process_func )
{
// DEBUG NAC
// printf("entered getFilterAndProcessAds\n"); // NAC
// char constraint[ATTRLIST_MAX_EXPRESSION]; /* yuk! */
char constraint[10240]; // NAC
string constraint_string; // NAC
ExprTree *tree;
ClassAd *ad;
ClassAdUnParser unp; // NAC
// constraint[0] = '\0';
tree = queryad.Lookup(ATTR_REQUIREMENTS);
// if (!tree) {
// return Q_INVALID_QUERY;
// }
// tree->RArg()->PrintToStr(constraint);
unp.Unparse( constraint_string, tree ); // NAC
// DEBUG NAC
// cout << "constraints_string = " << constraint_string << endl; // NAC
strncpy( constraint, constraint_string.c_str( ), 10240 ); // NAC
// DEBUG NAC
// cout << "constraint = " << constraint << endl; // NAC
if ((ad = GetNextJobByConstraint(constraint, 1)) != NULL) {
// Process the data and insert it into the list
if ( ( *process_func )( ad ) ) {
delete(ad);
}
while((ad = GetNextJobByConstraint(constraint, 0)) != NULL) {
// Process the data and insert it into the list
// DEBUG NAC
// cout << "about to call process_func" << endl;
if ( ( *process_func )( ad ) ) {
delete(ad);
}
// cout << "done process_func" << endl;
}
}
// DEBUG NAC
// cout << "done GetNextJobByConstraint" << endl;
// here GetNextJobByConstraint returned NULL. check if it was
// because of the network or not. if qmgmt had a problem with
// the net, then errno is set to ETIMEDOUT, and we should fail.
if ( errno == ETIMEDOUT ) {
return Q_SCHEDD_COMMUNICATION_ERROR;
}
// DEBUG NAC
// printf("exiting getFilterAndProcessAds\n"); // NAC
return Q_OK;
}
int CondorQ::
getAndFilterAds (ClassAd &queryad, ClassAdList &ca_list)
{
// char constraint[ATTRLIST_MAX_EXPRESSION]; /* yuk! */
char constraint[10240]; // NAC
string constraint_string; // NAC
ExprTree *tree;
ClassAd *ad;
ClassAdUnParser unp; // NAC
// constraint[0] = '\0';
tree = queryad.Lookup( ATTR_REQUIREMENTS );
// if (!tree) {
// return Q_INVALID_QUERY;
// }
// tree->RArg()->PrintToStr(constraint);
unp.Unparse( constraint_string, tree ); // NAC
strncpy( constraint, constraint_string.c_str( ), 10240 ); // NAC
if ((ad = GetNextJobByConstraint(constraint, 1)) != NULL) {
ca_list.Insert(ad);
while((ad = GetNextJobByConstraint(constraint, 0)) != NULL) {
ca_list.Insert(ad);
}
}
// here GetNextJobByConstraint returned NULL. check if it was
// because of the network or not. if qmgmt had a problem with
// the net, then errno is set to ETIMEDOUT, and we should fail.
if ( errno == ETIMEDOUT ) {
return Q_SCHEDD_COMMUNICATION_ERROR;
}
return Q_OK;
}
int JobSort(ClassAd *job1, ClassAd *job2, void *data)
{
int cluster1=0, cluster2=0, proc1=0, proc2=0;
// job1->LookupInteger(ATTR_CLUSTER_ID, cluster1);
// job2->LookupInteger(ATTR_CLUSTER_ID, cluster2);
job1->EvaluateAttrInt( ATTR_CLUSTER_ID, cluster1 ); // NAC
job2->EvaluateAttrInt( ATTR_CLUSTER_ID, cluster2 ); // NAC
if (cluster1 < cluster2) return 1;
if (cluster1 > cluster2) return 0;
// job1->LookupInteger(ATTR_PROC_ID, proc1);
// job2->LookupInteger(ATTR_PROC_ID, proc2);
job1->EvaluateAttrInt( ATTR_PROC_ID, proc1 ); // NAC
job2->EvaluateAttrInt( ATTR_PROC_ID, proc2 ); // NAC
if (proc1 < proc2) return 1;
else return 0;
}
/*
Encode a status from a PROC structure as a single letter suited for
printing.
*/
const char
encode_status( int status )
{
switch( status ) {
case UNEXPANDED:
return 'U';
case IDLE:
return 'I';
case RUNNING:
return 'R';
case COMPLETED:
return 'C';
case REMOVED:
return 'X';
case HELD:
return 'H';
case SUBMISSION_ERR:
return 'E';
default:
return ' ';
}
}
/*
Print a line of data for the "short" display of a PROC structure. The
"short" display is the one used by "condor_q". N.B. the columns used
by this routine must match those defined by the short_header routine
defined above.
*/
void
short_print(
int cluster,
int proc,
const char *owner,
int date,
int time,
int status,
int prio,
int image_size,
const char *cmd
) {
printf( "%4d.%-3d %-14s %-11s %-12s %-2c %-3d %-4.1f %-18.18s\n",
cluster,
proc,
owner,
format_date((time_t)date),
format_time(time),
encode_status(status),
prio,
image_size/1024.0,
cmd
);
}
<|endoftext|> |
<commit_before>#include <vector>
#include <unordered_map>
#include <blackhole/attribute/view.hpp>
#include "global.hpp"
using namespace blackhole;
using aux::iterator::join_t;
using aux::iterator::invalidate_tag;
#define TEST_JOIN_ITERATOR(Suite, Case) \
TEST(join_t##_##Suite, Case)
TEST_JOIN_ITERATOR(Cons, Converting) {
typedef std::vector<int> container_type;
container_type c1, c2;
join_t<container_type, true> it({ &c1, &c2 });
UNUSED(it);
}
TEST_JOIN_ITERATOR(Cons, Invalidation) {
typedef std::vector<int> container_type;
container_type c1, c2;
join_t<container_type, true> it({ &c1, &c2 }, invalidate_tag);
UNUSED(it);
}
TEST_JOIN_ITERATOR(Cons, Copy) {
typedef std::vector<int> container_type;
container_type c1 = { 0, 1, 2 };
container_type c2 = { 3, 4, 5 };
join_t<container_type, true> it1({ &c1, &c2 });
join_t<container_type, true> it2 = it1;
EXPECT_TRUE(it1 == it2);
container_type expected = { 0, 1, 2, 3, 4, 5 };
EXPECT_TRUE(std::equal(expected.begin(), expected.end(), it2));
}
TEST_JOIN_ITERATOR(Cons, Move) {
typedef std::vector<int> container_type;
container_type c1 = { 0, 1, 2 };
container_type c2 = { 3, 4, 5 };
join_t<container_type, true> it1({ &c1, &c2 });
join_t<container_type, true> it2 = std::move(it1);
container_type expected = { 0, 1, 2, 3, 4, 5 };
EXPECT_TRUE(std::equal(expected.begin(), expected.end(), it2));
}
TEST_JOIN_ITERATOR(Equality, EmptyContainers) {
typedef std::vector<int> container_type;
container_type c1, c2;
join_t<container_type, true> it1({ &c1, &c2 });
join_t<container_type, true> it2({ &c1, &c2 });
EXPECT_TRUE(it1 == it2);
EXPECT_FALSE(it1 != it2);
}
TEST_JOIN_ITERATOR(Equality, EqualContainers) {
typedef std::vector<int> container_type;
container_type c1 = { 0, 1, 2 };
container_type c2 = { 0, 1, 2 };
join_t<container_type, true> it1({ &c1, &c2 });
join_t<container_type, true> it2({ &c1, &c2 });
EXPECT_TRUE(it1 == it2);
EXPECT_FALSE(it1 != it2);
}
TEST_JOIN_ITERATOR(Equality, NotEqualContainers) {
typedef std::vector<int> container_type;
container_type c1 = { 0, 1, 2 };
container_type c2 = { 0, 1, 2 };
join_t<container_type, true> it1({ &c1, &c2 });
join_t<container_type, true> it2({ &c2, &c1 });
EXPECT_FALSE(it1 == it2);
EXPECT_TRUE(it1 != it2);
}
TEST_JOIN_ITERATOR(Forward, EmptyFirst) {
typedef std::vector<int> container_type;
container_type c1 = {};
container_type c2 = { 3, 4, 5 };
join_t<container_type, true> it({ &c1, &c2 });
container_type expected = { 3, 4, 5 };
EXPECT_TRUE(std::equal(expected.begin(), expected.end(), it));
}
TEST_JOIN_ITERATOR(Forward, EmptyMiddle) {
typedef std::vector<int> container_type;
container_type c1 = { 0, 1, 2 };
container_type c2 = {};
container_type c3 = { 3, 4, 5 };
join_t<container_type, true> it({ &c1, &c2, &c3 });
container_type expected = { 0, 1, 2, 3, 4, 5 };
EXPECT_TRUE(std::equal(expected.begin(), expected.end(), it));
}
TEST_JOIN_ITERATOR(Forward, EmptyLast) {
typedef std::vector<int> container_type;
container_type c1 = { 0, 1, 2 };
container_type c2 = {};
join_t<container_type, true> it({ &c1, &c2 });
container_type expected = { 0, 1, 2 };
EXPECT_TRUE(std::equal(expected.begin(), expected.end(), it));
}
TEST_JOIN_ITERATOR(Forward, Loop) {
typedef std::vector<int> container_type;
container_type c1 = { 0, 1, 2 };
container_type c2 = { 3, 4, 5 };
join_t<container_type, true> begin({ &c1, &c2 });
join_t<container_type, true> end({ &c1, &c2 }, invalidate_tag);
container_type expected = { 0, 1, 2, 3, 4, 5 };
size_t s = 0;
for (auto it = begin; it != end; ++it) {
EXPECT_EQ(expected[s++], *it);
}
}
TEST_JOIN_ITERATOR(Forward, LoopPostIncrement) {
typedef std::vector<int> container_type;
container_type c1 = { 0, 1, 2 };
container_type c2 = { 3, 4, 5 };
join_t<container_type, true> begin({ &c1, &c2 });
join_t<container_type, true> end({ &c1, &c2 }, invalidate_tag);
container_type expected = { 0, 1, 2, 3, 4, 5 };
size_t s = 0;
for (auto it = begin; it != end; it++) {
EXPECT_EQ(expected[s++], *it);
}
}
TEST_JOIN_ITERATOR(Forward, Map) {
typedef std::unordered_map<std::string, int> container_type;
container_type c1 = { {"0", 0}, {"1", 1}, {"2", 2} };
container_type c2 = { {"3", 0}, {"4", 1}, {"5", 2} };
const join_t<container_type, true> begin({ &c1, &c2 });
join_t<container_type, true> end({ &c1, &c2 }, invalidate_tag);
container_type expected = {
{"0", 0}, {"1", 1}, {"2", 2}, {"3", 0}, {"4", 1}, {"5", 2}
};
ASSERT_EQ(expected.size(), std::distance(begin, end));
for (auto it = begin; it != end; ++it) {
EXPECT_TRUE(expected.find(it->first)->second == it->second);
}
}
TEST(set_view_t, DefaultConstructor) {
attribute::set_view_t view;
EXPECT_TRUE(view.empty());
}
<commit_msg>[Unit Testing] Fixing tests for new API.<commit_after>#include <vector>
#include <unordered_map>
#include <blackhole/attribute/view.hpp>
#include "global.hpp"
using namespace blackhole;
using aux::iterator::join_t;
using aux::iterator::invalidate_tag;
#define TEST_JOIN_ITERATOR(Suite, Case) \
TEST(join_t##_##Suite, Case)
TEST_JOIN_ITERATOR(Cons, Converting) {
typedef std::vector<int> container_type;
container_type c1, c2;
std::array<const container_type*, 2> array {{ &c1, &c2 }};
join_t<container_type, true> it(array);
UNUSED(it);
}
TEST_JOIN_ITERATOR(Cons, Invalidation) {
typedef std::vector<int> container_type;
container_type c1, c2;
std::array<const container_type*, 2> array {{ &c1, &c2 }};
join_t<container_type, true> it(array, invalidate_tag);
UNUSED(it);
}
TEST_JOIN_ITERATOR(Cons, Copy) {
typedef std::vector<int> container_type;
container_type c1 = { 0, 1, 2 };
container_type c2 = { 3, 4, 5 };
std::array<const container_type*, 2> array {{ &c1, &c2 }};
join_t<container_type, true> it1(array);
join_t<container_type, true> it2 = it1;
EXPECT_TRUE(it1 == it2);
container_type expected = { 0, 1, 2, 3, 4, 5 };
EXPECT_TRUE(std::equal(expected.begin(), expected.end(), it2));
}
TEST_JOIN_ITERATOR(Cons, Move) {
typedef std::vector<int> container_type;
container_type c1 = { 0, 1, 2 };
container_type c2 = { 3, 4, 5 };
std::array<const container_type*, 2> array {{ &c1, &c2 }};
join_t<container_type, true> it1(array);
join_t<container_type, true> it2 = std::move(it1);
container_type expected = { 0, 1, 2, 3, 4, 5 };
EXPECT_TRUE(std::equal(expected.begin(), expected.end(), it2));
}
TEST_JOIN_ITERATOR(Equality, EmptyContainers) {
typedef std::vector<int> container_type;
container_type c1, c2;
std::array<const container_type*, 2> array {{ &c1, &c2 }};
join_t<container_type, true> it1(array);
join_t<container_type, true> it2(array);
EXPECT_TRUE(it1 == it2);
EXPECT_FALSE(it1 != it2);
}
TEST_JOIN_ITERATOR(Equality, EqualContainers) {
typedef std::vector<int> container_type;
container_type c1 = { 0, 1, 2 };
container_type c2 = { 0, 1, 2 };
std::array<const container_type*, 2> array {{ &c1, &c2 }};
join_t<container_type, true> it1(array);
join_t<container_type, true> it2(array);
EXPECT_TRUE(it1 == it2);
EXPECT_FALSE(it1 != it2);
}
TEST_JOIN_ITERATOR(Equality, NotEqualContainers) {
typedef std::vector<int> container_type;
container_type c1 = { 0, 1, 2 };
container_type c2 = { 0, 1, 2 };
std::array<const container_type*, 2> array1 {{ &c1, &c2 }};
std::array<const container_type*, 2> array2 {{ &c2, &c1 }};
join_t<container_type, true> it1(array1);
join_t<container_type, true> it2(array2);
EXPECT_FALSE(it1 == it2);
EXPECT_TRUE(it1 != it2);
}
TEST_JOIN_ITERATOR(Forward, EmptyFirst) {
typedef std::vector<int> container_type;
container_type c1 = {};
container_type c2 = { 3, 4, 5 };
std::array<const container_type*, 2> array {{ &c1, &c2 }};
join_t<container_type, true> it(array);
container_type expected = { 3, 4, 5 };
EXPECT_TRUE(std::equal(expected.begin(), expected.end(), it));
}
TEST_JOIN_ITERATOR(Forward, EmptyMiddle) {
typedef std::vector<int> container_type;
container_type c1 = { 0, 1, 2 };
container_type c2 = {};
container_type c3 = { 3, 4, 5 };
std::array<const container_type*, 3> array {{ &c1, &c2, &c3 }};
join_t<container_type, true> it(array);
container_type expected = { 0, 1, 2, 3, 4, 5 };
EXPECT_TRUE(std::equal(expected.begin(), expected.end(), it));
}
TEST_JOIN_ITERATOR(Forward, EmptyLast) {
typedef std::vector<int> container_type;
container_type c1 = { 0, 1, 2 };
container_type c2 = {};
std::array<const container_type*, 2> array {{ &c1, &c2 }};
join_t<container_type, true> it(array);
container_type expected = { 0, 1, 2 };
EXPECT_TRUE(std::equal(expected.begin(), expected.end(), it));
}
TEST_JOIN_ITERATOR(Forward, Loop) {
typedef std::vector<int> container_type;
container_type c1 = { 0, 1, 2 };
container_type c2 = { 3, 4, 5 };
std::array<const container_type*, 2> array {{ &c1, &c2 }};
join_t<container_type, true> begin(array);
join_t<container_type, true> end(array, invalidate_tag);
container_type expected = { 0, 1, 2, 3, 4, 5 };
size_t s = 0;
for (auto it = begin; it != end; ++it) {
EXPECT_EQ(expected[s++], *it);
}
}
TEST_JOIN_ITERATOR(Forward, LoopPostIncrement) {
typedef std::vector<int> container_type;
container_type c1 = { 0, 1, 2 };
container_type c2 = { 3, 4, 5 };
std::array<const container_type*, 2> array {{ &c1, &c2 }};
join_t<container_type, true> begin(array);
join_t<container_type, true> end(array, invalidate_tag);
container_type expected = { 0, 1, 2, 3, 4, 5 };
size_t s = 0;
for (auto it = begin; it != end; it++) {
EXPECT_EQ(expected[s++], *it);
}
}
TEST_JOIN_ITERATOR(Forward, Map) {
typedef std::unordered_map<std::string, int> container_type;
container_type c1 = { {"0", 0}, {"1", 1}, {"2", 2} };
container_type c2 = { {"3", 0}, {"4", 1}, {"5", 2} };
std::array<const container_type*, 2> array {{ &c1, &c2 }};
const join_t<container_type, true> begin(array);
join_t<container_type, true> end(array, invalidate_tag);
container_type expected = {
{"0", 0}, {"1", 1}, {"2", 2}, {"3", 0}, {"4", 1}, {"5", 2}
};
ASSERT_EQ(expected.size(), std::distance(begin, end));
for (auto it = begin; it != end; ++it) {
EXPECT_TRUE(expected.find(it->first)->second == it->second);
}
}
TEST(set_view_t, DefaultConstructor) {
attribute::set_view_t view;
EXPECT_TRUE(view.empty());
}
<|endoftext|> |
<commit_before>//@author A0094446X
#include "stdafx.h"
#include <QApplication>
#include <QList>
#include "you_main_gui.h"
#include "system_tray_manager.h"
YouMainGUI::SystemTrayManager::~SystemTrayManager() {
}
void YouMainGUI::SystemTrayManager::setup() {
createActions();
setIcon();
makeContextMenu();
connectTrayActivatedSlot();
parentGUI->setVisible(true);
}
void YouMainGUI::SystemTrayManager::setIcon() {
QIcon icon(":/Icon.png");
trayIcon.setIcon(icon);
parentGUI->setWindowIcon(icon);
trayIcon.show();
}
void YouMainGUI::SystemTrayManager::makeContextMenu() {
trayIconMenu = new QMenu(parentGUI);
trayIconMenu->addAction(minimizeAction);
trayIconMenu->addAction(maximizeAction);
trayIconMenu->addAction(restoreAction);
trayIconMenu->addSeparator();
trayIconMenu->addAction(quitAction);
trayIcon.setContextMenu(trayIconMenu);
}
void YouMainGUI::SystemTrayManager::connectTrayActivatedSlot() {
connect(&trayIcon, SIGNAL(activated(QSystemTrayIcon::ActivationReason)),
this, SLOT(iconActivated(QSystemTrayIcon::ActivationReason)));
}
void YouMainGUI::SystemTrayManager::iconActivated(
QSystemTrayIcon::ActivationReason reason) {
if (reason == QSystemTrayIcon::Trigger) {
bool visible = parentGUI->isVisible();
bool minimized = parentGUI->isMinimized();
assert( (visible == true && minimized == true) ||
(visible == true && minimized == false) ||
(visible == false));
Qt::WindowStates toggleState
(parentGUI->windowState() & ~Qt::WindowMinimized);
// Visible and minimized
if (visible && minimized) {
parentGUI->setWindowState(toggleState | Qt::WindowActive);
} // Visible and not minimized
else if (visible && !minimized) {
parentGUI->setWindowState(toggleState | Qt::WindowActive);
parentGUI->hide();
} else if (!visible) { // Not visible
parentGUI->show();
parentGUI->setWindowState(toggleState | Qt::WindowActive);
}
}
}
void YouMainGUI::SystemTrayManager::createActions() {
minimizeAction = new QAction(tr("Minimize"), parentGUI);
connect(minimizeAction, SIGNAL(triggered()), parentGUI, SLOT(hide()));
maximizeAction = new QAction(tr("Maximize"), parentGUI);
connect(maximizeAction, SIGNAL(triggered()), parentGUI, SLOT(showMaximized()));
restoreAction = new QAction(tr("Restore"), parentGUI);
connect(restoreAction, SIGNAL(triggered()), parentGUI, SLOT(showNormal()));
quitAction = new QAction(tr("Quit"), parentGUI);
connect(quitAction, SIGNAL(triggered()), qApp, SLOT(quit()));
}
<commit_msg>Fixed comments.<commit_after>//@author A0094446X
#include "stdafx.h"
#include <QApplication>
#include <QList>
#include "you_main_gui.h"
#include "system_tray_manager.h"
YouMainGUI::SystemTrayManager::~SystemTrayManager() {
}
void YouMainGUI::SystemTrayManager::setup() {
createActions();
setIcon();
makeContextMenu();
connectTrayActivatedSlot();
parentGUI->setVisible(true);
}
void YouMainGUI::SystemTrayManager::setIcon() {
QIcon icon(":/Icon.png");
trayIcon.setIcon(icon);
parentGUI->setWindowIcon(icon);
trayIcon.show();
}
void YouMainGUI::SystemTrayManager::makeContextMenu() {
trayIconMenu = new QMenu(parentGUI);
trayIconMenu->addAction(minimizeAction);
trayIconMenu->addAction(maximizeAction);
trayIconMenu->addAction(restoreAction);
trayIconMenu->addSeparator();
trayIconMenu->addAction(quitAction);
trayIcon.setContextMenu(trayIconMenu);
}
void YouMainGUI::SystemTrayManager::connectTrayActivatedSlot() {
connect(&trayIcon, SIGNAL(activated(QSystemTrayIcon::ActivationReason)),
this, SLOT(iconActivated(QSystemTrayIcon::ActivationReason)));
}
void YouMainGUI::SystemTrayManager::iconActivated(
QSystemTrayIcon::ActivationReason reason) {
if (reason == QSystemTrayIcon::Trigger) {
bool visible = parentGUI->isVisible();
bool minimized = parentGUI->isMinimized();
assert((visible == true && minimized == true) ||
(visible == true && minimized == false) ||
(visible == false));
Qt::WindowStates toggleState
(parentGUI->windowState() & ~Qt::WindowMinimized);
if (visible && minimized) {
parentGUI->setWindowState(toggleState | Qt::WindowActive);
} else if (visible && !minimized) {
parentGUI->setWindowState(toggleState | Qt::WindowActive);
parentGUI->hide();
} else if (!visible) {
parentGUI->show();
parentGUI->setWindowState(toggleState | Qt::WindowActive);
}
}
}
void YouMainGUI::SystemTrayManager::createActions() {
minimizeAction = new QAction(tr("Minimize"), parentGUI);
connect(minimizeAction, SIGNAL(triggered()), parentGUI, SLOT(hide()));
maximizeAction = new QAction(tr("Maximize"), parentGUI);
connect(maximizeAction, SIGNAL(triggered()), parentGUI, SLOT(showMaximized()));
restoreAction = new QAction(tr("Restore"), parentGUI);
connect(restoreAction, SIGNAL(triggered()), parentGUI, SLOT(showNormal()));
quitAction = new QAction(tr("Quit"), parentGUI);
connect(quitAction, SIGNAL(triggered()), qApp, SLOT(quit()));
}
<|endoftext|> |
<commit_before>#include <gmock/gmock.h>
#include <gtest/gtest.h>
#include <sauce/sauce.h>
using ::testing::Sequence;
using ::testing::Return;
namespace sauce { namespace test {
struct Chasis {};
struct CoupChasis: public Chasis {};
struct Engine {};
struct HybridEngine: public Engine {};
struct Vehicle {};
struct Herbie: public Vehicle {
Chasis * chasis;
Engine * engine;
Herbie(Chasis * chasis, Engine * engine):
chasis(chasis),
engine(engine) {}
};
class LoveBugModule {
public:
template<typename Injector>
static ::sauce::internal::bindings::New<Injector, Chasis, CoupChasis()> * bindings(Chasis *) {
return 0;
}
template<typename Injector>
static ::sauce::internal::bindings::Dereference<Injector, Chasis> * bindings(Chasis &) {
return 0;
}
template<typename Injector>
static ::sauce::internal::bindings::New<Injector, Engine, HybridEngine()> * bindings(Engine *) {
return 0;
}
template<typename Injector>
static ::sauce::internal::bindings::Dereference<Injector, Engine> * bindings(Engine &) {
return 0;
}
template<typename Injector>
static ::sauce::internal::bindings::New<Injector, Vehicle, Herbie(Chasis *, Engine *)> * bindings(Vehicle *) {
return 0;
}
template<typename Injector>
static ::sauce::internal::bindings::Dereference<Injector, Vehicle> * bindings(Vehicle &) {
return 0;
}
};
// Our mock for the new and delete operations.
//
// Gmock is unable to provide a general mock, so we roll one for our fixure
// types. Our mocked methods are actually arbitrary non-templated methods,
// delegated to by template specializations for our types.
class MockNewDelete {
public:
template<class C> C * _new();
template<class C, typename A1, typename A2> C * _new(A1, A2);
template<class C> void _delete(C *);
MOCK_METHOD0(new_coup_chasis, CoupChasis * ());
MOCK_METHOD0(new_hybrid_engine, HybridEngine * ());
MOCK_METHOD2(new_herbie, Herbie * (Chasis *, Engine *));
MOCK_METHOD1(delete_chasis, void (Chasis *));
MOCK_METHOD1(delete_engine, void (Engine *));
MOCK_METHOD1(delete_vehicle, void (Vehicle *));
};
template<> CoupChasis * MockNewDelete::_new<CoupChasis>() {
return new_coup_chasis();
}
template<> HybridEngine * MockNewDelete::_new<HybridEngine>() {
return new_hybrid_engine();
}
template<> Herbie * MockNewDelete::_new<Herbie>(Chasis * chasis, Engine * engine) {
return new_herbie(chasis, engine);
}
template<> void MockNewDelete::_delete<Chasis>(Chasis * chasis) {
delete_chasis(chasis);
}
template<> void MockNewDelete::_delete<Engine>(Engine * engine) {
delete_engine(engine);
}
template<> void MockNewDelete::_delete<Vehicle>(Vehicle * vehicle) {
delete_vehicle(vehicle);
}
class SauceTest: public ::testing::Test {
public:
::sauce::Injector<LoveBugModule, MockNewDelete> injector;
MockNewDelete & new_delete;
// SauceTest is a friend of Injector
SauceTest():
injector(),
new_delete(injector.new_delete) {}
};
TEST_F(SauceTest, should_provide_a_dependency) {
CoupChasis chasis;
EXPECT_CALL(new_delete, new_coup_chasis()).WillOnce(Return(&chasis));
Chasis * actual = injector.provide<Chasis *>();
ASSERT_EQ(&chasis, actual);
}
TEST_F(SauceTest, should_dispose_a_dependency) {
CoupChasis chasis;
EXPECT_CALL(new_delete, delete_chasis(&chasis));
injector.dispose<Chasis *>(&chasis);
}
TEST_F(SauceTest, should_dereference_addresses_with_dereference_bindings) {
CoupChasis chasis;
EXPECT_CALL(new_delete, new_coup_chasis()).WillOnce(Return(&chasis));
EXPECT_CALL(new_delete, delete_chasis(&chasis));
Chasis & actual = injector.provide<Chasis &>();
ASSERT_EQ(&chasis, &actual);
injector.dispose<Chasis &>(chasis);
}
// TEST_F(SauceTest, should_provide_and_dispose_of_dependencies_transitively) {
// CoupChasis chasis;
// HybridEngine engine;
// Herbie vehicle(&chasis, &engine);
//
// // We don't care about the relative ordering between chasis and engine:
// // only about how they stand relative to the vehicle.
// Sequence injected_chasis, injected_engine;
//
// EXPECT_CALL(new_delete, new_coup_chasis()).
// InSequence(injected_chasis).
// WillOnce(Return(&chasis));
//
// EXPECT_CALL(new_delete, new_hybrid_engine()).
// InSequence(injected_engine).
// WillOnce(Return(&engine));
//
// EXPECT_CALL(new_delete, new_herbie(&chasis, &engine)).
// InSequence(injected_chasis, injected_engine).
// WillOnce(Return(&vehicle));
//
// EXPECT_CALL(new_delete, delete_vehicle(&vehicle)).
// InSequence(injected_chasis, injected_engine);
//
// EXPECT_CALL(new_delete, delete_engine(&engine)).
// InSequence(injected_engine);
//
// EXPECT_CALL(new_delete, delete_chasis(&chasis)).
// InSequence(injected_chasis);
//
// Vehicle & actual = injector.provide<Vehicle &>();
// ASSERT_EQ(&vehicle, &actual);
// injector.dispose<Vehicle &>(vehicle);
// }
} } // namespace test, namespace sauce
<commit_msg>Ditch unused Dereference bindings.<commit_after>#include <gmock/gmock.h>
#include <gtest/gtest.h>
#include <sauce/sauce.h>
using ::testing::Sequence;
using ::testing::Return;
namespace sauce { namespace test {
struct Chasis {};
struct CoupChasis: public Chasis {};
struct Engine {};
struct HybridEngine: public Engine {};
struct Vehicle {};
struct Herbie: public Vehicle {
Chasis * chasis;
Engine * engine;
Herbie(Chasis * chasis, Engine * engine):
chasis(chasis),
engine(engine) {}
};
class LoveBugModule {
public:
template<typename Injector>
static ::sauce::internal::bindings::New<Injector, Chasis, CoupChasis()> * bindings(Chasis *) {
return 0;
}
template<typename Injector>
static ::sauce::internal::bindings::Dereference<Injector, Chasis> * bindings(Chasis &) {
return 0;
}
template<typename Injector>
static ::sauce::internal::bindings::New<Injector, Engine, HybridEngine()> * bindings(Engine *) {
return 0;
}
template<typename Injector>
static ::sauce::internal::bindings::New<Injector, Vehicle, Herbie(Chasis *, Engine *)> * bindings(Vehicle *) {
return 0;
}
};
// Our mock for the new and delete operations.
//
// Gmock is unable to provide a general mock, so we roll one for our fixure
// types. Our mocked methods are actually arbitrary non-templated methods,
// delegated to by template specializations for our types.
class MockNewDelete {
public:
template<class C> C * _new();
template<class C, typename A1, typename A2> C * _new(A1, A2);
template<class C> void _delete(C *);
MOCK_METHOD0(new_coup_chasis, CoupChasis * ());
MOCK_METHOD0(new_hybrid_engine, HybridEngine * ());
MOCK_METHOD2(new_herbie, Herbie * (Chasis *, Engine *));
MOCK_METHOD1(delete_chasis, void (Chasis *));
MOCK_METHOD1(delete_engine, void (Engine *));
MOCK_METHOD1(delete_vehicle, void (Vehicle *));
};
template<> CoupChasis * MockNewDelete::_new<CoupChasis>() {
return new_coup_chasis();
}
template<> HybridEngine * MockNewDelete::_new<HybridEngine>() {
return new_hybrid_engine();
}
template<> Herbie * MockNewDelete::_new<Herbie>(Chasis * chasis, Engine * engine) {
return new_herbie(chasis, engine);
}
template<> void MockNewDelete::_delete<Chasis>(Chasis * chasis) {
delete_chasis(chasis);
}
template<> void MockNewDelete::_delete<Engine>(Engine * engine) {
delete_engine(engine);
}
template<> void MockNewDelete::_delete<Vehicle>(Vehicle * vehicle) {
delete_vehicle(vehicle);
}
class SauceTest: public ::testing::Test {
public:
::sauce::Injector<LoveBugModule, MockNewDelete> injector;
MockNewDelete & new_delete;
// SauceTest is a friend of Injector
SauceTest():
injector(),
new_delete(injector.new_delete) {}
};
TEST_F(SauceTest, should_provide_a_dependency) {
CoupChasis chasis;
EXPECT_CALL(new_delete, new_coup_chasis()).WillOnce(Return(&chasis));
Chasis * actual = injector.provide<Chasis *>();
ASSERT_EQ(&chasis, actual);
}
TEST_F(SauceTest, should_dispose_a_dependency) {
CoupChasis chasis;
EXPECT_CALL(new_delete, delete_chasis(&chasis));
injector.dispose<Chasis *>(&chasis);
}
TEST_F(SauceTest, should_dereference_addresses_with_dereference_bindings) {
CoupChasis chasis;
EXPECT_CALL(new_delete, new_coup_chasis()).WillOnce(Return(&chasis));
EXPECT_CALL(new_delete, delete_chasis(&chasis));
Chasis & actual = injector.provide<Chasis &>();
ASSERT_EQ(&chasis, &actual);
injector.dispose<Chasis &>(chasis);
}
// TEST_F(SauceTest, should_provide_and_dispose_of_dependencies_transitively) {
// CoupChasis chasis;
// HybridEngine engine;
// Herbie vehicle(&chasis, &engine);
//
// // We don't care about the relative ordering between chasis and engine:
// // only about how they stand relative to the vehicle.
// Sequence injected_chasis, injected_engine;
//
// EXPECT_CALL(new_delete, new_coup_chasis()).
// InSequence(injected_chasis).
// WillOnce(Return(&chasis));
//
// EXPECT_CALL(new_delete, new_hybrid_engine()).
// InSequence(injected_engine).
// WillOnce(Return(&engine));
//
// EXPECT_CALL(new_delete, new_herbie(&chasis, &engine)).
// InSequence(injected_chasis, injected_engine).
// WillOnce(Return(&vehicle));
//
// EXPECT_CALL(new_delete, delete_vehicle(&vehicle)).
// InSequence(injected_chasis, injected_engine);
//
// EXPECT_CALL(new_delete, delete_engine(&engine)).
// InSequence(injected_engine);
//
// EXPECT_CALL(new_delete, delete_chasis(&chasis)).
// InSequence(injected_chasis);
//
// Vehicle & actual = injector.provide<Vehicle &>();
// ASSERT_EQ(&vehicle, &actual);
// injector.dispose<Vehicle &>(vehicle);
// }
} } // namespace test, namespace sauce
<|endoftext|> |
<commit_before>/*
* Copyright (C) 2015 Luke San Antonio
* All rights reserved.
*/
#include "../common/mesh.h"
#include "../common/mesh_load.h"
#include "../common/software_mesh.h"
#include <sstream>
#define CATCH_CONFIG_MAIN
#include "catch/catch.hpp"
TEST_CASE("Face index string is properly parsed", "[struct Face]")
{
using namespace game;
auto f = parse_face("6");
REQUIRE(f.vertex == 6);
REQUIRE(f.tex_coord == 0);
REQUIRE(f.normal == 0);
f = parse_face("5//2");
REQUIRE(f.vertex == 5);
REQUIRE(f.tex_coord == 0);
REQUIRE(f.normal == 2);
f = parse_face("7/1/5");
REQUIRE(f.vertex == 7);
REQUIRE(f.tex_coord == 1);
REQUIRE(f.normal == 5);
f = parse_face("9/8");
REQUIRE(f.vertex == 9);
REQUIRE(f.tex_coord == 8);
REQUIRE(f.normal == 0);
}
TEST_CASE(".obj mesh is properly parsed", "[struct Mesh]")
{
using namespace game;
std::string data =
"v -10.0 10.0 0.0\n"
"v -10.0 -10.0 0.0\n"
"v 10.0 10.0 0.0\n"
"v 10.0 -10.0 0.0\n"
"f 2 4 3\n"
"f 1 2 3\n";
Software_Mesh mesh;
std::istringstream stream{data};
load_obj(stream, mesh);
REQUIRE(mesh.mesh_data().vertices.size() == 4);
REQUIRE(mesh.mesh_data().elements.size() == 6);
}
<commit_msg>We're now checking the exact contents of loading mesh (from .obj) in the test case.<commit_after>/*
* Copyright (C) 2015 Luke San Antonio
* All rights reserved.
*/
#include "../common/mesh.h"
#include "../common/mesh_load.h"
#include "../common/software_mesh.h"
#include <sstream>
#define CATCH_CONFIG_MAIN
#include "catch/catch.hpp"
TEST_CASE("Face index string is properly parsed", "[struct Face]")
{
using namespace game;
auto f = parse_face("6");
REQUIRE(f.vertex == 6);
REQUIRE(f.tex_coord == 0);
REQUIRE(f.normal == 0);
f = parse_face("5//2");
REQUIRE(f.vertex == 5);
REQUIRE(f.tex_coord == 0);
REQUIRE(f.normal == 2);
f = parse_face("7/1/5");
REQUIRE(f.vertex == 7);
REQUIRE(f.tex_coord == 1);
REQUIRE(f.normal == 5);
f = parse_face("9/8");
REQUIRE(f.vertex == 9);
REQUIRE(f.tex_coord == 8);
REQUIRE(f.normal == 0);
}
TEST_CASE(".obj mesh is properly parsed", "[struct Mesh]")
{
using namespace game;
std::string data =
"v -10.0 10.0 0.0\n"
"v -10.0 -10.0 0.0\n"
"v 10.0 10.0 0.0\n"
"v 10.0 -10.0 0.0\n"
"f 2 4 3\n"
"f 1 2 3\n";
Software_Mesh mesh;
std::istringstream stream{data};
load_obj(stream, mesh);
REQUIRE(mesh.mesh_data().vertices.size() == 4);
REQUIRE(mesh.mesh_data().elements.size() == 6);
glm::vec3 pt;
pt = {-10.0, 10.0, 0.0};
REQUIRE(mesh.mesh_data().vertices[0].position == pt);
pt = {-10.0, -10.0, 0.0};
REQUIRE(mesh.mesh_data().vertices[1].position == pt);
pt = {10.0, 10.0, 0.0};
REQUIRE(mesh.mesh_data().vertices[2].position == pt);
pt = {10.0, -10.0, 0.0};
REQUIRE(mesh.mesh_data().vertices[3].position == pt);
}
<|endoftext|> |
<commit_before>
// Copyright 2010-2012 University of Washington. All Rights Reserved.
// LICENSE_PLACEHOLDER
// This software was created with Government support under DE
// AC05-76RL01830 awarded by the United States Department of
// Energy. The Government has certain rights in the software.
#include <boost/test/unit_test.hpp>
#include "Grappa.hpp"
#include "ParallelLoop.hpp"
#include "GlobalAllocator.hpp"
#include "Delegate.hpp"
#include "GlobalVector.hpp"
#include "Statistics.hpp"
#include <boost/random/mersenne_twister.hpp>
#include <boost/random/uniform_int.hpp>
#include <boost/random/variate_generator.hpp>
#include <random>
using namespace Grappa;
BOOST_AUTO_TEST_SUITE( GlobalVector_tests );
static size_t N = (1L<<10) - 21;
DEFINE_int64(nelems, N, "number of elements in (large) test arrays");
DEFINE_int64(vector_size, N, "number of elements in (large) test arrays");
DEFINE_double(fraction_push, 0.5, "fraction of accesses that should be pushes");
// DEFINE_int64(buffer_size, 1<<10, "number of elements in buffer");
DEFINE_int64(ntrials, 1, "number of independent trials to average over");
DEFINE_bool(queue_perf, false, "do queue performance test");
DEFINE_bool(stack_perf, false, "do stack performance test");
GRAPPA_DEFINE_STAT(SummarizingStatistic<double>, trial_time, 0);
template< typename T >
inline T next_random() {
using engine_t = boost::mt19937_64;
using dist_t = boost::uniform_int<T>;
using gen_t = boost::variate_generator<engine_t&,dist_t>;
// continue using same generator with multiple calls (to not repeat numbers)
// but start at different seed on each node so we don't get overlap
static engine_t engine(12345L*mycore());
static gen_t gen(engine, dist_t(0, std::numeric_limits<T>::max()));
return gen();
}
bool choose_random(double probability) {
std::default_random_engine e(12345L);
std::uniform_real_distribution<double> dist(0.0, 1.0);
return dist(e) < probability;
}
enum class Exp { PUSH, POP, DEQUEUE, QUEUE, STACK };
template< Exp EXP >
double perf_test(GlobalAddress<GlobalVector<int64_t>> qa) {
double t = Grappa_walltime();
forall_global_private(0, FLAGS_nelems, [qa](int64_t i){
if (EXP == Exp::QUEUE) {
if (choose_random(FLAGS_fraction_push)) {
qa->push(next_random<int64_t>());
} else {
qa->dequeue();
}
} else if (EXP == Exp::STACK) {
if (choose_random(FLAGS_fraction_push)) {
qa->push(next_random<int64_t>());
} else {
qa->pop();
}
} else if (EXP == Exp::PUSH) {
qa->push(next_random<int64_t>());
} else if (EXP == Exp::POP) {
qa->pop();
} else if (EXP == Exp::DEQUEUE) {
qa->dequeue();
}
});
t = Grappa_walltime() - t;
return t;
}
void test_global_vector() {
BOOST_MESSAGE("Testing GlobalVector"); VLOG(1) << "testing global queue";
auto qa = GlobalVector<int64_t>::create(N);
VLOG(1) << "queue addr: " << qa;
BOOST_CHECK_EQUAL(qa->empty(), true);
VLOG(0) << qa->storage();
on_all_cores([qa] {
auto f = [qa](int64_t s, int64_t n) {
for (int64_t i=s; i<s+n; i++) {
qa->push(7);
}
BOOST_CHECK_EQUAL(qa->empty(), false);
};
switch (mycore()) {
case 0:
forall_here(0, N/2, f);
break;
case 1:
forall_here(N/2, N-N/2, f);
break;
}
});
for (int i=0; i<N; i++) {
BOOST_CHECK_EQUAL(delegate::read(qa->storage()+i), 7);
}
// forall_localized(qa->begin(), qa->size(), [](int64_t i, int64_t& e) { e = 9; });
forall_localized(qa, [](int64_t& e){ e = 9; });
for (int i=0; i<N; i++) {
BOOST_CHECK_EQUAL(delegate::read(qa->storage()+i), 9);
}
qa->destroy();
}
void test_dequeue() {
auto qa = GlobalVector<long>::create(N);
on_all_cores([qa]{
auto NC = N/cores();
for (int i=0; i<NC; i++) {
qa->enqueue(37);
}
auto size = qa->size();
BOOST_CHECK(size >= NC);
if (mycore() == 1) barrier();
forall_here(0, NC/2, [qa](long s, long n) {
for (int i=s; i<s+n; i++) {
auto e = qa->dequeue();
BOOST_CHECK_EQUAL(e, 37);
}
});
if (mycore() != 1) barrier();
forall_here(0, NC-NC/2, [qa](long s, long n) {
for (int i=s; i<s+n; i++) {
auto e = qa->dequeue();
BOOST_CHECK_EQUAL(e, 37);
}
});
});
BOOST_CHECK_EQUAL(qa->size(), 0);
qa->destroy();
}
void test_stack() {
LOG(INFO) << "testing stack...";
auto sa = GlobalVector<long>::create(N);
forall_localized(sa->storage(), N, [](int64_t& e){ e = -1; });
on_all_cores([sa]{
forall_here(0, 100, [sa](int64_t i) {
sa->push(17);
BOOST_CHECK_EQUAL(sa->pop(), 17);
});
});
LOG(INFO) << "second phase...";
on_all_cores([sa]{
for (int i=0; i<10; i++) sa->push(43);
for (int i=0; i<5; i++) BOOST_CHECK_EQUAL(sa->pop(), 43);
});
BOOST_CHECK_EQUAL(sa->size(), cores()*5);
while (!sa->empty()) BOOST_CHECK_EQUAL(sa->pop(), 43);
BOOST_CHECK_EQUAL(sa->size(), 0);
BOOST_CHECK(sa->empty());
sa->destroy();
}
void user_main( void * ignore ) {
if (FLAGS_queue_perf || FLAGS_stack_perf) {
LOG(INFO) << "beginning performance test";
auto qa = GlobalVector<int64_t>::create(FLAGS_vector_size);
for (int i=0; i<FLAGS_ntrials; i++) {
qa->clear();
if (FLAGS_fraction_push < 1.0) { // fill halfway so we don't hit either rail
forall_global_public(0, FLAGS_vector_size/2, [qa](int64_t i){
qa->push(next_random<int64_t>());
});
}
if (FLAGS_queue_perf) {
trial_time += perf_test<Exp::QUEUE>(qa);
} else if (FLAGS_stack_perf) {
trial_time += perf_test<Exp::STACK>(qa);
}
}
Statistics::merge_and_print();
qa->destroy();
} else {
test_global_vector();
test_dequeue();
test_stack();
}
}
BOOST_AUTO_TEST_CASE( test1 ) {
Grappa_init( &(boost::unit_test::framework::master_test_suite().argc),
&(boost::unit_test::framework::master_test_suite().argv) );
Grappa_activate();
N = FLAGS_nelems;
Grappa_run_user_main( &user_main, (void*)NULL );
Grappa_finish( 0 );
}
BOOST_AUTO_TEST_SUITE_END();
<commit_msg>just push/pop to get back to half-full between trials<commit_after>
// Copyright 2010-2012 University of Washington. All Rights Reserved.
// LICENSE_PLACEHOLDER
// This software was created with Government support under DE
// AC05-76RL01830 awarded by the United States Department of
// Energy. The Government has certain rights in the software.
#include <boost/test/unit_test.hpp>
#include "Grappa.hpp"
#include "ParallelLoop.hpp"
#include "GlobalAllocator.hpp"
#include "Delegate.hpp"
#include "GlobalVector.hpp"
#include "Statistics.hpp"
#include <boost/random/mersenne_twister.hpp>
#include <boost/random/uniform_int.hpp>
#include <boost/random/variate_generator.hpp>
#include <random>
using namespace Grappa;
BOOST_AUTO_TEST_SUITE( GlobalVector_tests );
static size_t N = (1L<<10) - 21;
DEFINE_int64(nelems, N, "number of elements in (large) test arrays");
DEFINE_int64(vector_size, N, "number of elements in (large) test arrays");
DEFINE_double(fraction_push, 0.5, "fraction of accesses that should be pushes");
// DEFINE_int64(buffer_size, 1<<10, "number of elements in buffer");
DEFINE_int64(ntrials, 1, "number of independent trials to average over");
DEFINE_bool(queue_perf, false, "do queue performance test");
DEFINE_bool(stack_perf, false, "do stack performance test");
GRAPPA_DEFINE_STAT(SummarizingStatistic<double>, trial_time, 0);
template< typename T >
inline T next_random() {
using engine_t = boost::mt19937_64;
using dist_t = boost::uniform_int<T>;
using gen_t = boost::variate_generator<engine_t&,dist_t>;
// continue using same generator with multiple calls (to not repeat numbers)
// but start at different seed on each node so we don't get overlap
static engine_t engine(12345L*mycore());
static gen_t gen(engine, dist_t(0, std::numeric_limits<T>::max()));
return gen();
}
bool choose_random(double probability) {
std::default_random_engine e(12345L);
std::uniform_real_distribution<double> dist(0.0, 1.0);
return dist(e) < probability;
}
enum class Exp { PUSH, POP, DEQUEUE, QUEUE, STACK };
template< Exp EXP >
double perf_test(GlobalAddress<GlobalVector<int64_t>> qa) {
double t = Grappa_walltime();
forall_global_private(0, FLAGS_nelems, [qa](int64_t i){
if (EXP == Exp::QUEUE) {
if (choose_random(FLAGS_fraction_push)) {
qa->push(next_random<int64_t>());
} else {
qa->dequeue();
}
} else if (EXP == Exp::STACK) {
if (choose_random(FLAGS_fraction_push)) {
qa->push(next_random<int64_t>());
} else {
qa->pop();
}
} else if (EXP == Exp::PUSH) {
qa->push(next_random<int64_t>());
} else if (EXP == Exp::POP) {
qa->pop();
} else if (EXP == Exp::DEQUEUE) {
qa->dequeue();
}
});
t = Grappa_walltime() - t;
return t;
}
void test_global_vector() {
BOOST_MESSAGE("Testing GlobalVector"); VLOG(1) << "testing global queue";
auto qa = GlobalVector<int64_t>::create(N);
VLOG(1) << "queue addr: " << qa;
BOOST_CHECK_EQUAL(qa->empty(), true);
VLOG(0) << qa->storage();
on_all_cores([qa] {
auto f = [qa](int64_t s, int64_t n) {
for (int64_t i=s; i<s+n; i++) {
qa->push(7);
}
BOOST_CHECK_EQUAL(qa->empty(), false);
};
switch (mycore()) {
case 0:
forall_here(0, N/2, f);
break;
case 1:
forall_here(N/2, N-N/2, f);
break;
}
});
for (int i=0; i<N; i++) {
BOOST_CHECK_EQUAL(delegate::read(qa->storage()+i), 7);
}
// forall_localized(qa->begin(), qa->size(), [](int64_t i, int64_t& e) { e = 9; });
forall_localized(qa, [](int64_t& e){ e = 9; });
for (int i=0; i<N; i++) {
BOOST_CHECK_EQUAL(delegate::read(qa->storage()+i), 9);
}
qa->destroy();
}
void test_dequeue() {
auto qa = GlobalVector<long>::create(N);
on_all_cores([qa]{
auto NC = N/cores();
for (int i=0; i<NC; i++) {
qa->enqueue(37);
}
auto size = qa->size();
BOOST_CHECK(size >= NC);
if (mycore() == 1) barrier();
forall_here(0, NC/2, [qa](long s, long n) {
for (int i=s; i<s+n; i++) {
auto e = qa->dequeue();
BOOST_CHECK_EQUAL(e, 37);
}
});
if (mycore() != 1) barrier();
forall_here(0, NC-NC/2, [qa](long s, long n) {
for (int i=s; i<s+n; i++) {
auto e = qa->dequeue();
BOOST_CHECK_EQUAL(e, 37);
}
});
});
BOOST_CHECK_EQUAL(qa->size(), 0);
qa->destroy();
}
void test_stack() {
LOG(INFO) << "testing stack...";
auto sa = GlobalVector<long>::create(N);
forall_localized(sa->storage(), N, [](int64_t& e){ e = -1; });
on_all_cores([sa]{
forall_here(0, 100, [sa](int64_t i) {
sa->push(17);
BOOST_CHECK_EQUAL(sa->pop(), 17);
});
});
LOG(INFO) << "second phase...";
on_all_cores([sa]{
for (int i=0; i<10; i++) sa->push(43);
for (int i=0; i<5; i++) BOOST_CHECK_EQUAL(sa->pop(), 43);
});
BOOST_CHECK_EQUAL(sa->size(), cores()*5);
while (!sa->empty()) BOOST_CHECK_EQUAL(sa->pop(), 43);
BOOST_CHECK_EQUAL(sa->size(), 0);
BOOST_CHECK(sa->empty());
sa->destroy();
}
void user_main( void * ignore ) {
if (FLAGS_queue_perf || FLAGS_stack_perf) {
LOG(INFO) << "beginning performance test";
auto qa = GlobalVector<int64_t>::create(FLAGS_vector_size);
for (int i=0; i<FLAGS_ntrials; i++) {
// qa->clear();
if (FLAGS_fraction_push < 1.0) { // fill halfway so we don't hit either rail
long diff = (FLAGS_vector_size/2) - qa->size();
if (diff > 0) { // too small
forall_global_public(0, diff, [qa](int64_t i){
qa->push(next_random<int64_t>());
});
} else { // too large
forall_global_public(0, 0-diff, [qa](int64_t i){
qa->pop();
});
}
}
if (FLAGS_queue_perf) {
trial_time += perf_test<Exp::QUEUE>(qa);
} else if (FLAGS_stack_perf) {
trial_time += perf_test<Exp::STACK>(qa);
}
}
Statistics::merge_and_print();
qa->destroy();
} else {
test_global_vector();
test_dequeue();
test_stack();
}
}
BOOST_AUTO_TEST_CASE( test1 ) {
Grappa_init( &(boost::unit_test::framework::master_test_suite().argc),
&(boost::unit_test::framework::master_test_suite().argv) );
Grappa_activate();
N = FLAGS_nelems;
Grappa_run_user_main( &user_main, (void*)NULL );
Grappa_finish( 0 );
}
BOOST_AUTO_TEST_SUITE_END();
<|endoftext|> |
<commit_before>////////////////////////////////////////////////////////////////////////
// This file is part of Grappa, a system for scaling irregular
// applications on commodity clusters.
// Copyright (C) 2010-2014 University of Washington and Battelle
// Memorial Institute. University of Washington authorizes use of this
// Grappa software.
// Grappa is free software: you can redistribute it and/or modify it
// under the terms of the Affero General Public License as published
// by Affero, Inc., either version 1 of the License, or (at your
// option) any later version.
// Grappa 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
// Affero General Public License for more details.
// You should have received a copy of the Affero General Public
// License along with this program. If not, you may obtain one from
// http://www.affero.org/oagpl.html.
////////////////////////////////////////////////////////////////////////
#pragma once
#ifndef __LOCALE_SHARED_MEMORY_HPP__
#define __LOCALE_SHARED_MEMORY_HPP__
#include <gflags/gflags.h>
#include <glog/logging.h>
#include <string>
#include <boost/interprocess/managed_shared_memory.hpp>
#include "Communicator.hpp"
namespace Grappa {
namespace impl {
class LocaleSharedMemory {
private:
size_t region_size;
std::string region_name;
void * base_address;
size_t allocated;
void create();
void attach();
void destroy();
friend class RDMAAggregator;
public: // TODO: fix Gups
boost::interprocess::fixed_managed_shared_memory segment;
public:
LocaleSharedMemory();
~LocaleSharedMemory();
// called before gasnet is ready to operate
void init();
// called after gasnet is ready to operate, but before user_main
void activate();
// clean up before shutting down
void finish();
// make sure an address is in the locale shared memory
inline void validate_address( void * addr ) {
//#ifndef NDEBUG
char * char_base = reinterpret_cast< char* >( base_address );
char * char_addr = reinterpret_cast< char* >( addr );
CHECK( (char_base <= addr) && (addr < (char_base + region_size) ) )
<< "Address " << addr << " out of locale shared range!";
}
//#endif
void * allocate( size_t size );
void * allocate_aligned( size_t size, size_t alignment );
void deallocate( void * ptr );
const size_t get_free_memory() const { return segment.get_free_memory(); }
const size_t get_size() const { return segment.get_size(); }
const size_t get_allocated() const { return allocated; }
};
/// global LocaleSharedMemory instance
extern LocaleSharedMemory locale_shared_memory;
} // namespace impl
/// @addtogroup Memory
/// @{
/// Allocate memory in locale shared heap.
template<typename T>
inline T* locale_alloc(size_t n = 1) {
return reinterpret_cast<T*>(impl::locale_shared_memory.allocate(sizeof(T)*n));
}
inline void* locale_alloc(size_t n = 1) {
return impl::locale_shared_memory.allocate(n);
}
template<typename T>
inline T* locale_alloc_aligned(size_t alignment, size_t n = 1) {
return reinterpret_cast<T*>(impl::locale_shared_memory.allocate_aligned(sizeof(T)*n, alignment));
}
inline void* locale_alloc_aligned(size_t alignment, size_t n = 1) {
return impl::locale_shared_memory.allocate_aligned(n, alignment);
}
template< typename T, typename... Args >
inline T* locale_new(Args&&... args) {
return new (locale_alloc<T>()) T(std::forward<Args...>(args...));
}
template< typename T >
inline T* locale_new() {
return new (locale_alloc<T>()) T();
}
/// Free memory that was allocated from locale shared heap.
inline void locale_free(void * ptr) {
impl::locale_shared_memory.deallocate(ptr);
}
/// @}
} // namespace Grappa
#endif
<commit_msg>add locale heap allocation for arrays<commit_after>////////////////////////////////////////////////////////////////////////
// This file is part of Grappa, a system for scaling irregular
// applications on commodity clusters.
// Copyright (C) 2010-2014 University of Washington and Battelle
// Memorial Institute. University of Washington authorizes use of this
// Grappa software.
// Grappa is free software: you can redistribute it and/or modify it
// under the terms of the Affero General Public License as published
// by Affero, Inc., either version 1 of the License, or (at your
// option) any later version.
// Grappa 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
// Affero General Public License for more details.
// You should have received a copy of the Affero General Public
// License along with this program. If not, you may obtain one from
// http://www.affero.org/oagpl.html.
////////////////////////////////////////////////////////////////////////
#pragma once
#ifndef __LOCALE_SHARED_MEMORY_HPP__
#define __LOCALE_SHARED_MEMORY_HPP__
#include <gflags/gflags.h>
#include <glog/logging.h>
#include <string>
#include <boost/interprocess/managed_shared_memory.hpp>
#include "Communicator.hpp"
namespace Grappa {
namespace impl {
class LocaleSharedMemory {
private:
size_t region_size;
std::string region_name;
void * base_address;
size_t allocated;
void create();
void attach();
void destroy();
friend class RDMAAggregator;
public: // TODO: fix Gups
boost::interprocess::fixed_managed_shared_memory segment;
public:
LocaleSharedMemory();
~LocaleSharedMemory();
// called before gasnet is ready to operate
void init();
// called after gasnet is ready to operate, but before user_main
void activate();
// clean up before shutting down
void finish();
// make sure an address is in the locale shared memory
inline void validate_address( void * addr ) {
//#ifndef NDEBUG
char * char_base = reinterpret_cast< char* >( base_address );
char * char_addr = reinterpret_cast< char* >( addr );
CHECK( (char_base <= addr) && (addr < (char_base + region_size) ) )
<< "Address " << addr << " out of locale shared range!";
}
//#endif
void * allocate( size_t size );
void * allocate_aligned( size_t size, size_t alignment );
void deallocate( void * ptr );
const size_t get_free_memory() const { return segment.get_free_memory(); }
const size_t get_size() const { return segment.get_size(); }
const size_t get_allocated() const { return allocated; }
};
/// global LocaleSharedMemory instance
extern LocaleSharedMemory locale_shared_memory;
} // namespace impl
/// @addtogroup Memory
/// @{
/// Allocate memory in locale shared heap.
template<typename T>
inline T* locale_alloc(size_t n = 1) {
return reinterpret_cast<T*>(impl::locale_shared_memory.allocate(sizeof(T)*n));
}
inline void* locale_alloc(size_t n = 1) {
return impl::locale_shared_memory.allocate(n);
}
template<typename T>
inline T* locale_alloc_aligned(size_t alignment, size_t n = 1) {
return reinterpret_cast<T*>(impl::locale_shared_memory.allocate_aligned(sizeof(T)*n, alignment));
}
inline void* locale_alloc_aligned(size_t alignment, size_t n = 1) {
return impl::locale_shared_memory.allocate_aligned(n, alignment);
}
/// allocate an object in the locale shared heap, passing arguments to its constructor
template< typename T, typename... Args >
inline T* locale_new(Args&&... args) {
return new (locale_alloc<T>()) T(std::forward<Args...>(args...));
}
/// allocate an object in the locale shared heap
template< typename T >
inline T* locale_new() {
return new (locale_alloc<T>()) T();
}
/// allocate an array in the locale shared heap
template< typename T >
inline T* locale_new_array(size_t n = 1) {
return new (locale_alloc<T>(n)) T[n];
}
/// Free memory that was allocated from locale shared heap.
inline void locale_free(void * ptr) {
impl::locale_shared_memory.deallocate(ptr);
}
/// @}
} // namespace Grappa
#endif
<|endoftext|> |
<commit_before>/****************************************************************************
*
* Copyright (c) 2015 PX4 Development Team. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 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. Neither the name PX4 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.
*
****************************************************************************/
/**
* @file ekf2_main.cpp
* Implementation of the attitude and position estimator.
*
* @author Roman Bapst
*/
#include <px4_config.h>
#include <px4_defines.h>
#include <px4_tasks.h>
#include <px4_posix.h>
#include <px4_time.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <fcntl.h>
#include <errno.h>
#include <math.h>
#include <poll.h>
#include <time.h>
#include <float.h>
#include <arch/board/board.h>
#include <systemlib/param/param.h>
#include <systemlib/err.h>
#include <systemlib/systemlib.h>
#include <mathlib/mathlib.h>
#include <mathlib/math/filter/LowPassFilter2p.hpp>
#include <mavlink/mavlink_log.h>
#include <platforms/px4_defines.h>
#include <drivers/drv_hrt.h>
#include <uORB/topics/sensor_combined.h>
#include <uORB/topics/vehicle_gps_position.h>
#include <uORB/topics/airspeed.h>
#include <ecl/EKF/ekf.h>
extern "C" __EXPORT int ekf2_main(int argc, char *argv[]);
class Ekf2;
namespace ekf2
{
Ekf2 *instance;
}
class Ekf2
{
public:
/**
* Constructor
*/
Ekf2();
/**
* Destructor, also kills task.
*/
~Ekf2();
/**
* Start task.
*
* @return OK on success.
*/
int start();
static void task_main_trampoline(int argc, char *argv[]);
void task_main();
void print();
private:
static constexpr float _dt_max = 0.02;
bool _task_should_exit = false; /**< if true, task should exit */
int _control_task = -1; /**< task handle for task */
int _sensors_sub = -1;
int _gps_sub = -1;
int _airspeed_sub = -1;
EstimatorBase *_ekf;
void update_parameters(bool force);
int update_subscriptions();
};
Ekf2::Ekf2()
{
_ekf = new Ekf();
}
Ekf2::~Ekf2()
{
}
void Ekf2::print()
{
_ekf->printStoredGps();
_ekf->printStoredBaro();
_ekf->printStoredMag();
_ekf->printStoredIMU();
}
void Ekf2::task_main()
{
// subscribe to relevant topics
_sensors_sub = orb_subscribe(ORB_ID(sensor_combined));
_gps_sub = orb_subscribe(ORB_ID(vehicle_gps_position));
_airspeed_sub = orb_subscribe(ORB_ID(airspeed));
px4_pollfd_struct_t fds[1];
fds[0].fd = _sensors_sub;
fds[0].events = POLLIN;
while (!_task_should_exit) {
int ret = px4_poll(fds, 1, 1000);
if (ret < 0) {
// Poll error, sleep and try again
usleep(10000);
continue;
} else if (ret == 0 || fds[0].revents != POLLIN) {
// Poll timeout or no new data, do nothing
continue;
}
bool gps_updated = false;
bool airspeed_updated = false;
sensor_combined_s sensors = {};
vehicle_gps_position_s gps = {};
airspeed_s airspeed = {};
orb_copy(ORB_ID(sensor_combined), _sensors_sub, &sensors);
// update all other topics if they have new data
orb_check(_gps_sub, &gps_updated);
if (gps_updated) {
orb_copy(ORB_ID(vehicle_gps_position), _gps_sub, &gps);
}
orb_check(_airspeed_sub, &airspeed_updated);
if (airspeed_updated) {
orb_copy(ORB_ID(airspeed), _airspeed_sub, &airspeed);
}
hrt_abstime now = hrt_absolute_time();
// push imu data into estimator
_ekf->setIMUData(now, sensors.gyro_integral_dt[0], sensors.accelerometer_integral_dt[0],
&sensors.gyro_integral_rad[0], &sensors.accelerometer_integral_m_s[0]);
// read mag data
_ekf->setMagData(sensors.magnetometer_timestamp[0], &sensors.magnetometer_ga[0]);
// read baro data
_ekf->setBaroData(sensors.baro_timestamp[0], &sensors.baro_alt_meter[0]);
// read gps data if available
if (gps_updated) {
struct gps_message gps_msg = {};
gps_msg.time_usec = gps.timestamp_position;
gps_msg.lat = gps.lat;
gps_msg.lon = gps.lon;
gps_msg.alt = gps.alt;
gps_msg.fix_type = gps.fix_type;
gps_msg.eph = gps.eph;
gps_msg.epv = gps.epv;
gps_msg.time_usec_vel = gps.timestamp_velocity;
gps_msg.vel_m_s = gps.vel_m_s;
gps_msg.vel_ned[0] = gps.vel_n_m_s;
gps_msg.vel_ned[1] = gps.vel_e_m_s;
gps_msg.vel_ned[2] = gps.vel_d_m_s;
gps_msg.vel_ned_valid = gps.vel_ned_valid;
_ekf->setGpsData(gps.timestamp_position, &gps_msg);
}
// read airspeed data if available
if (airspeed_updated) {
_ekf->setAirspeedData(airspeed.timestamp, &airspeed.indicated_airspeed_m_s);
}
_ekf->update();
}
}
void Ekf2::task_main_trampoline(int argc, char *argv[])
{
ekf2::instance->task_main();
}
int Ekf2::start()
{
ASSERT(_control_task == -1);
/* start the task */
_control_task = px4_task_spawn_cmd("ekf2",
SCHED_DEFAULT,
SCHED_PRIORITY_MAX - 5,
30000,
(px4_main_t)&Ekf2::task_main_trampoline,
nullptr);
if (_control_task < 0) {
PX4_WARN("task start failed");
return -errno;
}
return OK;
}
int ekf2_main(int argc, char *argv[])
{
if (argc < 1) {
PX4_WARN("usage: ekf2 {start|stop|status}");
return 1;
}
if (!strcmp(argv[1], "start")) {
if (ekf2::instance != nullptr) {
PX4_WARN("already running");
return 1;
}
ekf2::instance = new Ekf2();
if (ekf2::instance == nullptr) {
PX4_WARN("alloc failed");
return 1;
}
if (OK != ekf2::instance->start()) {
delete ekf2::instance;
ekf2::instance = nullptr;
PX4_WARN("start failed");
return 1;
}
return 0;
}
if (!strcmp(argv[1], "stop")) {
if (ekf2::instance == nullptr) {
PX4_WARN("not running");
return 1;
}
delete ekf2::instance;
ekf2::instance = nullptr;
return 0;
}
if (!strcmp(argv[1], "print")) {
if (ekf2::instance != nullptr) {
ekf2::instance->print();
return 0;
}
return 1;
}
if (!strcmp(argv[1], "status")) {
if (ekf2::instance) {
PX4_WARN("running");
return 0;
} else {
PX4_WARN("not running");
return 1;
}
}
PX4_WARN("unrecognized command");
return 1;
}<commit_msg>ekf2 publish attitude position and control state<commit_after>/****************************************************************************
*
* Copyright (c) 2015 PX4 Development Team. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 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. Neither the name PX4 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.
*
****************************************************************************/
/**
* @file ekf2_main.cpp
* Implementation of the attitude and position estimator.
*
* @author Roman Bapst
*/
#include <px4_config.h>
#include <px4_defines.h>
#include <px4_tasks.h>
#include <px4_posix.h>
#include <px4_time.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <fcntl.h>
#include <errno.h>
#include <math.h>
#include <poll.h>
#include <time.h>
#include <float.h>
#include <arch/board/board.h>
#include <systemlib/param/param.h>
#include <systemlib/err.h>
#include <systemlib/systemlib.h>
#include <mathlib/mathlib.h>
#include <mathlib/math/filter/LowPassFilter2p.hpp>
#include <mavlink/mavlink_log.h>
#include <platforms/px4_defines.h>
#include <drivers/drv_hrt.h>
#include <uORB/topics/sensor_combined.h>
#include <uORB/topics/vehicle_gps_position.h>
#include <uORB/topics/airspeed.h>
#include <uORB/topics/vehicle_attitude.h>
#include <uORB/topics/vehicle_local_position.h>
#include <uORB/topics/control_state.h>
#include <ecl/EKF/ekf.h>
extern "C" __EXPORT int ekf2_main(int argc, char *argv[]);
class Ekf2;
namespace ekf2
{
Ekf2 *instance;
}
class Ekf2
{
public:
/**
* Constructor
*/
Ekf2();
/**
* Destructor, also kills task.
*/
~Ekf2();
/**
* Start task.
*
* @return OK on success.
*/
int start();
static void task_main_trampoline(int argc, char *argv[]);
void task_main();
void print();
private:
static constexpr float _dt_max = 0.02;
bool _task_should_exit = false; /**< if true, task should exit */
int _control_task = -1; /**< task handle for task */
int _sensors_sub = -1;
int _gps_sub = -1;
int _airspeed_sub = -1;
orb_advert_t _att_pub;
orb_advert_t _lpos_pub;
orb_advert_t _control_state_pub;
/* Low pass filter for attitude rates */
math::LowPassFilter2p _lp_roll_rate;
math::LowPassFilter2p _lp_pitch_rate;
math::LowPassFilter2p _lp_yaw_rate;
EstimatorBase *_ekf;
void update_parameters(bool force);
int update_subscriptions();
};
Ekf2::Ekf2():
_lp_roll_rate(250.0f, 30.0f),
_lp_pitch_rate(250.0f, 30.0f),
_lp_yaw_rate(250.0f, 20.0f)
{
_ekf = new Ekf();
_att_pub = nullptr;
_lpos_pub = nullptr;
_control_state_pub = nullptr;
}
Ekf2::~Ekf2()
{
}
void Ekf2::print()
{
_ekf->printStoredGps();
_ekf->printStoredBaro();
_ekf->printStoredMag();
_ekf->printStoredIMU();
}
void Ekf2::task_main()
{
// subscribe to relevant topics
_sensors_sub = orb_subscribe(ORB_ID(sensor_combined));
_gps_sub = orb_subscribe(ORB_ID(vehicle_gps_position));
_airspeed_sub = orb_subscribe(ORB_ID(airspeed));
px4_pollfd_struct_t fds[1];
fds[0].fd = _sensors_sub;
fds[0].events = POLLIN;
while (!_task_should_exit) {
int ret = px4_poll(fds, 1, 1000);
if (ret < 0) {
// Poll error, sleep and try again
usleep(10000);
continue;
} else if (ret == 0 || fds[0].revents != POLLIN) {
// Poll timeout or no new data, do nothing
continue;
}
bool gps_updated = false;
bool airspeed_updated = false;
sensor_combined_s sensors = {};
vehicle_gps_position_s gps = {};
airspeed_s airspeed = {};
orb_copy(ORB_ID(sensor_combined), _sensors_sub, &sensors);
// update all other topics if they have new data
orb_check(_gps_sub, &gps_updated);
if (gps_updated) {
orb_copy(ORB_ID(vehicle_gps_position), _gps_sub, &gps);
}
orb_check(_airspeed_sub, &airspeed_updated);
if (airspeed_updated) {
orb_copy(ORB_ID(airspeed), _airspeed_sub, &airspeed);
}
hrt_abstime now = hrt_absolute_time();
// push imu data into estimator
_ekf->setIMUData(now, sensors.gyro_integral_dt[0], sensors.accelerometer_integral_dt[0],
&sensors.gyro_integral_rad[0], &sensors.accelerometer_integral_m_s[0]);
// read mag data
_ekf->setMagData(sensors.magnetometer_timestamp[0], &sensors.magnetometer_ga[0]);
// read baro data
_ekf->setBaroData(sensors.baro_timestamp[0], &sensors.baro_alt_meter[0]);
// read gps data if available
if (gps_updated) {
struct gps_message gps_msg = {};
gps_msg.time_usec = gps.timestamp_position;
gps_msg.lat = gps.lat;
gps_msg.lon = gps.lon;
gps_msg.alt = gps.alt;
gps_msg.fix_type = gps.fix_type;
gps_msg.eph = gps.eph;
gps_msg.epv = gps.epv;
gps_msg.time_usec_vel = gps.timestamp_velocity;
gps_msg.vel_m_s = gps.vel_m_s;
gps_msg.vel_ned[0] = gps.vel_n_m_s;
gps_msg.vel_ned[1] = gps.vel_e_m_s;
gps_msg.vel_ned[2] = gps.vel_d_m_s;
gps_msg.vel_ned_valid = gps.vel_ned_valid;
_ekf->setGpsData(gps.timestamp_position, &gps_msg);
}
// read airspeed data if available
if (airspeed_updated) {
_ekf->setAirspeedData(airspeed.timestamp, &airspeed.indicated_airspeed_m_s);
}
struct vehicle_attitude_s att;
struct vehicle_local_position_s lpos;
att.timestamp = hrt_absolute_time();
lpos.timestamp = hrt_absolute_time();
_ekf->update();
_ekf->copy_quaternion(att.q);
matrix::Quaternion<float> q(att.q[0], att.q[1], att.q[2], att.q[3]);
matrix::Euler<float> euler(q);
att.roll = euler(0);
att.pitch = euler(1);
att.yaw = euler(2);
float pos[3] = {};
float vel[3] = {};
_ekf->copy_position(pos);
lpos.x = pos[0];
lpos.y = pos[1];
lpos.z = pos[2];
_ekf->copy_velocity(vel);
lpos.vx = vel[0];
lpos.vy = vel[1];
lpos.vz = vel[2];
control_state_s ctrl_state = {};
ctrl_state.timestamp = hrt_absolute_time();
ctrl_state.roll_rate = _lp_roll_rate.apply(sensors.gyro_rad_s[0]);
ctrl_state.pitch_rate = _lp_pitch_rate.apply(sensors.gyro_rad_s[1]);
ctrl_state.yaw_rate = _lp_yaw_rate.apply(sensors.gyro_rad_s[2]);
ctrl_state.q[0] = q(0);
ctrl_state.q[1] = q(1);
ctrl_state.q[2] = q(2);
ctrl_state.q[3] = q(3);
if (_control_state_pub == nullptr) {
_control_state_pub = orb_advertise(ORB_ID(control_state), &ctrl_state);
} else {
orb_publish(ORB_ID(control_state), _control_state_pub, &ctrl_state);
}
if (_att_pub == nullptr) {
_att_pub = orb_advertise(ORB_ID(vehicle_attitude), &att);
} else {
orb_publish(ORB_ID(vehicle_attitude), _att_pub, &att);
}
if (_lpos_pub == nullptr) {
_lpos_pub = orb_advertise(ORB_ID(vehicle_local_position), &lpos);
} else {
orb_publish(ORB_ID(vehicle_local_position), _lpos_pub, &lpos);
}
}
}
void Ekf2::task_main_trampoline(int argc, char *argv[])
{
ekf2::instance->task_main();
}
int Ekf2::start()
{
ASSERT(_control_task == -1);
/* start the task */
_control_task = px4_task_spawn_cmd("ekf2",
SCHED_DEFAULT,
SCHED_PRIORITY_MAX - 5,
30000,
(px4_main_t)&Ekf2::task_main_trampoline,
nullptr);
if (_control_task < 0) {
PX4_WARN("task start failed");
return -errno;
}
return OK;
}
int ekf2_main(int argc, char *argv[])
{
if (argc < 1) {
PX4_WARN("usage: ekf2 {start|stop|status}");
return 1;
}
if (!strcmp(argv[1], "start")) {
if (ekf2::instance != nullptr) {
PX4_WARN("already running");
return 1;
}
ekf2::instance = new Ekf2();
if (ekf2::instance == nullptr) {
PX4_WARN("alloc failed");
return 1;
}
if (OK != ekf2::instance->start()) {
delete ekf2::instance;
ekf2::instance = nullptr;
PX4_WARN("start failed");
return 1;
}
return 0;
}
if (!strcmp(argv[1], "stop")) {
if (ekf2::instance == nullptr) {
PX4_WARN("not running");
return 1;
}
delete ekf2::instance;
ekf2::instance = nullptr;
return 0;
}
if (!strcmp(argv[1], "print")) {
if (ekf2::instance != nullptr) {
ekf2::instance->print();
return 0;
}
return 1;
}
if (!strcmp(argv[1], "status")) {
if (ekf2::instance) {
PX4_WARN("running");
return 0;
} else {
PX4_WARN("not running");
return 1;
}
}
PX4_WARN("unrecognized command");
return 1;
}<|endoftext|> |
<commit_before>/*
* Response.cpp
*
* Copyright (C) 2009-12 by RStudio, Inc.
*
* Unless you have received this program directly from RStudio pursuant
* to the terms of a commercial license agreement with RStudio, then
* this program is licensed to you under the terms of version 3 of the
* GNU Affero General Public License. This program is distributed WITHOUT
* ANY EXPRESS OR IMPLIED WARRANTY, INCLUDING THOSE OF NON-INFRINGEMENT,
* MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Please refer to the
* AGPL (http://www.gnu.org/licenses/agpl-3.0.txt) for more details.
*
*/
#include <core/http/Response.hpp>
#include <algorithm>
#include <boost/regex.hpp>
#include <boost/format.hpp>
#include <boost/lexical_cast.hpp>
#include <boost/algorithm/string.hpp>
#include <boost/date_time/posix_time/posix_time.hpp>
#include <boost/asio/buffer.hpp>
#include <core/http/URL.hpp>
#include <core/http/Util.hpp>
#include <core/http/Cookie.hpp>
#include <core/Hash.hpp>
#include <core/FileSerializer.hpp>
namespace core {
namespace http {
Response::Response()
: Message(), statusCode_(status::Ok)
{
}
const std::string& Response::statusMessage() const
{
ensureStatusMessage();
return statusMessage_;
}
void Response::setStatusMessage(const std::string& statusMessage)
{
statusMessage_ = statusMessage ;
}
std::string Response::contentEncoding() const
{
return headerValue("Content-Encoding");
}
void Response::setContentEncoding(const std::string& encoding)
{
setHeader("Content-Encoding", encoding);
}
void Response::setCacheWithRevalidationHeaders()
{
setHeader("Expires", http::util::httpDate());
setHeader("Cache-Control", "public, max-age=0, must-revalidate");
}
void Response::setCacheForeverHeaders(bool publicAccessiblity)
{
// set Expires header
using namespace boost::posix_time;
time_duration yearDuration = hours(365 * 24);
ptime expireTime = second_clock::universal_time() + yearDuration;
setHeader("Expires", http::util::httpDate(expireTime));
// set Cache-Control header
int durationSeconds = yearDuration.total_seconds();
std::string accessibility = publicAccessiblity ? "public" : "private";
std::string cacheControl(accessibility + ", max-age=" +
safe_convert::numberToString(durationSeconds));
setHeader("Cache-Control", cacheControl);
}
void Response::setCacheForeverHeaders()
{
setCacheForeverHeaders(true);
}
void Response::setPrivateCacheForeverHeaders()
{
// NOTE: the Google article referenced above indicates that for the
// private scenario you should set the Expires header in the past so
// that HTTP 1.0 proxies never cache it. Unfortuantely when running
// against localhost in Firefox we observed that this prevented Firefox
// from caching.
setCacheForeverHeaders(false);
}
// WARNING: This appears to break IE8 if Content-Disposition: attachment
void Response::setNoCacheHeaders()
{
setHeader("Expires", "Fri, 01 Jan 1990 00:00:00 GMT");
setHeader("Pragma", "no-cache");
setHeader("Cache-Control",
"no-cache, no-store, max-age=0, must-revalidate");
}
void Response::setChromeFrameCompatible(const Request& request)
{
if (boost::algorithm::contains(request.userAgent(), "chromeframe"))
setHeader("X-UA-Compatible", "chrome=1");
}
void Response::addCookie(const Cookie& cookie)
{
addHeader("Set-Cookie", cookie.cookieHeaderValue()) ;
}
Error Response::setBody(const std::string& content)
{
std::istringstream is(content);
return setBody(is);
}
void Response::setDynamicHtml(const std::string& html,
const Request& request)
{
// dynamic html
setContentType("text/html");
setNoCacheHeaders();
// gzip if possible
if (request.acceptsEncoding(kGzipEncoding))
setContentEncoding(kGzipEncoding);
// set body
setBody(html);
}
void Response::setRangeableFile(const FilePath& filePath,
const Request& request)
{
// read the file in from disk
std::string contents;
Error error = core::readStringFromFile(filePath, &contents);
if (error)
{
setError(error);
return;
}
// set content type
setContentType(filePath.mimeContentType());
// parse the range field
std::string range = request.headerValue("Range");
boost::regex re("bytes=(\\d*)\\-(\\d*)");
boost::smatch match;
if (boost::regex_match(range, match, re))
{
// specify partial content
setStatusCode(http::status::PartialContent);
// determine the byte range
const size_t kNone = -1;
size_t begin = safe_convert::stringTo<size_t>(match[1], kNone);
size_t end = safe_convert::stringTo<size_t>(match[2], kNone);
size_t total = contents.length();
if (end == kNone)
{
end = total-1;
}
if (begin == kNone)
{
begin = total - end;
end = total-1;
}
// set the byte range
addHeader("Accept-Ranges", "bytes");
boost::format fmt("bytes %1%-%2%/%3%");
std::string range = boost::str(fmt % begin % end % contents.length());
addHeader("Content-Range", range);
// always attempt gzip
if (request.acceptsEncoding(http::kGzipEncoding))
setContentEncoding(http::kGzipEncoding);
// set body
if (begin == 0 && end == (contents.length()-1))
setBody(contents);
else
setBody(contents.substr(begin, end-begin));
}
else
{
setStatusCode(http::status::RangeNotSatisfiable);
boost::format fmt("bytes */%1%");
std::string range = boost::str(fmt % contents.length());
addHeader("Content-Range", range);
}
}
void Response::setBodyUnencoded(const std::string& body)
{
removeHeader("Content-Encoding");
body_ = body;
setContentLength(body_.length());
}
void Response::setError(int statusCode, const std::string& message)
{
setStatusCode(statusCode);
removeCachingHeaders();
setContentType("text/plain");
setBodyUnencoded(message);
}
void Response::setError(const Error& error)
{
setError(status::InternalServerError, error.code().message());
}
namespace {
// only take up to the first newline to prevent http response split
std::string safeLocation(const std::string& location)
{
std::vector<std::string> lines;
boost::algorithm::split(lines,
location,
boost::algorithm::is_any_of("\r\n"));
return lines.size() > 0 ? lines[0] : "";
}
} // anonymous namespace
void Response::setMovedPermanently(const http::Request& request,
const std::string& location)
{
std::string uri = URL::complete(request.absoluteUri(),
safeLocation(location));
setError(http::status::MovedPermanently, uri);
setHeader("Location", uri);
}
void Response::setMovedTemporarily(const http::Request& request,
const std::string& location)
{
std::string uri = URL::complete(request.absoluteUri(),
safeLocation(location));
setError(http::status::MovedTemporarily, uri);
setHeader("Location", uri);
}
void Response::resetMembers()
{
statusCode_ = status::Ok ;
statusCodeStr_.clear() ;
statusMessage_.clear() ;
}
void Response::removeCachingHeaders()
{
removeHeader("Expires");
removeHeader("Pragma");
removeHeader("Cache-Control");
removeHeader("Last-Modified");
removeHeader("ETag");
}
std::string Response::eTagForContent(const std::string& content)
{
return core::hash::crc32Hash(content);
}
void Response::appendFirstLineBuffers(
std::vector<boost::asio::const_buffer>& buffers) const
{
// create status code string (needs to be a member so memory is still valid
// for use of buffers)
std::ostringstream statusCodeStream ;
statusCodeStream << statusCode_ ;
statusCodeStr_ = statusCodeStream.str() ;
// status line
appendHttpVersionBuffers(buffers) ;
appendSpaceBuffer(buffers) ;
buffers.push_back(boost::asio::buffer(statusCodeStr_)) ;
appendSpaceBuffer(buffers) ;
ensureStatusMessage() ;
buffers.push_back(boost::asio::buffer(statusMessage_)) ;
}
namespace status {
namespace Message {
const char * const Ok = "OK" ;
const char * const Created = "Created";
const char * const PartialContent = "Partial Content";
const char * const MovedPermanently = "Moved Permanently" ;
const char * const MovedTemporarily = "Moved Temporarily" ;
const char * const SeeOther = "See Other" ;
const char * const NotModified = "Not Modified" ;
const char * const BadRequest = "Bad Request" ;
const char * const Unauthorized = "Unauthorized" ;
const char * const Forbidden = "Forbidden" ;
const char * const NotFound = "Not Found" ;
const char * const MethodNotAllowed = "Method Not Allowed" ;
const char * const RangeNotSatisfiable = "Range Not Satisfyable";
const char * const InternalServerError = "Internal Server Error" ;
const char * const NotImplemented = "Not Implemented" ;
const char * const BadGateway = "Bad Gateway" ;
const char * const ServiceUnavailable = "Service Unavailable" ;
const char * const GatewayTimeout = "Gateway Timeout" ;
} // namespace Message
} // namespace status
void Response::ensureStatusMessage() const
{
if ( statusMessage_.empty() )
{
using namespace status ;
switch(statusCode_)
{
case Ok:
statusMessage_ = status::Message::Ok ;
break;
case Created:
statusMessage_ = status::Message::Created;
break;
case PartialContent:
statusMessage_ = status::Message::PartialContent;
break;
case MovedPermanently:
statusMessage_ = status::Message::MovedPermanently ;
break;
case MovedTemporarily:
statusMessage_ = status::Message::MovedTemporarily ;
break;
case SeeOther:
statusMessage_ = status::Message::SeeOther ;
break;
case NotModified:
statusMessage_ = status::Message::NotModified ;
break;
case BadRequest:
statusMessage_ = status::Message::BadRequest ;
break;
case Unauthorized:
statusMessage_ = status::Message::Unauthorized ;
break;
case Forbidden:
statusMessage_ = status::Message::Forbidden ;
break;
case NotFound:
statusMessage_ = status::Message::NotFound ;
break;
case MethodNotAllowed:
statusMessage_ = status::Message::MethodNotAllowed ;
break;
case RangeNotSatisfiable:
statusMessage_ = status::Message::RangeNotSatisfiable;
break;
case InternalServerError:
statusMessage_ = status::Message::InternalServerError ;
break;
case NotImplemented:
statusMessage_ = status::Message::NotImplemented ;
break;
case BadGateway:
statusMessage_ = status::Message::BadGateway ;
break;
case ServiceUnavailable:
statusMessage_ = status::Message::ServiceUnavailable ;
break;
case GatewayTimeout:
statusMessage_ = status::Message::GatewayTimeout ;
break;
}
}
}
std::ostream& operator << (std::ostream& stream, const Response& r)
{
// output status line
stream << "HTTP/" << r.httpVersionMajor() << "." << r.httpVersionMinor()
<< " " << r.statusCode() << " " << r.statusMessage()
<< std::endl ;
// output headers and body
const Message& m = r ;
stream << m ;
return stream ;
}
} // namespacc http
} // namespace core
<commit_msg>correct logic for partial byte range fetch<commit_after>/*
* Response.cpp
*
* Copyright (C) 2009-12 by RStudio, Inc.
*
* Unless you have received this program directly from RStudio pursuant
* to the terms of a commercial license agreement with RStudio, then
* this program is licensed to you under the terms of version 3 of the
* GNU Affero General Public License. This program is distributed WITHOUT
* ANY EXPRESS OR IMPLIED WARRANTY, INCLUDING THOSE OF NON-INFRINGEMENT,
* MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Please refer to the
* AGPL (http://www.gnu.org/licenses/agpl-3.0.txt) for more details.
*
*/
#include <core/http/Response.hpp>
#include <algorithm>
#include <boost/regex.hpp>
#include <boost/format.hpp>
#include <boost/lexical_cast.hpp>
#include <boost/algorithm/string.hpp>
#include <boost/date_time/posix_time/posix_time.hpp>
#include <boost/asio/buffer.hpp>
#include <core/http/URL.hpp>
#include <core/http/Util.hpp>
#include <core/http/Cookie.hpp>
#include <core/Hash.hpp>
#include <core/FileSerializer.hpp>
namespace core {
namespace http {
Response::Response()
: Message(), statusCode_(status::Ok)
{
}
const std::string& Response::statusMessage() const
{
ensureStatusMessage();
return statusMessage_;
}
void Response::setStatusMessage(const std::string& statusMessage)
{
statusMessage_ = statusMessage ;
}
std::string Response::contentEncoding() const
{
return headerValue("Content-Encoding");
}
void Response::setContentEncoding(const std::string& encoding)
{
setHeader("Content-Encoding", encoding);
}
void Response::setCacheWithRevalidationHeaders()
{
setHeader("Expires", http::util::httpDate());
setHeader("Cache-Control", "public, max-age=0, must-revalidate");
}
void Response::setCacheForeverHeaders(bool publicAccessiblity)
{
// set Expires header
using namespace boost::posix_time;
time_duration yearDuration = hours(365 * 24);
ptime expireTime = second_clock::universal_time() + yearDuration;
setHeader("Expires", http::util::httpDate(expireTime));
// set Cache-Control header
int durationSeconds = yearDuration.total_seconds();
std::string accessibility = publicAccessiblity ? "public" : "private";
std::string cacheControl(accessibility + ", max-age=" +
safe_convert::numberToString(durationSeconds));
setHeader("Cache-Control", cacheControl);
}
void Response::setCacheForeverHeaders()
{
setCacheForeverHeaders(true);
}
void Response::setPrivateCacheForeverHeaders()
{
// NOTE: the Google article referenced above indicates that for the
// private scenario you should set the Expires header in the past so
// that HTTP 1.0 proxies never cache it. Unfortuantely when running
// against localhost in Firefox we observed that this prevented Firefox
// from caching.
setCacheForeverHeaders(false);
}
// WARNING: This appears to break IE8 if Content-Disposition: attachment
void Response::setNoCacheHeaders()
{
setHeader("Expires", "Fri, 01 Jan 1990 00:00:00 GMT");
setHeader("Pragma", "no-cache");
setHeader("Cache-Control",
"no-cache, no-store, max-age=0, must-revalidate");
}
void Response::setChromeFrameCompatible(const Request& request)
{
if (boost::algorithm::contains(request.userAgent(), "chromeframe"))
setHeader("X-UA-Compatible", "chrome=1");
}
void Response::addCookie(const Cookie& cookie)
{
addHeader("Set-Cookie", cookie.cookieHeaderValue()) ;
}
Error Response::setBody(const std::string& content)
{
std::istringstream is(content);
return setBody(is);
}
void Response::setDynamicHtml(const std::string& html,
const Request& request)
{
// dynamic html
setContentType("text/html");
setNoCacheHeaders();
// gzip if possible
if (request.acceptsEncoding(kGzipEncoding))
setContentEncoding(kGzipEncoding);
// set body
setBody(html);
}
void Response::setRangeableFile(const FilePath& filePath,
const Request& request)
{
// read the file in from disk
std::string contents;
Error error = core::readStringFromFile(filePath, &contents);
if (error)
{
setError(error);
return;
}
// set content type
setContentType(filePath.mimeContentType());
// parse the range field
std::string range = request.headerValue("Range");
boost::regex re("bytes=(\\d*)\\-(\\d*)");
boost::smatch match;
if (boost::regex_match(range, match, re))
{
// specify partial content
setStatusCode(http::status::PartialContent);
// determine the byte range
const size_t kNone = -1;
size_t begin = safe_convert::stringTo<size_t>(match[1], kNone);
size_t end = safe_convert::stringTo<size_t>(match[2], kNone);
size_t total = contents.length();
if (end == kNone)
{
end = total-1;
}
if (begin == kNone)
{
begin = total - end;
end = total-1;
}
// set the byte range
addHeader("Accept-Ranges", "bytes");
boost::format fmt("bytes %1%-%2%/%3%");
std::string range = boost::str(fmt % begin % end % contents.length());
addHeader("Content-Range", range);
// always attempt gzip
if (request.acceptsEncoding(http::kGzipEncoding))
setContentEncoding(http::kGzipEncoding);
// set body
if (begin == 0 && end == (contents.length()-1))
setBody(contents);
else
setBody(contents.substr(begin, end-begin+1));
}
else
{
setStatusCode(http::status::RangeNotSatisfiable);
boost::format fmt("bytes */%1%");
std::string range = boost::str(fmt % contents.length());
addHeader("Content-Range", range);
}
}
void Response::setBodyUnencoded(const std::string& body)
{
removeHeader("Content-Encoding");
body_ = body;
setContentLength(body_.length());
}
void Response::setError(int statusCode, const std::string& message)
{
setStatusCode(statusCode);
removeCachingHeaders();
setContentType("text/plain");
setBodyUnencoded(message);
}
void Response::setError(const Error& error)
{
setError(status::InternalServerError, error.code().message());
}
namespace {
// only take up to the first newline to prevent http response split
std::string safeLocation(const std::string& location)
{
std::vector<std::string> lines;
boost::algorithm::split(lines,
location,
boost::algorithm::is_any_of("\r\n"));
return lines.size() > 0 ? lines[0] : "";
}
} // anonymous namespace
void Response::setMovedPermanently(const http::Request& request,
const std::string& location)
{
std::string uri = URL::complete(request.absoluteUri(),
safeLocation(location));
setError(http::status::MovedPermanently, uri);
setHeader("Location", uri);
}
void Response::setMovedTemporarily(const http::Request& request,
const std::string& location)
{
std::string uri = URL::complete(request.absoluteUri(),
safeLocation(location));
setError(http::status::MovedTemporarily, uri);
setHeader("Location", uri);
}
void Response::resetMembers()
{
statusCode_ = status::Ok ;
statusCodeStr_.clear() ;
statusMessage_.clear() ;
}
void Response::removeCachingHeaders()
{
removeHeader("Expires");
removeHeader("Pragma");
removeHeader("Cache-Control");
removeHeader("Last-Modified");
removeHeader("ETag");
}
std::string Response::eTagForContent(const std::string& content)
{
return core::hash::crc32Hash(content);
}
void Response::appendFirstLineBuffers(
std::vector<boost::asio::const_buffer>& buffers) const
{
// create status code string (needs to be a member so memory is still valid
// for use of buffers)
std::ostringstream statusCodeStream ;
statusCodeStream << statusCode_ ;
statusCodeStr_ = statusCodeStream.str() ;
// status line
appendHttpVersionBuffers(buffers) ;
appendSpaceBuffer(buffers) ;
buffers.push_back(boost::asio::buffer(statusCodeStr_)) ;
appendSpaceBuffer(buffers) ;
ensureStatusMessage() ;
buffers.push_back(boost::asio::buffer(statusMessage_)) ;
}
namespace status {
namespace Message {
const char * const Ok = "OK" ;
const char * const Created = "Created";
const char * const PartialContent = "Partial Content";
const char * const MovedPermanently = "Moved Permanently" ;
const char * const MovedTemporarily = "Moved Temporarily" ;
const char * const SeeOther = "See Other" ;
const char * const NotModified = "Not Modified" ;
const char * const BadRequest = "Bad Request" ;
const char * const Unauthorized = "Unauthorized" ;
const char * const Forbidden = "Forbidden" ;
const char * const NotFound = "Not Found" ;
const char * const MethodNotAllowed = "Method Not Allowed" ;
const char * const RangeNotSatisfiable = "Range Not Satisfyable";
const char * const InternalServerError = "Internal Server Error" ;
const char * const NotImplemented = "Not Implemented" ;
const char * const BadGateway = "Bad Gateway" ;
const char * const ServiceUnavailable = "Service Unavailable" ;
const char * const GatewayTimeout = "Gateway Timeout" ;
} // namespace Message
} // namespace status
void Response::ensureStatusMessage() const
{
if ( statusMessage_.empty() )
{
using namespace status ;
switch(statusCode_)
{
case Ok:
statusMessage_ = status::Message::Ok ;
break;
case Created:
statusMessage_ = status::Message::Created;
break;
case PartialContent:
statusMessage_ = status::Message::PartialContent;
break;
case MovedPermanently:
statusMessage_ = status::Message::MovedPermanently ;
break;
case MovedTemporarily:
statusMessage_ = status::Message::MovedTemporarily ;
break;
case SeeOther:
statusMessage_ = status::Message::SeeOther ;
break;
case NotModified:
statusMessage_ = status::Message::NotModified ;
break;
case BadRequest:
statusMessage_ = status::Message::BadRequest ;
break;
case Unauthorized:
statusMessage_ = status::Message::Unauthorized ;
break;
case Forbidden:
statusMessage_ = status::Message::Forbidden ;
break;
case NotFound:
statusMessage_ = status::Message::NotFound ;
break;
case MethodNotAllowed:
statusMessage_ = status::Message::MethodNotAllowed ;
break;
case RangeNotSatisfiable:
statusMessage_ = status::Message::RangeNotSatisfiable;
break;
case InternalServerError:
statusMessage_ = status::Message::InternalServerError ;
break;
case NotImplemented:
statusMessage_ = status::Message::NotImplemented ;
break;
case BadGateway:
statusMessage_ = status::Message::BadGateway ;
break;
case ServiceUnavailable:
statusMessage_ = status::Message::ServiceUnavailable ;
break;
case GatewayTimeout:
statusMessage_ = status::Message::GatewayTimeout ;
break;
}
}
}
std::ostream& operator << (std::ostream& stream, const Response& r)
{
// output status line
stream << "HTTP/" << r.httpVersionMajor() << "." << r.httpVersionMinor()
<< " " << r.statusCode() << " " << r.statusMessage()
<< std::endl ;
// output headers and body
const Message& m = r ;
stream << m ;
return stream ;
}
} // namespacc http
} // namespace core
<|endoftext|> |
<commit_before>// Copyright 2020 Tangent Animation
//
// 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,
// including without limitation, as related to merchantability and fitness
// for a particular purpose.
//
// In no event shall any copyright holder be liable for any damages of any kind
// arising from the use of this software, whether in contract, tort or otherwise.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "renderBuffer.h"
#include "renderDelegate.h"
#include "renderPass.h"
#include "renderParam.h"
#include <pxr/base/gf/vec2i.h>
#include <pxr/base/gf/vec3i.h>
PXR_NAMESPACE_OPEN_SCOPE
namespace {
template<typename T>
void
_ConvertPixel(HdFormat dstFormat, uint8_t* dst, HdFormat srcFormat, uint8_t const* src)
{
HdFormat srcComponentFormat = HdGetComponentFormat(srcFormat);
HdFormat dstComponentFormat = HdGetComponentFormat(dstFormat);
size_t srcComponentCount = HdGetComponentCount(srcFormat);
size_t dstComponentCount = HdGetComponentCount(dstFormat);
for (size_t c = 0; c < dstComponentCount; ++c) {
T readValue = 0;
if (c < srcComponentCount) {
if (srcComponentFormat == HdFormatInt32) {
readValue = static_cast<T>(reinterpret_cast<const int32_t*>(src)[c]);
} else if (srcComponentFormat == HdFormatFloat16) {
GfHalf half;
half.setBits(reinterpret_cast<const uint16_t*>(src)[c]);
readValue = static_cast<T>(half);
} else if (srcComponentFormat == HdFormatFloat32) {
// We need to subtract one from here due to cycles prim defaulting to 0 but hydra to -1
readValue = static_cast<T>(reinterpret_cast<const float*>(src)[c]);
} else if (srcComponentFormat == HdFormatUNorm8) {
readValue = static_cast<T>(reinterpret_cast<const uint8_t*>(src)[c] / 255.0f);
} else if (srcComponentFormat == HdFormatSNorm8) {
readValue = static_cast<T>(reinterpret_cast<const int8_t*>(src)[c] / 127.0f);
}
}
if (dstComponentFormat == HdFormatInt32) {
reinterpret_cast<int32_t*>(dst)[c] = static_cast<int32_t>(readValue);
} else if (dstComponentFormat == HdFormatFloat16) {
reinterpret_cast<uint16_t*>(dst)[c] = GfHalf(float(readValue)).bits();
} else if (dstComponentFormat == HdFormatFloat32) {
reinterpret_cast<float*>(dst)[c] = static_cast<float>(readValue);
} else if (dstComponentFormat == HdFormatUNorm8) {
reinterpret_cast<uint8_t*>(dst)[c] = static_cast<uint8_t>(static_cast<float>(readValue) * 255.0f);
} else if (dstComponentFormat == HdFormatSNorm8) {
reinterpret_cast<int8_t*>(dst)[c] = static_cast<int8_t>(static_cast<float>(readValue) * 127.0f);
}
}
}
} // namespace
HdCyclesRenderBuffer::HdCyclesRenderBuffer(HdCyclesRenderDelegate* renderDelegate, const SdfPath& id)
: HdRenderBuffer(id)
, m_width(0)
, m_height(0)
, m_format(HdFormatInvalid)
, m_pixelSize(0)
, m_mappers(0)
, m_converged(false)
, m_renderDelegate(renderDelegate)
, m_wasUpdated(false)
{
}
HdCyclesRenderBuffer::~HdCyclesRenderBuffer() {}
bool
HdCyclesRenderBuffer::Allocate(const GfVec3i& dimensions, HdFormat format, bool multiSampled)
{
_Deallocate();
if (dimensions[2] != 1) {
TF_WARN("Render buffer allocated with dims <%d, %d, %d> and format %s; depth must be 1!", dimensions[0],
dimensions[1], dimensions[2], TfEnum::GetName(format).c_str());
return false;
}
m_mutex.lock();
m_width = static_cast<unsigned int>(dimensions[0]);
m_height = static_cast<unsigned int>(dimensions[1]);
m_format = format;
m_pixelSize = static_cast<unsigned int>(HdDataSizeOfFormat(format));
m_buffer.resize(m_width * m_height * m_pixelSize, 0);
m_mutex.unlock();
return true;
}
unsigned int
HdCyclesRenderBuffer::GetWidth() const
{
return m_width;
}
unsigned int
HdCyclesRenderBuffer::GetHeight() const
{
return m_height;
}
unsigned int
HdCyclesRenderBuffer::GetDepth() const
{
return 1;
}
HdFormat
HdCyclesRenderBuffer::GetFormat() const
{
return m_format;
}
bool
HdCyclesRenderBuffer::IsMultiSampled() const
{
return false;
}
void*
HdCyclesRenderBuffer::Map()
{
if (m_buffer.empty()) {
return nullptr;
}
m_mutex.lock();
m_mappers++;
return m_buffer.data();
}
void
HdCyclesRenderBuffer::Unmap()
{
if (!m_buffer.empty()) {
m_mappers--;
m_mutex.unlock();
}
}
bool
HdCyclesRenderBuffer::IsMapped() const
{
return m_mappers.load() != 0;
}
void
HdCyclesRenderBuffer::Resolve()
{
}
bool
HdCyclesRenderBuffer::IsConverged() const
{
return m_converged.load();
}
void
HdCyclesRenderBuffer::SetConverged(bool cv)
{
m_converged.store(cv);
}
void
HdCyclesRenderBuffer::Clear()
{
if (m_format == HdFormatInvalid)
return;
m_mutex.lock();
size_t pixelSize = HdDataSizeOfFormat(m_format);
memset(&m_buffer[0], 0, m_buffer.size() * pixelSize);
m_mutex.unlock();
}
void
HdCyclesRenderBuffer::Finalize(HdRenderParam *renderParam) {
auto param = dynamic_cast<HdCyclesRenderParam*>(renderParam);
param->tagSettingsDirty();
}
void
HdCyclesRenderBuffer::BlitTile(HdFormat format, unsigned int x, unsigned int y, int unsigned width, unsigned int height,
int offset, int stride, uint8_t const* data)
{
// TODO: BlitTile shouldnt be called but it is...
if (m_width <= 0) {
return;
}
if (m_height <= 0) {
return;
}
if (m_buffer.size() <= 0) {
return;
}
size_t pixelSize = HdDataSizeOfFormat(format);
if (m_format == format) {
for (unsigned int j = 0; j < height; ++j) {
if ((x + width) <= m_width) {
if ((y + height) <= m_height) {
int mem_start = static_cast<int>((((y + j) * m_width) * pixelSize) + (x * pixelSize));
unsigned int tile_mem_start = (j * width) * static_cast<unsigned int>(pixelSize);
memcpy(&m_buffer[mem_start], &data[tile_mem_start], width * pixelSize);
}
}
}
} else {
// Convert pixel by pixel, with nearest point sampling.
// If src and dst are both int-based, don't round trip to float.
bool convertAsInt = (HdGetComponentFormat(format) == HdFormatInt32)
&& (HdGetComponentFormat(m_format) == HdFormatInt32);
for (unsigned int j = 0; j < height; ++j) {
for (unsigned int i = 0; i < width; ++i) {
size_t mem_start = (((y + j) * m_width) * m_pixelSize) + ((x + i) * m_pixelSize);
int tile_mem_start = static_cast<int>(((j * width) * pixelSize) + (i * pixelSize));
if (convertAsInt) {
_ConvertPixel<int32_t>(m_format, &m_buffer[mem_start], format, &data[tile_mem_start]);
} else {
if (mem_start >= m_buffer.size()) {
// TODO: This is triggered more times than it should be
} else {
_ConvertPixel<float>(m_format, &m_buffer[mem_start], format, &data[tile_mem_start]);
}
}
}
}
}
}
void
HdCyclesRenderBuffer::_Deallocate()
{
m_mutex.lock();
m_wasUpdated = true;
m_width = 0;
m_height = 0;
m_format = HdFormatInvalid;
m_buffer.resize(0);
m_mappers.store(0);
m_converged.store(false);
m_mutex.unlock();
}
PXR_NAMESPACE_CLOSE_SCOPE<commit_msg>Removed unused code<commit_after>// Copyright 2020 Tangent Animation
//
// 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,
// including without limitation, as related to merchantability and fitness
// for a particular purpose.
//
// In no event shall any copyright holder be liable for any damages of any kind
// arising from the use of this software, whether in contract, tort or otherwise.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "renderBuffer.h"
#include "renderDelegate.h"
#include "renderPass.h"
#include "renderParam.h"
#include <pxr/base/gf/vec2i.h>
#include <pxr/base/gf/vec3i.h>
PXR_NAMESPACE_OPEN_SCOPE
namespace {
template<typename T>
void
_ConvertPixel(HdFormat dstFormat, uint8_t* dst, HdFormat srcFormat, uint8_t const* src)
{
HdFormat srcComponentFormat = HdGetComponentFormat(srcFormat);
HdFormat dstComponentFormat = HdGetComponentFormat(dstFormat);
size_t srcComponentCount = HdGetComponentCount(srcFormat);
size_t dstComponentCount = HdGetComponentCount(dstFormat);
for (size_t c = 0; c < dstComponentCount; ++c) {
T readValue = 0;
if (c < srcComponentCount) {
if (srcComponentFormat == HdFormatInt32) {
readValue = static_cast<T>(reinterpret_cast<const int32_t*>(src)[c]);
} else if (srcComponentFormat == HdFormatFloat16) {
GfHalf half;
half.setBits(reinterpret_cast<const uint16_t*>(src)[c]);
readValue = static_cast<T>(half);
} else if (srcComponentFormat == HdFormatFloat32) {
// We need to subtract one from here due to cycles prim defaulting to 0 but hydra to -1
readValue = static_cast<T>(reinterpret_cast<const float*>(src)[c]);
} else if (srcComponentFormat == HdFormatUNorm8) {
readValue = static_cast<T>(reinterpret_cast<const uint8_t*>(src)[c] / 255.0f);
} else if (srcComponentFormat == HdFormatSNorm8) {
readValue = static_cast<T>(reinterpret_cast<const int8_t*>(src)[c] / 127.0f);
}
}
if (dstComponentFormat == HdFormatInt32) {
reinterpret_cast<int32_t*>(dst)[c] = static_cast<int32_t>(readValue);
} else if (dstComponentFormat == HdFormatFloat16) {
reinterpret_cast<uint16_t*>(dst)[c] = GfHalf(float(readValue)).bits();
} else if (dstComponentFormat == HdFormatFloat32) {
reinterpret_cast<float*>(dst)[c] = static_cast<float>(readValue);
} else if (dstComponentFormat == HdFormatUNorm8) {
reinterpret_cast<uint8_t*>(dst)[c] = static_cast<uint8_t>(static_cast<float>(readValue) * 255.0f);
} else if (dstComponentFormat == HdFormatSNorm8) {
reinterpret_cast<int8_t*>(dst)[c] = static_cast<int8_t>(static_cast<float>(readValue) * 127.0f);
}
}
}
} // namespace
HdCyclesRenderBuffer::HdCyclesRenderBuffer(HdCyclesRenderDelegate* renderDelegate, const SdfPath& id)
: HdRenderBuffer(id)
, m_width(0)
, m_height(0)
, m_format(HdFormatInvalid)
, m_pixelSize(0)
, m_mappers(0)
, m_converged(false)
, m_renderDelegate(renderDelegate)
, m_wasUpdated(false)
{
}
HdCyclesRenderBuffer::~HdCyclesRenderBuffer() {}
bool
HdCyclesRenderBuffer::Allocate(const GfVec3i& dimensions, HdFormat format, bool multiSampled)
{
_Deallocate();
if (dimensions[2] != 1) {
TF_WARN("Render buffer allocated with dims <%d, %d, %d> and format %s; depth must be 1!", dimensions[0],
dimensions[1], dimensions[2], TfEnum::GetName(format).c_str());
return false;
}
m_mutex.lock();
m_width = static_cast<unsigned int>(dimensions[0]);
m_height = static_cast<unsigned int>(dimensions[1]);
m_format = format;
m_pixelSize = static_cast<unsigned int>(HdDataSizeOfFormat(format));
m_buffer.resize(m_width * m_height * m_pixelSize, 0);
m_mutex.unlock();
return true;
}
unsigned int
HdCyclesRenderBuffer::GetWidth() const
{
return m_width;
}
unsigned int
HdCyclesRenderBuffer::GetHeight() const
{
return m_height;
}
unsigned int
HdCyclesRenderBuffer::GetDepth() const
{
return 1;
}
HdFormat
HdCyclesRenderBuffer::GetFormat() const
{
return m_format;
}
bool
HdCyclesRenderBuffer::IsMultiSampled() const
{
return false;
}
void*
HdCyclesRenderBuffer::Map()
{
if (m_buffer.empty()) {
return nullptr;
}
m_mutex.lock();
m_mappers++;
return m_buffer.data();
}
void
HdCyclesRenderBuffer::Unmap()
{
if (!m_buffer.empty()) {
m_mappers--;
m_mutex.unlock();
}
}
bool
HdCyclesRenderBuffer::IsMapped() const
{
return m_mappers.load() != 0;
}
void
HdCyclesRenderBuffer::Resolve()
{
}
bool
HdCyclesRenderBuffer::IsConverged() const
{
return m_converged.load();
}
void
HdCyclesRenderBuffer::SetConverged(bool cv)
{
m_converged.store(cv);
}
void
HdCyclesRenderBuffer::Clear()
{
if (m_format == HdFormatInvalid)
return;
m_mutex.lock();
size_t pixelSize = HdDataSizeOfFormat(m_format);
memset(&m_buffer[0], 0, m_buffer.size() * pixelSize);
m_mutex.unlock();
}
void
HdCyclesRenderBuffer::Finalize(HdRenderParam *renderParam) {
auto param = dynamic_cast<HdCyclesRenderParam*>(renderParam);
param->tagSettingsDirty();
}
void
HdCyclesRenderBuffer::BlitTile(HdFormat format, unsigned int x, unsigned int y, int unsigned width, unsigned int height,
int offset, int stride, uint8_t const* data)
{
// TODO: BlitTile shouldnt be called but it is...
if (m_width <= 0) {
return;
}
if (m_height <= 0) {
return;
}
if (m_buffer.size() <= 0) {
return;
}
size_t pixelSize = HdDataSizeOfFormat(format);
if (m_format == format) {
for (unsigned int j = 0; j < height; ++j) {
if ((x + width) <= m_width) {
if ((y + height) <= m_height) {
int mem_start = static_cast<int>((((y + j) * m_width) * pixelSize) + (x * pixelSize));
unsigned int tile_mem_start = (j * width) * static_cast<unsigned int>(pixelSize);
memcpy(&m_buffer[mem_start], &data[tile_mem_start], width * pixelSize);
}
}
}
} else {
// Convert pixel by pixel, with nearest point sampling.
// If src and dst are both int-based, don't round trip to float.
bool convertAsInt = (HdGetComponentFormat(format) == HdFormatInt32)
&& (HdGetComponentFormat(m_format) == HdFormatInt32);
for (unsigned int j = 0; j < height; ++j) {
for (unsigned int i = 0; i < width; ++i) {
size_t mem_start = (((y + j) * m_width) * m_pixelSize) + ((x + i) * m_pixelSize);
int tile_mem_start = static_cast<int>(((j * width) * pixelSize) + (i * pixelSize));
if (convertAsInt) {
_ConvertPixel<int32_t>(m_format, &m_buffer[mem_start], format, &data[tile_mem_start]);
} else {
if (mem_start >= m_buffer.size()) {
// TODO: This is triggered more times than it should be
} else {
_ConvertPixel<float>(m_format, &m_buffer[mem_start], format, &data[tile_mem_start]);
}
}
}
}
}
}
void
HdCyclesRenderBuffer::_Deallocate()
{
m_mutex.lock();
m_wasUpdated = true;
m_width = 0;
m_height = 0;
m_format = HdFormatInvalid;
std::vector<float> buffer_empty {};
m_buffer.swap(buffer_empty);
m_mappers.store(0);
m_converged.store(false);
m_mutex.unlock();
}
PXR_NAMESPACE_CLOSE_SCOPE<|endoftext|> |
<commit_before>//---------------------------------------------------------
// Copyright 2020 Ontario Institute for Cancer Research
// Written by Jared Simpson ([email protected])
//
// nanopolish fast5-check - check fast5 files for common
// I/O problems
//
//---------------------------------------------------------
//
//
// Getopt
//
#define SUBPROGRAM "fast5-check"
#include <iostream>
#include <fstream>
#include <sstream>
#include <getopt.h>
#include <fast5.hpp>
#include "nanopolish_fast5_check.h"
#include "nanopolish_common.h"
#include "nanopolish_read_db.h"
#include "fs_support.hpp"
#include "nanopolish_fast5_io.h"
static const char *FAST5_CHECK_VERSION_MESSAGE =
SUBPROGRAM " Version " PACKAGE_VERSION "\n"
"Written by Jared Simpson.\n"
"\n"
"Copyright 2020 Ontario Institute for Cancer Research\n";
static const char *FAST5_CHECK_USAGE_MESSAGE =
"Usage: " PACKAGE_NAME " " SUBPROGRAM " [OPTIONS] -r reads.fastq\n"
"Check whether the fast5 files are indexed correctly and readable by nanopolish\n"
"\n"
" --help display this help and exit\n"
" --version display version\n"
" -r, --reads file containing the basecalled reads\n"
"\nReport bugs to " PACKAGE_BUGREPORT "\n\n";
namespace opt
{
static unsigned int verbose = 0;
static std::string reads_file;
}
static const char* shortopts = "vr:";
enum {
OPT_HELP = 1,
OPT_VERSION,
OPT_LOG_LEVEL,
};
static const struct option longopts[] = {
{ "help", no_argument, NULL, OPT_HELP },
{ "version", no_argument, NULL, OPT_VERSION },
{ "log-level", required_argument, NULL, OPT_LOG_LEVEL },
{ "verbose", no_argument, NULL, 'v' },
{ "reads", required_argument, NULL, 'r' },
{ NULL, 0, NULL, 0 }
};
void parse_fast5_check_options(int argc, char** argv)
{
bool die = false;
std::vector< std::string> log_level;
for (char c; (c = getopt_long(argc, argv, shortopts, longopts, NULL)) != -1;) {
std::istringstream arg(optarg != NULL ? optarg : "");
switch (c) {
case OPT_HELP:
std::cout << FAST5_CHECK_USAGE_MESSAGE;
exit(EXIT_SUCCESS);
case OPT_VERSION:
std::cout << FAST5_CHECK_VERSION_MESSAGE;
exit(EXIT_SUCCESS);
case OPT_LOG_LEVEL:
log_level.push_back(arg.str());
break;
case 'v': opt::verbose++; break;
case 'r': arg >> opt::reads_file; break;
}
}
if (argc - optind < 0) {
std::cerr << SUBPROGRAM ": not enough arguments\n";
die = true;
}
if (argc - optind > 0) {
std::cerr << SUBPROGRAM ": too many arguments\n";
die = true;
}
if (die)
{
std::cout << "\n" << FAST5_CHECK_USAGE_MESSAGE;
exit(EXIT_FAILURE);
}
}
void check_read(fast5_file& f5_fh, const std::string& read_name)
{
fast5_raw_scaling scaling = fast5_get_channel_params(f5_fh, read_name);
if(isnan(scaling.digitisation)) {
fprintf(stdout, "\t[read] ERROR: could not read scaling for %s\n", read_name.c_str());
}
raw_table rt = fast5_get_raw_samples(f5_fh, read_name, scaling);
if(rt.n <= 0) {
fprintf(stdout, "\t[read] ERROR: could not read raw samples for %s\n", read_name.c_str());
} else {
fprintf(stdout, "\t[read] OK: found %zu raw samples for %s\n", rt.n, read_name.c_str());
}
free(rt.raw);
rt.raw = NULL;
}
int fast5_check_main(int argc, char** argv)
{
parse_fast5_check_options(argc, argv);
// Attempt to load the read_db
ReadDB read_db;
read_db.load(opt::reads_file);
std::vector<std::string> fast5_files = read_db.get_unique_fast5s();
fprintf(stdout, "The readdb file contains %zu fast5 files\n", fast5_files.size());
for(size_t i = 0; i < fast5_files.size(); ++i) {
fast5_file f5_fh = fast5_open(fast5_files[i]);
if(fast5_is_open(f5_fh)) {
fprintf(stdout, "[fast5] OK: opened %s\n", fast5_files[i].c_str());
// check the individual reads in the file
std::vector<std::string> reads = fast5_get_multi_read_groups(f5_fh);
for(size_t j = 0; j < reads.size(); ++j) {
std::string read_name = reads[j].substr(5);
check_read(f5_fh, read_name);
}
} else {
fprintf(stdout, "[fast5] ERROR: failed to open %s\n", fast5_files[i].c_str());
}
fast5_close(f5_fh);
}
return 0;
}
<commit_msg>do not use isnan<commit_after>//---------------------------------------------------------
// Copyright 2020 Ontario Institute for Cancer Research
// Written by Jared Simpson ([email protected])
//
// nanopolish fast5-check - check fast5 files for common
// I/O problems
//
//---------------------------------------------------------
//
//
// Getopt
//
#define SUBPROGRAM "fast5-check"
#include <iostream>
#include <fstream>
#include <sstream>
#include <getopt.h>
#include <fast5.hpp>
#include "nanopolish_fast5_check.h"
#include "nanopolish_common.h"
#include "nanopolish_read_db.h"
#include "fs_support.hpp"
#include "nanopolish_fast5_io.h"
static const char *FAST5_CHECK_VERSION_MESSAGE =
SUBPROGRAM " Version " PACKAGE_VERSION "\n"
"Written by Jared Simpson.\n"
"\n"
"Copyright 2020 Ontario Institute for Cancer Research\n";
static const char *FAST5_CHECK_USAGE_MESSAGE =
"Usage: " PACKAGE_NAME " " SUBPROGRAM " [OPTIONS] -r reads.fastq\n"
"Check whether the fast5 files are indexed correctly and readable by nanopolish\n"
"\n"
" --help display this help and exit\n"
" --version display version\n"
" -r, --reads file containing the basecalled reads\n"
"\nReport bugs to " PACKAGE_BUGREPORT "\n\n";
namespace opt
{
static unsigned int verbose = 0;
static std::string reads_file;
}
static const char* shortopts = "vr:";
enum {
OPT_HELP = 1,
OPT_VERSION,
OPT_LOG_LEVEL,
};
static const struct option longopts[] = {
{ "help", no_argument, NULL, OPT_HELP },
{ "version", no_argument, NULL, OPT_VERSION },
{ "log-level", required_argument, NULL, OPT_LOG_LEVEL },
{ "verbose", no_argument, NULL, 'v' },
{ "reads", required_argument, NULL, 'r' },
{ NULL, 0, NULL, 0 }
};
void parse_fast5_check_options(int argc, char** argv)
{
bool die = false;
std::vector< std::string> log_level;
for (char c; (c = getopt_long(argc, argv, shortopts, longopts, NULL)) != -1;) {
std::istringstream arg(optarg != NULL ? optarg : "");
switch (c) {
case OPT_HELP:
std::cout << FAST5_CHECK_USAGE_MESSAGE;
exit(EXIT_SUCCESS);
case OPT_VERSION:
std::cout << FAST5_CHECK_VERSION_MESSAGE;
exit(EXIT_SUCCESS);
case OPT_LOG_LEVEL:
log_level.push_back(arg.str());
break;
case 'v': opt::verbose++; break;
case 'r': arg >> opt::reads_file; break;
}
}
if (argc - optind < 0) {
std::cerr << SUBPROGRAM ": not enough arguments\n";
die = true;
}
if (argc - optind > 0) {
std::cerr << SUBPROGRAM ": too many arguments\n";
die = true;
}
if (die)
{
std::cout << "\n" << FAST5_CHECK_USAGE_MESSAGE;
exit(EXIT_FAILURE);
}
}
void check_read(fast5_file& f5_fh, const std::string& read_name)
{
fast5_raw_scaling scaling = fast5_get_channel_params(f5_fh, read_name);
if(scaling.digitisation != scaling.digitisation) {
fprintf(stdout, "\t[read] ERROR: could not read scaling for %s\n", read_name.c_str());
}
raw_table rt = fast5_get_raw_samples(f5_fh, read_name, scaling);
if(rt.n <= 0) {
fprintf(stdout, "\t[read] ERROR: could not read raw samples for %s\n", read_name.c_str());
} else {
fprintf(stdout, "\t[read] OK: found %zu raw samples for %s\n", rt.n, read_name.c_str());
}
free(rt.raw);
rt.raw = NULL;
}
int fast5_check_main(int argc, char** argv)
{
parse_fast5_check_options(argc, argv);
// Attempt to load the read_db
ReadDB read_db;
read_db.load(opt::reads_file);
std::vector<std::string> fast5_files = read_db.get_unique_fast5s();
fprintf(stdout, "The readdb file contains %zu fast5 files\n", fast5_files.size());
for(size_t i = 0; i < fast5_files.size(); ++i) {
fast5_file f5_fh = fast5_open(fast5_files[i]);
if(fast5_is_open(f5_fh)) {
fprintf(stdout, "[fast5] OK: opened %s\n", fast5_files[i].c_str());
// check the individual reads in the file
std::vector<std::string> reads = fast5_get_multi_read_groups(f5_fh);
for(size_t j = 0; j < reads.size(); ++j) {
std::string read_name = reads[j].substr(5);
check_read(f5_fh, read_name);
}
} else {
fprintf(stdout, "[fast5] ERROR: failed to open %s\n", fast5_files[i].c_str());
}
fast5_close(f5_fh);
}
return 0;
}
<|endoftext|> |
<commit_before>/*
latexguiclient.cpp - Kopete Latex plugin
Copyright (c) 2003-2005 by Olivier Goffart <[email protected]>
Kopete (c) 2003-2005 by the Kopete developers <[email protected]>
*************************************************************************
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation; either version 2 of the License, or *
* (at your option) any later version. *
* *
*************************************************************************
*/
#include <qvariant.h>
#include <kaction.h>
#include <klocale.h>
#include <kmessagebox.h>
#include <kicon.h>
#include <qimage.h>
#include <qregexp.h>
#include "kopetechatsession.h"
#include "kopeteview.h"
#include "kopetemessage.h"
#include "latexplugin.h"
#include "latexguiclient.h"
#include <kactioncollection.h>
LatexGUIClient::LatexGUIClient( Kopete::ChatSession *parent )
: QObject( parent), KXMLGUIClient( parent )
{
setComponentData( LatexPlugin::plugin()->componentData() );
connect( LatexPlugin::plugin(), SIGNAL( destroyed( QObject * ) ), this, SLOT( deleteLater() ) );
m_manager = parent;
KAction *previewAction = new KAction( KIcon("latex"), i18n( "Preview Latex Images" ), this );
actionCollection()->addAction( "latexPreview", previewAction );
previewAction->setShortcut( KShortcut(Qt::CTRL + Qt::Key_L) );
connect(previewAction, SIGNAL( triggered(bool) ), this, SLOT( slotPreview() ) );
setXMLFile( "latexchatui.rc" );
}
LatexGUIClient::~LatexGUIClient()
{
}
void LatexGUIClient::slotPreview()
{
if ( !m_manager->view() )
return;
Kopete::Message msg = m_manager->view()->currentMessage();
QString messageText = msg.plainBody();
if(!messageText.contains("$$")) //we haven't found any latex strings
{
KMessageBox::sorry(reinterpret_cast<QWidget*>(m_manager->view()) , i18n("There are no latex in the message you are typing. The latex formula must be included between $$ and $$ "), i18n("No Latex Formula") );
return;
}
QString oldBody = msg.plainBody();
msg=Kopete::Message( msg.from() , msg.to() );
msg.setHtmlBody( i18n("<b>Preview of the latex message :</b> <br />%1", oldBody) );
msg.setDirection( Kopete::Message::Internal );
m_manager->appendMessage(msg) ;
}
#include "latexguiclient.moc"
// vim: set noet ts=4 sts=4 sw=4:
<commit_msg>Don't crash message box: QWidget* cast from a baseless class is now gone, and a real QWidget is used<commit_after>/*
latexguiclient.cpp - Kopete Latex plugin
Copyright (c) 2003-2005 by Olivier Goffart <[email protected]>
Kopete (c) 2003-2005 by the Kopete developers <[email protected]>
*************************************************************************
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation; either version 2 of the License, or *
* (at your option) any later version. *
* *
*************************************************************************
*/
#include <qvariant.h>
#include <kaction.h>
#include <klocale.h>
#include <kmessagebox.h>
#include <kicon.h>
#include <qimage.h>
#include <qregexp.h>
#include "kopetechatsession.h"
#include "kopeteview.h"
#include "kopetemessage.h"
#include "latexplugin.h"
#include "latexguiclient.h"
#include <kactioncollection.h>
LatexGUIClient::LatexGUIClient( Kopete::ChatSession *parent )
: QObject( parent), KXMLGUIClient( parent )
{
setComponentData( LatexPlugin::plugin()->componentData() );
connect( LatexPlugin::plugin(), SIGNAL( destroyed( QObject * ) ), this, SLOT( deleteLater() ) );
m_manager = parent;
KAction *previewAction = new KAction( KIcon("latex"), i18n( "Preview Latex Images" ), this );
actionCollection()->addAction( "latexPreview", previewAction );
previewAction->setShortcut( KShortcut(Qt::CTRL + Qt::Key_L) );
connect(previewAction, SIGNAL( triggered(bool) ), this, SLOT( slotPreview() ) );
setXMLFile( "latexchatui.rc" );
}
LatexGUIClient::~LatexGUIClient()
{
}
void LatexGUIClient::slotPreview()
{
if ( !m_manager->view() )
return;
Kopete::Message msg = m_manager->view()->currentMessage();
QString messageText = msg.plainBody();
if(!messageText.contains("$$")) //we haven't found any latex strings
{
KMessageBox::sorry(m_manager->view()->mainWidget() , i18n("There are no LaTeX in the message you are typing. The LaTeX formula must be included between $$ and $$ "), i18n("No LaTeX Formula") );
return;
}
QString oldBody = msg.plainBody();
msg=Kopete::Message( msg.from() , msg.to() );
msg.setHtmlBody( i18n("<b>Preview of the latex message :</b> <br />%1", oldBody) );
msg.setDirection( Kopete::Message::Internal );
m_manager->appendMessage(msg) ;
}
#include "latexguiclient.moc"
// vim: set noet ts=4 sts=4 sw=4:
<|endoftext|> |
<commit_before>#include <sdl/SDLWindow.hpp>
#include <Assets.hpp>
#include <gl/Program.hpp>
#include <gl/VAO.hpp>
#include <array>
#include <exception>
using namespace std;
using namespace tetra;
struct Vertex
{
array<float, 2> pos;
Vertex() = default;
Vertex(float x, float y) : pos{x, y} {}
};
void sdlmain()
{
auto sdl = SDL{};
auto window = SDLWindow::Builder{}.build();
auto gl = window.contextBuilder()
.majorVersion(3)
.minorVersion(3)
.build();
auto vertex = Shader{ShaderType::VERTEX};
auto fragment = Shader{ShaderType::FRAGMENT};
fragment.compile(loadShaderSrc("identity.frag"));
vertex.compile(loadShaderSrc("identity_offset.vert"));
auto program = ProgramLinker{}
.vertexAttributes({"vertex"})
.attach(vertex)
.attach(fragment)
.link();
// lookup offset location
auto offsetLocation = program.uniformLocation("offset");
auto vao = Vao{};
auto buffer = AttribBinder<Vertex>{vao}
.attrib(&Vertex::pos)
.bind();
buffer.write({ Vertex {0.2, 0.3}
, Vertex {-0.1, 0.2}
, Vertex {-0.5, -0.5}
});
auto shouldExit = false;
auto event = SDL_Event{};
while (!shouldExit)
{
while (SDL_PollEvent(&event))
{
if (event.type == SDL_QUIT)
{
shouldExit = true;
}
}
// update the offset vector based on time! wooooo, spooky
auto time = (SDL_GetTicks()/1000.0f);
auto offset = array<float, 2>{cosf(time), sinf(time)};
auto frame = window.draw();
glClearColor(0.0, 0.0, 0.0, 0.0);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
vao.bind();
program.use();
// Set the uniform value
program.uniform(offsetLocation, offset);
glDrawArrays(GL_TRIANGLES, 0, buffer.size());
THROW_ON_GL_ERROR();
}
}
int main()
{
try
{
sdlmain();
}
catch (exception& ex)
{
cout << ex.what() << endl;
return 1;
}
return 0;
}
<commit_msg>made some crazy event junk in offsetTriangle<commit_after>#include <sdl/SDLWindow.hpp>
#include <Assets.hpp>
#include <gl/Program.hpp>
#include <gl/VAO.hpp>
#include <boost/any.hpp>
#include <array>
#include <exception>
using namespace std;
using namespace tetra;
class Sink
{
public:
virtual void receive(boost::any msg) = 0;
template <class SType>
SType& addSink(SType&& sink)
{
auto mysink = unique_ptr<Sink>(new SType(move(sink)));
observers.push_back(move(mysink));
return (SType&)*observers[observers.size()-1];
}
protected:
vector<unique_ptr<Sink>> observers;
};
class DumpIntSink : public Sink
{
public:
virtual void receive(boost::any msg) override
{
auto i = boost::any_cast<int>(msg);
cout << "dump int sink: " << i << endl;
}
};
template <class T>
class TypedSignal : public Sink
{
public:
T& value()
{
return lastValue;
}
virtual void receive(boost::any msg) override
{
if (msg.type() != boost::typeindex::type_id<T>())
{
return;
}
lastValue = boost::any_cast<T>(msg);
}
private:
T lastValue;
};
class Observable : public Sink
{
public:
using Handler = function<boost::any(boost::any)>;
virtual void receive(boost::any msg) override
{
for (auto& observer : observers)
{
observer->receive(msg);
}
}
};
class IntFilter : public Sink
{
public:
virtual void receive(boost::any msg) override
{
if (msg.type() != boost::typeindex::type_id<int>())
{
return;
}
for (auto& observer : observers)
{
observer->receive(msg);
}
}
};
template <class In, class Out>
class Map : public Sink
{
public:
using Func = function<Out(In)>;
Map(Func func)
{
myfunc = func;
}
virtual void receive(boost::any msg) override
{
if (msg.type() != boost::typeindex::type_id<In>())
{
for (auto& observer : observers)
{
observer->receive(msg);
}
return;
}
auto typedMsg = boost::any_cast<In>(msg);
auto result = boost::any{myfunc(typedMsg)};
for (auto& observer : observers)
{
observer->receive(result);
}
}
private:
Func myfunc;
};
struct Vertex
{
array<float, 2> pos;
Vertex() = default;
Vertex(float x, float y) : pos{x, y} {}
};
void sdlmain()
{
auto pump = Observable{};
auto& signal = pump
.addSink(Map<int, string>{[](int i) { return to_string(i); }})
.addSink(TypedSignal<string>{});
auto& otherSig = pump
.addSink(TypedSignal<int>{});
pump.receive({3});
pump.receive({string("aoeu")});
cout << signal.value() << endl;
cout << otherSig.value() << endl;
return ;
auto sdl = SDL{};
auto window = SDLWindow::Builder{}.build();
auto gl = window.contextBuilder()
.majorVersion(3)
.minorVersion(3)
.build();
auto vertex = Shader{ShaderType::VERTEX};
auto fragment = Shader{ShaderType::FRAGMENT};
fragment.compile(loadShaderSrc("identity.frag"));
vertex.compile(loadShaderSrc("identity_offset.vert"));
auto program = ProgramLinker{}
.vertexAttributes({"vertex"})
.attach(vertex)
.attach(fragment)
.link();
// lookup offset location
auto offsetLocation = program.uniformLocation("offset");
auto vao = Vao{};
auto buffer = AttribBinder<Vertex>{vao}
.attrib(&Vertex::pos)
.bind();
buffer.write({ Vertex {0.2, 0.3}
, Vertex {-0.1, 0.2}
, Vertex {-0.5, -0.5}
});
auto shouldExit = false;
auto event = SDL_Event{};
while (!shouldExit)
{
while (SDL_PollEvent(&event))
{
if (event.type == SDL_QUIT)
{
shouldExit = true;
}
}
// update the offset vector based on time! wooooo, spooky
auto time = (SDL_GetTicks()/1000.0f);
auto offset = array<float, 2>{cosf(time), sinf(time)};
auto frame = window.draw();
glClearColor(0.0, 0.0, 0.0, 0.0);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
vao.bind();
program.use();
// Set the uniform value
program.uniform(offsetLocation, offset);
glDrawArrays(GL_TRIANGLES, 0, buffer.size());
THROW_ON_GL_ERROR();
}
}
int main()
{
try
{
sdlmain();
}
catch (exception& ex)
{
cout << ex.what() << endl;
return 1;
}
return 0;
}
<|endoftext|> |
<commit_before>// Copyright 2011 Google Inc. 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 "build.h"
#include "tools/deps.h"
namespace shk {
int toolDeps(int argc, char **argv, const ToolParams ¶ms) {
const auto step_indices = computeStepsToBuild(
params.paths, params.manifest, argc, argv);
for (const auto step : params.manifest.steps) {
if (step.phony()) {
continue;
}
const auto entry_it = params.invocations.entries.find(step.hash());
if (entry_it == params.invocations.entries.end()) {
continue;
}
const auto &entry = entry_it->second;
const auto &fingerprint = params.invocations.fingerprints;
const auto file_to_str = [&](size_t idx) {
const auto &file = fingerprint[idx];
const auto &path = file.first.original();
const auto &fp = file.second;
const auto result = fingerprintMatches(params.file_system, path, fp);
return path +
(result.clean ? "" : " [dirty]") +
(result.should_update ? " [should update]" : "");
};
bool first = true;
for (const auto &output : entry.output_files) {
printf("%s%s", first ? "" : "\n", file_to_str(output).c_str());
first = false;
}
if (first) {
printf("[no output file]");
}
printf(
": #deps %lu\n",
entry.input_files.size());
for (const auto &input : entry.input_files) {
printf(" %s\n", file_to_str(input).c_str());
}
printf("\n");
}
return 0;
}
} // namespace shk
<commit_msg>Print command in deps tool<commit_after>// Copyright 2011 Google Inc. 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 "build.h"
#include "tools/deps.h"
namespace shk {
int toolDeps(int argc, char **argv, const ToolParams ¶ms) {
const auto step_indices = computeStepsToBuild(
params.paths, params.manifest, argc, argv);
for (const auto step : params.manifest.steps) {
if (step.phony()) {
continue;
}
const auto entry_it = params.invocations.entries.find(step.hash());
if (entry_it == params.invocations.entries.end()) {
continue;
}
const auto &entry = entry_it->second;
const auto &fingerprint = params.invocations.fingerprints;
const auto file_to_str = [&](size_t idx) {
const auto &file = fingerprint[idx];
const auto &path = file.first.original();
const auto &fp = file.second;
const auto result = fingerprintMatches(params.file_system, path, fp);
return path +
(result.clean ? "" : " [dirty]") +
(result.should_update ? " [should update]" : "");
};
printf("%s\n", step.command.c_str());
bool first = true;
for (const auto &output : entry.output_files) {
printf(" %s%s", first ? "" : "\n", file_to_str(output).c_str());
first = false;
}
if (first) {
printf("[no output file]");
}
printf(
": #deps %lu\n",
entry.input_files.size());
for (const auto &input : entry.input_files) {
printf(" %s\n", file_to_str(input).c_str());
}
printf("\n");
}
return 0;
}
} // namespace shk
<|endoftext|> |
<commit_before>/* -*- mode:linux -*- */
/**
* \file grid_world.cc
*
*
*
* \author Ethan Burns
* \date 2008-10-08
*/
#include <iostream>
#include <stdlib.h>
#include <string.h>
#include "grid_state.h"
#include "grid_world.h"
using namespace std;
/**
* Create a new GridWorld.
*/
GridWorld::GridWorld(const Heuristic *h, istream &s)
: SearchDomain(h)
{
char line[100];
char c;
s >> height;
s >> width;
cerr << height << " " << width << endl;
s >> line;
if(strcmp(line, "Board:") != 0) {
cerr << "Parse error" << endl;
exit(EXIT_FAILURE);
}
for (int h = 0; h < height; h += 1) {
for (int w = 0; w < width; w += 1) {
c = s.get();
if (c == '#') {
obstacle_x.push_back(w);
obstacle_y.push_back(h);
}
}
c = s.get();
if (c != '\n') {
cerr << "Parse error: [" << c << "], h=" << h << endl;
exit(EXIT_FAILURE);
}
}
// Cost (Unit/Life)
s >> line;
// Movement (Four-way/Eight-way)
s >> line;
s >> start_x;
s >> start_y;
s >> goal_x;
s >> goal_y;
}
/**
* Get the initial state.
*/
State *GridWorld::initial_state(void)
{
return new GridState(this, NULL, 0, start_x, start_y);
}
/**
* Expand a gridstate.
*/
vector<const State*> *GridWorld::expand(const State *state) const
{
const int cost = 1;
const GridState *s;
vector<const State*> *children;
s = dynamic_cast<const GridState*>(state);
children = new vector<const State*>();
if (s->get_x() > 0 && !is_obstacle(s->get_x() + 1, s->get_y())) {
children->push_back(new GridState(this, state, s->get_g() + cost,
s->get_x() + 1, s->get_y()));
}
if (s->get_x() < height - 1 && !is_obstacle(s->get_x() - 1, s->get_y())) {
children->push_back(new GridState(this, state, s->get_g() + cost,
s->get_x() - 1, s->get_y()));
}
if (s->get_y() > 0 && !is_obstacle(s->get_x(), s->get_y() + 1)) {
children->push_back(new GridState(this, state, s->get_g() + cost,
s->get_x(), s->get_y() + 1));
}
if (s->get_y() > width - 1 && !is_obstacle(s->get_x(), s->get_y() - 1)) {
children->push_back(new GridState(this, state, s->get_g() + cost,
s->get_x(), s->get_y() - 1));
}
return children;
}
int GridWorld::get_goal_x(void) const
{
return goal_x;
}
int GridWorld::get_goal_y(void) const
{
return goal_y;
}
int GridWorld::get_width(void) const
{
return width;
}
int GridWorld::get_height(void) const
{
return height;
}
/**
* Test if there is an obstacle at the given location.
*/
bool GridWorld::is_obstacle(int x, int y) const
{
for (int i = 0; i < obstacle_x.size(); i += 1) {
if (obstacle_x.at(i) == x
&& obstacle_y.at(i) == y)
return true;
}
return false;
}
/**
* Prints the grid world to the given stream.
*/
void GridWorld::print(ostream &o) const
{
o << height << " " << width << endl;
o << "Board:" << endl;
for (int h = 0; h < height; h += 1) {
for (int w = 0; w < width; w += 1) {
if (is_obstacle(w, h))
o << "#";
else
o << " ";
}
o << endl;;
}
o << "Unit" << endl;
o << "Four-way" << endl;
o << start_x << " " << start_y << "\t" << goal_x << " " << goal_y << endl;
}
<commit_msg>Fix grid reading.<commit_after>/* -*- mode:linux -*- */
/**
* \file grid_world.cc
*
*
*
* \author Ethan Burns
* \date 2008-10-08
*/
#include <iostream>
#include <stdlib.h>
#include <string.h>
#include "grid_state.h"
#include "grid_world.h"
using namespace std;
/**
* Create a new GridWorld.
*/
GridWorld::GridWorld(const Heuristic *h, istream &s)
: SearchDomain(h)
{
char line[100];
char c;
s >> height;
s >> width;
s >> line;
if(strcmp(line, "Board:") != 0) {
cerr << "Parse error: expected \"Board:\"" << endl;
exit(EXIT_FAILURE);
}
c = s.get(); // new-line
if (c != '\n') {
cerr << endl << "Parse error: [" << c << "], h=" << h << endl;
exit(EXIT_FAILURE);
}
for (int h = 0; h < height; h += 1) {
for (int w = 0; w < width; w += 1) {
c = s.get();
if (c == '#') {
obstacle_x.push_back(w);
obstacle_y.push_back(h);
}
}
c = s.get(); // new-line
if (c != '\n') {
cerr << endl << "Parse error: [" << c << "], h=" << h << endl;
exit(EXIT_FAILURE);
}
}
// Cost (Unit/Life)
s >> line;
// Movement (Four-way/Eight-way)
s >> line;
s >> start_x;
s >> start_y;
s >> goal_x;
s >> goal_y;
}
/**
* Get the initial state.
*/
State *GridWorld::initial_state(void)
{
return new GridState(this, NULL, 0, start_x, start_y);
}
/**
* Expand a gridstate.
*/
vector<const State*> *GridWorld::expand(const State *state) const
{
const int cost = 1;
const GridState *s;
vector<const State*> *children;
s = dynamic_cast<const GridState*>(state);
children = new vector<const State*>();
if (s->get_x() > 0 && !is_obstacle(s->get_x() + 1, s->get_y())) {
children->push_back(new GridState(this, state, s->get_g() + cost,
s->get_x() + 1, s->get_y()));
}
if (s->get_x() < height - 1 && !is_obstacle(s->get_x() - 1, s->get_y())) {
children->push_back(new GridState(this, state, s->get_g() + cost,
s->get_x() - 1, s->get_y()));
}
if (s->get_y() > 0 && !is_obstacle(s->get_x(), s->get_y() + 1)) {
children->push_back(new GridState(this, state, s->get_g() + cost,
s->get_x(), s->get_y() + 1));
}
if (s->get_y() > width - 1 && !is_obstacle(s->get_x(), s->get_y() - 1)) {
children->push_back(new GridState(this, state, s->get_g() + cost,
s->get_x(), s->get_y() - 1));
}
return children;
}
int GridWorld::get_goal_x(void) const
{
return goal_x;
}
int GridWorld::get_goal_y(void) const
{
return goal_y;
}
int GridWorld::get_width(void) const
{
return width;
}
int GridWorld::get_height(void) const
{
return height;
}
/**
* Test if there is an obstacle at the given location.
*/
bool GridWorld::is_obstacle(int x, int y) const
{
for (int i = 0; i < obstacle_x.size(); i += 1) {
if (obstacle_x.at(i) == x
&& obstacle_y.at(i) == y)
return true;
}
return false;
}
/**
* Prints the grid world to the given stream.
*/
void GridWorld::print(ostream &o) const
{
o << height << " " << width << endl;
o << "Board:" << endl;
for (int h = 0; h < height; h += 1) {
for (int w = 0; w < width; w += 1) {
if (is_obstacle(w, h))
o << "#";
else
o << " ";
}
o << endl;;
}
o << "Unit" << endl;
o << "Four-way" << endl;
o << start_x << " " << start_y << "\t" << goal_x << " " << goal_y << endl;
}
<|endoftext|> |
<commit_before>/* Copyright 2018 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#include "tensorflow/core/kernels/data/generator_dataset_op.h"
#include <iterator>
#include <vector>
#include "tensorflow/core/framework/partial_tensor_shape.h"
#include "tensorflow/core/framework/tensor.h"
#include "tensorflow/core/kernels/data/captured_function.h"
#include "tensorflow/core/lib/random/random.h"
namespace tensorflow {
namespace data {
// See documentation in ../../ops/dataset_ops.cc for a high-level
// description of the following op.
class GeneratorDatasetOp::Dataset : public DatasetBase {
public:
Dataset(OpKernelContext* ctx, std::unique_ptr<CapturedFunction> init_func,
std::unique_ptr<CapturedFunction> next_func,
std::unique_ptr<CapturedFunction> finalize_func,
const DataTypeVector& output_types,
const std::vector<PartialTensorShape>& output_shapes)
: DatasetBase(DatasetContext(ctx)),
init_func_(std::move(init_func)),
next_func_(std::move(next_func)),
finalize_func_(std::move(finalize_func)),
output_types_(output_types),
output_shapes_(output_shapes) {}
std::unique_ptr<IteratorBase> MakeIteratorInternal(
const string& prefix) const override {
return absl::make_unique<Iterator>(
Iterator::Params{this, strings::StrCat(prefix, "::Generator")});
}
const DataTypeVector& output_dtypes() const override { return output_types_; }
const std::vector<PartialTensorShape>& output_shapes() const override {
return output_shapes_;
}
string DebugString() const override { return "GeneratorDatasetOp::Dataset"; }
protected:
Status AsGraphDefInternal(SerializationContext* ctx,
DatasetGraphDefBuilder* b,
Node** output) const override {
return errors::Unimplemented("%s does not support serialization",
DebugString());
}
private:
class Iterator : public DatasetIterator<Dataset> {
public:
explicit Iterator(const Params& params)
: DatasetIterator<Dataset>(params) {}
~Iterator() override {
if (!finalized_) {
std::vector<Tensor> ignored;
Status s =
instantiated_finalize_func_->RunInstantiated(state_, &ignored);
if (!s.ok()) {
LOG(WARNING)
<< "Error occurred when finalizing GeneratorDataset iterator: "
<< s;
}
}
}
Status Initialize(IteratorContext* ctx) override {
TF_RETURN_IF_ERROR(
dataset()->init_func_->Instantiate(ctx, &instantiated_init_func_));
TF_RETURN_IF_ERROR(
dataset()->next_func_->Instantiate(ctx, &instantiated_next_func_));
TF_RETURN_IF_ERROR(dataset()->finalize_func_->Instantiate(
ctx, &instantiated_finalize_func_));
return Status::OK();
}
Status GetNextInternal(IteratorContext* ctx,
std::vector<Tensor>* out_tensors,
bool* end_of_sequence) override {
mutex_lock l(mu_);
if (!initialized_) {
TF_RETURN_IF_ERROR(
instantiated_init_func_->RunWithBorrowedArgs(ctx, {}, &state_));
initialized_ = true;
}
if (finalized_) {
*end_of_sequence = true;
return Status::OK();
}
Status s = instantiated_next_func_->RunWithBorrowedArgs(ctx, state_,
out_tensors);
if (s.ok()) {
*end_of_sequence = false;
} else if (errors::IsOutOfRange(s)) {
// `next_func` may deliberately raise `errors::OutOfRange`
// to indicate that we should terminate the iteration.
s = Status::OK();
*end_of_sequence = true;
// NOTE(mrry): We ignore any tensors returned by the
// finalize function.
std::vector<Tensor> ignored;
TF_RETURN_IF_ERROR(
instantiated_finalize_func_->RunInstantiated(state_, &ignored));
finalized_ = true;
}
return s;
}
protected:
std::shared_ptr<model::Node> CreateNode(
IteratorContext* ctx, model::Node::Args args) const override {
return model::MakeSourceNode(std::move(args));
}
private:
mutex mu_;
bool initialized_ GUARDED_BY(mu_) = false;
bool finalized_ GUARDED_BY(mu_) = false;
std::vector<Tensor> state_ GUARDED_BY(mu_);
std::unique_ptr<InstantiatedCapturedFunction> instantiated_init_func_;
std::unique_ptr<InstantiatedCapturedFunction> instantiated_next_func_;
std::unique_ptr<InstantiatedCapturedFunction> instantiated_finalize_func_;
};
const std::unique_ptr<CapturedFunction> init_func_;
const std::unique_ptr<CapturedFunction> next_func_;
const std::unique_ptr<CapturedFunction> finalize_func_;
const DataTypeVector output_types_;
const std::vector<PartialTensorShape> output_shapes_;
};
GeneratorDatasetOp::GeneratorDatasetOp(OpKernelConstruction* ctx)
: DatasetOpKernel(ctx) {
OP_REQUIRES_OK(ctx, ctx->GetAttr("init_func", &init_func_));
OP_REQUIRES_OK(ctx, ctx->GetAttr("next_func", &next_func_));
OP_REQUIRES_OK(ctx, ctx->GetAttr("finalize_func", &finalize_func_));
OP_REQUIRES_OK(ctx, ctx->GetAttr("output_types", &output_types_));
OP_REQUIRES_OK(ctx, ctx->GetAttr("output_shapes", &output_shapes_));
}
void GeneratorDatasetOp::MakeDataset(OpKernelContext* ctx,
DatasetBase** output) {
std::unique_ptr<CapturedFunction> init_func;
OP_REQUIRES_OK(ctx, CapturedFunction::Create(
init_func_, ctx, "init_func_other_args", &init_func));
std::unique_ptr<CapturedFunction> next_func;
OP_REQUIRES_OK(ctx, CapturedFunction::Create(
next_func_, ctx, "next_func_other_args", &next_func));
std::unique_ptr<CapturedFunction> finalize_func;
OP_REQUIRES_OK(ctx, CapturedFunction::Create(finalize_func_, ctx,
"finalize_func_other_args",
&finalize_func));
*output =
new Dataset(ctx, std::move(init_func), std::move(next_func),
std::move(finalize_func), output_types_, output_shapes_);
}
namespace {
REGISTER_KERNEL_BUILDER(Name("GeneratorDataset").Device(DEVICE_CPU).Priority(2),
GeneratorDatasetOp);
REGISTER_KERNEL_BUILDER(Name("GeneratorDataset")
.Device(DEVICE_GPU)
.HostMemory("handle")
.Priority(1),
GeneratorDatasetOp);
} // namespace
} // namespace data
} // namespace tensorflow
<commit_msg>In case we delete the iterator before the GeneratorDataset is initialized, we still ran the finalize function. This causes errors because state_ hasn't been computed.<commit_after>/* Copyright 2018 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#include "tensorflow/core/kernels/data/generator_dataset_op.h"
#include <iterator>
#include <vector>
#include "tensorflow/core/framework/partial_tensor_shape.h"
#include "tensorflow/core/framework/tensor.h"
#include "tensorflow/core/kernels/data/captured_function.h"
#include "tensorflow/core/lib/random/random.h"
namespace tensorflow {
namespace data {
// See documentation in ../../ops/dataset_ops.cc for a high-level
// description of the following op.
class GeneratorDatasetOp::Dataset : public DatasetBase {
public:
Dataset(OpKernelContext* ctx, std::unique_ptr<CapturedFunction> init_func,
std::unique_ptr<CapturedFunction> next_func,
std::unique_ptr<CapturedFunction> finalize_func,
const DataTypeVector& output_types,
const std::vector<PartialTensorShape>& output_shapes)
: DatasetBase(DatasetContext(ctx)),
init_func_(std::move(init_func)),
next_func_(std::move(next_func)),
finalize_func_(std::move(finalize_func)),
output_types_(output_types),
output_shapes_(output_shapes) {}
std::unique_ptr<IteratorBase> MakeIteratorInternal(
const string& prefix) const override {
return absl::make_unique<Iterator>(
Iterator::Params{this, strings::StrCat(prefix, "::Generator")});
}
const DataTypeVector& output_dtypes() const override { return output_types_; }
const std::vector<PartialTensorShape>& output_shapes() const override {
return output_shapes_;
}
string DebugString() const override { return "GeneratorDatasetOp::Dataset"; }
protected:
Status AsGraphDefInternal(SerializationContext* ctx,
DatasetGraphDefBuilder* b,
Node** output) const override {
return errors::Unimplemented("%s does not support serialization",
DebugString());
}
private:
class Iterator : public DatasetIterator<Dataset> {
public:
explicit Iterator(const Params& params)
: DatasetIterator<Dataset>(params) {}
~Iterator() override {
if (!finalized_ && initialized_) {
std::vector<Tensor> ignored;
Status s =
instantiated_finalize_func_->RunInstantiated(state_, &ignored);
if (!s.ok()) {
LOG(WARNING)
<< "Error occurred when finalizing GeneratorDataset iterator: "
<< s;
}
}
}
Status Initialize(IteratorContext* ctx) override {
TF_RETURN_IF_ERROR(
dataset()->init_func_->Instantiate(ctx, &instantiated_init_func_));
TF_RETURN_IF_ERROR(
dataset()->next_func_->Instantiate(ctx, &instantiated_next_func_));
TF_RETURN_IF_ERROR(dataset()->finalize_func_->Instantiate(
ctx, &instantiated_finalize_func_));
return Status::OK();
}
Status GetNextInternal(IteratorContext* ctx,
std::vector<Tensor>* out_tensors,
bool* end_of_sequence) override {
mutex_lock l(mu_);
if (!initialized_) {
TF_RETURN_IF_ERROR(
instantiated_init_func_->RunWithBorrowedArgs(ctx, {}, &state_));
initialized_ = true;
}
if (finalized_) {
*end_of_sequence = true;
return Status::OK();
}
Status s = instantiated_next_func_->RunWithBorrowedArgs(ctx, state_,
out_tensors);
if (s.ok()) {
*end_of_sequence = false;
} else if (errors::IsOutOfRange(s)) {
// `next_func` may deliberately raise `errors::OutOfRange`
// to indicate that we should terminate the iteration.
s = Status::OK();
*end_of_sequence = true;
// NOTE(mrry): We ignore any tensors returned by the
// finalize function.
std::vector<Tensor> ignored;
TF_RETURN_IF_ERROR(
instantiated_finalize_func_->RunInstantiated(state_, &ignored));
finalized_ = true;
}
return s;
}
protected:
std::shared_ptr<model::Node> CreateNode(
IteratorContext* ctx, model::Node::Args args) const override {
return model::MakeSourceNode(std::move(args));
}
private:
mutex mu_;
bool initialized_ GUARDED_BY(mu_) = false;
bool finalized_ GUARDED_BY(mu_) = false;
std::vector<Tensor> state_ GUARDED_BY(mu_);
std::unique_ptr<InstantiatedCapturedFunction> instantiated_init_func_;
std::unique_ptr<InstantiatedCapturedFunction> instantiated_next_func_;
std::unique_ptr<InstantiatedCapturedFunction> instantiated_finalize_func_;
};
const std::unique_ptr<CapturedFunction> init_func_;
const std::unique_ptr<CapturedFunction> next_func_;
const std::unique_ptr<CapturedFunction> finalize_func_;
const DataTypeVector output_types_;
const std::vector<PartialTensorShape> output_shapes_;
};
GeneratorDatasetOp::GeneratorDatasetOp(OpKernelConstruction* ctx)
: DatasetOpKernel(ctx) {
OP_REQUIRES_OK(ctx, ctx->GetAttr("init_func", &init_func_));
OP_REQUIRES_OK(ctx, ctx->GetAttr("next_func", &next_func_));
OP_REQUIRES_OK(ctx, ctx->GetAttr("finalize_func", &finalize_func_));
OP_REQUIRES_OK(ctx, ctx->GetAttr("output_types", &output_types_));
OP_REQUIRES_OK(ctx, ctx->GetAttr("output_shapes", &output_shapes_));
}
void GeneratorDatasetOp::MakeDataset(OpKernelContext* ctx,
DatasetBase** output) {
std::unique_ptr<CapturedFunction> init_func;
OP_REQUIRES_OK(ctx, CapturedFunction::Create(
init_func_, ctx, "init_func_other_args", &init_func));
std::unique_ptr<CapturedFunction> next_func;
OP_REQUIRES_OK(ctx, CapturedFunction::Create(
next_func_, ctx, "next_func_other_args", &next_func));
std::unique_ptr<CapturedFunction> finalize_func;
OP_REQUIRES_OK(ctx, CapturedFunction::Create(finalize_func_, ctx,
"finalize_func_other_args",
&finalize_func));
*output =
new Dataset(ctx, std::move(init_func), std::move(next_func),
std::move(finalize_func), output_types_, output_shapes_);
}
namespace {
REGISTER_KERNEL_BUILDER(Name("GeneratorDataset").Device(DEVICE_CPU).Priority(2),
GeneratorDatasetOp);
REGISTER_KERNEL_BUILDER(Name("GeneratorDataset")
.Device(DEVICE_GPU)
.HostMemory("handle")
.Priority(1),
GeneratorDatasetOp);
} // namespace
} // namespace data
} // namespace tensorflow
<|endoftext|> |
<commit_before>/* Copyright (c) 2015, AOYAMA Kazuharu
* All rights reserved.
*
* This software may be used and distributed according to the terms of
* the New BSD License, which is incorporated herein by reference.
*/
#include <QUuid>
#include <TWebSocketEndpoint>
#include <TWebApplication>
#include "twebsocket.h"
#include "twebsocketworker.h"
#include "turlroute.h"
#include "tdispatcher.h"
const qint64 WRITE_LENGTH = 1280;
const int BUFFER_RESERVE_SIZE = 127;
TWebSocket::TWebSocket(int socketDescriptor, const QHostAddress &address, const THttpRequestHeader &header, QObject *parent)
: QTcpSocket(parent), frames(), uuid(), reqHeader(header), recvBuffer(),
myWorkerCounter(0), deleting(false)
{
setSocketDescriptor(socketDescriptor);
setPeerAddress(address);
uuid = QUuid::createUuid().toByteArray().replace('-', ""); // not thread safe
uuid = uuid.mid(1, uuid.length() - 2);
recvBuffer.reserve(BUFFER_RESERVE_SIZE);
connect(this, SIGNAL(readyRead()), this, SLOT(readRequest()));
connect(this, SIGNAL(sendByWorker(const QByteArray &)), this, SLOT(sendRawData(const QByteArray &)));
connect(this, SIGNAL(disconnectByWorker()), this, SLOT(close()));
}
TWebSocket::~TWebSocket()
{
tSystemDebug("~TWebSocket");
}
void TWebSocket::close()
{
QTcpSocket::close();
}
bool TWebSocket::canReadRequest() const
{
for (const auto &frm : frames) {
if (frm.isFinalFrame() && frm.state() == TWebSocketFrame::Completed) {
return true;
}
}
return false;
}
void TWebSocket::readRequest()
{
qint64 bytes;
QByteArray buf;
while ((bytes = bytesAvailable()) > 0) {
buf.resize(bytes);
bytes = QTcpSocket::read(buf.data(), bytes);
if (Q_UNLIKELY(bytes < 0)) {
tSystemError("socket read error");
break;
}
recvBuffer.append(buf.data(), bytes);
}
int len = parse(recvBuffer);
if (len < 0) {
tSystemError("WebSocket parse error [%s:%d]", __FILE__, __LINE__);
disconnect();
return;
}
QByteArray binary;
while (!frames.isEmpty()) {
binary.clear();
TWebSocketFrame::OpCode opcode = frames.first().opCode();
while (!frames.isEmpty()) {
TWebSocketFrame frm = frames.takeFirst();
binary += frm.payload();
if (frm.isFinalFrame() && frm.state() == TWebSocketFrame::Completed) {
break;
}
}
// Starts worker thread
TWebSocketWorker *worker = new TWebSocketWorker(this, reqHeader.path(), opcode, binary);
worker->moveToThread(Tf::app()->thread());
connect(worker, SIGNAL(finished()), this, SLOT(releaseWorker()));
myWorkerCounter.fetchAndAddOrdered(1); // count-up
worker->start();
}
}
void TWebSocket::startWorkerForOpening(const TSession &session)
{
TWebSocketWorker *worker = new TWebSocketWorker(this, reqHeader.path(), session);
worker->moveToThread(Tf::app()->thread());
connect(worker, SIGNAL(finished()), this, SLOT(releaseWorker()));
myWorkerCounter.fetchAndAddOrdered(1); // count-up
worker->start();
}
void TWebSocket::deleteLater()
{
tSystemDebug("TWebSocket::deleteLater countWorkers:%d", countWorkers());
deleting = true;
QObject::disconnect(this, SIGNAL(readyRead()), this, SLOT(readRequest()));
QObject::disconnect(this, SIGNAL(sendByWorker(const QByteArray &)), this, SLOT(sendRawData(const QByteArray &)));
QObject::disconnect(this, SIGNAL(disconnectByWorker()), this, SLOT(close()));
if (countWorkers() == 0) {
QTcpSocket::deleteLater();
}
}
void TWebSocket::releaseWorker()
{
TWebSocketWorker *worker = dynamic_cast<TWebSocketWorker *>(sender());
if (worker) {
worker->deleteLater();
myWorkerCounter.fetchAndAddOrdered(-1); // count-down
if (deleting) {
deleteLater();
}
}
}
void TWebSocket::sendRawData(const QByteArray &data)
{
if (data.isEmpty())
return;
qint64 total = 0;
for (;;) {
if (!deleting)
return;
qint64 written = QTcpSocket::write(data.data() + total, qMin(data.length() - total, WRITE_LENGTH));
if (Q_UNLIKELY(written <= 0)) {
tWarn("socket write error: total:%d (%d)", (int)total, (int)written);
break;
}
total += written;
if (total >= data.length())
break;
if (Q_UNLIKELY(!waitForBytesWritten())) {
tWarn("socket error: waitForBytesWritten function [%s]", qPrintable(errorString()));
break;
}
}
}
qint64 TWebSocket::writeRawData(const QByteArray &data)
{
emit sendByWorker(data);
return data.length();
}
void TWebSocket::disconnect()
{
emit disconnectByWorker();
}
<commit_msg>fix a bug of writing flag.<commit_after>/* Copyright (c) 2015, AOYAMA Kazuharu
* All rights reserved.
*
* This software may be used and distributed according to the terms of
* the New BSD License, which is incorporated herein by reference.
*/
#include <QUuid>
#include <TWebSocketEndpoint>
#include <TWebApplication>
#include "twebsocket.h"
#include "twebsocketworker.h"
#include "turlroute.h"
#include "tdispatcher.h"
const qint64 WRITE_LENGTH = 1280;
const int BUFFER_RESERVE_SIZE = 127;
TWebSocket::TWebSocket(int socketDescriptor, const QHostAddress &address, const THttpRequestHeader &header, QObject *parent)
: QTcpSocket(parent), frames(), uuid(), reqHeader(header), recvBuffer(),
myWorkerCounter(0), deleting(false)
{
setSocketDescriptor(socketDescriptor);
setPeerAddress(address);
uuid = QUuid::createUuid().toByteArray().replace('-', ""); // not thread safe
uuid = uuid.mid(1, uuid.length() - 2);
recvBuffer.reserve(BUFFER_RESERVE_SIZE);
connect(this, SIGNAL(readyRead()), this, SLOT(readRequest()));
connect(this, SIGNAL(sendByWorker(const QByteArray &)), this, SLOT(sendRawData(const QByteArray &)));
connect(this, SIGNAL(disconnectByWorker()), this, SLOT(close()));
}
TWebSocket::~TWebSocket()
{
tSystemDebug("~TWebSocket");
}
void TWebSocket::close()
{
QTcpSocket::close();
}
bool TWebSocket::canReadRequest() const
{
for (const auto &frm : frames) {
if (frm.isFinalFrame() && frm.state() == TWebSocketFrame::Completed) {
return true;
}
}
return false;
}
void TWebSocket::readRequest()
{
qint64 bytes;
QByteArray buf;
while ((bytes = bytesAvailable()) > 0) {
buf.resize(bytes);
bytes = QTcpSocket::read(buf.data(), bytes);
if (Q_UNLIKELY(bytes < 0)) {
tSystemError("socket read error");
break;
}
recvBuffer.append(buf.data(), bytes);
}
int len = parse(recvBuffer);
if (len < 0) {
tSystemError("WebSocket parse error [%s:%d]", __FILE__, __LINE__);
disconnect();
return;
}
QByteArray binary;
while (!frames.isEmpty()) {
binary.clear();
TWebSocketFrame::OpCode opcode = frames.first().opCode();
while (!frames.isEmpty()) {
TWebSocketFrame frm = frames.takeFirst();
binary += frm.payload();
if (frm.isFinalFrame() && frm.state() == TWebSocketFrame::Completed) {
break;
}
}
// Starts worker thread
TWebSocketWorker *worker = new TWebSocketWorker(this, reqHeader.path(), opcode, binary);
worker->moveToThread(Tf::app()->thread());
connect(worker, SIGNAL(finished()), this, SLOT(releaseWorker()));
myWorkerCounter.fetchAndAddOrdered(1); // count-up
worker->start();
}
}
void TWebSocket::startWorkerForOpening(const TSession &session)
{
TWebSocketWorker *worker = new TWebSocketWorker(this, reqHeader.path(), session);
worker->moveToThread(Tf::app()->thread());
connect(worker, SIGNAL(finished()), this, SLOT(releaseWorker()));
myWorkerCounter.fetchAndAddOrdered(1); // count-up
worker->start();
}
void TWebSocket::deleteLater()
{
tSystemDebug("TWebSocket::deleteLater countWorkers:%d", countWorkers());
deleting = true;
QObject::disconnect(this, SIGNAL(readyRead()), this, SLOT(readRequest()));
QObject::disconnect(this, SIGNAL(sendByWorker(const QByteArray &)), this, SLOT(sendRawData(const QByteArray &)));
QObject::disconnect(this, SIGNAL(disconnectByWorker()), this, SLOT(close()));
if (countWorkers() == 0) {
QTcpSocket::deleteLater();
}
}
void TWebSocket::releaseWorker()
{
TWebSocketWorker *worker = dynamic_cast<TWebSocketWorker *>(sender());
if (worker) {
worker->deleteLater();
myWorkerCounter.fetchAndAddOrdered(-1); // count-down
if (deleting) {
deleteLater();
}
}
}
void TWebSocket::sendRawData(const QByteArray &data)
{
if (data.isEmpty())
return;
qint64 total = 0;
for (;;) {
if (deleting)
return;
qint64 written = QTcpSocket::write(data.data() + total, qMin(data.length() - total, WRITE_LENGTH));
if (Q_UNLIKELY(written <= 0)) {
tWarn("socket write error: total:%d (%d)", (int)total, (int)written);
break;
}
total += written;
if (total >= data.length())
break;
if (Q_UNLIKELY(!waitForBytesWritten())) {
tWarn("socket error: waitForBytesWritten function [%s]", qPrintable(errorString()));
break;
}
}
}
qint64 TWebSocket::writeRawData(const QByteArray &data)
{
emit sendByWorker(data);
return data.length();
}
void TWebSocket::disconnect()
{
emit disconnectByWorker();
}
<|endoftext|> |
<commit_before>/**
* @file consensushash.cpp
*
* This file contains the function to generate consensus hashes.
*/
#include "omnicore/consensushash.h"
#include "omnicore/dex.h"
#include "omnicore/log.h"
#include "omnicore/omnicore.h"
#include <stdint.h>
#include <string>
#include <openssl/sha.h>
namespace mastercore
{
/**
* Obtains a hash of all balances to use for consensus verification and checkpointing.
*
* For increased flexibility, so other implementations like OmniWallet and OmniChest can
* also apply this methodology without necessarily using the same exact data types (which
* would be needed to hash the data bytes directly), create a string in the following
* format for each address/property identifier combo to use for hashing:
*
* Format specifiers:
* "%s|%d|%d|%d|%d|%d"
*
* With placeholders:
* "address|propertyid|balance|selloffer_reserve|accept_reserve|metadex_reserve"
*
* Example:
* SHA256 round 1: "1LCShN3ntEbeRrj8XBFWdScGqw5NgDXL5R|31|8000|0|0|0"
* SHA256 round 2: "1LCShN3ntEbeRrj8XBFWdScGqw5NgDXL5R|2147483657|0|0|0|234235245"
* SHA256 round 3: "1LP7G6uiHPaG8jm64aconFF8CLBAnRGYcb|1|0|100|0|0"
* SHA256 round 4: "1LP7G6uiHPaG8jm64aconFF8CLBAnRGYcb|2|0|0|0|50000"
* SHA256 round 5: "1LP7G6uiHPaG8jm64aconFF8CLBAnRGYcb|10|0|0|1|0"
* SHA256 round 6: "3CwZ7FiQ4MqBenRdCkjjc41M5bnoKQGC2b|1|12345|5|777|9000"
*
* Result:
* "3580e94167f75620dfa8c267862aa47af46164ed8edaec3a800d732050ec0607"
*
* The byte order is important, and in the example we assume:
* SHA256("abc") = "ad1500f261ff10b49c7a1796a36103b02322ae5dde404141eacf018fbf1678ba"
*
* Note: empty balance records and the pending tally are ignored. Addresses are sorted based
* on lexicographical order, and balance records are sorted by the property identifiers.
*/
uint256 GetConsensusHash()
{
// allocate and init a SHA256_CTX
SHA256_CTX shaCtx;
SHA256_Init(&shaCtx);
LOCK(cs_tally);
if (msc_debug_consensus_hash) PrintToLog("Beginning generation of current consensus hash...\n");
// Balances - loop through the tally map, updating the sha context with the data from each balance and tally type
for (std::map<string, CMPTally>::iterator my_it = mp_tally_map.begin(); my_it != mp_tally_map.end(); ++my_it) {
const std::string& address = my_it->first;
CMPTally& tally = my_it->second;
tally.init();
uint32_t propertyId = 0;
while (0 != (propertyId = (tally.next()))) {
int64_t balance = tally.getMoney(propertyId, BALANCE);
int64_t sellOfferReserve = tally.getMoney(propertyId, SELLOFFER_RESERVE);
int64_t acceptReserve = tally.getMoney(propertyId, ACCEPT_RESERVE);
int64_t metaDExReserve = tally.getMoney(propertyId, METADEX_RESERVE);
// skip this entry if all balances are empty
if (!balance && !sellOfferReserve && !acceptReserve && !metaDExReserve) continue;
std::string dataStr = strprintf("%s|%d|%d|%d|%d|%d",
address, propertyId, balance, sellOfferReserve, acceptReserve, metaDExReserve);
if (msc_debug_consensus_hash) PrintToLog("Adding balance data to consensus hash: %s\n", dataStr);
// update the sha context with the data string
SHA256_Update(&shaCtx, dataStr.c_str(), dataStr.length());
}
}
// DEx sell offers - loop through the DEx and add each sell offer to the consensus hash
for (OfferMap::iterator it = my_offers.begin(); it != my_offers.end(); ++it) {
const CMPOffer& selloffer = it->second;
const std::string& sellCombo = it->first;
uint32_t propertyId = selloffer.getProperty();
std::string seller = sellCombo.substr(0, sellCombo.size() - 2);
// "txid|address|propertyid|offeramount|btcdesired|minfee|timelimit|availableamount|acceptedamount"
std::string dataStr = strprintf("%s|%s|%d|%d|%d|%d|%d|%d|%d",
selloffer.getHash().GetHex(), seller, propertyId, selloffer.getOfferAmountOriginal(),
selloffer.getBTCDesiredOriginal(), selloffer.getMinFee(), selloffer.getBlockTimeLimit(),
getMPbalance(seller, propertyId, SELLOFFER_RESERVE), getMPbalance(seller, propertyId, ACCEPT_RESERVE));
if (msc_debug_consensus_hash) PrintToLog("Adding DEx offer data to consensus hash: %s\n", dataStr);
// update the sha context with the data string
SHA256_Update(&shaCtx, dataStr.c_str(), dataStr.length());
}
// extract the final result and return the hash
uint256 consensusHash;
SHA256_Final((unsigned char*)&consensusHash, &shaCtx);
if (msc_debug_consensus_hash) PrintToLog("Finished generation of consensus hash. Result: %s\n", consensusHash.GetHex());
return consensusHash;
}
} // namespace mastercore
<commit_msg>Add MetaDEx trade data to consensus hash<commit_after>/**
* @file consensushash.cpp
*
* This file contains the function to generate consensus hashes.
*/
#include "omnicore/consensushash.h"
#include "omnicore/dex.h"
#include "omnicore/mdex.h"
#include "omnicore/log.h"
#include "omnicore/omnicore.h"
#include <stdint.h>
#include <string>
#include <openssl/sha.h>
namespace mastercore
{
/**
* Obtains a hash of all balances to use for consensus verification and checkpointing.
*
* For increased flexibility, so other implementations like OmniWallet and OmniChest can
* also apply this methodology without necessarily using the same exact data types (which
* would be needed to hash the data bytes directly), create a string in the following
* format for each address/property identifier combo to use for hashing:
*
* Format specifiers:
* "%s|%d|%d|%d|%d|%d"
*
* With placeholders:
* "address|propertyid|balance|selloffer_reserve|accept_reserve|metadex_reserve"
*
* Example:
* SHA256 round 1: "1LCShN3ntEbeRrj8XBFWdScGqw5NgDXL5R|31|8000|0|0|0"
* SHA256 round 2: "1LCShN3ntEbeRrj8XBFWdScGqw5NgDXL5R|2147483657|0|0|0|234235245"
* SHA256 round 3: "1LP7G6uiHPaG8jm64aconFF8CLBAnRGYcb|1|0|100|0|0"
* SHA256 round 4: "1LP7G6uiHPaG8jm64aconFF8CLBAnRGYcb|2|0|0|0|50000"
* SHA256 round 5: "1LP7G6uiHPaG8jm64aconFF8CLBAnRGYcb|10|0|0|1|0"
* SHA256 round 6: "3CwZ7FiQ4MqBenRdCkjjc41M5bnoKQGC2b|1|12345|5|777|9000"
*
* Result:
* "3580e94167f75620dfa8c267862aa47af46164ed8edaec3a800d732050ec0607"
*
* The byte order is important, and in the example we assume:
* SHA256("abc") = "ad1500f261ff10b49c7a1796a36103b02322ae5dde404141eacf018fbf1678ba"
*
* Note: empty balance records and the pending tally are ignored. Addresses are sorted based
* on lexicographical order, and balance records are sorted by the property identifiers.
*/
uint256 GetConsensusHash()
{
// allocate and init a SHA256_CTX
SHA256_CTX shaCtx;
SHA256_Init(&shaCtx);
LOCK(cs_tally);
if (msc_debug_consensus_hash) PrintToLog("Beginning generation of current consensus hash...\n");
// Balances - loop through the tally map, updating the sha context with the data from each balance and tally type
for (std::map<string, CMPTally>::iterator my_it = mp_tally_map.begin(); my_it != mp_tally_map.end(); ++my_it) {
const std::string& address = my_it->first;
CMPTally& tally = my_it->second;
tally.init();
uint32_t propertyId = 0;
while (0 != (propertyId = (tally.next()))) {
int64_t balance = tally.getMoney(propertyId, BALANCE);
int64_t sellOfferReserve = tally.getMoney(propertyId, SELLOFFER_RESERVE);
int64_t acceptReserve = tally.getMoney(propertyId, ACCEPT_RESERVE);
int64_t metaDExReserve = tally.getMoney(propertyId, METADEX_RESERVE);
// skip this entry if all balances are empty
if (!balance && !sellOfferReserve && !acceptReserve && !metaDExReserve) continue;
std::string dataStr = strprintf("%s|%d|%d|%d|%d|%d",
address, propertyId, balance, sellOfferReserve, acceptReserve, metaDExReserve);
if (msc_debug_consensus_hash) PrintToLog("Adding balance data to consensus hash: %s\n", dataStr);
// update the sha context with the data string
SHA256_Update(&shaCtx, dataStr.c_str(), dataStr.length());
}
}
// DEx sell offers - loop through the DEx and add each sell offer to the consensus hash
for (OfferMap::iterator it = my_offers.begin(); it != my_offers.end(); ++it) {
const CMPOffer& selloffer = it->second;
const std::string& sellCombo = it->first;
uint32_t propertyId = selloffer.getProperty();
std::string seller = sellCombo.substr(0, sellCombo.size() - 2);
// "txid|address|propertyid|offeramount|btcdesired|minfee|timelimit|availableamount|acceptedamount"
std::string dataStr = strprintf("%s|%s|%d|%d|%d|%d|%d|%d|%d",
selloffer.getHash().GetHex(), seller, propertyId, selloffer.getOfferAmountOriginal(),
selloffer.getBTCDesiredOriginal(), selloffer.getMinFee(), selloffer.getBlockTimeLimit(),
getMPbalance(seller, propertyId, SELLOFFER_RESERVE), getMPbalance(seller, propertyId, ACCEPT_RESERVE));
if (msc_debug_consensus_hash) PrintToLog("Adding DEx offer data to consensus hash: %s\n", dataStr);
// update the sha context with the data string
SHA256_Update(&shaCtx, dataStr.c_str(), dataStr.length());
}
// MetaDEx trades - loop through the MetaDEx maps and add each open trade to the consensus hash
for (md_PropertiesMap::const_iterator my_it = metadex.begin(); my_it != metadex.end(); ++my_it) {
const md_PricesMap& prices = my_it->second;
for (md_PricesMap::const_iterator it = prices.begin(); it != prices.end(); ++it) {
const md_Set& indexes = it->second;
for (md_Set::const_iterator it = indexes.begin(); it != indexes.end(); ++it) {
const CMPMetaDEx& obj = *it;
// "txid|address|propertyidforsale|amountforsale|propertyiddesired|amountdesired|amountremaining"
std::string dataStr = strprintf("%s|%s|%d|%d|%d|%d|%d",
obj.getHash().GetHex(), obj.getAddr(), obj.getProperty(), obj.getAmountForSale(),
obj.getDesProperty(), obj.getAmountDesired(), obj.getAmountRemaining());
if (msc_debug_consensus_hash) PrintToLog("Adding MetaDEx trade data to consensus hash: %s\n", dataStr);
// update the sha context with the data string
SHA256_Update(&shaCtx, dataStr.c_str(), dataStr.length());
}
}
}
// extract the final result and return the hash
uint256 consensusHash;
SHA256_Final((unsigned char*)&consensusHash, &shaCtx);
if (msc_debug_consensus_hash) PrintToLog("Finished generation of consensus hash. Result: %s\n", consensusHash.GetHex());
return consensusHash;
}
} // namespace mastercore
<|endoftext|> |
<commit_before>#ifndef HEX_STR_HPP
#define HEX_STR_HPP
#include <string>
template <typename FwdIt>
std::string hex_str(FwdIt first, FwdIt last)
{
static_assert(sizeof(typename std::iterator_traits<FwdIt>::value_type) == 1,
"value_type must be 1 byte.");
constexpr const char *bytemap = "0123456789abcdef";
std::string result(std::distance(first, last) * 2, '0');
auto pos = begin(result);
while (first != last)
{
*pos++ = bytemap[ *first >> 4 & 0xF ];
*pos++ = bytemap[ *first++ & 0xF ];
}
return result;
}
#endif
<commit_msg>Allow specifying uppercase or lowercase.<commit_after>#ifndef HEX_STR_HPP
#define HEX_STR_HPP
#include <string>
enum
{
upperhex,
lowerhex
};
template <bool Caps = lowerhex, typename FwdIt>
std::string hex_str(FwdIt first, FwdIt last)
{
static_assert(sizeof(typename std::iterator_traits<FwdIt>::value_type) == 1,
"value_type must be 1 byte.");
constexpr const char *bytemap = Caps ?
"0123456789abcdef" :
"0123456789ABCDEF";
std::string result(std::distance(first, last) * 2, '0');
auto pos = begin(result);
while (first != last)
{
*pos++ = bytemap[ *first >> 4 & 0xF ];
*pos++ = bytemap[ *first++ & 0xF ];
}
return result;
}
#endif
<|endoftext|> |
<commit_before>#include <bitcoin/bitcoin.hpp>
#include <obelisk/obelisk.hpp>
#include "config.hpp"
#include "util.hpp"
using namespace bc;
using std::placeholders::_1;
using std::placeholders::_2;
typedef std::vector<payment_address> payaddr_list;
std::atomic_uint fetch_count(0);
void history_fetched(const payment_address& payaddr,
const std::error_code& ec, const blockchain::history_list& history)
{
if (ec)
{
std::cerr << "history: Failed to fetch history: "
<< ec.message() << std::endl;
return;
}
for (const auto& row: history)
{
std::cout << "Address: " << payaddr.encoded() << std::endl;
std::cout << " output: " << row.output << std::endl;
std::cout << " output_height: ";
if (!row.output_height)
std::cout << "Pending";
else
std::cout << row.output_height;
std::cout << std::endl;
std::cout << " value: " << row.value << std::endl;
if (row.spend.hash == null_hash)
{
std::cout << " spend: Unspent" << std::endl;
std::cout << " spend_height: Unspent" << std::endl;
}
else
{
std::cout << " spend: " << row.spend << std::endl;
std::cout << " spend_height: ";
if (!row.spend_height)
std::cout << "Pending";
else
std::cout << row.spend_height;
std::cout << std::endl;
}
std::cout << std::endl;
}
++fetch_count;
}
bool payaddr_from_stdin(payment_address& payaddr)
{
if (!payaddr.set_encoded(read_stdin()))
{
std::cerr << "history: Invalid address." << std::endl;
return false;
}
return true;
}
bool payaddr_from_argv(payaddr_list& payaddrs, int argc, char** argv)
{
for (size_t i = 1; i < argc; ++i)
{
payment_address payaddr;
if (!payaddr.set_encoded(argv[i]))
return false;
payaddrs.push_back(payaddr);
}
return true;
}
int main(int argc, char** argv)
{
config_map_type config;
load_config(config);
payaddr_list payaddrs;
if (argc == 1)
{
payment_address payaddr;
if (!payaddr_from_stdin(payaddr))
return -1;
payaddrs.push_back(payaddr);
}
else
{
if (!payaddr_from_argv(payaddrs, argc, argv))
return -1;
}
threadpool pool(1);
obelisk::fullnode_interface fullnode(pool, config["service"]);
for (const payment_address& payaddr: payaddrs)
fullnode.address.fetch_history(payaddr,
std::bind(history_fetched, payaddr, _1, _2));
while (fetch_count < payaddrs.size())
{
fullnode.update();
sleep(0.1);
}
BITCOIN_ASSERT(fetch_count == payaddrs.size());
pool.stop();
pool.join();
return 0;
}
<commit_msg>-j for history to convert to json.<commit_after>#include <bitcoin/bitcoin.hpp>
#include <obelisk/obelisk.hpp>
#include "config.hpp"
#include "util.hpp"
using namespace bc;
using std::placeholders::_1;
using std::placeholders::_2;
typedef std::vector<payment_address> payaddr_list;
std::atomic_uint remaining_count;
bool json_output = false;
void history_fetched(const payment_address& payaddr,
const std::error_code& ec, const blockchain::history_list& history)
{
if (ec)
{
std::cerr << "history: Failed to fetch history: "
<< ec.message() << std::endl;
return;
}
for (const auto& row: history)
{
std::cout << "Address: " << payaddr.encoded() << std::endl;
std::cout << " output: " << row.output << std::endl;
std::cout << " output_height: ";
if (!row.output_height)
std::cout << "Pending";
else
std::cout << row.output_height;
std::cout << std::endl;
std::cout << " value: " << row.value << std::endl;
if (row.spend.hash == null_hash)
{
std::cout << " spend: Unspent" << std::endl;
std::cout << " spend_height: Unspent" << std::endl;
}
else
{
std::cout << " spend: " << row.spend << std::endl;
std::cout << " spend_height: ";
if (!row.spend_height)
std::cout << "Pending";
else
std::cout << row.spend_height;
std::cout << std::endl;
}
std::cout << std::endl;
}
--remaining_count;
}
void json_history_fetched(const payment_address& payaddr,
const std::error_code& ec, const blockchain::history_list& history)
{
if (ec)
{
std::cerr << "history: Failed to fetch history: "
<< ec.message() << std::endl;
return;
}
bool is_first = true;
for (const auto& row: history)
{
// Put commas between each array item in json output.
if (is_first)
is_first = false;
else
std::cout << "," << std::endl;
// Actual row data.
std::cout << "{" << std::endl;
std::cout << " \"address\": \"" << payaddr.encoded()
<< "\"," << std::endl;
std::cout << " \"output\": \"" << row.output
<< "\"," << std::endl;
std::cout << " \"output_height\": ";
if (!row.output_height)
std::cout << "\"Pending\"";
else
std::cout << row.output_height;
std::cout << "," << std::endl;
std::cout << " \"value\": \"" << row.value << "\"," << std::endl;
if (row.spend.hash == null_hash)
{
std::cout << " \"spend\": \"Unspent\"," << std::endl;
std::cout << " \"spend_height\": \"Unspent\"" << std::endl;
}
else
{
std::cout << " \"spend\": \"" << row.spend << "\"," << std::endl;
std::cout << " \"spend_height\": ";
if (!row.spend_height)
std::cout << "\"Pending\"";
else
std::cout << "\"" << row.spend_height << "\"";
}
std::cout << "}";
}
if (--remaining_count > 0)
std::cout << ",";
std::cout << std::endl;
}
bool payaddr_from_stdin(payment_address& payaddr)
{
if (!payaddr.set_encoded(read_stdin()))
{
std::cerr << "history: Invalid address." << std::endl;
return false;
}
return true;
}
bool payaddr_from_argv(payaddr_list& payaddrs, int argc, char** argv)
{
for (size_t i = 1; i < argc; ++i)
{
const std::string arg = argv[i];
if (arg == "-j")
{
json_output = true;
continue;
}
payment_address payaddr;
if (!payaddr.set_encoded(arg))
return false;
payaddrs.push_back(payaddr);
}
return true;
}
int main(int argc, char** argv)
{
config_map_type config;
load_config(config);
payaddr_list payaddrs;
if (argc == 1)
{
payment_address payaddr;
if (!payaddr_from_stdin(payaddr))
return -1;
payaddrs.push_back(payaddr);
}
else
{
if (!payaddr_from_argv(payaddrs, argc, argv))
return -1;
}
remaining_count = payaddrs.size();
threadpool pool(1);
obelisk::fullnode_interface fullnode(pool, config["service"]);
if (json_output)
std::cout << "[" << std::endl;
for (const payment_address& payaddr: payaddrs)
{
if (json_output)
fullnode.address.fetch_history(payaddr,
std::bind(json_history_fetched, payaddr, _1, _2));
else
fullnode.address.fetch_history(payaddr,
std::bind(history_fetched, payaddr, _1, _2));
}
while (remaining_count > 0)
{
fullnode.update();
sleep(0.1);
}
if (json_output)
std::cout << "]" << std::endl;
pool.stop();
pool.join();
return 0;
}
<|endoftext|> |
<commit_before>/**
* Copyright (c) 2014, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*/
#include <memory>
#include <vector>
#include <gtest/gtest.h>
#include "folly/io/IOBuf.h"
#include "mcrouter/lib/McStringData.h"
#include "mcrouter/lib/test/RouteHandleTestUtil.h"
using namespace facebook::memcache;
using std::vector;
TEST(mcStringData, basic) {
std::string s ("key");
folly::StringPiece sp (s);
McMsgRef msg = createMcMsgRef(sp);
McStringData a(
McStringData::SaveMsgKey, std::move(msg));
auto buf_a = a.asIOBuf();
folly::StringPiece sp_a(reinterpret_cast<const char *>(buf_a->data()),
buf_a->length());
EXPECT_EQ(sp, a.dataRange());
McStringData b = a;
auto buf_b = b.asIOBuf();
folly::StringPiece sp_b(reinterpret_cast<const char *>(buf_b->data()),
buf_b->length());
EXPECT_EQ(sp, a.dataRange());
}
TEST(mcStringData, memoryRegionCheck) {
auto value1 = McStringData(folly::IOBuf::copyBuffer("testing "));
auto value2 = McStringData(folly::IOBuf::copyBuffer("releasedMsg"));
vector<McStringData> string_vec;
string_vec.push_back(value1);
string_vec.push_back(value2);
auto value3 = concatAll(string_vec.begin(), string_vec.end());
auto value4 = concatAll(string_vec.begin(), string_vec.end());
EXPECT_FALSE(value1.asIOBuf()->isChained());
EXPECT_FALSE(value2.asIOBuf()->isChained());
EXPECT_TRUE(value3.asIOBuf()->isChained());
EXPECT_TRUE(value4.asIOBuf()->isChained());
EXPECT_TRUE(value1.hasSameMemoryRegion(value1));
EXPECT_FALSE(value1.hasSameMemoryRegion(value2));
EXPECT_TRUE(value3.hasSameMemoryRegion(value4));
EXPECT_FALSE(value3.hasSameMemoryRegion(value2));
}
TEST(mcStringData, copy) {
{
McStringData a("key");
McStringData b = a;
EXPECT_EQ(a.dataRange(), b.dataRange());
EXPECT_EQ(a.dataRange().str(), "key");
}
{ // small size that will require an internal buffer.
McStringData a(folly::IOBuf::copyBuffer("key"));
McStringData b = a;
EXPECT_EQ(a.dataRange(), b.dataRange());
EXPECT_EQ(a.dataRange().str(), "key");
}
{ // large size that will require an external buffer.
McStringData a(folly::IOBuf::copyBuffer(std::string(640, 'b')));
McStringData b = a;
// no copy when external buffer used
EXPECT_TRUE(sameMemoryRegion(a.dataRange(), b.dataRange()));
McStringData a_subdata = a.substr(100, 100);
auto buf = a.asIOBuf(); // backing buffer for a_subdata
auto buf_subdata = a_subdata.asIOBuf(); // actual data in a_subdata
folly::StringPiece buf_sp(
reinterpret_cast<const char*> (buf->data()), buf->length()
);
folly::StringPiece buf_subdata_sp(
reinterpret_cast<const char*> (buf_subdata->data()), buf_subdata->length()
);
// no copy made in asIOBuf()
EXPECT_TRUE(sameMemoryRegion(buf_sp.subpiece(100, 100), buf_subdata_sp));
}
}
TEST(mcStringData, substr) {
std::string s("test_subpiece_and_concat");
{
McStringData a(s);
auto sp = a.dataRange();
auto value_size = sp.size();
int substr_size = 5;
int num_chunks = (value_size + substr_size - 1)/ substr_size;
size_t s_pos = 0;
std::vector<McStringData> subdata_vec;
// create substrings from McStringData a
for (int i = 0; i < num_chunks; i++) {
auto len = ((s_pos + substr_size) >= value_size) ?
std::string::npos : substr_size;
subdata_vec.push_back(a.substr(s_pos, len));
auto sp_piece = sp.subpiece(s_pos, len);
EXPECT_EQ(subdata_vec[i].dataRange(), sp_piece);
EXPECT_EQ(subdata_vec[i].dataRange().toString(), sp_piece.toString());
auto buf = subdata_vec[i].asIOBuf();
auto sp_buf = folly::StringPiece(
reinterpret_cast<const char*> (buf->data()), buf->length());
EXPECT_EQ(sp_buf, sp_piece);
EXPECT_EQ(sp_buf.toString(), sp_piece.toString());
s_pos += len;
}
// McStringData a has the same datarange
EXPECT_EQ(a.dataRange().toString(), s);
McStringData concatstr = concatAll(subdata_vec.begin(), subdata_vec.end());
EXPECT_EQ(concatstr.dataRange(), sp);
EXPECT_EQ(concatstr.dataRange().toString(), sp.toString());
}
{ // empty McStringData
McStringData s_empty;
auto sub_str = s_empty.substr(0);
EXPECT_EQ(s_empty.dataRange().str(), "");
}
{ // substr length greater than orignal string length
McStringData str(s);
auto sub_str = str.substr(0, 100);
EXPECT_EQ(str.dataRange().str(), sub_str.dataRange().str());
}
{ // substr for a McStringData with non-zero begin in relative range
McStringData str(s);
auto sub_str1 = str.substr(3);
auto sub_str2 = str.substr(2);
auto sub_str3 = sub_str2.substr(1);
EXPECT_EQ(sub_str1.dataRange().str(), sub_str3.dataRange().str());
}
}
<commit_msg>Remove dead test<commit_after><|endoftext|> |
<commit_before>/* vim: set sw=4 sts=4 et foldmethod=syntax : */
#include <graph/is_club.hh>
#include <limits>
using namespace parasols;
auto
parasols::is_club(const Graph & graph, int k, const std::set<int> & members) -> bool
{
std::vector<std::vector<int> > distances((graph.size()));
for (auto & d : distances)
d.resize((graph.size()));
for (int i = 0 ; i < graph.size() ; ++i)
for (int j = 0 ; j < graph.size() ; ++j) {
if (i == j)
distances[i][j] = 0;
else if (members.count(i) && members.count(j) && graph.adjacent(i, j))
distances[i][j] = 1;
else
distances[i][j] = std::numeric_limits<int>::max();
}
/* shorten */
for (int k = 0 ; k < graph.size() ; ++k)
for (int i = 0 ; i < graph.size() ; ++i)
for (int j = 0 ; j < graph.size() ; ++j)
if (distances[i][k] != std::numeric_limits<int>::max() &&
distances[k][j] != std::numeric_limits<int>::max()) {
int d = distances[i][k] + distances[k][j];
if (distances[i][j] > d)
distances[i][j] = d;
}
for (auto & i : members)
for (auto & j : members)
if (distances[i][j] > k)
return false;
return true;
}
<commit_msg>Faster club detection<commit_after>/* vim: set sw=4 sts=4 et foldmethod=syntax : */
#include <graph/is_club.hh>
#include <limits>
using namespace parasols;
auto
parasols::is_club(const Graph & graph, int k, const std::set<int> & members) -> bool
{
std::vector<std::vector<int> > distances((graph.size()));
for (auto & d : distances)
d.resize((graph.size()));
for (int i : members)
for (int j : members) {
if (i == j)
distances[i][j] = 0;
else if (members.count(i) && members.count(j) && graph.adjacent(i, j))
distances[i][j] = 1;
else
distances[i][j] = std::numeric_limits<int>::max();
}
/* shorten */
for (int k : members)
for (int i : members)
for (int j : members)
if (distances[i][k] != std::numeric_limits<int>::max() &&
distances[k][j] != std::numeric_limits<int>::max()) {
int d = distances[i][k] + distances[k][j];
if (distances[i][j] > d)
distances[i][j] = d;
}
for (auto & i : members)
for (auto & j : members)
if (distances[i][j] > k)
return false;
return true;
}
<|endoftext|> |
<commit_before>// Copyright (c) 2015 Pierre MOULON.
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/.
#ifndef OPENMVG_GEOMETRY_POSE3_H_
#define OPENMVG_GEOMETRY_POSE3_H_
#include "openMVG/multiview/projection.hpp"
#include <cereal/cereal.hpp> // Serialization
namespace openMVG {
namespace geometry {
// Define a 3D Pose as a 3D transform: [R|C] t = -RC
class Pose3
{
protected:
Mat3 _rotation;
Vec3 _center;
public:
// Constructors
Pose3() : _rotation(Mat3::Identity()), _center(Vec3::Zero()) {}
Pose3(const Mat3& r, const Vec3& c) : _rotation(r), _center(c) {}
Pose3(const Mat34& Rt)
: _rotation(Rt.block<3,3>(0,0))
{
Vec3 t = Rt.block<3, 1>(0,3);
_center = -_rotation.transpose() * t;
}
// Accessors
const Mat3& rotation() const { return _rotation; }
Mat3& rotation() { return _rotation; }
const Vec3& center() const { return _center; }
Vec3& center() { return _center; }
// Translation vector t = -RC
inline Vec3 translation() const { return -(_rotation * _center); }
// Apply pose
inline Mat3X operator () (const Mat3X& p) const
{
return _rotation * (p.colwise() - _center);
}
// Composition
Pose3 operator * (const Pose3& P) const
{
return Pose3(_rotation * P._rotation, P._center + P._rotation.transpose() * _center );
}
// Operator ==
bool operator==(const Pose3& other) const
{
return AreMatNearEqual(_rotation, other._rotation, 1e-6) &&
AreVecNearEqual(_center, other._center, 1e-6);
}
// Inverse
Pose3 inverse() const
{
return Pose3(_rotation.transpose(), -(_rotation * _center));
}
/// Return the depth (distance) of a point respect to the camera center
double depth(const Vec3 &X) const
{
return (_rotation * (X - _center))[2];
}
/// Return the pose with the Scale, Rotation and translation applied.
Pose3 transformSRt(const double S, const Mat3 & R, const Vec3 & t) const
{
Pose3 pose;
pose._center = S * R * _center + t;
pose._rotation = _rotation * R.transpose();
return pose;
}
// Serialization
template <class Archive>
void save( Archive & ar) const
{
const std::vector<std::vector<double>> mat =
{
{ _rotation(0,0), _rotation(0,1), _rotation(0,2) },
{ _rotation(1,0), _rotation(1,1), _rotation(1,2) },
{ _rotation(2,0), _rotation(2,1), _rotation(2,2) }
};
ar(cereal::make_nvp("rotation", mat));
const std::vector<double> vec = { _center(0), _center(1), _center(2) };
ar(cereal::make_nvp("center", vec ));
}
template <class Archive>
void load( Archive & ar)
{
std::vector<std::vector<double>> mat(3, std::vector<double>(3));
ar(cereal::make_nvp("rotation", mat));
// copy back to the rotation
_rotation.row(0) = Eigen::Map<const Vec3>(&(mat[0][0]));
_rotation.row(1) = Eigen::Map<const Vec3>(&(mat[1][0]));
_rotation.row(2) = Eigen::Map<const Vec3>(&(mat[2][0]));
std::vector<double> vec(3);
ar(cereal::make_nvp("center", vec));
_center = Eigen::Map<const Vec3>(&vec[0]);
}
};
/**
* @brief Build a pose froma a rotation and a translation.
* @param[in] R The 3x3 rotation.
* @param[in] t The 3x1 translation.
* @return The pose as [R, -R'*t]
*/
inline Pose3 poseFromRT(const Mat3& R, const Vec3& t)
{
return Pose3(R, -R.transpose()*t);
}
} // namespace geometry
} // namespace openMVG
#endif // OPENMVG_GEOMETRY_POSE3_H_
<commit_msg>fix typo<commit_after>// Copyright (c) 2015 Pierre MOULON.
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/.
#ifndef OPENMVG_GEOMETRY_POSE3_H_
#define OPENMVG_GEOMETRY_POSE3_H_
#include "openMVG/multiview/projection.hpp"
#include <cereal/cereal.hpp> // Serialization
namespace openMVG {
namespace geometry {
// Define a 3D Pose as a 3D transform: [R|C] t = -RC
class Pose3
{
protected:
Mat3 _rotation;
Vec3 _center;
public:
// Constructors
Pose3() : _rotation(Mat3::Identity()), _center(Vec3::Zero()) {}
Pose3(const Mat3& r, const Vec3& c) : _rotation(r), _center(c) {}
Pose3(const Mat34& Rt)
: _rotation(Rt.block<3,3>(0,0))
{
Vec3 t = Rt.block<3, 1>(0,3);
_center = -_rotation.transpose() * t;
}
// Accessors
const Mat3& rotation() const { return _rotation; }
Mat3& rotation() { return _rotation; }
const Vec3& center() const { return _center; }
Vec3& center() { return _center; }
// Translation vector t = -RC
inline Vec3 translation() const { return -(_rotation * _center); }
// Apply pose
inline Mat3X operator () (const Mat3X& p) const
{
return _rotation * (p.colwise() - _center);
}
// Composition
Pose3 operator * (const Pose3& P) const
{
return Pose3(_rotation * P._rotation, P._center + P._rotation.transpose() * _center );
}
// Operator ==
bool operator==(const Pose3& other) const
{
return AreMatNearEqual(_rotation, other._rotation, 1e-6) &&
AreVecNearEqual(_center, other._center, 1e-6);
}
// Inverse
Pose3 inverse() const
{
return Pose3(_rotation.transpose(), -(_rotation * _center));
}
/// Return the depth (distance) of a point respect to the camera center
double depth(const Vec3 &X) const
{
return (_rotation * (X - _center))[2];
}
/// Return the pose with the Scale, Rotation and translation applied.
Pose3 transformSRt(const double S, const Mat3 & R, const Vec3 & t) const
{
Pose3 pose;
pose._center = S * R * _center + t;
pose._rotation = _rotation * R.transpose();
return pose;
}
// Serialization
template <class Archive>
void save( Archive & ar) const
{
const std::vector<std::vector<double>> mat =
{
{ _rotation(0,0), _rotation(0,1), _rotation(0,2) },
{ _rotation(1,0), _rotation(1,1), _rotation(1,2) },
{ _rotation(2,0), _rotation(2,1), _rotation(2,2) }
};
ar(cereal::make_nvp("rotation", mat));
const std::vector<double> vec = { _center(0), _center(1), _center(2) };
ar(cereal::make_nvp("center", vec ));
}
template <class Archive>
void load( Archive & ar)
{
std::vector<std::vector<double>> mat(3, std::vector<double>(3));
ar(cereal::make_nvp("rotation", mat));
// copy back to the rotation
_rotation.row(0) = Eigen::Map<const Vec3>(&(mat[0][0]));
_rotation.row(1) = Eigen::Map<const Vec3>(&(mat[1][0]));
_rotation.row(2) = Eigen::Map<const Vec3>(&(mat[2][0]));
std::vector<double> vec(3);
ar(cereal::make_nvp("center", vec));
_center = Eigen::Map<const Vec3>(&vec[0]);
}
};
/**
* @brief Build a pose from a rotation and a translation.
* @param[in] R The 3x3 rotation.
* @param[in] t The 3x1 translation.
* @return The pose as [R, -R'*t]
*/
inline Pose3 poseFromRT(const Mat3& R, const Vec3& t)
{
return Pose3(R, -R.transpose()*t);
}
} // namespace geometry
} // namespace openMVG
#endif // OPENMVG_GEOMETRY_POSE3_H_
<|endoftext|> |
<commit_before>#include "dynamic_buffer_iterator.hh"
namespace Kakoune
{
DynamicBufferIterator::DynamicBufferIterator(const Buffer& buffer,
BufferPos position)
: BufferIterator(buffer, position)
{
register_ifp();
}
DynamicBufferIterator::DynamicBufferIterator(DynamicBufferIterator&& other)
: BufferIterator(other)
{
register_ifp();
}
DynamicBufferIterator::DynamicBufferIterator(const BufferIterator& other)
: BufferIterator(other)
{
register_ifp();
}
DynamicBufferIterator& DynamicBufferIterator::operator=(const BufferIterator& other)
{
unregister_ifn();
BufferIterator::operator=(other);
register_ifp();
return *this;
}
DynamicBufferIterator::~DynamicBufferIterator()
{
unregister_ifn();
}
void DynamicBufferIterator::on_modification(const BufferModification& modification)
{
if (*this < modification.position)
return;
size_t length = modification.content.length();
if (modification.type == BufferModification::Erase)
{
if (*this <= modification.position + length)
BufferIterator::operator=(modification.position);
else
*this -= length;
}
else
{
assert(modification.type == BufferModification::Insert);
*this += length;
}
}
void DynamicBufferIterator::register_ifp()
{
if (is_valid())
const_cast<Buffer&>(buffer()).register_modification_listener(this);
}
void DynamicBufferIterator::unregister_ifn()
{
if (is_valid())
const_cast<Buffer&>(buffer()).unregister_modification_listener(this);
}
}
<commit_msg>DynamicBufferIterator: fix end of buffer corner case<commit_after>#include "dynamic_buffer_iterator.hh"
namespace Kakoune
{
DynamicBufferIterator::DynamicBufferIterator(const Buffer& buffer,
BufferPos position)
: BufferIterator(buffer, position)
{
register_ifp();
}
DynamicBufferIterator::DynamicBufferIterator(DynamicBufferIterator&& other)
: BufferIterator(other)
{
register_ifp();
}
DynamicBufferIterator::DynamicBufferIterator(const BufferIterator& other)
: BufferIterator(other)
{
register_ifp();
}
DynamicBufferIterator& DynamicBufferIterator::operator=(const BufferIterator& other)
{
unregister_ifn();
BufferIterator::operator=(other);
register_ifp();
return *this;
}
DynamicBufferIterator::~DynamicBufferIterator()
{
unregister_ifn();
}
void DynamicBufferIterator::on_modification(const BufferModification& modification)
{
if (*this < modification.position)
return;
size_t length = modification.content.length();
if (modification.type == BufferModification::Erase)
{
// do not move length on the other side of the inequality,
// as modification.position + length may be after buffer end
if (*this - length <= modification.position)
BufferIterator::operator=(modification.position);
else
*this -= length;
}
else
{
assert(modification.type == BufferModification::Insert);
*this += length;
}
}
void DynamicBufferIterator::register_ifp()
{
if (is_valid())
const_cast<Buffer&>(buffer()).register_modification_listener(this);
}
void DynamicBufferIterator::unregister_ifn()
{
if (is_valid())
const_cast<Buffer&>(buffer()).unregister_modification_listener(this);
}
}
<|endoftext|> |
<commit_before>/////////////////////////////////////////////////////////////////////////////
// Original authors: SangGi Do([email protected]), Mingyu Woo([email protected])
// (respective Ph.D. advisors: Seokhyeong Kang, Andrew B. Kahng)
// Rewrite by James Cherry, Parallax Software, Inc.
// BSD 3-Clause License
//
// Copyright (c) 2019, James Cherry, Parallax Software, Inc.
// Copyright (c) 2018, SangGi Do and Mingyu Woo
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// * Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// * Neither the name of the copyright holder nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
///////////////////////////////////////////////////////////////////////////////
#include <iostream>
#include <limits>
#include <iomanip>
#include <cmath>
#include "opendp/Opendp.h"
namespace opendp {
using std::cout;
using std::endl;
using std::make_pair;
using std::max;
using std::min;
using std::ofstream;
using std::pair;
using std::to_string;
using std::vector;
using odb::adsRect;
bool Opendp::checkLegality(bool verbose) {
cout << "Check Legality" << endl;
bool legal = true;
legal &= row_check(verbose);
legal &= site_check(verbose);
legal &= power_line_check(verbose);
legal &= edge_check(verbose);
legal &= placed_check(verbose);
legal &= overlap_check(verbose);
return legal;
}
bool Opendp::row_check(bool verbose) {
bool valid = true;
int count = 0;
for(int i = 0; i < cells_.size(); i++) {
Cell* cell = &cells_[i];
if(!isFixed(cell)) {
if(cell->y_ % row_height_ != 0) {
if (verbose)
cout << "row_check fail => " << cell->name()
<< " y_ : " << cell->y_ << endl;
valid = false;
count++;
}
}
}
if(!valid)
cout << "row check ==> FAIL (" << count << ")" << endl;
else
cout << "row check ==> PASS " << endl;
return valid;
}
bool Opendp::site_check(bool verbose) {
bool valid = true;
int count = 0;
for(int i = 0; i < cells_.size(); i++) {
Cell* cell = &cells_[i];
if(!isFixed(cell)) {
if(cell->x_ % site_width_ != 0) {
if (verbose)
cout << "site check fail ==> " << cell->name()
<< " x_ : " << cell->x_ << endl;
valid = false;
count++;
}
}
}
if(!valid)
cout << "site check ==> FAIL (" << count << ")" << endl;
else
cout << "site check ==> PASS " << endl;
return valid;
}
bool Opendp::edge_check(bool verbose) {
bool valid = true;
int count = 0;
for(int i = 0; i < row_count_; i++) {
vector< Cell* > cells;
for(int j = 0; j < row_site_count_; j++) {
Cell* grid_cell = grid_[i][j].cell;
if(grid_[i][j].is_valid) {
if(grid_cell && grid_cell != &dummy_cell_) {
#ifdef ODP_DEBUG
cout << "grid util : " << grid[i][j].util << endl;
cout << "cell name : "
<< grid[i][j].cell->name() << endl;
#endif
if(cells.empty()) {
cells.push_back(grid_[i][j].cell);
}
else if(cells[cells.size() - 1] != grid_[i][j].cell) {
cells.push_back(grid_[i][j].cell);
}
}
}
}
}
if(!valid)
cout << "edge check ==> FAIL (" << count << ")" << endl;
else
cout << "edge_check ==> PASS " << endl;
return valid;
}
bool Opendp::power_line_check(bool verbose) {
bool valid = true;
int count = 0;
for(Cell& cell : cells_) {
if(!isFixed(&cell)
// Magic number alert
// Shouldn't this be odd test instead of 1 or 3? -cherry
&& !(cell.height_ == row_height_ || cell.height_ == row_height_ * 3)
// should removed later
&& cell.inGroup()) {
int y_size = gridHeight(&cell);
int grid_y = gridY(&cell);
power top_power = topPower(&cell);
if(y_size % 2 == 0) {
if(top_power == rowTopPower(grid_y)) {
cout << "power check fail ( even height ) ==> "
<< cell.name() << endl;
valid = false;
count++;
}
}
else {
if(top_power == rowTopPower(grid_y)) {
if(cell.db_inst_->getOrient() != dbOrientType::R0) {
cout << "power check fail ( Should be N ) ==> "
<< cell.name() << endl;
valid = false;
count++;
}
}
else {
if(cell.db_inst_->getOrient() != dbOrientType::MX) {
cout << "power_check fail ( Should be FS ) ==> "
<< cell.name() << endl;
valid = false;
count++;
}
}
}
}
}
if(!valid)
cout << "power check ==> FAIL (" << count << ")" << endl;
else
cout << "power check ==> PASS " << endl;
return valid;
}
bool Opendp::placed_check(bool verbose) {
bool valid = true;
int count = 0;
for(Cell& cell : cells_) {
if(!cell.is_placed_) {
if (verbose)
cout << "placed check fail ==> " << cell.name() << endl;
valid = false;
count++;
}
}
if(!valid)
cout << "placed_check ==> FAIL (" << count << ")" << endl;
else
cout << "placed_check ==>> PASS " << endl;
return valid;
}
bool Opendp::overlap_check(bool verbose) {
bool valid = true;
Grid *grid = makeGrid();
for(Cell& cell : cells_) {
int grid_x = gridX(&cell);
int grid_y = gridY(&cell);
int x_ur = gridEndX(&cell);
int y_ur = gridEndY(&cell);
// Fixed cells can be outside DIEAREA.
if(isFixed(&cell)) {
grid_x = max(0, grid_x);
grid_y = max(0, grid_y);
x_ur = min(x_ur, row_site_count_);
y_ur = min(y_ur, row_count_);
}
assert(grid_x >= 0);
assert(grid_y >= 0);
assert(x_ur <= row_site_count_);
assert(y_ur <= row_count_);
for(int j = grid_y; j < y_ur; j++) {
for(int k = grid_x; k < x_ur; k++) {
if(grid[j][k].cell == nullptr) {
grid[j][k].cell = &cell;
grid[j][k].util = 1.0;
}
else {
if (verbose)
cout << "overlap_check ==> FAIL ( cell " << cell.name()
<< " overlaps " << grid[j][k].cell->name() << " ) "
<< " ( " << (k * site_width_ + core_.xMin()) << ", "
<< (j * row_height_ + core_.yMin()) << " )" << endl;
valid = false;
}
}
}
}
deleteGrid(grid);
if(valid)
cout << "overlap_check ==> PASS " << endl;
else
cout << "overlap_check ==> FAIL " << endl;
return valid;
}
} // namespace opendp
<commit_msg>opendp cleanup<commit_after>/////////////////////////////////////////////////////////////////////////////
// Original authors: SangGi Do([email protected]), Mingyu Woo([email protected])
// (respective Ph.D. advisors: Seokhyeong Kang, Andrew B. Kahng)
// Rewrite by James Cherry, Parallax Software, Inc.
// BSD 3-Clause License
//
// Copyright (c) 2019, James Cherry, Parallax Software, Inc.
// Copyright (c) 2018, SangGi Do and Mingyu Woo
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// * Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// * Neither the name of the copyright holder nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
///////////////////////////////////////////////////////////////////////////////
#include <iostream>
#include <limits>
#include <iomanip>
#include <cmath>
#include "opendp/Opendp.h"
namespace opendp {
using std::cout;
using std::endl;
using std::make_pair;
using std::max;
using std::min;
using std::ofstream;
using std::pair;
using std::to_string;
using std::vector;
using odb::adsRect;
bool Opendp::checkLegality(bool verbose) {
cout << "Check Legality" << endl;
bool legal = true;
legal &= row_check(verbose);
legal &= site_check(verbose);
legal &= power_line_check(verbose);
legal &= edge_check(verbose);
legal &= placed_check(verbose);
legal &= overlap_check(verbose);
return legal;
}
bool Opendp::row_check(bool verbose) {
bool valid = true;
int count = 0;
for(Cell& cell : cells_) {
if(!isFixed(&cell)) {
if(cell.y_ % row_height_ != 0) {
if (verbose)
cout << "row_check fail => " << cell.name()
<< " y_ : " << cell.y_ << endl;
valid = false;
count++;
}
}
}
if(!valid)
cout << "row check ==> FAIL (" << count << ")" << endl;
else
cout << "row check ==> PASS " << endl;
return valid;
}
bool Opendp::site_check(bool verbose) {
bool valid = true;
int count = 0;
for(Cell& cell : cells_) {
if(!isFixed(&cell)) {
if(cell.x_ % site_width_ != 0) {
if (verbose)
cout << "site check fail ==> " << cell.name()
<< " x_ : " << cell.x_ << endl;
valid = false;
count++;
}
}
}
if(!valid)
cout << "site check ==> FAIL (" << count << ")" << endl;
else
cout << "site check ==> PASS " << endl;
return valid;
}
bool Opendp::edge_check(bool verbose) {
bool valid = true;
int count = 0;
for(int i = 0; i < row_count_; i++) {
vector< Cell* > cells;
for(int j = 0; j < row_site_count_; j++) {
Cell* grid_cell = grid_[i][j].cell;
if(grid_[i][j].is_valid) {
if(grid_cell && grid_cell != &dummy_cell_) {
#ifdef ODP_DEBUG
cout << "grid util : " << grid[i][j].util << endl;
cout << "cell name : "
<< grid[i][j].cell->name() << endl;
#endif
if(cells.empty()) {
cells.push_back(grid_[i][j].cell);
}
else if(cells[cells.size() - 1] != grid_[i][j].cell) {
cells.push_back(grid_[i][j].cell);
}
}
}
}
}
if(!valid)
cout << "edge check ==> FAIL (" << count << ")" << endl;
else
cout << "edge_check ==> PASS " << endl;
return valid;
}
bool Opendp::power_line_check(bool verbose) {
bool valid = true;
int count = 0;
for(Cell& cell : cells_) {
if(!isFixed(&cell)
// Magic number alert
// Shouldn't this be odd test instead of 1 or 3? -cherry
&& !(cell.height_ == row_height_ || cell.height_ == row_height_ * 3)
// should removed later
&& cell.inGroup()) {
int y_size = gridHeight(&cell);
int grid_y = gridY(&cell);
power top_power = topPower(&cell);
if(y_size % 2 == 0) {
if(top_power == rowTopPower(grid_y)) {
cout << "power check fail ( even height ) ==> "
<< cell.name() << endl;
valid = false;
count++;
}
}
else {
if(top_power == rowTopPower(grid_y)) {
if(cell.db_inst_->getOrient() != dbOrientType::R0) {
cout << "power check fail ( Should be N ) ==> "
<< cell.name() << endl;
valid = false;
count++;
}
}
else {
if(cell.db_inst_->getOrient() != dbOrientType::MX) {
cout << "power_check fail ( Should be FS ) ==> "
<< cell.name() << endl;
valid = false;
count++;
}
}
}
}
}
if(!valid)
cout << "power check ==> FAIL (" << count << ")" << endl;
else
cout << "power check ==> PASS " << endl;
return valid;
}
bool Opendp::placed_check(bool verbose) {
bool valid = true;
int count = 0;
for(Cell& cell : cells_) {
if(!cell.is_placed_) {
if (verbose)
cout << "placed check fail ==> " << cell.name() << endl;
valid = false;
count++;
}
}
if(!valid)
cout << "placed_check ==> FAIL (" << count << ")" << endl;
else
cout << "placed_check ==>> PASS " << endl;
return valid;
}
bool Opendp::overlap_check(bool verbose) {
bool valid = true;
Grid *grid = makeGrid();
for(Cell& cell : cells_) {
int grid_x = gridX(&cell);
int grid_y = gridY(&cell);
int x_ur = gridEndX(&cell);
int y_ur = gridEndY(&cell);
// Fixed cells can be outside DIEAREA.
if(isFixed(&cell)) {
grid_x = max(0, grid_x);
grid_y = max(0, grid_y);
x_ur = min(x_ur, row_site_count_);
y_ur = min(y_ur, row_count_);
}
assert(grid_x >= 0);
assert(grid_y >= 0);
assert(x_ur <= row_site_count_);
assert(y_ur <= row_count_);
for(int j = grid_y; j < y_ur; j++) {
for(int k = grid_x; k < x_ur; k++) {
if(grid[j][k].cell == nullptr) {
grid[j][k].cell = &cell;
grid[j][k].util = 1.0;
}
else {
if (verbose)
cout << "overlap_check ==> FAIL ( cell " << cell.name()
<< " overlaps " << grid[j][k].cell->name() << " ) "
<< " ( " << (k * site_width_ + core_.xMin()) << ", "
<< (j * row_height_ + core_.yMin()) << " )" << endl;
valid = false;
}
}
}
}
deleteGrid(grid);
if(valid)
cout << "overlap_check ==> PASS " << endl;
else
cout << "overlap_check ==> FAIL " << endl;
return valid;
}
} // namespace opendp
<|endoftext|> |
<commit_before>#include "mesh.h"
#include <iostream>
#include "gl/vertexLayout.h"
Mesh::Mesh():m_drawMode(GL_TRIANGLES) {
}
Mesh::Mesh(const Mesh &_mother):m_drawMode(_mother.getDrawMode()) {
add(_mother);
}
Mesh::~Mesh() {
}
void Mesh::setDrawMode(GLenum _drawMode) {
m_drawMode = _drawMode;
}
void Mesh::setColor(const glm::vec4 &_color) {
m_colors.clear();
for (uint32_t i = 0; i < m_vertices.size(); i++) {
m_colors.push_back(_color);
}
}
void Mesh::addColor(const glm::vec4 &_color) {
m_colors.push_back(_color);
}
void Mesh::addColors(const std::vector<glm::vec4> &_colors) {
m_colors.insert(m_colors.end(), _colors.begin(), _colors.end());
}
void Mesh::addVertex(const glm::vec3 &_point) {
m_vertices.push_back(_point);
}
void Mesh::addVertices(const std::vector<glm::vec3>& _verts) {
m_vertices.insert(m_vertices.end(),_verts.begin(),_verts.end());
}
void Mesh::addVertices(const glm::vec3* verts, int amt) {
m_vertices.insert(m_vertices.end(),verts,verts+amt);
}
void Mesh::addNormal(const glm::vec3 &_normal) {
m_normals.push_back(_normal);
}
void Mesh::addNormals(const std::vector<glm::vec3> &_normals ) {
m_normals.insert(m_normals.end(), _normals.begin(), _normals.end());
}
void Mesh::addTangent(const glm::vec4 &_tangent) {
m_tangents.push_back(_tangent);
}
void Mesh::addTexCoord(const glm::vec2 &_uv) {
m_texCoords.push_back(_uv);
}
void Mesh::addTexCoords(const std::vector<glm::vec2> &_uvs) {
m_texCoords.insert(m_texCoords.end(), _uvs.begin(), _uvs.end());
}
void Mesh::addIndex(INDEX_TYPE _i) {
m_indices.push_back(_i);
}
void Mesh::addIndices(const std::vector<INDEX_TYPE>& inds) {
m_indices.insert(m_indices.end(),inds.begin(),inds.end());
}
void Mesh::addIndices(const INDEX_TYPE* inds, int amt) {
m_indices.insert(m_indices.end(),inds,inds+amt);
}
void Mesh::addTriangle(INDEX_TYPE index1, INDEX_TYPE index2, INDEX_TYPE index3) {
addIndex(index1);
addIndex(index2);
addIndex(index3);
}
void Mesh::add(const Mesh &_mesh) {
if (_mesh.getDrawMode() != m_drawMode) {
std::cout << "INCOMPATIBLE DRAW MODES" << std::endl;
return;
}
INDEX_TYPE indexOffset = (INDEX_TYPE)getVertices().size();
addColors(_mesh.getColors());
addVertices(_mesh.getVertices());
addNormals(_mesh.getNormals());
addTexCoords(_mesh.getTexCoords());
for (uint32_t i = 0; i < _mesh.getIndices().size(); i++) {
addIndex(indexOffset+_mesh.getIndices()[i]);
}
}
GLenum Mesh::getDrawMode() const{
return m_drawMode;
}
const std::vector<glm::vec4> & Mesh::getColors() const{
return m_colors;
}
const std::vector<glm::vec4> & Mesh::getTangents() const {
return m_tangents;
}
const std::vector<glm::vec3> & Mesh::getVertices() const{
return m_vertices;
}
const std::vector<glm::vec3> & Mesh::getNormals() const{
return m_normals;
}
const std::vector<glm::vec2> & Mesh::getTexCoords() const{
return m_texCoords;
}
const std::vector<INDEX_TYPE> & Mesh::getIndices() const{
return m_indices;
}
std::vector<glm::ivec3> Mesh::getTriangles() const {
std::vector<glm::ivec3> faces;
if (getDrawMode() == GL_TRIANGLES) {
if (hasIndices()) {
for(unsigned int j = 0; j < m_indices.size(); j += 3) {
glm::ivec3 tri;
for(int k = 0; k < 3; k++) {
tri[k] = m_indices[j+k];
}
faces.push_back(tri);
}
}
else {
for( unsigned int j = 0; j < m_vertices.size(); j += 3) {
glm::ivec3 tri;
for(int k = 0; k < 3; k++) {
tri[k] = j+k;
}
faces.push_back(tri);
}
}
}
else {
// TODO
//
std::cout << "ERROR: getTriangles(): Mesh only add GL_TRIANGLES for NOW !!" << std::endl;
}
return faces;
}
void Mesh::clear() {
if (!m_vertices.empty()) {
m_vertices.clear();
}
if (hasColors()) {
m_colors.clear();
}
if (hasNormals()) {
m_normals.clear();
}
if (hasTexCoords()) {
m_texCoords.clear();
}
if (hasTangents()) {
m_tangents.clear();
}
if (hasIndices()) {
m_indices.clear();
}
}
bool Mesh::computeNormals() {
if (getDrawMode() != GL_TRIANGLES)
return false;
//The number of the vertices
int nV = m_vertices.size();
//The number of the triangles
int nT = m_indices.size() / 3;
std::vector<glm::vec3> norm( nV ); //Array for the normals
//Scan all the triangles. For each triangle add its
//normal to norm's vectors of triangle's vertices
for (int t=0; t<nT; t++) {
//Get indices of the triangle t
int i1 = m_indices[ 3 * t ];
int i2 = m_indices[ 3 * t + 1 ];
int i3 = m_indices[ 3 * t + 2 ];
//Get vertices of the triangle
const glm::vec3 &v1 = m_vertices[ i1 ];
const glm::vec3 &v2 = m_vertices[ i2 ];
const glm::vec3 &v3 = m_vertices[ i3 ];
//Compute the triangle's normal
glm::vec3 dir = glm::normalize(glm::cross(v2-v1,v3-v1));
//Accumulate it to norm array for i1, i2, i3
norm[ i1 ] += dir;
norm[ i2 ] += dir;
norm[ i3 ] += dir;
}
//Normalize the normal's length and add it.
m_normals.clear();
for (int i=0; i<nV; i++) {
addNormal( glm::normalize(norm[i]) );
}
return true;
}
// http://www.terathon.com/code/tangent.html
bool Mesh::computeTangents() {
//The number of the vertices
size_t nV = m_vertices.size();
if (m_texCoords.size() != nV ||
m_normals.size() != nV ||
getDrawMode() != GL_TRIANGLES)
return false;
//The number of the triangles
size_t nT = m_indices.size() / 3;
std::vector<glm::vec3> tan1( nV );
std::vector<glm::vec3> tan2( nV );
//Scan all the triangles. For each triangle add its
//normal to norm's vectors of triangle's vertices
for (size_t t = 0; t < nT; t++) {
//Get indices of the triangle t
int i1 = m_indices[ 3 * t ];
int i2 = m_indices[ 3 * t + 1 ];
int i3 = m_indices[ 3 * t + 2 ];
//Get vertices of the triangle
const glm::vec3 &v1 = m_vertices[ i1 ];
const glm::vec3 &v2 = m_vertices[ i2 ];
const glm::vec3 &v3 = m_vertices[ i3 ];
const glm::vec2 &w1 = m_texCoords[i1];
const glm::vec2 &w2 = m_texCoords[i2];
const glm::vec2 &w3 = m_texCoords[i3];
float x1 = v2.x - v1.x;
float x2 = v3.x - v1.x;
float y1 = v2.y - v1.y;
float y2 = v3.y - v1.y;
float z1 = v2.z - v1.z;
float z2 = v3.z - v1.z;
float s1 = w2.x - w1.x;
float s2 = w3.x - w1.x;
float t1 = w2.y - w1.y;
float t2 = w3.y - w1.y;
float r = 1.0f / (s1 * t2 - s2 * t1);
glm::vec3 sdir( (t2 * x1 - t1 * x2) * r,
(t2 * y1 - t1 * y2) * r,
(t2 * z1 - t1 * z2) * r);
glm::vec3 tdir( (s1 * x2 - s2 * x1) * r,
(s1 * y2 - s2 * y1) * r,
(s1 * z2 - s2 * z1) * r);
tan1[i1] += sdir;
tan1[i2] += sdir;
tan1[i3] += sdir;
tan2[i1] += tdir;
tan2[i2] += tdir;
tan2[i3] += tdir;
}
//Normalize the normal's length and add it.
m_tangents.clear();
for (size_t i = 0; i < nV; i++) {
const glm::vec3 &n = m_normals[i];
const glm::vec3 &t = tan1[i];
// Gram-Schmidt orthogonalize
glm::vec3 tangent = t - n * glm::normalize( glm::dot(n, t));
// Calculate handedness
float hardedness = (glm::dot( glm::cross(n, t), tan2[i]) < 0.0f) ? -1.0f : 1.0f;
addTangent(glm::vec4(tangent, hardedness));
}
return true;
}
Vbo* Mesh::getVbo() {
// Create Vertex Layout
//
std::vector<VertexAttrib> attribs;
attribs.push_back({"position", 3, GL_FLOAT, false, 0});
int nBits = 3;
bool bColor = false;
if (hasColors() && getColors().size() == m_vertices.size()) {
attribs.push_back({"color", 4, GL_FLOAT, false, 0});
bColor = true;
nBits += 4;
}
bool bNormals = false;
if (hasNormals() && getNormals().size() == m_vertices.size()) {
attribs.push_back({"normal", 3, GL_FLOAT, false, 0});
bNormals = true;
nBits += 3;
}
bool bTexCoords = false;
if (hasTexCoords() && getTexCoords().size() == m_vertices.size()) {
attribs.push_back({"texcoord", 2, GL_FLOAT, false, 0});
bTexCoords = true;
nBits += 2;
}
bool bTangents = false;
if (hasTangents() && getTangents().size() == m_vertices.size()) {
attribs.push_back({"tangent", 4, GL_FLOAT, false, 0});
bTangents = true;
nBits += 4;
}
VertexLayout* vertexLayout = new VertexLayout(attribs);
Vbo* tmpMesh = new Vbo(vertexLayout);
tmpMesh->setDrawMode(getDrawMode());
std::vector<GLfloat> data;
for (unsigned int i = 0; i < m_vertices.size(); i++) {
data.push_back(m_vertices[i].x);
data.push_back(m_vertices[i].y);
data.push_back(m_vertices[i].z);
if (bColor) {
data.push_back(m_colors[i].r);
data.push_back(m_colors[i].g);
data.push_back(m_colors[i].b);
data.push_back(m_colors[i].a);
}
if (bNormals) {
data.push_back(m_normals[i].x);
data.push_back(m_normals[i].y);
data.push_back(m_normals[i].z);
}
if (bTexCoords) {
data.push_back(m_texCoords[i].x);
data.push_back(m_texCoords[i].y);
}
if (bTangents) {
data.push_back(m_tangents[i].x);
data.push_back(m_tangents[i].y);
data.push_back(m_tangents[i].z);
data.push_back(m_tangents[i].w);
}
}
tmpMesh->addVertices((GLbyte*)data.data(), m_vertices.size());
if (!hasIndices()) {
if ( getDrawMode() == GL_LINES ) {
for (uint32_t i = 0; i < getVertices().size(); i++) {
addIndex(i);
}
}
else if ( getDrawMode() == GL_LINE_STRIP ) {
for (uint32_t i = 1; i < getVertices().size(); i++) {
addIndex(i-1);
addIndex(i);
}
}
}
tmpMesh->addIndices(m_indices.data(), m_indices.size());
return tmpMesh;
}
<commit_msg>dont' normaize float<commit_after>#include "mesh.h"
#include <iostream>
#include "gl/vertexLayout.h"
Mesh::Mesh():m_drawMode(GL_TRIANGLES) {
}
Mesh::Mesh(const Mesh &_mother):m_drawMode(_mother.getDrawMode()) {
add(_mother);
}
Mesh::~Mesh() {
}
void Mesh::setDrawMode(GLenum _drawMode) {
m_drawMode = _drawMode;
}
void Mesh::setColor(const glm::vec4 &_color) {
m_colors.clear();
for (uint32_t i = 0; i < m_vertices.size(); i++) {
m_colors.push_back(_color);
}
}
void Mesh::addColor(const glm::vec4 &_color) {
m_colors.push_back(_color);
}
void Mesh::addColors(const std::vector<glm::vec4> &_colors) {
m_colors.insert(m_colors.end(), _colors.begin(), _colors.end());
}
void Mesh::addVertex(const glm::vec3 &_point) {
m_vertices.push_back(_point);
}
void Mesh::addVertices(const std::vector<glm::vec3>& _verts) {
m_vertices.insert(m_vertices.end(),_verts.begin(),_verts.end());
}
void Mesh::addVertices(const glm::vec3* verts, int amt) {
m_vertices.insert(m_vertices.end(),verts,verts+amt);
}
void Mesh::addNormal(const glm::vec3 &_normal) {
m_normals.push_back(_normal);
}
void Mesh::addNormals(const std::vector<glm::vec3> &_normals ) {
m_normals.insert(m_normals.end(), _normals.begin(), _normals.end());
}
void Mesh::addTangent(const glm::vec4 &_tangent) {
m_tangents.push_back(_tangent);
}
void Mesh::addTexCoord(const glm::vec2 &_uv) {
m_texCoords.push_back(_uv);
}
void Mesh::addTexCoords(const std::vector<glm::vec2> &_uvs) {
m_texCoords.insert(m_texCoords.end(), _uvs.begin(), _uvs.end());
}
void Mesh::addIndex(INDEX_TYPE _i) {
m_indices.push_back(_i);
}
void Mesh::addIndices(const std::vector<INDEX_TYPE>& inds) {
m_indices.insert(m_indices.end(),inds.begin(),inds.end());
}
void Mesh::addIndices(const INDEX_TYPE* inds, int amt) {
m_indices.insert(m_indices.end(),inds,inds+amt);
}
void Mesh::addTriangle(INDEX_TYPE index1, INDEX_TYPE index2, INDEX_TYPE index3) {
addIndex(index1);
addIndex(index2);
addIndex(index3);
}
void Mesh::add(const Mesh &_mesh) {
if (_mesh.getDrawMode() != m_drawMode) {
std::cout << "INCOMPATIBLE DRAW MODES" << std::endl;
return;
}
INDEX_TYPE indexOffset = (INDEX_TYPE)getVertices().size();
addColors(_mesh.getColors());
addVertices(_mesh.getVertices());
addNormals(_mesh.getNormals());
addTexCoords(_mesh.getTexCoords());
for (uint32_t i = 0; i < _mesh.getIndices().size(); i++) {
addIndex(indexOffset+_mesh.getIndices()[i]);
}
}
GLenum Mesh::getDrawMode() const{
return m_drawMode;
}
const std::vector<glm::vec4> & Mesh::getColors() const{
return m_colors;
}
const std::vector<glm::vec4> & Mesh::getTangents() const {
return m_tangents;
}
const std::vector<glm::vec3> & Mesh::getVertices() const{
return m_vertices;
}
const std::vector<glm::vec3> & Mesh::getNormals() const{
return m_normals;
}
const std::vector<glm::vec2> & Mesh::getTexCoords() const{
return m_texCoords;
}
const std::vector<INDEX_TYPE> & Mesh::getIndices() const{
return m_indices;
}
std::vector<glm::ivec3> Mesh::getTriangles() const {
std::vector<glm::ivec3> faces;
if (getDrawMode() == GL_TRIANGLES) {
if (hasIndices()) {
for(unsigned int j = 0; j < m_indices.size(); j += 3) {
glm::ivec3 tri;
for(int k = 0; k < 3; k++) {
tri[k] = m_indices[j+k];
}
faces.push_back(tri);
}
}
else {
for( unsigned int j = 0; j < m_vertices.size(); j += 3) {
glm::ivec3 tri;
for(int k = 0; k < 3; k++) {
tri[k] = j+k;
}
faces.push_back(tri);
}
}
}
else {
// TODO
//
std::cout << "ERROR: getTriangles(): Mesh only add GL_TRIANGLES for NOW !!" << std::endl;
}
return faces;
}
void Mesh::clear() {
if (!m_vertices.empty()) {
m_vertices.clear();
}
if (hasColors()) {
m_colors.clear();
}
if (hasNormals()) {
m_normals.clear();
}
if (hasTexCoords()) {
m_texCoords.clear();
}
if (hasTangents()) {
m_tangents.clear();
}
if (hasIndices()) {
m_indices.clear();
}
}
bool Mesh::computeNormals() {
if (getDrawMode() != GL_TRIANGLES)
return false;
//The number of the vertices
int nV = m_vertices.size();
//The number of the triangles
int nT = m_indices.size() / 3;
std::vector<glm::vec3> norm( nV ); //Array for the normals
//Scan all the triangles. For each triangle add its
//normal to norm's vectors of triangle's vertices
for (int t=0; t<nT; t++) {
//Get indices of the triangle t
int i1 = m_indices[ 3 * t ];
int i2 = m_indices[ 3 * t + 1 ];
int i3 = m_indices[ 3 * t + 2 ];
//Get vertices of the triangle
const glm::vec3 &v1 = m_vertices[ i1 ];
const glm::vec3 &v2 = m_vertices[ i2 ];
const glm::vec3 &v3 = m_vertices[ i3 ];
//Compute the triangle's normal
glm::vec3 dir = glm::normalize(glm::cross(v2-v1,v3-v1));
//Accumulate it to norm array for i1, i2, i3
norm[ i1 ] += dir;
norm[ i2 ] += dir;
norm[ i3 ] += dir;
}
//Normalize the normal's length and add it.
m_normals.clear();
for (int i=0; i<nV; i++) {
addNormal( glm::normalize(norm[i]) );
}
return true;
}
// http://www.terathon.com/code/tangent.html
bool Mesh::computeTangents() {
//The number of the vertices
size_t nV = m_vertices.size();
if (m_texCoords.size() != nV ||
m_normals.size() != nV ||
getDrawMode() != GL_TRIANGLES)
return false;
//The number of the triangles
size_t nT = m_indices.size() / 3;
std::vector<glm::vec3> tan1( nV );
std::vector<glm::vec3> tan2( nV );
//Scan all the triangles. For each triangle add its
//normal to norm's vectors of triangle's vertices
for (size_t t = 0; t < nT; t++) {
//Get indices of the triangle t
int i1 = m_indices[ 3 * t ];
int i2 = m_indices[ 3 * t + 1 ];
int i3 = m_indices[ 3 * t + 2 ];
//Get vertices of the triangle
const glm::vec3 &v1 = m_vertices[ i1 ];
const glm::vec3 &v2 = m_vertices[ i2 ];
const glm::vec3 &v3 = m_vertices[ i3 ];
const glm::vec2 &w1 = m_texCoords[i1];
const glm::vec2 &w2 = m_texCoords[i2];
const glm::vec2 &w3 = m_texCoords[i3];
float x1 = v2.x - v1.x;
float x2 = v3.x - v1.x;
float y1 = v2.y - v1.y;
float y2 = v3.y - v1.y;
float z1 = v2.z - v1.z;
float z2 = v3.z - v1.z;
float s1 = w2.x - w1.x;
float s2 = w3.x - w1.x;
float t1 = w2.y - w1.y;
float t2 = w3.y - w1.y;
float r = 1.0f / (s1 * t2 - s2 * t1);
glm::vec3 sdir( (t2 * x1 - t1 * x2) * r,
(t2 * y1 - t1 * y2) * r,
(t2 * z1 - t1 * z2) * r);
glm::vec3 tdir( (s1 * x2 - s2 * x1) * r,
(s1 * y2 - s2 * y1) * r,
(s1 * z2 - s2 * z1) * r);
tan1[i1] += sdir;
tan1[i2] += sdir;
tan1[i3] += sdir;
tan2[i1] += tdir;
tan2[i2] += tdir;
tan2[i3] += tdir;
}
//Normalize the normal's length and add it.
m_tangents.clear();
for (size_t i = 0; i < nV; i++) {
const glm::vec3 &n = m_normals[i];
const glm::vec3 &t = tan1[i];
// Gram-Schmidt orthogonalize
glm::vec3 tangent = t - n * glm::dot(n, t);
// Calculate handedness
float hardedness = (glm::dot( glm::cross(n, t), tan2[i]) < 0.0f) ? -1.0f : 1.0f;
addTangent(glm::vec4(tangent, hardedness));
}
return true;
}
Vbo* Mesh::getVbo() {
// Create Vertex Layout
//
std::vector<VertexAttrib> attribs;
attribs.push_back({"position", 3, GL_FLOAT, false, 0});
int nBits = 3;
bool bColor = false;
if (hasColors() && getColors().size() == m_vertices.size()) {
attribs.push_back({"color", 4, GL_FLOAT, false, 0});
bColor = true;
nBits += 4;
}
bool bNormals = false;
if (hasNormals() && getNormals().size() == m_vertices.size()) {
attribs.push_back({"normal", 3, GL_FLOAT, false, 0});
bNormals = true;
nBits += 3;
}
bool bTexCoords = false;
if (hasTexCoords() && getTexCoords().size() == m_vertices.size()) {
attribs.push_back({"texcoord", 2, GL_FLOAT, false, 0});
bTexCoords = true;
nBits += 2;
}
bool bTangents = false;
if (hasTangents() && getTangents().size() == m_vertices.size()) {
attribs.push_back({"tangent", 4, GL_FLOAT, false, 0});
bTangents = true;
nBits += 4;
}
VertexLayout* vertexLayout = new VertexLayout(attribs);
Vbo* tmpMesh = new Vbo(vertexLayout);
tmpMesh->setDrawMode(getDrawMode());
std::vector<GLfloat> data;
for (unsigned int i = 0; i < m_vertices.size(); i++) {
data.push_back(m_vertices[i].x);
data.push_back(m_vertices[i].y);
data.push_back(m_vertices[i].z);
if (bColor) {
data.push_back(m_colors[i].r);
data.push_back(m_colors[i].g);
data.push_back(m_colors[i].b);
data.push_back(m_colors[i].a);
}
if (bNormals) {
data.push_back(m_normals[i].x);
data.push_back(m_normals[i].y);
data.push_back(m_normals[i].z);
}
if (bTexCoords) {
data.push_back(m_texCoords[i].x);
data.push_back(m_texCoords[i].y);
}
if (bTangents) {
data.push_back(m_tangents[i].x);
data.push_back(m_tangents[i].y);
data.push_back(m_tangents[i].z);
data.push_back(m_tangents[i].w);
}
}
tmpMesh->addVertices((GLbyte*)data.data(), m_vertices.size());
if (!hasIndices()) {
if ( getDrawMode() == GL_LINES ) {
for (uint32_t i = 0; i < getVertices().size(); i++) {
addIndex(i);
}
}
else if ( getDrawMode() == GL_LINE_STRIP ) {
for (uint32_t i = 1; i < getVertices().size(); i++) {
addIndex(i-1);
addIndex(i);
}
}
}
tmpMesh->addIndices(m_indices.data(), m_indices.size());
return tmpMesh;
}
<|endoftext|> |
<commit_before>//
// EEPreferences.cpp
// ee-library
//
// Created by Zinge on 2/27/17.
//
//
#include "ee/cocos/EEPreferences.hpp"
#include <base/CCDirector.h>
#include <base/CCScheduler.h>
#include <platform/CCFileUtils.h>
#include <json/document.h>
#include <json/stringbuffer.h>
#include <json/writer.h>
#include "ee/cocos/EEDataHandler.hpp"
namespace ee {
namespace {
void writeData(const DataStorage& data, const std::string& filePath) {
auto fileUtils = cocos2d::FileUtils::getInstance();
rapidjson::Document document;
document.SetObject();
for (auto&& elt : data) {
document.AddMember(rapidjson::StringRef(elt.first.c_str()),
rapidjson::StringRef(elt.second.c_str()),
document.GetAllocator());
}
rapidjson::StringBuffer buffer;
buffer.Clear();
rapidjson::Writer<rapidjson::StringBuffer> writer(buffer);
document.Accept(writer);
fileUtils->writeStringToFile(buffer.GetString(), filePath);
}
DataStorage readData(const std::string& filePath) {
auto fileUtils = cocos2d::FileUtils::getInstance();
auto content = fileUtils->getStringFromFile(filePath);
DataStorage data;
if (not content.empty()) {
rapidjson::Document document;
document.Parse(content.c_str());
if (not document.HasParseError()) {
for (auto iter = document.MemberBegin();
iter != document.MemberEnd(); ++iter) {
data[iter->name.GetString()] = iter->value.GetString();
}
}
}
return data;
}
} // namespace
void Preferences::initializeWithFilename(const std::string& filename) {
if (isInitialized_) {
return;
}
handler_ = std::make_unique<ee::DataHandler>(0);
handler_->setCallback(
std::bind(&Self::onSaving, this, std::placeholders::_1,
std::placeholders::_2, std::placeholders::_3));
handler_->setCallback(
std::bind(&Self::onLoading, this, std::placeholders::_1,
std::placeholders::_2, std::placeholders::_3));
handler_->setCallback(
[](int dataId, const std::string& key) { CC_ASSERT(false); });
filePath_ = cocos2d::FileUtils::getInstance()->getWritablePath() + filename;
persistedData_ = readData(filePath_);
isInitialized_ = true;
}
Preferences::Preferences() {
cocos2d::Director::getInstance()->getScheduler()->schedule(
std::bind(&Self::updateData, this), this, 0.0f, CC_REPEAT_FOREVER, 0.0f,
false, "update__");
}
Preferences::~Preferences() {
cocos2d::Director::getInstance()->getScheduler()->unschedule("update__",
this);
}
std::string Preferences::encrypt(const std::string& value) const {
return encrypt("", value);
}
std::string Preferences::encrypt(const std::string& key,
const std::string& value) const {
auto hash = calculateHash(key + value);
return value + "_" + hash;
}
bool Preferences::decrypt(const std::string& encryptedValue,
std::string& result) const {
return decrypt(encryptedValue, "", result);
}
bool Preferences::decrypt(const std::string& encryptedValue,
const std::string& key, std::string& result) const {
auto dashIndex = encryptedValue.rfind('_');
if (dashIndex == std::string::npos) {
return false;
}
auto storedHash = encryptedValue.substr(dashIndex + 1);
auto storedValue = encryptedValue.substr(0, dashIndex);
auto expectedHash = calculateHash(key + storedValue);
if (storedHash != expectedHash) {
return false;
}
result = storedValue;
return true;
}
void Preferences::save(const std::string& key, const std::string& value,
Encryption mode) {
if (mode == Encryption::Value) {
return save(key, encrypt(value), Encryption::None);
}
if (mode == Encryption::KeyValue) {
return save(key, encrypt(key, value), Encryption::None);
}
dirtyData_[key] = value;
}
bool Preferences::load(const std::string& key, std::string& value,
Encryption mode) {
if (mode == Encryption::Value || mode == Encryption::KeyValue) {
if (not load(key, value, Encryption::None)) {
return false;
}
std::string decryptedValue;
if (mode == Encryption::Value && decrypt(value, decryptedValue)) {
value = decryptedValue;
return true;
}
if (mode == Encryption::KeyValue &&
decrypt(value, key, decryptedValue)) {
value = decryptedValue;
return true;
}
return false;
}
if (dirtyData_.count(key) > 0) {
value = dirtyData_[key];
return true;
}
if (persistedData_.count(key) > 0) {
value = persistedData_[key];
return true;
}
return false;
}
void Preferences::forceLoadData() {
merge();
auto data = readData(filePath_);
merge(data);
writeData(persistedData_, filePath_);
}
void Preferences::updateData() {
if (merge()) {
writeData(persistedData_, filePath_);
}
}
bool Preferences::merge() {
return merge(dirtyData_);
}
bool Preferences::merge(DataStorage& data) {
if (data.empty()) {
return false;
}
for (auto&& iter : data) {
persistedData_[iter.first] = iter.second;
}
data.clear();
return true;
}
} // namespace ee
<commit_msg>Replace rapidjson with nlohmann json (cocos plugin).<commit_after>//
// EEPreferences.cpp
// ee-library
//
// Created by Zinge on 2/27/17.
//
//
#include "ee/cocos/EEPreferences.hpp"
#include <ee/nlohmann/json.hpp>
#include <base/CCDirector.h>
#include <base/CCScheduler.h>
#include <platform/CCFileUtils.h>
#include "ee/cocos/EEDataHandler.hpp"
namespace ee {
namespace {
void writeData(const DataStorage& data, const std::string& filePath) {
auto fileUtils = cocos2d::FileUtils::getInstance();
nlohmann::json document;
for (auto&& elt : data) {
document[elt.first] = elt.second;
}
fileUtils->writeStringToFile(document.dump(), filePath);
}
DataStorage readData(const std::string& filePath) {
auto fileUtils = cocos2d::FileUtils::getInstance();
auto content = fileUtils->getStringFromFile(filePath);
DataStorage data;
if (not content.empty()) {
try {
auto document = nlohmann::json::parse(content);
for (auto&& iter : document.items()) {
data[iter.key()] = iter.value();
}
} catch (const std::exception& ex) {
}
}
return data;
}
} // namespace
void Preferences::initializeWithFilename(const std::string& filename) {
if (isInitialized_) {
return;
}
handler_ = std::make_unique<ee::DataHandler>(0);
handler_->setCallback(
std::bind(&Self::onSaving, this, std::placeholders::_1,
std::placeholders::_2, std::placeholders::_3));
handler_->setCallback(
std::bind(&Self::onLoading, this, std::placeholders::_1,
std::placeholders::_2, std::placeholders::_3));
handler_->setCallback(
[](int dataId, const std::string& key) { CC_ASSERT(false); });
filePath_ = cocos2d::FileUtils::getInstance()->getWritablePath() + filename;
persistedData_ = readData(filePath_);
isInitialized_ = true;
}
Preferences::Preferences() {
cocos2d::Director::getInstance()->getScheduler()->schedule(
std::bind(&Self::updateData, this), this, 0.0f, CC_REPEAT_FOREVER, 0.0f,
false, "update__");
}
Preferences::~Preferences() {
cocos2d::Director::getInstance()->getScheduler()->unschedule("update__",
this);
}
std::string Preferences::encrypt(const std::string& value) const {
return encrypt("", value);
}
std::string Preferences::encrypt(const std::string& key,
const std::string& value) const {
auto hash = calculateHash(key + value);
return value + "_" + hash;
}
bool Preferences::decrypt(const std::string& encryptedValue,
std::string& result) const {
return decrypt(encryptedValue, "", result);
}
bool Preferences::decrypt(const std::string& encryptedValue,
const std::string& key, std::string& result) const {
auto dashIndex = encryptedValue.rfind('_');
if (dashIndex == std::string::npos) {
return false;
}
auto storedHash = encryptedValue.substr(dashIndex + 1);
auto storedValue = encryptedValue.substr(0, dashIndex);
auto expectedHash = calculateHash(key + storedValue);
if (storedHash != expectedHash) {
return false;
}
result = storedValue;
return true;
}
void Preferences::save(const std::string& key, const std::string& value,
Encryption mode) {
if (mode == Encryption::Value) {
return save(key, encrypt(value), Encryption::None);
}
if (mode == Encryption::KeyValue) {
return save(key, encrypt(key, value), Encryption::None);
}
dirtyData_[key] = value;
}
bool Preferences::load(const std::string& key, std::string& value,
Encryption mode) {
if (mode == Encryption::Value || mode == Encryption::KeyValue) {
if (not load(key, value, Encryption::None)) {
return false;
}
std::string decryptedValue;
if (mode == Encryption::Value && decrypt(value, decryptedValue)) {
value = decryptedValue;
return true;
}
if (mode == Encryption::KeyValue &&
decrypt(value, key, decryptedValue)) {
value = decryptedValue;
return true;
}
return false;
}
if (dirtyData_.count(key) > 0) {
value = dirtyData_[key];
return true;
}
if (persistedData_.count(key) > 0) {
value = persistedData_[key];
return true;
}
return false;
}
void Preferences::forceLoadData() {
merge();
auto data = readData(filePath_);
merge(data);
writeData(persistedData_, filePath_);
}
void Preferences::updateData() {
if (merge()) {
writeData(persistedData_, filePath_);
}
}
bool Preferences::merge() {
return merge(dirtyData_);
}
bool Preferences::merge(DataStorage& data) {
if (data.empty()) {
return false;
}
for (auto&& iter : data) {
persistedData_[iter.first] = iter.second;
}
data.clear();
return true;
}
} // namespace ee
<|endoftext|> |
<commit_before>/*
* Adapted from the Willow Garage pose_graph package by Paul Furgale on October 22, 2010.
*
* Original file:
* Copyright (c) 2008, Willow Garage, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the Willow Garage, Inc. nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
*/
#ifndef SM_ID_HPP
#define SM_ID_HPP
#include <boost/cstdint.hpp>
#include <iostream>
// The definition of std::tr1::hash
#ifdef _WIN32
#include <functional>
#else
#include <tr1/functional>
#endif
#include <boost/serialization/nvp.hpp>
namespace sm {
typedef boost::uint64_t id_type;
///
/// \class Id
/// \brief superclass for stronly-typed uint64 ids
///
/// Usage:
/// \code
/// // MyId is a stronly typed Id for my object.
/// class MyId : public Id
/// {
/// public:
///
/// explicit MyId (id_type id = -1) : Id(id) {}
///
/// template<class Archive>
/// void serialize(Archive & ar, const unsigned int version)
/// {
/// ar & id_;
/// }
/// };
/// \endcode
///
class Id
{
public:
explicit Id (id_type id) : id_(id) {}
/// Only for stl use
Id () : id_(-1) {}
friend std::ostream& operator<< (std::ostream& str, const Id& n)
{
str << n.id_;
return str;
}
bool operator== (const Id& other) const
{
return other.id_ == id_;
}
bool operator!= (const Id& other) const
{
return other.id_ != id_;
}
bool operator< (const Id& other) const
{
return id_ < other.id_;
}
id_type getId () const
{
return id_;
}
// postincrement.
void operator++ (int unused)
{
id_++;
}
// preincrement
Id & operator++ ()
{
++id_;
return (*this);
}
Id& operator= (const Id& other)
{
id_ = other.id_;
return *this;
}
bool isSet() const
{
return id_ != id_type(-1);
}
id_type value() const
{
return id_;
}
protected:
id_type id_;
};
} // namespace aslam
#define SM_DEFINE_ID(IdTypeName) \
class IdTypeName : public sm::Id \
{ \
public: \
explicit IdTypeName (sm::id_type id = -1) : sm::Id(id) {} \
\
template<class Archive> \
void serialize(Archive & ar, const unsigned int version) \
{ \
ar & BOOST_SERIALIZATION_NVP(id_); \
} \
};
#ifdef _WIN32
// If you need to use the ID in a tr1 hashing container,
// use this macro outside of any namespace:
// SM_DEFINE_ID_HASH(my_namespace::myIdType);
#define SM_DEFINE_ID_HASH(FullyQualifiedIdTypeName) \
namespace std { \
template<> \
struct hash<FullyQualifiedIdTypeName> \
{ \
hash<boost::uint64_t> _hash; \
size_t operator()(const FullyQualifiedIdTypeName & id) \
{ \
return _hash(id.getId()); \
} \
}; \
} // namespace std
#else
// If you need to use the ID in a tr1 hashing container,
// use this macro outside of any namespace:
// SM_DEFINE_ID_HASH(my_namespace::myIdType);
#define SM_DEFINE_ID_HASH(FullyQualifiedIdTypeName) \
namespace std { namespace tr1 { \
template<> \
struct hash<FullyQualifiedIdTypeName> \
{ \
hash<boost::uint64_t> _hash; \
size_t operator()(const FullyQualifiedIdTypeName & id) \
{ \
return _hash(id.getId()); \
} \
}; \
}} // namespace std::tr1
#endif
#endif /* SM_ID_HPP */
<commit_msg>Fixed a bug in the id postincrement'<commit_after>/*
* Adapted from the Willow Garage pose_graph package by Paul Furgale on October 22, 2010.
*
* Original file:
* Copyright (c) 2008, Willow Garage, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the Willow Garage, Inc. nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
*/
#ifndef SM_ID_HPP
#define SM_ID_HPP
#include <boost/cstdint.hpp>
#include <iostream>
// The definition of std::tr1::hash
#ifdef _WIN32
#include <functional>
#else
#include <tr1/functional>
#endif
#include <boost/serialization/nvp.hpp>
namespace sm {
typedef boost::uint64_t id_type;
///
/// \class Id
/// \brief superclass for stronly-typed uint64 ids
///
/// Usage:
/// \code
/// // MyId is a stronly typed Id for my object.
/// class MyId : public Id
/// {
/// public:
///
/// explicit MyId (id_type id = -1) : Id(id) {}
///
/// template<class Archive>
/// void serialize(Archive & ar, const unsigned int version)
/// {
/// ar & id_;
/// }
/// };
/// \endcode
///
class Id
{
public:
explicit Id (id_type id) : id_(id) {}
/// Only for stl use
Id () : id_(-1) {}
friend std::ostream& operator<< (std::ostream& str, const Id& n)
{
str << n.id_;
return str;
}
bool operator== (const Id& other) const
{
return other.id_ == id_;
}
bool operator!= (const Id& other) const
{
return other.id_ != id_;
}
bool operator< (const Id& other) const
{
return id_ < other.id_;
}
id_type getId () const
{
return id_;
}
// postincrement.
Id operator++ (int unused)
{
Id rval(id_);
++id_;
return rval;
}
// preincrement
Id & operator++ ()
{
++id_;
return (*this);
}
Id& operator= (const Id& other)
{
id_ = other.id_;
return *this;
}
bool isSet() const
{
return id_ != id_type(-1);
}
id_type value() const
{
return id_;
}
protected:
id_type id_;
};
} // namespace aslam
#define SM_DEFINE_ID(IdTypeName) \
class IdTypeName : public sm::Id \
{ \
public: \
explicit IdTypeName (sm::id_type id = -1) : sm::Id(id) {} \
IdTypeName(const sm::Id & id) : sm::Id(id){} \
template<class Archive> \
void serialize(Archive & ar, const unsigned int version) \
{ \
ar & BOOST_SERIALIZATION_NVP(id_); \
} \
};
#ifdef _WIN32
// If you need to use the ID in a tr1 hashing container,
// use this macro outside of any namespace:
// SM_DEFINE_ID_HASH(my_namespace::myIdType);
#define SM_DEFINE_ID_HASH(FullyQualifiedIdTypeName) \
namespace std { \
template<> \
struct hash<FullyQualifiedIdTypeName> \
{ \
hash<boost::uint64_t> _hash; \
size_t operator()(const FullyQualifiedIdTypeName & id) \
{ \
return _hash(id.getId()); \
} \
}; \
} // namespace std
#else
// If you need to use the ID in a tr1 hashing container,
// use this macro outside of any namespace:
// SM_DEFINE_ID_HASH(my_namespace::myIdType);
#define SM_DEFINE_ID_HASH(FullyQualifiedIdTypeName) \
namespace std { namespace tr1 { \
template<> \
struct hash<FullyQualifiedIdTypeName> \
{ \
hash<boost::uint64_t> _hash; \
size_t operator()(const FullyQualifiedIdTypeName & id) \
{ \
return _hash(id.getId()); \
} \
}; \
}} // namespace std::tr1
#endif
#endif /* SM_ID_HPP */
<|endoftext|> |
<commit_before>/*
* This file is open source software, licensed to you under the terms
* of the Apache License, Version 2.0 (the "License"). See the NOTICE file
* distributed with this work for additional information regarding copyright
* ownership. You may not use this file except in compliance with the License.
*
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
/*
* Copyright (C) 2019 ScyllaDB Ltd.
*/
#include <iostream>
#ifndef SEASTAR_COROUTINES_ENABLED
int main(int argc, char** argv) {
std::cout << "coroutines not available\n";
return 0;
}
#else
#include <seastar/core/app-template.hh>
#include <seastar/core/coroutine.hh>
#include <seastar/core/fstream.hh>
#include <seastar/core/sleep.hh>
#include <seastar/core/seastar.hh>
int main(int argc, char** argv) {
seastar::app_template app;
app.run(argc, argv, [] () -> seastar::future<> {
std::cout << "this is a completely useless program\nplease stand by...\n";
auto f = seastar::parallel_for_each(std::vector<int> { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }, [] (int i) -> seastar::future<> {
co_await seastar::sleep(std::chrono::seconds(i));
std::cout << i << "\n";
});
auto file = co_await seastar::open_file_dma("useless_file.txt", seastar::open_flags::create | seastar::open_flags::wo);
auto out = co_await seastar::make_file_output_stream(file);
seastar::sstring str = "nothing to see here, move along now\n";
co_await out.write(str);
co_await out.flush();
co_await out.close();
co_await std::move(f);
std::cout << "done\n";
});
}
#endif
<commit_msg>demos: coroutines: include std-compat.hh<commit_after>/*
* This file is open source software, licensed to you under the terms
* of the Apache License, Version 2.0 (the "License"). See the NOTICE file
* distributed with this work for additional information regarding copyright
* ownership. You may not use this file except in compliance with the License.
*
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
/*
* Copyright (C) 2019 ScyllaDB Ltd.
*/
#include <iostream>
#include <seastar/util/std-compat.hh>
#ifndef SEASTAR_COROUTINES_ENABLED
int main(int argc, char** argv) {
std::cout << "coroutines not available\n";
return 0;
}
#else
#include <seastar/core/app-template.hh>
#include <seastar/core/coroutine.hh>
#include <seastar/core/fstream.hh>
#include <seastar/core/sleep.hh>
#include <seastar/core/seastar.hh>
int main(int argc, char** argv) {
seastar::app_template app;
app.run(argc, argv, [] () -> seastar::future<> {
std::cout << "this is a completely useless program\nplease stand by...\n";
auto f = seastar::parallel_for_each(std::vector<int> { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }, [] (int i) -> seastar::future<> {
co_await seastar::sleep(std::chrono::seconds(i));
std::cout << i << "\n";
});
auto file = co_await seastar::open_file_dma("useless_file.txt", seastar::open_flags::create | seastar::open_flags::wo);
auto out = co_await seastar::make_file_output_stream(file);
seastar::sstring str = "nothing to see here, move along now\n";
co_await out.write(str);
co_await out.flush();
co_await out.close();
co_await std::move(f);
std::cout << "done\n";
});
}
#endif
<|endoftext|> |
<commit_before>/*
* Author: Henry Bruce <[email protected]>
* Copyright (c) 2015 Intel Corporation.
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice 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 <unistd.h>
#include <iostream>
#include "max44009.h"
#include "si1132.h"
#define EDISON_I2C_BUS 1
#define FT4222_I2C_BUS 0
//! [Interesting]
// Simple example of using ILightSensor to determine
// which sensor is present and return its name.
// ILightSensor is then used to get readings from sensor
upm::ILightSensor* getLightSensor()
{
upm::ILightSensor* lightSensor = NULL;
try {
lightSensor = new upm::SI1132(mraa_get_sub_platform_id(FT4222_I2C_BUS));
return lightSensor;
} catch (std::exception& e) {
std::cerr << "SI1132: " << e.what() << std::endl;
}
try {
lightSensor = new upm::SI1132(mraa_get_sub_platform_id(FT4222_I2C_BUS + 1));
return lightSensor;
} catch (std::exception& e) {
std::cerr << "SI1132: " << e.what() << std::endl;
}
try {
lightSensor = new upm::MAX44009(EDISON_I2C_BUS);
return lightSensor;
} catch (std::exception& e) {
std::cerr << "MAX44009: " << e.what() << std::endl;
}
return lightSensor;
}
int main ()
{
upm::ILightSensor* lightSensor = getLightSensor();
if (lightSensor == NULL) {
std::cout << "Light sensor not detected" << std::endl;
return 1;
}
std::cout << "Light sensor " << lightSensor->getModuleName() << " detected" << std::endl;
while (true) {
try {
float value = lightSensor->getVisibleLux();
std::cout << "Light level = " << value << " lux" << std::endl;
} catch (std::exception& e) {
std::cerr << e.what() << std::endl;
}
sleep(1);
}
delete lightSensor;
return 0;
}
//! [Interesting]<commit_msg>examples/c++: light-sensor now catches CTRL+C and exits polling loop.<commit_after>/*
* Author: Henry Bruce <[email protected]>
* Copyright (c) 2015 Intel Corporation.
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice 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 <unistd.h>
#include <signal.h>
#include <iostream>
#include "max44009.h"
#include "si1132.h"
#define EDISON_I2C_BUS 1
#define FT4222_I2C_BUS 0
//! [Interesting]
// Simple example of using ILightSensor to determine
// which sensor is present and return its name.
// ILightSensor is then used to get readings from sensor
bool shouldRun = true;
void signalHandler(int signo)
{
if (signo == SIGINT)
shouldRun = false;
}
upm::ILightSensor* getLightSensor()
{
upm::ILightSensor* lightSensor = NULL;
try {
lightSensor = new upm::SI1132(mraa_get_sub_platform_id(FT4222_I2C_BUS));
return lightSensor;
} catch (std::exception& e) {
std::cerr << "SI1132: " << e.what() << std::endl;
}
try {
lightSensor = new upm::SI1132(mraa_get_sub_platform_id(FT4222_I2C_BUS + 1));
return lightSensor;
} catch (std::exception& e) {
std::cerr << "SI1132: " << e.what() << std::endl;
}
try {
lightSensor = new upm::MAX44009(EDISON_I2C_BUS);
return lightSensor;
} catch (std::exception& e) {
std::cerr << "MAX44009: " << e.what() << std::endl;
}
return lightSensor;
}
int main ()
{
upm::ILightSensor* lightSensor = getLightSensor();
if (lightSensor == NULL) {
std::cout << "Light sensor not detected" << std::endl;
return 1;
}
std::cout << "Light sensor " << lightSensor->getModuleName() << " detected" << std::endl;
signal(SIGINT, signalHandler);
while (shouldRun) {
try {
float value = lightSensor->getVisibleLux();
std::cout << "Light level = " << value << " lux" << std::endl;
} catch (std::exception& e) {
std::cerr << e.what() << std::endl;
}
sleep(1);
}
delete lightSensor;
return 0;
}
//! [Interesting]<|endoftext|> |
<commit_before>
#include "BSPLoad.h"
#include <fstream>
bool BSPLoad::Load(const std::string& filename, int curveTesselation)
{
std::ifstream file(filename.c_str(),std::ios::binary);
if(!file.is_open())
{
//errorLog.OutputError("Unable to open %s", filename);
return false;
}
//read in header
file.read((char*)&m_header, sizeof(BSP_HEADER));
//check header data is correct
if( m_header.m_string[0]!='I' || m_header.m_string[1]!='B' ||
m_header.m_string[2]!='S' || m_header.m_string[3]!='P' ||
m_header.m_version !=0x2E )
{
//errorLog.OutputError("%s is not a version 0x2E .bsp map file", filename);
return false;
}
//Load in vertices
LoadVertices(file);
//Load in mesh indices
//Calculate number of indices
int numMeshIndices=m_header.m_directoryEntries[bspMeshIndices].m_length/sizeof(int);
//Create space
m_loadMeshIndices.resize(numMeshIndices);
//read in the mesh indices
file.seekg(m_header.m_directoryEntries[bspMeshIndices].m_offset,std::ios::beg);
file.read((char*) &m_loadMeshIndices[0], m_header.m_directoryEntries[bspMeshIndices].m_length);
//Load in faces
LoadFaces(file, curveTesselation);
//Load textures
LoadTextures(file);
//Load Lightmaps
LoadLightmaps(file);
//Load BSP Data
LoadBSPData(file);
//Load in entity string
m_entityString.resize(m_header.m_directoryEntries[bspEntities].m_length);
//Go to entity string in file
file.seekg(m_header.m_directoryEntries[bspEntities].m_offset,std::ios::beg);
file.read(&m_entityString[0], m_header.m_directoryEntries[bspEntities].m_length);
//errorLog.OutputSuccess("%s Loaded successfully", filename);
return true;
}
void BSPLoad::LoadVertices(std::ifstream& aFile)
{
//calculate number of vertices
int num_vertices=m_header.m_directoryEntries[bspVertices].m_length/sizeof(BSP_LOAD_VERTEX);
//Create space for this many BSP_LOAD_VERTICES
m_loadVertices.resize(num_vertices);
//go to vertices in file
aFile.seekg(m_header.m_directoryEntries[bspVertices].m_offset,std::ios::beg);
//read in the vertices
aFile.read((char*)&m_loadVertices[0], m_header.m_directoryEntries[bspVertices].m_length);
}
void BSPLoad::LoadFaces(std::ifstream& aFile, int curveTesselation)
{
//calculate number of load faces
int numTotalFaces=m_header.m_directoryEntries[bspFaces].m_length/sizeof(BSP_LOAD_FACE);
//Create space for this many BSP_LOAD_FACES
m_loadFaces.resize(numTotalFaces);
//go to faces in file
aFile.seekg(m_header.m_directoryEntries[bspFaces].m_offset,std::ios::beg);
//read in the faces
aFile.read((char*)&m_loadFaces[0], m_header.m_directoryEntries[bspFaces].m_length);
}
void BSPLoad::LoadTextures(std::ifstream& aFile)
{
//Calculate number of textures
int num_textures=m_header.m_directoryEntries[bspTextures].m_length/sizeof(BSP_LOAD_TEXTURE);
//Create space for this many BSP_LOAD_TEXTUREs
m_loadTextures.resize(num_textures);
//Load textures
aFile.seekg(m_header.m_directoryEntries[bspTextures].m_offset,std::ios::beg);
aFile.read((char*)&m_loadTextures[0], m_header.m_directoryEntries[bspTextures].m_length);
}
void BSPLoad::LoadLightmaps(std::ifstream& aFile)
{
//Calculate number of lightmaps
int num_lightmaps=m_header.m_directoryEntries[bspLightmaps].m_length/sizeof(BSP_LOAD_LIGHTMAP);
//Create space for this many BSP_LOAD_LIGHTMAPs
m_loadLightmaps.resize(num_lightmaps);
//Load textures
aFile.seekg(m_header.m_directoryEntries[bspLightmaps].m_offset,std::ios::beg);
aFile.read((char*)&m_loadLightmaps[0], m_header.m_directoryEntries[bspLightmaps].m_length);
//Change the gamma settings on the lightmaps (make them brighter)
float gamma=2.5f;
for(int i=0; i<num_lightmaps; ++i)
{
for(int j=0; j<128*128; ++j)
{
float r, g, b;
r=m_loadLightmaps[i].m_lightmapData[j*3+0];
g=m_loadLightmaps[i].m_lightmapData[j*3+1];
b=m_loadLightmaps[i].m_lightmapData[j*3+2];
r*=gamma/255.0f;
g*=gamma/255.0f;
b*=gamma/255.0f;
//find the value to scale back up
float scale=1.0f;
float temp;
if(r > 1.0f && (temp = (1.0f/r)) < scale) scale=temp;
if(g > 1.0f && (temp = (1.0f/g)) < scale) scale=temp;
if(b > 1.0f && (temp = (1.0f/b)) < scale) scale=temp;
// scale up color values
scale*=255.0f;
r*=scale;
g*=scale;
b*=scale;
//fill data back in
m_loadLightmaps[i].m_lightmapData[j*3+0]=(unsigned char)r;
m_loadLightmaps[i].m_lightmapData[j*3+1]=(unsigned char)g;
m_loadLightmaps[i].m_lightmapData[j*3+2]=(unsigned char)b;
//m_loadLightmaps[i].m_lightmapData[j*3+0]=(GLubyte)255;
//m_loadLightmaps[i].m_lightmapData[j*3+1]=(GLubyte)255;
//m_loadLightmaps[i].m_lightmapData[j*3+2]=(GLubyte)255;
}
}
}
void BSPLoad::LoadBSPData(std::ifstream& aFile)
{
//Load leaves
//Calculate number of leaves
int numLeaves=m_header.m_directoryEntries[bspLeaves].m_length/sizeof(BSP_LOAD_LEAF);
//Create space for this many BSP_LOAD_LEAFS
m_loadLeaves.resize(numLeaves);
//Load leaves
aFile.seekg(m_header.m_directoryEntries[bspLeaves].m_offset,std::ios::beg);
aFile.read((char*)&m_loadLeaves[0], m_header.m_directoryEntries[bspLeaves].m_length);
//Load leaf faces array
int num_leaf_faces=m_header.m_directoryEntries[bspLeafFaces].m_length/sizeof(int);
//Create space for this many leaf faces
m_loadLeafFaces.resize(num_leaf_faces);
//Load leaf faces
aFile.seekg(m_header.m_directoryEntries[bspLeafFaces].m_offset,std::ios::beg);
aFile.read((char*)&m_loadLeafFaces[0], m_header.m_directoryEntries[bspLeafFaces].m_length);
//Load Planes
int num_planes=m_header.m_directoryEntries[bspPlanes].m_length/sizeof(BSP_LoadPlane);
//Create space for this many planes
m_loadPlanes.resize(num_planes);
aFile.seekg(m_header.m_directoryEntries[bspPlanes].m_offset,std::ios::beg);
aFile.read((char*)&m_loadPlanes[0], m_header.m_directoryEntries[bspPlanes].m_length);
//Load nodes
int num_nodes=m_header.m_directoryEntries[bspNodes].m_length/sizeof(BSP_NODE);
//Create space for this many nodes
m_loadNodes.resize(num_nodes);
aFile.seekg(m_header.m_directoryEntries[bspNodes].m_offset,std::ios::beg);
aFile.read((char*)&m_loadNodes[0], m_header.m_directoryEntries[bspNodes].m_length);
//Load visibility data
//load numClusters and bytesPerCluster
aFile.seekg(m_header.m_directoryEntries[bspVisData].m_offset,std::ios::beg);
aFile.read((char*)&m_loadVisibilityData, 2 * sizeof(int));
//Calculate the size of the bitset
int bitsetSize=m_loadVisibilityData.m_numClusters*m_loadVisibilityData.m_bytesPerCluster;
//Create space for bitset
m_loadVisibilityData.m_bitset.resize(bitsetSize);
//read bitset
aFile.read((char*)&m_loadVisibilityData.m_bitset[0], bitsetSize);
}
<commit_msg>Warning fix.<commit_after>
#include "BSPLoad.h"
#include <fstream>
bool BSPLoad::Load(const std::string& filename, int curveTesselation)
{
std::ifstream file(filename.c_str(),std::ios::binary);
if(!file.is_open())
{
//errorLog.OutputError("Unable to open %s", filename);
return false;
}
//read in header
file.read((char*)&m_header, sizeof(BSP_HEADER));
//check header data is correct
if( m_header.m_string[0]!='I' || m_header.m_string[1]!='B' ||
m_header.m_string[2]!='S' || m_header.m_string[3]!='P' ||
m_header.m_version !=0x2E )
{
//errorLog.OutputError("%s is not a version 0x2E .bsp map file", filename);
return false;
}
//Load in vertices
LoadVertices(file);
//Load in mesh indices
//Calculate number of indices
int numMeshIndices=m_header.m_directoryEntries[bspMeshIndices].m_length/sizeof(int);
//Create space
m_loadMeshIndices.resize(numMeshIndices);
//read in the mesh indices
file.seekg(m_header.m_directoryEntries[bspMeshIndices].m_offset,std::ios::beg);
file.read((char*) &m_loadMeshIndices[0], m_header.m_directoryEntries[bspMeshIndices].m_length);
//Load in faces
LoadFaces(file, curveTesselation);
//Load textures
LoadTextures(file);
//Load Lightmaps
LoadLightmaps(file);
//Load BSP Data
LoadBSPData(file);
//Load in entity string
m_entityString.resize(m_header.m_directoryEntries[bspEntities].m_length);
//Go to entity string in file
file.seekg(m_header.m_directoryEntries[bspEntities].m_offset,std::ios::beg);
file.read(&m_entityString[0], m_header.m_directoryEntries[bspEntities].m_length);
//errorLog.OutputSuccess("%s Loaded successfully", filename);
return true;
}
void BSPLoad::LoadVertices(std::ifstream& aFile)
{
//calculate number of vertices
int num_vertices=m_header.m_directoryEntries[bspVertices].m_length/sizeof(BSP_LOAD_VERTEX);
//Create space for this many BSP_LOAD_VERTICES
m_loadVertices.resize(num_vertices);
//go to vertices in file
aFile.seekg(m_header.m_directoryEntries[bspVertices].m_offset,std::ios::beg);
//read in the vertices
aFile.read((char*)&m_loadVertices[0], m_header.m_directoryEntries[bspVertices].m_length);
}
void BSPLoad::LoadFaces(std::ifstream& aFile, int /*curveTesselation*/)
{
//calculate number of load faces
int numTotalFaces=m_header.m_directoryEntries[bspFaces].m_length/sizeof(BSP_LOAD_FACE);
//Create space for this many BSP_LOAD_FACES
m_loadFaces.resize(numTotalFaces);
//go to faces in file
aFile.seekg(m_header.m_directoryEntries[bspFaces].m_offset,std::ios::beg);
//read in the faces
aFile.read((char*)&m_loadFaces[0], m_header.m_directoryEntries[bspFaces].m_length);
}
void BSPLoad::LoadTextures(std::ifstream& aFile)
{
//Calculate number of textures
int num_textures=m_header.m_directoryEntries[bspTextures].m_length/sizeof(BSP_LOAD_TEXTURE);
//Create space for this many BSP_LOAD_TEXTUREs
m_loadTextures.resize(num_textures);
//Load textures
aFile.seekg(m_header.m_directoryEntries[bspTextures].m_offset,std::ios::beg);
aFile.read((char*)&m_loadTextures[0], m_header.m_directoryEntries[bspTextures].m_length);
}
void BSPLoad::LoadLightmaps(std::ifstream& aFile)
{
//Calculate number of lightmaps
int num_lightmaps=m_header.m_directoryEntries[bspLightmaps].m_length/sizeof(BSP_LOAD_LIGHTMAP);
//Create space for this many BSP_LOAD_LIGHTMAPs
m_loadLightmaps.resize(num_lightmaps);
//Load textures
aFile.seekg(m_header.m_directoryEntries[bspLightmaps].m_offset,std::ios::beg);
aFile.read((char*)&m_loadLightmaps[0], m_header.m_directoryEntries[bspLightmaps].m_length);
//Change the gamma settings on the lightmaps (make them brighter)
float gamma=2.5f;
for(int i=0; i<num_lightmaps; ++i)
{
for(int j=0; j<128*128; ++j)
{
float r, g, b;
r=m_loadLightmaps[i].m_lightmapData[j*3+0];
g=m_loadLightmaps[i].m_lightmapData[j*3+1];
b=m_loadLightmaps[i].m_lightmapData[j*3+2];
r*=gamma/255.0f;
g*=gamma/255.0f;
b*=gamma/255.0f;
//find the value to scale back up
float scale=1.0f;
float temp;
if(r > 1.0f && (temp = (1.0f/r)) < scale) scale=temp;
if(g > 1.0f && (temp = (1.0f/g)) < scale) scale=temp;
if(b > 1.0f && (temp = (1.0f/b)) < scale) scale=temp;
// scale up color values
scale*=255.0f;
r*=scale;
g*=scale;
b*=scale;
//fill data back in
m_loadLightmaps[i].m_lightmapData[j*3+0]=(unsigned char)r;
m_loadLightmaps[i].m_lightmapData[j*3+1]=(unsigned char)g;
m_loadLightmaps[i].m_lightmapData[j*3+2]=(unsigned char)b;
//m_loadLightmaps[i].m_lightmapData[j*3+0]=(GLubyte)255;
//m_loadLightmaps[i].m_lightmapData[j*3+1]=(GLubyte)255;
//m_loadLightmaps[i].m_lightmapData[j*3+2]=(GLubyte)255;
}
}
}
void BSPLoad::LoadBSPData(std::ifstream& aFile)
{
//Load leaves
//Calculate number of leaves
int numLeaves=m_header.m_directoryEntries[bspLeaves].m_length/sizeof(BSP_LOAD_LEAF);
//Create space for this many BSP_LOAD_LEAFS
m_loadLeaves.resize(numLeaves);
//Load leaves
aFile.seekg(m_header.m_directoryEntries[bspLeaves].m_offset,std::ios::beg);
aFile.read((char*)&m_loadLeaves[0], m_header.m_directoryEntries[bspLeaves].m_length);
//Load leaf faces array
int num_leaf_faces=m_header.m_directoryEntries[bspLeafFaces].m_length/sizeof(int);
//Create space for this many leaf faces
m_loadLeafFaces.resize(num_leaf_faces);
//Load leaf faces
aFile.seekg(m_header.m_directoryEntries[bspLeafFaces].m_offset,std::ios::beg);
aFile.read((char*)&m_loadLeafFaces[0], m_header.m_directoryEntries[bspLeafFaces].m_length);
//Load Planes
int num_planes=m_header.m_directoryEntries[bspPlanes].m_length/sizeof(BSP_LoadPlane);
//Create space for this many planes
m_loadPlanes.resize(num_planes);
aFile.seekg(m_header.m_directoryEntries[bspPlanes].m_offset,std::ios::beg);
aFile.read((char*)&m_loadPlanes[0], m_header.m_directoryEntries[bspPlanes].m_length);
//Load nodes
int num_nodes=m_header.m_directoryEntries[bspNodes].m_length/sizeof(BSP_NODE);
//Create space for this many nodes
m_loadNodes.resize(num_nodes);
aFile.seekg(m_header.m_directoryEntries[bspNodes].m_offset,std::ios::beg);
aFile.read((char*)&m_loadNodes[0], m_header.m_directoryEntries[bspNodes].m_length);
//Load visibility data
//load numClusters and bytesPerCluster
aFile.seekg(m_header.m_directoryEntries[bspVisData].m_offset,std::ios::beg);
aFile.read((char*)&m_loadVisibilityData, 2 * sizeof(int));
//Calculate the size of the bitset
int bitsetSize=m_loadVisibilityData.m_numClusters*m_loadVisibilityData.m_bytesPerCluster;
//Create space for bitset
m_loadVisibilityData.m_bitset.resize(bitsetSize);
//read bitset
aFile.read((char*)&m_loadVisibilityData.m_bitset[0], bitsetSize);
}
<|endoftext|> |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.