text
stringlengths 54
60.6k
|
---|
<commit_before>/*
* Copyright (C) 2012 The Android Open Source Project
*
* 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 "compiler_llvm.h"
#include "class_linker.h"
#include "compilation_unit.h"
#include "compiler.h"
#include "dex_cache.h"
#include "ir_builder.h"
#include "jni_compiler.h"
#include "method_compiler.h"
#include "oat_compilation_unit.h"
#include "stl_util.h"
#include "upcall_compiler.h"
#include <llvm/LinkAllPasses.h>
#include <llvm/LinkAllVMCore.h>
#include <llvm/Support/CommandLine.h>
#include <llvm/Support/ManagedStatic.h>
#include <llvm/Support/TargetSelect.h>
#include <llvm/Support/Threading.h>
namespace llvm {
extern bool TimePassesIsEnabled;
}
extern llvm::cl::opt<bool> EnableARMLongCalls;
// NOTE: Although EnableARMLongCalls is defined in llvm/lib/Target/ARM/
// ARMISelLowering.cpp, however, it is not in the llvm namespace.
namespace {
pthread_once_t llvm_initialized = PTHREAD_ONCE_INIT;
void InitializeLLVM() {
// NOTE: Uncomment following line to show the time consumption of LLVM passes
//llvm::TimePassesIsEnabled = true;
// Initialize LLVM target, MC subsystem, asm printer, and asm parser
llvm::InitializeAllTargets();
llvm::InitializeAllTargetMCs();
llvm::InitializeAllAsmPrinters();
llvm::InitializeAllAsmParsers();
// TODO: Maybe we don't have to initialize "all" targets.
// Enable -arm-long-calls
EnableARMLongCalls = true;
// Initialize LLVM optimization passes
llvm::PassRegistry ®istry = *llvm::PassRegistry::getPassRegistry();
llvm::initializeCore(registry);
llvm::initializeScalarOpts(registry);
llvm::initializeIPO(registry);
llvm::initializeAnalysis(registry);
llvm::initializeIPA(registry);
llvm::initializeTransformUtils(registry);
llvm::initializeInstCombine(registry);
llvm::initializeInstrumentation(registry);
llvm::initializeTarget(registry);
// Initialize LLVM internal data structure for multithreading
llvm::llvm_start_multithreaded();
}
// Singleton. Otherwise, multiple CompilerLLVM instances may cause crashes if
// one shuts down prematurely.
llvm::llvm_shutdown_obj llvm_guard;
} // anonymous namespace
namespace art {
namespace compiler_llvm {
llvm::Module* makeLLVMModuleContents(llvm::Module* module);
CompilerLLVM::CompilerLLVM(Compiler* compiler, InstructionSet insn_set)
: compiler_(compiler), compiler_lock_("llvm_compiler_lock"),
insn_set_(insn_set), curr_cunit_(NULL) {
// Initialize LLVM libraries
pthread_once(&llvm_initialized, InitializeLLVM);
}
CompilerLLVM::~CompilerLLVM() {
STLDeleteElements(&cunits_);
}
void CompilerLLVM::EnsureCompilationUnit() {
compiler_lock_.AssertHeld();
if (curr_cunit_ != NULL) {
return;
}
// Allocate compilation unit
size_t cunit_idx = cunits_.size();
curr_cunit_ = new CompilationUnit(insn_set_);
// Setup output filename
curr_cunit_->SetElfFileName(
StringPrintf("%s-%zu", elf_filename_.c_str(), cunit_idx));
if (IsBitcodeFileNameAvailable()) {
curr_cunit_->SetBitcodeFileName(
StringPrintf("%s-%zu", bitcode_filename_.c_str(), cunit_idx));
}
// Register compilation unit
cunits_.push_back(curr_cunit_);
}
void CompilerLLVM::MaterializeRemainder() {
MutexLock GUARD(compiler_lock_);
if (curr_cunit_ != NULL) {
Materialize();
}
}
void CompilerLLVM::MaterializeIfThresholdReached() {
MutexLock GUARD(compiler_lock_);
if (curr_cunit_ != NULL && curr_cunit_->IsMaterializeThresholdReached()) {
Materialize();
}
}
void CompilerLLVM::Materialize() {
compiler_lock_.AssertHeld();
DCHECK(curr_cunit_ != NULL);
DCHECK(!curr_cunit_->IsMaterialized());
// Write bitcode to file when filename is set
if (IsBitcodeFileNameAvailable()) {
curr_cunit_->WriteBitcodeToFile();
}
// Materialize the llvm::Module into ELF object file
curr_cunit_->Materialize();
// Delete the compilation unit
curr_cunit_ = NULL;
}
CompiledMethod* CompilerLLVM::
CompileDexMethod(OatCompilationUnit* oat_compilation_unit) {
MutexLock GUARD(compiler_lock_);
EnsureCompilationUnit();
UniquePtr<MethodCompiler> method_compiler(
new MethodCompiler(curr_cunit_, compiler_, oat_compilation_unit));
return method_compiler->Compile();
}
CompiledMethod* CompilerLLVM::
CompileNativeMethod(OatCompilationUnit* oat_compilation_unit) {
MutexLock GUARD(compiler_lock_);
EnsureCompilationUnit();
UniquePtr<JniCompiler> jni_compiler(
new JniCompiler(curr_cunit_, *compiler_, oat_compilation_unit));
return jni_compiler->Compile();
}
CompiledInvokeStub* CompilerLLVM::CreateInvokeStub(bool is_static,
char const *shorty) {
MutexLock GUARD(compiler_lock_);
EnsureCompilationUnit();
UniquePtr<UpcallCompiler> upcall_compiler(
new UpcallCompiler(curr_cunit_, *compiler_));
return upcall_compiler->CreateStub(is_static, shorty);
}
CompilerLLVM* EnsureCompilerLLVM(art::Compiler& compiler) {
if (compiler.GetCompilerContext() == NULL) {
compiler.SetCompilerContext(new CompilerLLVM(&compiler, compiler.GetInstructionSet()));
}
CompilerLLVM* compiler_llvm = reinterpret_cast<CompilerLLVM*>(compiler.GetCompilerContext());
compiler_llvm->SetElfFileName(compiler.GetElfFileName());
compiler_llvm->SetBitcodeFileName(compiler.GetBitcodeFileName());
return compiler_llvm;
}
} // namespace compiler_llvm
} // namespace art
extern "C" art::CompiledMethod* ArtCompileMethod(art::Compiler& compiler,
const art::DexFile::CodeItem* code_item,
uint32_t access_flags, uint32_t method_idx,
const art::ClassLoader* class_loader,
const art::DexFile& dex_file)
{
art::ClassLinker *class_linker = art::Runtime::Current()->GetClassLinker();
art::DexCache *dex_cache = class_linker->FindDexCache(dex_file);
art::OatCompilationUnit oat_compilation_unit(
class_loader, class_linker, dex_file, *dex_cache, code_item,
method_idx, access_flags);
return art::compiler_llvm::EnsureCompilerLLVM(compiler)->CompileDexMethod(&oat_compilation_unit);
}
extern "C" art::CompiledMethod* ArtJniCompileMethod(art::Compiler& compiler,
uint32_t access_flags, uint32_t method_idx,
const art::ClassLoader* class_loader,
const art::DexFile& dex_file) {
art::ClassLinker *class_linker = art::Runtime::Current()->GetClassLinker();
art::DexCache *dex_cache = class_linker->FindDexCache(dex_file);
art::OatCompilationUnit oat_compilation_unit(
class_loader, class_linker, dex_file, *dex_cache, NULL,
method_idx, access_flags);
art::compiler_llvm::CompilerLLVM* compiler_llvm = art::compiler_llvm::EnsureCompilerLLVM(compiler);
art::CompiledMethod* result = compiler_llvm->CompileNativeMethod(&oat_compilation_unit);
compiler_llvm->MaterializeIfThresholdReached();
return result;
}
extern "C" art::CompiledInvokeStub* ArtCreateInvokeStub(art::Compiler& compiler, bool is_static,
const char* shorty, uint32_t shorty_len) {
return art::compiler_llvm::EnsureCompilerLLVM(compiler)->CreateInvokeStub(is_static, shorty);
}
extern "C" void compilerLLVMMaterializeRemainder(art::Compiler& compiler) {
art::compiler_llvm::EnsureCompilerLLVM(compiler)->MaterializeRemainder();
}
// Note: Using this function carefully!!! This is temporary solution, we will remove it.
extern "C" art::MutexLock* compilerLLVMMutexLock(art::Compiler& compiler) {
return new art::MutexLock(art::compiler_llvm::EnsureCompilerLLVM(compiler)->compiler_lock_);
}
extern "C" void compilerLLVMDispose(art::Compiler& compiler) {
delete art::compiler_llvm::EnsureCompilerLLVM(compiler);
}
<commit_msg>Workaround on SEGV of LLVM backend.<commit_after>/*
* Copyright (C) 2012 The Android Open Source Project
*
* 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 "compiler_llvm.h"
#include "class_linker.h"
#include "compilation_unit.h"
#include "compiler.h"
#include "dex_cache.h"
#include "ir_builder.h"
#include "jni_compiler.h"
#include "method_compiler.h"
#include "oat_compilation_unit.h"
#include "stl_util.h"
#include "upcall_compiler.h"
#include <llvm/LinkAllPasses.h>
#include <llvm/LinkAllVMCore.h>
#include <llvm/Support/CommandLine.h>
#include <llvm/Support/ManagedStatic.h>
#include <llvm/Support/TargetSelect.h>
#include <llvm/Support/Threading.h>
namespace llvm {
extern bool TimePassesIsEnabled;
}
extern llvm::cl::opt<bool> EnableARMLongCalls;
// NOTE: Although EnableARMLongCalls is defined in llvm/lib/Target/ARM/
// ARMISelLowering.cpp, however, it is not in the llvm namespace.
namespace {
pthread_once_t llvm_initialized = PTHREAD_ONCE_INIT;
void InitializeLLVM() {
// NOTE: Uncomment following line to show the time consumption of LLVM passes
//llvm::TimePassesIsEnabled = true;
// Initialize LLVM target, MC subsystem, asm printer, and asm parser
llvm::InitializeAllTargets();
llvm::InitializeAllTargetMCs();
llvm::InitializeAllAsmPrinters();
llvm::InitializeAllAsmParsers();
// TODO: Maybe we don't have to initialize "all" targets.
// Enable -arm-long-calls
EnableARMLongCalls = true;
// Initialize LLVM optimization passes
llvm::PassRegistry ®istry = *llvm::PassRegistry::getPassRegistry();
llvm::initializeCore(registry);
llvm::initializeScalarOpts(registry);
llvm::initializeIPO(registry);
llvm::initializeAnalysis(registry);
llvm::initializeIPA(registry);
llvm::initializeTransformUtils(registry);
llvm::initializeInstCombine(registry);
llvm::initializeInstrumentation(registry);
llvm::initializeTarget(registry);
// Initialize LLVM internal data structure for multithreading
llvm::llvm_start_multithreaded();
}
// The Guard to Shutdown LLVM
//llvm::llvm_shutdown_obj llvm_guard;
// TODO: We are commenting this line because this will cause SEGV. This may
// related to two possible reasons: (1) the order of the destruction of static
// objects, and (2) dlopen/dlclose side-effect on static objects.
} // anonymous namespace
namespace art {
namespace compiler_llvm {
llvm::Module* makeLLVMModuleContents(llvm::Module* module);
CompilerLLVM::CompilerLLVM(Compiler* compiler, InstructionSet insn_set)
: compiler_(compiler), compiler_lock_("llvm_compiler_lock"),
insn_set_(insn_set), curr_cunit_(NULL) {
// Initialize LLVM libraries
pthread_once(&llvm_initialized, InitializeLLVM);
}
CompilerLLVM::~CompilerLLVM() {
STLDeleteElements(&cunits_);
}
void CompilerLLVM::EnsureCompilationUnit() {
compiler_lock_.AssertHeld();
if (curr_cunit_ != NULL) {
return;
}
// Allocate compilation unit
size_t cunit_idx = cunits_.size();
curr_cunit_ = new CompilationUnit(insn_set_);
// Setup output filename
curr_cunit_->SetElfFileName(
StringPrintf("%s-%zu", elf_filename_.c_str(), cunit_idx));
if (IsBitcodeFileNameAvailable()) {
curr_cunit_->SetBitcodeFileName(
StringPrintf("%s-%zu", bitcode_filename_.c_str(), cunit_idx));
}
// Register compilation unit
cunits_.push_back(curr_cunit_);
}
void CompilerLLVM::MaterializeRemainder() {
MutexLock GUARD(compiler_lock_);
if (curr_cunit_ != NULL) {
Materialize();
}
}
void CompilerLLVM::MaterializeIfThresholdReached() {
MutexLock GUARD(compiler_lock_);
if (curr_cunit_ != NULL && curr_cunit_->IsMaterializeThresholdReached()) {
Materialize();
}
}
void CompilerLLVM::Materialize() {
compiler_lock_.AssertHeld();
DCHECK(curr_cunit_ != NULL);
DCHECK(!curr_cunit_->IsMaterialized());
// Write bitcode to file when filename is set
if (IsBitcodeFileNameAvailable()) {
curr_cunit_->WriteBitcodeToFile();
}
// Materialize the llvm::Module into ELF object file
curr_cunit_->Materialize();
// Delete the compilation unit
curr_cunit_ = NULL;
}
CompiledMethod* CompilerLLVM::
CompileDexMethod(OatCompilationUnit* oat_compilation_unit) {
MutexLock GUARD(compiler_lock_);
EnsureCompilationUnit();
UniquePtr<MethodCompiler> method_compiler(
new MethodCompiler(curr_cunit_, compiler_, oat_compilation_unit));
return method_compiler->Compile();
}
CompiledMethod* CompilerLLVM::
CompileNativeMethod(OatCompilationUnit* oat_compilation_unit) {
MutexLock GUARD(compiler_lock_);
EnsureCompilationUnit();
UniquePtr<JniCompiler> jni_compiler(
new JniCompiler(curr_cunit_, *compiler_, oat_compilation_unit));
return jni_compiler->Compile();
}
CompiledInvokeStub* CompilerLLVM::CreateInvokeStub(bool is_static,
char const *shorty) {
MutexLock GUARD(compiler_lock_);
EnsureCompilationUnit();
UniquePtr<UpcallCompiler> upcall_compiler(
new UpcallCompiler(curr_cunit_, *compiler_));
return upcall_compiler->CreateStub(is_static, shorty);
}
CompilerLLVM* EnsureCompilerLLVM(art::Compiler& compiler) {
if (compiler.GetCompilerContext() == NULL) {
compiler.SetCompilerContext(new CompilerLLVM(&compiler, compiler.GetInstructionSet()));
}
CompilerLLVM* compiler_llvm = reinterpret_cast<CompilerLLVM*>(compiler.GetCompilerContext());
compiler_llvm->SetElfFileName(compiler.GetElfFileName());
compiler_llvm->SetBitcodeFileName(compiler.GetBitcodeFileName());
return compiler_llvm;
}
} // namespace compiler_llvm
} // namespace art
extern "C" art::CompiledMethod* ArtCompileMethod(art::Compiler& compiler,
const art::DexFile::CodeItem* code_item,
uint32_t access_flags, uint32_t method_idx,
const art::ClassLoader* class_loader,
const art::DexFile& dex_file)
{
art::ClassLinker *class_linker = art::Runtime::Current()->GetClassLinker();
art::DexCache *dex_cache = class_linker->FindDexCache(dex_file);
art::OatCompilationUnit oat_compilation_unit(
class_loader, class_linker, dex_file, *dex_cache, code_item,
method_idx, access_flags);
return art::compiler_llvm::EnsureCompilerLLVM(compiler)->CompileDexMethod(&oat_compilation_unit);
}
extern "C" art::CompiledMethod* ArtJniCompileMethod(art::Compiler& compiler,
uint32_t access_flags, uint32_t method_idx,
const art::ClassLoader* class_loader,
const art::DexFile& dex_file) {
art::ClassLinker *class_linker = art::Runtime::Current()->GetClassLinker();
art::DexCache *dex_cache = class_linker->FindDexCache(dex_file);
art::OatCompilationUnit oat_compilation_unit(
class_loader, class_linker, dex_file, *dex_cache, NULL,
method_idx, access_flags);
art::compiler_llvm::CompilerLLVM* compiler_llvm = art::compiler_llvm::EnsureCompilerLLVM(compiler);
art::CompiledMethod* result = compiler_llvm->CompileNativeMethod(&oat_compilation_unit);
compiler_llvm->MaterializeIfThresholdReached();
return result;
}
extern "C" art::CompiledInvokeStub* ArtCreateInvokeStub(art::Compiler& compiler, bool is_static,
const char* shorty, uint32_t shorty_len) {
return art::compiler_llvm::EnsureCompilerLLVM(compiler)->CreateInvokeStub(is_static, shorty);
}
extern "C" void compilerLLVMMaterializeRemainder(art::Compiler& compiler) {
art::compiler_llvm::EnsureCompilerLLVM(compiler)->MaterializeRemainder();
}
// Note: Using this function carefully!!! This is temporary solution, we will remove it.
extern "C" art::MutexLock* compilerLLVMMutexLock(art::Compiler& compiler) {
return new art::MutexLock(art::compiler_llvm::EnsureCompilerLLVM(compiler)->compiler_lock_);
}
extern "C" void compilerLLVMDispose(art::Compiler& compiler) {
delete art::compiler_llvm::EnsureCompilerLLVM(compiler);
}
<|endoftext|>
|
<commit_before>/* Copyright (c) 2013 https://github.com/Naftoreiclag/
*
* Distributed under the MIT License (http://opensource.org/licenses/mit-license.html)
* See accompanying file LICENSE
*/
#include "util/Sysout.h"
#include "Game.h"
void initialize()
{
// Set the display width to 80 chars long (for word-wrap)
Sysout::setDisplayWidth(80);
// If we are in debug mode, then print that
#ifdef DEBUG
Sysout::println("Running in DEBUG mode!");
Sysout::printDictionaryEntries();
#endif
}
void run()
{
bool running = true;
while(running)
{
// Put a title screen here
// Run a game
Game* game = new Game();
game->load();
game->run();
delete game;
}
}
void finalize()
{
}
int main()
{
// Initialize
initialize();
// Run
run()
// Clean-up
finalize();
// Died quietly
return 0;
}
<commit_msg>Added missing semicolon<commit_after>/* Copyright (c) 2013 https://github.com/Naftoreiclag/
*
* Distributed under the MIT License (http://opensource.org/licenses/mit-license.html)
* See accompanying file LICENSE
*/
#include "util/Sysout.h"
#include "Game.h"
// Initialize
void initialize()
{
// Set the display width to 80 chars long (for word-wrap)
Sysout::setDisplayWidth(80);
// If we are in debug mode, then print that
#ifdef DEBUG
Sysout::println("Running in DEBUG mode!");
Sysout::printDictionaryEntries();
#endif
}
// Run
void run()
{
bool running = true;
while(running)
{
// Put a title screen here
// Run a game
Game* game = new Game();
game->load();
game->run();
delete game;
}
}
// Finalize
void finalize()
{
}
int main()
{
// Initialize
initialize();
// Run
run();
// Clean-up
finalize();
// Died quietly
return 0;
}
<|endoftext|>
|
<commit_before>//
// LineRenderer.cpp
//
#include "LineRenderer.h"
using namespace pockets;
using namespace cinder;
namespace {
using Vertex = LineRenderer::Vertex;
const auto VertexLayout = ([] {
geom::BufferLayout layout;
layout.append(geom::Attrib::POSITION, 3, sizeof(Vertex), offsetof(Vertex, position));
layout.append(geom::Attrib::COLOR, 4, sizeof(Vertex), offsetof(Vertex, color));
layout.append(geom::Attrib::CUSTOM_0, 3, sizeof(Vertex), offsetof(Vertex, previous));
layout.append(geom::Attrib::CUSTOM_1, 3, sizeof(Vertex), offsetof(Vertex, next));
layout.append(geom::Attrib::CUSTOM_2, 1, sizeof(Vertex), offsetof(Vertex, offset));
layout.append(geom::Attrib::CUSTOM_3, 1, sizeof(Vertex), offsetof(Vertex, mitered));
return layout;
}());
const auto VertexMapping = gl::Batch::AttributeMapping{ { geom::Attrib::POSITION, "ciPosition" },
{ geom::Attrib::COLOR, "ciColor" },
{ geom::Attrib::CUSTOM_0, "Previous" },
{ geom::Attrib::CUSTOM_1, "Next" },
{ geom::Attrib::CUSTOM_2, "EdgeOffset" },
{ geom::Attrib::CUSTOM_3, "Miter" } };
const auto VertexShader = R"vs(
#version 330 core
uniform mat4 ciModelViewProjection;
uniform float AspectRatio;
in vec3 ciPosition;
in vec4 ciColor;
in vec3 Previous;
in vec3 Next;
in float EdgeOffset;
in int Miter;
out Vertex {
vec4 Color;
} v;
void main() {
vec2 aspectVector = vec2(AspectRatio, 1.0);
vec4 previousPoint = ciModelViewProjection * vec4(Previous, 1.0);
vec4 currentPoint = ciModelViewProjection * vec4(ciPosition, 1.0);
vec4 nextPoint = ciModelViewProjection * vec4(Next, 1.0);
vec2 currentScreen = aspectVector * currentPoint.xy / currentPoint.w;
vec2 previousScreen = aspectVector * previousPoint.xy / previousPoint.w;
vec2 nextScreen = aspectVector * nextPoint.xy / nextPoint.w;
float len = EdgeOffset;
vec2 dir = vec2(0.0);
if (currentScreen == previousScreen) {
dir = normalize(nextScreen - currentScreen);
}
else if (currentScreen == nextScreen) {
dir = normalize(currentScreen - previousScreen);
}
else {
vec2 ab = normalize(currentScreen - previousScreen);
if (Miter == 1) {
vec2 bc = normalize(nextScreen - currentScreen);
vec2 tangent = normalize(ab + bc);
vec2 normal = vec2(-ab.y, ab.x);
vec2 miter = vec2(-tangent.y, tangent.x);
dir = tangent;
len = EdgeOffset / clamp(dot(miter, normal), 0.0, 1.0);
}
else {
dir = ab;
}
}
vec2 normal = vec2(-dir.y, dir.x);
normal *= len;
normal.x /= AspectRatio;
vec4 offset = vec4(normal, 0.0, 0.0);
gl_Position = currentPoint + offset;
v.Color = ciColor;
}
)vs";
const auto FragmentShader = R"fs(
#version 330 core
out vec4 fColor;
in Vertex {
vec4 Color;
} v;
void main() {
fColor = v.Color;
}
)fs";
} // namespace
LineRenderer::LineRenderer()
{
auto points = std::vector<Vertex>(2 * 10 * 1000);
auto indices = std::vector<uint16_t>(points.size() * 6);
_vertex_buffer = gl::Vbo::create(GL_ARRAY_BUFFER, points, GL_STREAM_DRAW);
_index_buffer = gl::Vbo::create(GL_ELEMENT_ARRAY_BUFFER, indices, GL_STREAM_DRAW);
auto mesh = gl::VboMesh::create(points.size(), GL_TRIANGLES, { { VertexLayout, _vertex_buffer } }, indices.size(), GL_UNSIGNED_INT, _index_buffer);
auto format = gl::GlslProg::Format().vertex(VertexShader).fragment(FragmentShader);
auto shader = gl::GlslProg::create(format);
_batch = gl::Batch::create(mesh, shader, VertexMapping);
}
void LineRenderer::clear()
{
_indices.clear();
_vertices.clear();
_needs_buffering = true;
}
void LineRenderer::addLine(const std::vector<ci::vec3> &positions, float width, const ColorA &frontColor, const ColorA &backColor, bool mitered)
{
// add indices
const auto index_offset = _vertices.size();
for (auto i = 0; i < (positions.size() - 1); i += 1) {
auto index = index_offset + i * 2;
_indices.push_back(index + 0);
_indices.push_back(index + 1);
_indices.push_back(index + 2);
_indices.push_back(index + 2);
_indices.push_back(index + 1);
_indices.push_back(index + 3);
}
// add positions
const auto previous = [&positions](int index) {
return positions[glm::clamp(index - 1, 0, index)];
};
const auto next = [&positions, high = positions.size() - 1](int index)
{
return positions[glm::clamp<int>(index + 1, 0, high)];
};
const auto color = [frontColor, backColor, end = positions.size()](int index)
{
return lerp(frontColor, backColor, (float)index / end);
};
auto mitered_int = mitered ? 1 : 0;
auto half_width = width / 2.0f;
for (auto i = 0; i < positions.size(); i += 1) {
_vertices.push_back(Vertex{ positions[i], previous(i), next(i), color(i), half_width, mitered_int });
_vertices.push_back(Vertex{ positions[i], previous(i), next(i), color(i), -half_width, mitered_int });
}
_needs_buffering = true;
}
void LineRenderer::bufferData()
{
if (_needs_buffering)
{
const auto vb = sizeof(Vertex) * _vertices.size();
_vertex_buffer->ensureMinimumSize(vb);
_vertex_buffer->bufferSubData(0, vb, _vertices.data());
const auto ib = sizeof(uint32_t) * _indices.size();
_index_buffer->ensureMinimumSize(ib);
_index_buffer->bufferSubData(0, ib, _indices.data());
_needs_buffering = false;
}
}
void LineRenderer::draw()
{
bufferData();
auto dims = vec2(gl::getViewport().second);
_batch->getGlslProg()->uniform("AspectRatio", dims.x / dims.y);
_batch->draw(0, _indices.size());
}
<commit_msg>Don't allow divide-by-zero.<commit_after>//
// LineRenderer.cpp
//
#include "LineRenderer.h"
using namespace pockets;
using namespace cinder;
namespace {
using Vertex = LineRenderer::Vertex;
const auto VertexLayout = ([] {
geom::BufferLayout layout;
layout.append(geom::Attrib::POSITION, 3, sizeof(Vertex), offsetof(Vertex, position));
layout.append(geom::Attrib::COLOR, 4, sizeof(Vertex), offsetof(Vertex, color));
layout.append(geom::Attrib::CUSTOM_0, 3, sizeof(Vertex), offsetof(Vertex, previous));
layout.append(geom::Attrib::CUSTOM_1, 3, sizeof(Vertex), offsetof(Vertex, next));
layout.append(geom::Attrib::CUSTOM_2, 1, sizeof(Vertex), offsetof(Vertex, offset));
layout.append(geom::Attrib::CUSTOM_3, 1, sizeof(Vertex), offsetof(Vertex, mitered));
return layout;
}());
const auto VertexMapping = gl::Batch::AttributeMapping{ { geom::Attrib::POSITION, "ciPosition" },
{ geom::Attrib::COLOR, "ciColor" },
{ geom::Attrib::CUSTOM_0, "Previous" },
{ geom::Attrib::CUSTOM_1, "Next" },
{ geom::Attrib::CUSTOM_2, "EdgeOffset" },
{ geom::Attrib::CUSTOM_3, "Miter" } };
const auto VertexShader = R"vs(
#version 330 core
uniform mat4 ciModelViewProjection;
uniform float AspectRatio;
in vec3 ciPosition;
in vec4 ciColor;
in vec3 Previous;
in vec3 Next;
in float EdgeOffset;
in int Miter;
out Vertex {
vec4 Color;
} v;
void main() {
vec2 aspectVector = vec2(AspectRatio, 1.0);
vec4 previousPoint = ciModelViewProjection * vec4(Previous, 1.0);
vec4 currentPoint = ciModelViewProjection * vec4(ciPosition, 1.0);
vec4 nextPoint = ciModelViewProjection * vec4(Next, 1.0);
vec2 currentScreen = aspectVector * currentPoint.xy / currentPoint.w;
vec2 previousScreen = aspectVector * previousPoint.xy / previousPoint.w;
vec2 nextScreen = aspectVector * nextPoint.xy / nextPoint.w;
float len = EdgeOffset;
vec2 dir = vec2(0.0);
if (currentScreen == previousScreen) {
dir = normalize(nextScreen - currentScreen);
}
else if (currentScreen == nextScreen) {
dir = normalize(currentScreen - previousScreen);
}
else {
vec2 ab = normalize(currentScreen - previousScreen);
if (Miter == 1) {
vec2 bc = normalize(nextScreen - currentScreen);
vec2 tangent = normalize(ab + bc);
vec2 normal = vec2(-ab.y, ab.x);
vec2 miter = vec2(-tangent.y, tangent.x);
dir = tangent;
len = EdgeOffset / clamp(dot(miter, normal), 0.1, 1.0);
}
else {
dir = ab;
}
}
vec2 normal = vec2(-dir.y, dir.x);
normal *= len;
normal.x /= AspectRatio;
vec4 offset = vec4(normal, 0.0, 0.0);
gl_Position = currentPoint + offset;
v.Color = ciColor;
}
)vs";
const auto FragmentShader = R"fs(
#version 330 core
out vec4 fColor;
in Vertex {
vec4 Color;
} v;
void main() {
fColor = v.Color;
}
)fs";
} // namespace
LineRenderer::LineRenderer()
{
auto points = std::vector<Vertex>(2 * 10 * 1000);
auto indices = std::vector<uint16_t>(points.size() * 6);
_vertex_buffer = gl::Vbo::create(GL_ARRAY_BUFFER, points, GL_STREAM_DRAW);
_index_buffer = gl::Vbo::create(GL_ELEMENT_ARRAY_BUFFER, indices, GL_STREAM_DRAW);
auto mesh = gl::VboMesh::create(points.size(), GL_TRIANGLES, { { VertexLayout, _vertex_buffer } }, indices.size(), GL_UNSIGNED_INT, _index_buffer);
auto format = gl::GlslProg::Format().vertex(VertexShader).fragment(FragmentShader);
auto shader = gl::GlslProg::create(format);
_batch = gl::Batch::create(mesh, shader, VertexMapping);
}
void LineRenderer::clear()
{
_indices.clear();
_vertices.clear();
_needs_buffering = true;
}
void LineRenderer::addLine(const std::vector<ci::vec3> &positions, float width, const ColorA &frontColor, const ColorA &backColor, bool mitered)
{
// add indices
const auto index_offset = _vertices.size();
for (auto i = 0; i < (positions.size() - 1); i += 1) {
auto index = index_offset + i * 2;
_indices.push_back(index + 0);
_indices.push_back(index + 1);
_indices.push_back(index + 2);
_indices.push_back(index + 2);
_indices.push_back(index + 1);
_indices.push_back(index + 3);
}
// add positions
const auto previous = [&positions](int index) {
return positions[glm::clamp(index - 1, 0, index)];
};
const auto next = [&positions, high = positions.size() - 1](int index)
{
return positions[glm::clamp<int>(index + 1, 0, high)];
};
const auto color = [frontColor, backColor, end = positions.size()](int index)
{
return lerp(frontColor, backColor, (float)index / end);
};
auto mitered_int = mitered ? 1 : 0;
auto half_width = width / 2.0f;
for (auto i = 0; i < positions.size(); i += 1) {
_vertices.push_back(Vertex{ positions[i], previous(i), next(i), color(i), half_width, mitered_int });
_vertices.push_back(Vertex{ positions[i], previous(i), next(i), color(i), -half_width, mitered_int });
}
_needs_buffering = true;
}
void LineRenderer::bufferData()
{
if (_needs_buffering)
{
const auto vb = sizeof(Vertex) * _vertices.size();
_vertex_buffer->ensureMinimumSize(vb);
_vertex_buffer->bufferSubData(0, vb, _vertices.data());
const auto ib = sizeof(uint32_t) * _indices.size();
_index_buffer->ensureMinimumSize(ib);
_index_buffer->bufferSubData(0, ib, _indices.data());
_needs_buffering = false;
}
}
void LineRenderer::draw()
{
bufferData();
auto dims = vec2(gl::getViewport().second);
_batch->getGlslProg()->uniform("AspectRatio", dims.x / dims.y);
_batch->draw(0, _indices.size());
}
<|endoftext|>
|
<commit_before>#include <common.h>
///////////////////////////////////////////////////////////////////////////////
#pragma region
typedef uint32_t CharEx;
namespace std {
template<>
class regex_traits<CharEx> : public _Regex_traits_base {
public:
typedef CharEx _Uelem;
typedef regex_traits<CharEx> _Myt;
typedef CharEx char_type;
typedef basic_string<CharEx> string_type;
typedef locale locale_type;
typedef typename string_type::size_type size_type;
static size_type length( const CharEx* str )
{
return string_type( str ).length();
}
regex_traits()
{
}
regex_traits( const regex_traits& _Right )
{
}
regex_traits& operator=( const regex_traits& _Right )
{
return ( *this );
}
CharEx translate( CharEx c ) const
{
return c;
}
CharEx translate_nocase( CharEx c ) const
{
return c;
}
template<class Iter>
string_type transform( Iter first, Iter last ) const
{
return string_type( first, last );
}
template<class Iter>
string_type transform_primary( Iter first, Iter last ) const
{
return string_type( first, last );
}
template<class Iter>
string_type lookup_collatename( Iter first, Iter last ) const
{
return string_type( first, last );
}
template<class Iter>
char_class_type lookup_classname( Iter /*first*/, Iter /*last*/,
bool /*case = false*/ ) const
{
return 0;
}
bool isctype( CharEx /*c*/, char_class_type /*type*/ ) const
{
return false;
}
int value( CharEx /*c*/, int /*base*/ ) const
{
throw logic_error( "regex_traits<CharEx>::value" );
return -1;
}
locale_type imbue( locale_type /*newLocale*/ )
{
return locale();
}
locale_type getloc() const
{
return locale();
}
};
}
class StringEx : public basic_string<CharEx> {
public:
StringEx()
{
}
StringEx( const string& str )
{
AppendString( str );
}
StringEx( const basic_string<CharEx>& str ) :
basic_string<CharEx>( str )
{
}
StringEx& operator=( const string& str )
{
clear();
AppendString( str );
return *this;
}
StringEx& operator=( const basic_string<CharEx>& str )
{
basic_string<CharEx>::operator=( str );
return *this;
}
void AppendString( const string& str )
{
reserve( length() + str.length() );
for( const char c : str ) {
push_back( static_cast<unsigned char>( c ) );
}
}
string ToString() const
{
string result;
result.reserve( length() );
for( const CharEx c : *this ) {
if( c < 128 ) {
result.push_back( c );
} else {
throw logic_error( "StringEx::ToString()" );
}
}
return result;
}
};
template<>
struct hash<StringEx> {
typedef StringEx argument_type;
typedef size_t result_type;
result_type operator()( argument_type const& str ) const
{
return hash<basic_string<CharEx>>{}( str );
}
};
typedef basic_regex<CharEx> RegexEx;
typedef match_results<StringEx::const_iterator> MatchResultsEx;
#pragma endregion
///////////////////////////////////////////////////////////////////////////////
//namespace Lspl {
//namespace Matching {
///////////////////////////////////////////////////////////////////////////////
typedef size_t TPatternElementIndex;
struct CWordValue {
static const CharEx ConformAny = static_cast<CharEx>( 128 );
static const StringEx::size_type ConformStartIndex = 1;
StringEx Value;
bool Match( const RegexEx& valueRegex ) const;
enum TConformity {
C_None,
C_Conform,
C_StrongConform
};
TConformity Conform( const CWordValue& other ) const;
};
bool CWordValue::Match( const RegexEx& valueRegex ) const
{
MatchResultsEx match;
return regex_match( Value, match, valueRegex );
}
CWordValue::TConformity CWordValue::Conform( const CWordValue& other ) const
{
debug_check_logic( Value.length() == other.Value.length() );
TConformity conformity = C_StrongConform;
for( auto i = ConformStartIndex; i < Value.length(); i++ ) {
const CharEx c1 = Value[i];
const CharEx c2 = other.Value[i];
if( c1 != c2 ) {
if( c1 == ConformAny || c2 == ConformAny ) {
conformity = C_Conform;
} else {
return C_None;
}
}
}
return conformity;
}
typedef vector<CWordValue> CWordValues;
typedef CWordValues::size_type TWordValueIndex;
class CWordValueIndices;
struct CWord {
string text;
StringEx word;
CWordValues values;
const CWordValues& Values() const
{
return values;
}
bool MatchWord( const RegexEx& wordRegex ) const;
bool MatchValues( const RegexEx& valueRegex,
CWordValueIndices& indices ) const;
};
bool CWord::MatchWord( const RegexEx& wordRegex ) const
{
MatchResultsEx match;
return regex_match( word, match, wordRegex );
}
typedef vector<CWord> CWords;
typedef CWords::size_type TWordIndex;
class CWordValueIndices {
public:
explicit CWordValueIndices( const TWordValueIndex count = 0 )
{
Reset( count );
}
void Reset( const TWordValueIndex count = 0 );
bool Filled() const
{
return !indices.empty();
}
void Add( const TWordValueIndex index );
CWordValueIndices Intersect( const CWordValueIndices& other );
private:
vector<TWordValueIndex> indices;
};
bool CWord::MatchValues( const RegexEx& valueRegex,
CWordValueIndices& indices ) const
{
indices.Reset();
for( TWordValueIndex index = 0; index < values.size(); index++ ) {
if( values[index].Match( valueRegex ) ) {
indices.Add( index );
}
}
return indices.Filled();
}
void CWordValueIndices::Reset( const TWordValueIndex count )
{
indices.clear();
indices.reserve( count );
for( TWordValueIndex i = 0; i < count; i++ ) {
indices.push_back( i );
}
}
void CWordValueIndices::Add( const TWordValueIndex index )
{
debug_check_logic( indices.empty() || indices.back() < index );
indices.push_back( index );
}
CWordValueIndices CWordValueIndices::Intersect(
const CWordValueIndices& other )
{
CWordValueIndices merged;
merge( indices.cbegin(), indices.cend(),
other.indices.cbegin(), other.indices.cend(),
back_inserter( merged.indices ) );
indices.swap( merged.indices );
return merged;
}
typedef pair<CWordValueIndices, CWordValueIndices> CArgreement;
typedef pair<TWordIndex, TWordIndex> CWordIndexPair;
template<>
struct hash<CWordIndexPair> {
typedef CWordIndexPair argument_type;
typedef size_t result_type;
result_type operator()( argument_type const& pair ) const
{
return ( ( hash<TWordIndex>{}( pair.first ) << 16 )
^ hash<TWordIndex>{}( pair.second ) );
}
};
class CWordArgreementsCache {
public:
CWordArgreementsCache( const CWords& text ) :
words( text )
{
}
const CArgreement& Agreement( const CWordIndexPair key,
const bool strong ) const;
private:
const CWords& words;
typedef pair<CArgreement, CArgreement> CAgreementPair;
mutable unordered_map<CWordIndexPair, CAgreementPair> argreements;
};
const CArgreement& CWordArgreementsCache::Agreement(
const CWordIndexPair key, const bool strong ) const
{
debug_check_logic( key.first < key.second );
auto pair = argreements.insert( make_pair( key, CAgreementPair() ) );
CAgreementPair& result = pair.first->second;
if( pair.second ) {
CArgreement argreement;
CArgreement strongArgreement;
const CWordValues& values1 = words[key.first].Values();
const CWordValues& values2 = words[key.first].Values();
for( size_t index1 = 0; index1 < values1.size(); index1++ ) {
for( size_t index2 = 0; index2 < values2.size(); index2++ ) {
switch( values1[index1].Conform( values2[index2] ) ) {
case CWordValue::C_None:
break;
case CWordValue::C_StrongConform:
strongArgreement.first.Add( index1 );
strongArgreement.second.Add( index2 );
case CWordValue::C_Conform:
argreement.first.Add( index1 );
argreement.second.Add( index2 );
break;
}
}
}
result.first = argreement;
result.first = strongArgreement;
}
return ( strong ? result.second : result.first );
}
class CText : public CWords {
public:
CText() :
wordArgreementsCache( static_cast<CWords&>( *this ) )
{
}
TWordIndex NextWord( const TWordIndex wordIndex ) const
{
return ( wordIndex + 1 );
}
bool HasWord( const TWordIndex wordIndex ) const
{
return ( wordIndex < size() );
}
const CWordArgreementsCache& Argreements() const
{
return wordArgreementsCache;
}
private:
CWordArgreementsCache wordArgreementsCache;
};
struct CState;
typedef vector<CState> CStates;
typedef CStates::size_type TStateIndex;
struct CTransition {
TStateIndex NextState;
shared_ptr<RegexEx> wordRegex;
shared_ptr<RegexEx> valueRegex;
TPatternElementIndex PatternElementIndex;
bool Match( const CWord& word,
/* out */ CWordValueIndices& wordValueIndices ) const;
};
bool CTransition::Match( const CWord& word,
CWordValueIndices& wordValueIndices ) const
{
wordValueIndices.Reset( word.values.size() );
if( wordRegex && !word.MatchWord( *wordRegex ) ) {
return false;
}
if( valueRegex ) {
return word.MatchValues( *valueRegex, wordValueIndices );
}
return true;
}
typedef vector<CTransition> CTransitions;
struct CMatching {
TWordIndex WordIndex;
TPatternElementIndex PatternElementIndex;
CWordValueIndices WordValueIndices;
};
typedef vector<CMatching> CMatchings;
struct IUndoAction {
virtual void Undo() const = 0;
};
class CUndoActions {
public:
CUndoActions()
{
}
~CUndoActions()
{
for( auto ri = undoActions.crbegin();
ri != undoActions.crend(); ++ri )
{
( *ri )->Undo();
}
}
void Add( IUndoAction* undoAction )
{
undoActions.emplace_back( undoAction );
}
private:
vector<unique_ptr<IUndoAction>> undoActions;
};
struct IAction {
virtual bool Do( const CText& text, CMatchings& matchings,
CUndoActions& undoActions ) const = 0;
};
class CActions {
public:
void Add( shared_ptr<IAction> action );
bool Do( const CText& text, CMatchings& matchings,
CUndoActions& undoActions ) const;
private:
vector<shared_ptr<IAction>> actions;
};
void CActions::Add( shared_ptr<IAction> action )
{
actions.push_back( action );
}
bool CActions::Do( const CText& text, CMatchings& matchings,
CUndoActions& undoActions ) const
{
for( const shared_ptr<IAction>& action : actions ) {
if( !action->Do( text, matchings, undoActions ) ) {
return false;
}
}
return true;
}
struct CState {
CActions Actions;
CTransitions Transitions;
vector<TStateIndex> EpsTransitions;
};
class CContext {
public:
const CText& text;
const CStates& states;
CMatchings matchings;
CContext( const CText& text, const CStates& states ) :
text( text ), states( states )
{
matchings.reserve( 32 );
}
void Match( const TWordIndex wordIndex );
private:
void match( const TStateIndex stateIndex,
const TWordIndex wordIndex );
};
void CContext::Match( const TWordIndex wordIndex )
{
match( 0, wordIndex );
}
void CContext::match( const TStateIndex stateIndex,
const TWordIndex wordIndex )
{
const CState& state = states[stateIndex];
const CTransitions& transitions = state.Transitions;
CUndoActions undoActions;
if( !state.Actions.Do( text, matchings, undoActions ) // conditions are not met
|| ( transitions.empty() && state.EpsTransitions.empty() )
|| !text.HasWord( wordIndex ) )
{
return;
}
matchings.emplace_back();
CMatching& matching = matchings.back();
matching.WordIndex = wordIndex;
for( const CTransition& transition : transitions ) {
if( transition.Match( text[wordIndex], matching.WordValueIndices ) ) {
matching.PatternElementIndex = transition.PatternElementIndex;
match( transition.NextState, text.NextWord( wordIndex ) );
}
}
matchings.pop_back();
for( const TStateIndex nextStateIndex : state.EpsTransitions ) {
match( nextStateIndex, wordIndex );
}
}
#pragma region CAgreementAction
class CAgreementUndoAction : public IUndoAction {
public:
CAgreementUndoAction( CWordValueIndices& target,
CWordValueIndices&& source ) :
targetWordValueIndicies( target ),
sourceWordValueIndicies( source )
{
}
virtual void Undo() const override;
private:
CWordValueIndices& targetWordValueIndicies;
CWordValueIndices sourceWordValueIndicies;
};
void CAgreementUndoAction::Undo() const
{
targetWordValueIndicies = move( sourceWordValueIndicies );
}
struct CAgreementAction : public IAction {
public:
virtual bool Do( const CText& text, CMatchings& matchings,
CUndoActions& undoActions ) const override;
private:
bool strong;
TPatternElementIndex firstElementIndex;
TPatternElementIndex secondElementIndex;
bool match( const CText& text,
CMatching& first, CMatching& second,
CUndoActions& undoActions ) const;
};
bool CAgreementAction::Do( const CText& text, CMatchings& matchings,
CUndoActions& undoActions ) const
{
CMatchings::reverse_iterator firstElement = matchings.rbegin();
while( firstElement != matchings.rend()
&& firstElement->PatternElementIndex != firstElementIndex
&& firstElement->PatternElementIndex != secondElementIndex )
{
++firstElement;
}
if( firstElement == matchings.rend() ) {
return true;
}
const TPatternElementIndex secondElementsIndex =
firstElement->PatternElementIndex == firstElementIndex ?
secondElementIndex : firstElementIndex;
for( auto secondElement = next( firstElement );
secondElement != matchings.rend(); ++secondElement )
{
if( secondElement->PatternElementIndex == secondElementsIndex ) {
if( !match( text, *firstElement, *secondElement, undoActions ) ) {
return false;
}
}
}
return true;
}
bool CAgreementAction::match( const CText& text,
CMatching& first, CMatching& second,
CUndoActions& undoActions ) const
{
cout << "Match('" << text[first.WordIndex].text
<< ",'" << text[second.WordIndex].text << ");";
const CArgreement& agreement = text.Argreements().Agreement(
make_pair( first.WordIndex, second.WordIndex ), strong );
auto undo1 = first.WordValueIndices.Intersect( agreement.first );
auto undo2 = second.WordValueIndices.Intersect( agreement.second );
undoActions.Add( new CAgreementUndoAction(
first.WordValueIndices, move( undo1 ) ) );
undoActions.Add( new CAgreementUndoAction(
second.WordValueIndices, move( undo2 ) ) );
return ( first.WordValueIndices.Filled()
&& second.WordValueIndices.Filled() );
}
#pragma endregion
#pragma region CDictionaryAction
struct CDictionaryAction : public IAction {
public:
const string Name;
explicit CDictionaryAction( const string& name ) :
Name( name )
{
}
void Add( const vector<TPatternElementIndex>& word )
{
elements.push_back( word );
}
virtual bool Do( const CText& text, CMatchings& matchings,
CUndoActions& undoActions ) const override;
private:
vector<vector<TPatternElementIndex>> elements;
};
bool CDictionaryAction::Do( const CText& text, CMatchings& matchings,
CUndoActions& /* undoActions */ ) const
{
unordered_multimap<TPatternElementIndex, TWordIndex> elementToWordIndex;
for( const CMatching& matching : matchings ) {
elementToWordIndex.emplace( matching.PatternElementIndex, matching.WordIndex );
}
vector<string> words;
words.reserve( elements.size() );
for( const vector<TPatternElementIndex>& wordElements : elements ) {
words.emplace_back();
for( const TPatternElementIndex wordElement : wordElements ) {
auto range = elementToWordIndex.equal_range( wordElement );
for( auto i = range.first; i != range.second; ++i ) {
words.back() += text[i->second].text + " ";
}
}
if( !words.back().empty() ) {
words.back().pop_back();
}
}
// check
cout << "Dictionary('" << Name << "'";
for( const string& word : words ) {
cout << "," << word;
}
cout << ");" << endl;
return true;
}
#pragma endregion
///////////////////////////////////////////////////////////////////////////////
void test()
{
CText text;
for( int i = 0; i < 10; i++ ) {
CWord word;
word.text = "word#" + to_string( i );
word.word = word.text;
CWordValue wordValue;
wordValue.Value = "W";
word.values.push_back( wordValue );
wordValue.Value = "A";
word.values.push_back( wordValue );
wordValue.Value = "N";
word.values.push_back( wordValue );
text.push_back( word );
}
CTransition a, n, w;
a.valueRegex.reset( new RegexEx( StringEx( "A" ) ) );
a.PatternElementIndex = 1;
n.valueRegex.reset( new RegexEx( StringEx( "N" ) ) );
n.PatternElementIndex = 2;
w.valueRegex.reset( new RegexEx( StringEx( "W" ) ) );
w.PatternElementIndex = 3;
CStates states;
{ // s0
CState state;
state.Transitions.push_back( n );
state.Transitions.back().PatternElementIndex = 0;
state.Transitions.back().NextState = 1;
state.EpsTransitions.push_back( 1 );
states.push_back( state );
}
{ // s1
CState state;
state.Transitions.push_back( a );
state.Transitions.back().NextState = 2;
state.Transitions.push_back( n );
state.Transitions.back().NextState = 3;
state.Transitions.push_back( w );
state.Transitions.back().NextState = 4;
states.push_back( state );
}
{ // s2
CState state;
state.Transitions.push_back( n );
state.Transitions.back().NextState = 5;
state.Transitions.push_back( w );
state.Transitions.back().NextState = 6;
states.push_back( state );
}
{ // s3
CState state;
state.Transitions.push_back( w );
state.Transitions.back().NextState = 7;
states.push_back( state );
}
{ // s4
CState state;
state.Transitions.push_back( n );
state.Transitions.back().NextState = 7;
states.push_back( state );
}
{ // s5
CState state;
state.Transitions.push_back( w );
state.Transitions.back().NextState = 8;
states.push_back( state );
}
{ // s6
CState state;
state.Transitions.push_back( n );
state.Transitions.back().NextState = 8;
states.push_back( state );
}
{ // s7
CState state;
state.Transitions.push_back( a );
state.Transitions.back().NextState = 8;
states.push_back( state );
}
{ // s8
CState state;
shared_ptr<CDictionaryAction> action( new CDictionaryAction( "svetlana" ) );
action->Add( { 0 } );
action->Add( { 1 } );
action->Add( { 2 } );
action->Add( { 3 } );
state.Actions.Add( action );
states.push_back( state );
}
CContext context( text, states );
context.Match( 0 );
}
///////////////////////////////////////////////////////////////////////////////
//} // end of Matching namespace
//} // end of Lspl namespace
<commit_msg>remove old file<commit_after><|endoftext|>
|
<commit_before>/* projectM -- Milkdrop-esque visualisation SDK
Copyright (C)2003-2007 projectM Team
*
* 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
* See 'LICENSE.txt' included within this release
*
*/
#ifndef _MOODBAR_HPP
#define _MOODBAR_HPP
#include "PCM.hpp"
#include "RingBuffer.hpp"
class MoodBar {
public:
MoodBar(PCM * pcm) : m_numFreqs(pcm->numsamples/2 + 1), m_size(pcm->numsamples), m_rate(FIXED_SAMPLE_RATE), m_pcm(pcm) {
calcBarkbandTable();
resetBuffer();
}
MoodBar(int rate, PCM * pcm) : m_numFreqs(pcm->numsamples/2 + 1), m_size(pcm->numsamples), m_rate(rate), m_pcm(pcm) {
calcBarkbandTable();
resetBuffer();
}
~MoodBar() { delete[](m_barkband_table); }
/// Calculate rgb mood values for both left and right channels.
/// Uses the pcm instance's latest assignment into its
/// pcmL/R data buffers as inputs
void calculateMood(float * rgb_left, float * rgb_right, float * rgb_avg);
void stretchNormalize (float * colors);
private:
void resetBuffer() ;
/// @bug need to find this elsewhere
static const int FIXED_SAMPLE_RATE = 44100;
unsigned int m_numFreqs;
int m_size;
int m_rate;
/* This calculates a table that caches which bark band slot each
* incoming band is supposed to go in. */
void calcBarkbandTable ();
PCM * m_pcm;
void standardNormalize(float * rgb);
float m_amplitudes_left[24];
float m_amplitudes_right[24];
float m_amplitudes_avg[24];
static const unsigned int s_bark_bands[24];
RingBuffer<float> m_ringBuffers[3];
unsigned int * m_barkband_table;
};
#endif
<commit_msg>another moodbar fix<commit_after>/* projectM -- Milkdrop-esque visualisation SDK
Copyright (C)2003-2007 projectM Team
*
* 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
* See 'LICENSE.txt' included within this release
*
*/
#ifndef _MOODBAR_HPP
#define _MOODBAR_HPP
#include "PCM.hpp"
#include "RingBuffer.hpp"
class MoodBar {
public:
MoodBar(PCM * pcm) : m_numFreqs(pcm->numsamples/2 + 1), m_size(pcm->numsamples), m_rate(FIXED_SAMPLE_RATE), m_pcm(pcm), m_barkband_table(0) {
calcBarkbandTable();
resetBuffer();
}
MoodBar(int rate, PCM * pcm) : m_numFreqs(pcm->numsamples/2 + 1), m_size(pcm->numsamples), m_rate(rate), m_pcm(pcm) {
calcBarkbandTable();
resetBuffer();
}
~MoodBar() { delete[](m_barkband_table); }
/// Calculate rgb mood values for both left and right channels.
/// Uses the pcm instance's latest assignment into its
/// pcmL/R data buffers as inputs
void calculateMood(float * rgb_left, float * rgb_right, float * rgb_avg);
void stretchNormalize (float * colors);
private:
void resetBuffer() ;
/// @bug need to find this elsewhere
static const int FIXED_SAMPLE_RATE = 44100;
unsigned int m_numFreqs;
int m_size;
int m_rate;
/* This calculates a table that caches which bark band slot each
* incoming band is supposed to go in. */
void calcBarkbandTable ();
PCM * m_pcm;
void standardNormalize(float * rgb);
float m_amplitudes_left[24];
float m_amplitudes_right[24];
float m_amplitudes_avg[24];
static const unsigned int s_bark_bands[24];
RingBuffer<float> m_ringBuffers[3];
unsigned int * m_barkband_table;
};
#endif
<|endoftext|>
|
<commit_before>#include "client.h"
Client::Client(std::string&& id, std::string&& nick, std::string&& ident, std::string&& gecos, const Protocol* mod)
: User(std::forward<std::string> (id), std::forward<std::string> (nick), std::forward<std::string> (ident), std::forward<std::string> (gecos)),
expectingReconnect(true), proto(mod) {}
// TODO: populate commandPenalty
Client::~Client() {
}
void Client::disconnect() {
// TODO
expectingReconnect = false;
}
bool Client::checkConnection() const {
if (socket)
return socket->isConnected();
return false;
}
bool Client::wantsToReconnect() const {
return expectingReconnect;
}
void Client::doReconnect() {
}
std::map<std::string, std::string> Client::modes() const {
return clientModes;
}
bool Client::modeSet(const std::string& mode) const {
return clientModes.find(mode) != clientModes.end();
}
std::string Client::modeParam(const std::string& mode) const {
auto modeIter = clientModes.find(mode);
if (modeIter == clientModes.end())
return "";
return modeIter->second;
}
std::list<std::string> Client::listModeList(const std::string& mode) const {
auto listModeIter = clientListModes.find(mode);
if (listModeIter == clientListModes.end())
return std::list<std::string> ();
return listModeIter->second;
}
bool Client::itemInList(const std::string& mode, const std::string& param) const {
auto listModeIter = clientListModes.find(mode);
if (listModeIter == clientListModes.end())
return false;
auto listIter = std::find(listModeIter->second.begin(), listModeIter->second.end(), param);
return listIter != listModeIter->second.end();
}
void Client::setMode(const std::string& mode) {
clientModes.insert(std::pair<std::string, std::string> (mode, ""));
}
void Client::setMode(const std::string& mode, const std::string& param) {
clientModes[mode] = param; // If the mode is already set, we should change its param, but if not, it should be added
}
void Client::unsetMode(const std::string& mode) {
clientModes.erase(mode);
}
void Client::setListMode(const std::string& mode, const std::string& param) {
auto listModeIter = clientListModes.find(mode);
if (listModeIter == clientListModes.end()) {
clientListModes[mode].push_back(param);
return;
}
auto listIter = std::find(listModeIter->second.begin(), listModeIter->second.end(), param);
if (listIter == listModeIter->second.end())
listModeIter->second.push_back(param);
}
void Client::unsetListMode(const std::string& mode, const std::string& param) {
auto listModeIter = clientListModes.find(mode);
if (listModeIter == clientListModes.end())
return;
listModeIter->second.remove(param);
if (listModeIter->second.empty())
clientListModes.erase(listModeIter);
}
void Client::sendLine(const IRCMessage* line) {
socket->sendData(line->rawLine());
}
void Client::receiveData() {
LogManager* logger = LogManager::getHandle();
while (socket->isConnected()) {
std::string newMsg;
try {
newMsg = socket->receive();
} catch (const SocketOperationFailed& ex) {
logger->log(LOG_DEFAULT, "protocol-client", "Connection failed for client " + userID + " (" + userNick + "!" + userIdent + "@" + userHost + " on server " + proto->servName() + ") during receive.");
break;
}
proto->processIncoming(userID, IRCMessage (newMsg));
logger->log(LOG_ALL, "protocol-client-recv-" + proto->servName(), newMsg);
}
}
void Client::sendQueue() {
while (socket->isConnected()) {
if (linesToSend.empty()) {
std::this_thread::sleep_for(std::chrono::milliseconds(25));
continue;
}
std::unique_ptr<IRCMessage> sendingLine = linesToSend.front();
linesToSend.pop();
unsigned int thisPenalty = 1;
auto penaltyIter = commandPenalty.find(sendingLine->command());
if (penaltyIter != commandPenalty.end())
thisPenalty = penaltyIter->second;
while (penaltySeconds > 10)
std::this_thread::sleep_for(std::chrono::seconds(1));
MutexLocker mutexLock (&sendMutex);
penaltySeconds += thisPenalty;
if (socket->isConnected()) // to make sure the connection didn't get lost during the wait
socket->sendData(sendingLine->rawLine());
}
if (socket->isConnected()) {
MutexLocker mutexLock (&sendMutex);
while (!linesToSend.empty()) {
socket->sendData(linesToSend.front()->rawLine());
linesToSend.pop();
}
}
}
void Client::decrementSeconds() {
LogManager* logger = LogManager::getHandle();
while (socket->isConnected()) {
std::this_thread::sleep_for(std::chrono::seconds(1));
MutexLocker mutexLock (&sendMutex);
if (penaltySeconds > 0) {
penaltySeconds--;
std::ostringstream logMsg;
logMsg << "Penalty second count reduced to " << penaltySeconds;
logger->log(LOG_ALL, "protocol-client-penalty-" + proto->servName(), logMsg.str());
}
}
MutexLocker mutexLock (&sendMutex);
penaltySeconds = 0;
}<commit_msg>Log messages being sent<commit_after>#include "client.h"
Client::Client(std::string&& id, std::string&& nick, std::string&& ident, std::string&& gecos, const Protocol* mod)
: User(std::forward<std::string> (id), std::forward<std::string> (nick), std::forward<std::string> (ident), std::forward<std::string> (gecos)),
expectingReconnect(true), proto(mod) {}
// TODO: populate commandPenalty
Client::~Client() {
}
void Client::disconnect() {
// TODO
expectingReconnect = false;
}
bool Client::checkConnection() const {
if (socket)
return socket->isConnected();
return false;
}
bool Client::wantsToReconnect() const {
return expectingReconnect;
}
void Client::doReconnect() {
}
std::map<std::string, std::string> Client::modes() const {
return clientModes;
}
bool Client::modeSet(const std::string& mode) const {
return clientModes.find(mode) != clientModes.end();
}
std::string Client::modeParam(const std::string& mode) const {
auto modeIter = clientModes.find(mode);
if (modeIter == clientModes.end())
return "";
return modeIter->second;
}
std::list<std::string> Client::listModeList(const std::string& mode) const {
auto listModeIter = clientListModes.find(mode);
if (listModeIter == clientListModes.end())
return std::list<std::string> ();
return listModeIter->second;
}
bool Client::itemInList(const std::string& mode, const std::string& param) const {
auto listModeIter = clientListModes.find(mode);
if (listModeIter == clientListModes.end())
return false;
auto listIter = std::find(listModeIter->second.begin(), listModeIter->second.end(), param);
return listIter != listModeIter->second.end();
}
void Client::setMode(const std::string& mode) {
clientModes.insert(std::pair<std::string, std::string> (mode, ""));
}
void Client::setMode(const std::string& mode, const std::string& param) {
clientModes[mode] = param; // If the mode is already set, we should change its param, but if not, it should be added
}
void Client::unsetMode(const std::string& mode) {
clientModes.erase(mode);
}
void Client::setListMode(const std::string& mode, const std::string& param) {
auto listModeIter = clientListModes.find(mode);
if (listModeIter == clientListModes.end()) {
clientListModes[mode].push_back(param);
return;
}
auto listIter = std::find(listModeIter->second.begin(), listModeIter->second.end(), param);
if (listIter == listModeIter->second.end())
listModeIter->second.push_back(param);
}
void Client::unsetListMode(const std::string& mode, const std::string& param) {
auto listModeIter = clientListModes.find(mode);
if (listModeIter == clientListModes.end())
return;
listModeIter->second.remove(param);
if (listModeIter->second.empty())
clientListModes.erase(listModeIter);
}
void Client::sendLine(const IRCMessage* line) {
socket->sendData(line->rawLine());
}
void Client::receiveData() {
LogManager* logger = LogManager::getHandle();
while (socket->isConnected()) {
std::string newMsg;
try {
newMsg = socket->receive();
} catch (const SocketOperationFailed& ex) {
logger->log(LOG_DEFAULT, "protocol-client", "Connection failed for client " + userID + " (" + userNick + "!" + userIdent + "@" + userHost + " on server " + proto->servName() + ") during receive.");
break;
}
proto->processIncoming(userID, IRCMessage (newMsg));
logger->log(LOG_ALL, "protocol-client-recv-" + proto->servName(), newMsg);
}
}
void Client::sendQueue() {
LogManager* logger = LogManager::getHandle();
while (socket->isConnected()) {
if (linesToSend.empty()) {
std::this_thread::sleep_for(std::chrono::milliseconds(25));
continue;
}
std::unique_ptr<IRCMessage> sendingLine = linesToSend.front();
linesToSend.pop();
unsigned int thisPenalty = 1;
auto penaltyIter = commandPenalty.find(sendingLine->command());
if (penaltyIter != commandPenalty.end())
thisPenalty = penaltyIter->second;
while (penaltySeconds > 10)
std::this_thread::sleep_for(std::chrono::seconds(1));
MutexLocker mutexLock (&sendMutex);
penaltySeconds += thisPenalty;
if (socket->isConnected()) { // to make sure the connection didn't get lost during the wait
std::string lineToSend (sendingLine->rawLine());
socket->sendData(lineToSend);
logger->log(LOG_ALL, "protocol-client-send-" + proto->servName(), lineToSend);
}
std::stringstream logMsg;
logMsg << "The command " << sendingLine->command() << " was sent; the penalty has increased by " << thisPenalty <<< " to " << penaltySeconds << ".";
logger->log(LOG_ALL, "protocol-client-penalty-" + proto->servName(), logMsg.str());
}
if (socket->isConnected()) {
MutexLocker mutexLock (&sendMutex);
while (!linesToSend.empty()) {
std::string lineToSend (linesToSend.front()->rawLine());
linesToSend.pop();
socket->sendData(lineToSend);
logger->log(LOG_ALL, "protocol-client-send-" + proto->servName(), lineToSend);
}
}
}
void Client::decrementSeconds() {
LogManager* logger = LogManager::getHandle();
while (socket->isConnected()) {
std::this_thread::sleep_for(std::chrono::seconds(1));
MutexLocker mutexLock (&sendMutex);
if (penaltySeconds > 0) {
penaltySeconds--;
std::ostringstream logMsg;
logMsg << "Penalty second count reduced to " << penaltySeconds;
logger->log(LOG_ALL, "protocol-client-penalty-" + proto->servName(), logMsg.str());
}
}
MutexLocker mutexLock (&sendMutex);
penaltySeconds = 0;
}<|endoftext|>
|
<commit_before>#include "NTClient.h"
using namespace std;
NTClient::NTClient(int _wpm, double _accuracy) {
typeIntervalMS = 12000 / _wpm;
wpm = _wpm;
accuracy = _accuracy;
hasError = false;
firstConnect = true;
connected = false;
lessonLen = 0;
lidx = 0;
log = new NTLogger("(Not logged in)");
}
NTClient::~NTClient() {
delete log;
if (wsh != nullptr) {
delete wsh;
wsh = nullptr;
}
}
bool NTClient::login(string username, string password) {
log->type(LOG_HTTP);
log->wr("Logging into the NitroType account...\n");
log->setUsername(username);
uname = username;
pword = password;
bool ret = true;
string data = string("username=");
data += uname;
data += "&password=";
data += pword;
data += "&adb=1&tz=America%2FChicago"; // No need to have anything other than Chicago timezone
httplib::SSLClient loginReq(NITROTYPE_HOSTNAME, HTTPS_PORT);
shared_ptr<httplib::Response> res = loginReq.post(NT_LOGIN_ENDPOINT, data, "application/x-www-form-urlencoded; charset=UTF-8");
if (res) {
bool foundLoginCookie = false;
for (int i = 0; i < res->cookies.size(); ++i) {
string cookie = res->cookies.at(i);
addCookie(Utils::extractCKey(cookie), Utils::extractCValue(cookie));
if (cookie.find("ntuserrem=") == 0) {
foundLoginCookie = true;
token = Utils::extractCValue(cookie);
log->type(LOG_HTTP);
log->wr("Resolved ntuserrem login token.\n");
// addCookie("ntuserrem", token);
}
}
if (!foundLoginCookie) {
ret = false;
cout << "Unable to locate the login cookie. Maybe try a different account?\n";
}
} else {
ret = false;
cout << "Login request failed. This might be a network issue. Maybe try resetting your internet connection?\n";
}
if (ret == false) {
log->type(LOG_HTTP);
log->wr("Failed to log in. This account is most likely banned.\n");
} else {
bool success = getPrimusSID();
if (!success) return false;
}
return ret;
}
bool NTClient::connect() {
wsh = new Hub();
time_t tnow = time(0);
rawCookieStr = Utils::stringifyCookies(&cookies);
stringstream uristream;
uristream << "wss://realtime1.nitrotype.com:443/realtime/?_primuscb=" << tnow << "-0&EIO=3&transport=websocket&sid=" << primusSid << "&t=" << tnow << "&b64=1";
string wsURI = uristream.str();
log->type(LOG_CONN);
log->wr("Attempting to open a WebSocket on NitroType realtime server...\n");
if (firstConnect) {
addListeners();
}
// cout << "Cookies: " << rawCookieStr << endl << endl;
// Create override headers
customHeaders["Cookie"] = rawCookieStr;
customHeaders["Origin"] = "https://www.nitrotype.com";
customHeaders["User-Agent"] = "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Ubuntu Chromium/55.0.2883.87 Chrome/55.0.2883.87 Safari/537.36";
// customHeaders["Host"] = "realtime1.nitrotype.com";
wsh->connect(wsURI, (void*)this, customHeaders, 7000);
// wsh->connect(wsURI);
if (firstConnect) {
wsh->run();
firstConnect = false;
}
return true;
}
void NTClient::addCookie(string key, string val) {
SPair sp = SPair(key, val);
cookies.push_back(sp);
}
bool NTClient::getPrimusSID() {
time_t tnow = time(0);
log->type(LOG_HTTP);
log->wr("Resolving Primus SID...\n");
rawCookieStr = Utils::stringifyCookies(&cookies);
stringstream squery;
squery << "?_primuscb=" << tnow << "-0&EIO=3&transport=polling&t=" << tnow << "-0&b64=1";
string queryStr = squery.str();
httplib::SSLClient loginReq(NT_REALTIME_HOST, HTTPS_PORT);
string path = NT_PRIMUS_ENDPOINT + queryStr;
shared_ptr<httplib::Response> res = loginReq.get(path.c_str(), rawCookieStr.c_str());
if (res) {
json jres = json::parse(res->body.substr(4, res->body.length()));
primusSid = jres["sid"];
log->type(LOG_HTTP);
log->wr("Resolved Primus SID successfully.\n");
// addCookie("io", primusSid);
} else {
cout << "Error retrieving primus handshake data.\n";
return false;
}
return true;
}
string NTClient::getJoinPacket(int avgSpeed) {
stringstream ss;
ss << "4{\"stream\":\"race\",\"msg\":\"join\",\"payload\":{\"debugging\":false,\"avgSpeed\":"
<< avgSpeed
<< ",\"forceEarlyPlace\":true,\"track\":\"desert\",\"music\":\"city_nights\"}}";
return ss.str();
}
void NTClient::addListeners() {
assert(wsh != nullptr);
wsh->onError([this](void* udata) {
cout << "Failed to connect to WebSocket server." << endl;
hasError = true;
});
wsh->onConnection([this](WebSocket<CLIENT>* wsocket, HttpRequest req) {
log->type(LOG_CONN);
log->wr("Established a WebSocket connection with the realtime server.\n");
onConnection(wsocket, req);
});
wsh->onDisconnection([this](WebSocket<CLIENT>* wsocket, int code, char* msg, size_t len) {
log->type(LOG_CONN);
log->wr("Disconnected from the realtime server.\n");
onDisconnection(wsocket, code, msg, len);
});
wsh->onMessage([this](WebSocket<CLIENT>* ws, char* msg, size_t len, OpCode opCode) {
onMessage(ws, msg, len, opCode);
});
}
void NTClient::onDisconnection(WebSocket<CLIENT>* wsocket, int code, char* msg, size_t len) {
/*
cout << "Disconn message: " << string(msg, len) << endl;
cout << "Disconn code: " << code << endl;
*/
log->type(LOG_CONN);
log->wr("Reconnecting to the realtime server...\n");
getPrimusSID();
rawCookieStr = Utils::stringifyCookies(&cookies);
stringstream uristream;
uristream << "wss://realtime1.nitrotype.com:443/realtime/?_primuscb=" << time(0) << "-0&EIO=3&transport=websocket&sid=" << primusSid << "&t=" << time(0) << "&b64=1";
string wsURI = uristream.str();
wsh->connect(wsURI, (void*)this, customHeaders, 7000);
}
void NTClient::handleData(WebSocket<CLIENT>* ws, json* j) {
// Uncomment to dump all raw JSON packets
// cout << "Recieved json data:" << endl << j->dump(4) << endl;
if (j->operator[]("msg") == "setup") {
log->type(LOG_RACE);
log->wr("I joined a new race.\n");
recievedEndPacket = false;
} else if (j->operator[]("msg") == "joined") {
string joinedName = j->operator[]("payload")["profile"]["username"];
string dispName;
try {
dispName = j->operator[]("payload")["profile"]["displayName"];
} catch (const exception& e) {
dispName = "[None]";
}
log->type(LOG_RACE);
if (joinedName == "bot") {
log->wr("Bot user '");
log->wrs(dispName);
log->wrs("' joined the race.\n");
} else {
log->wr("Human user '");
log->wrs(joinedName);
log->wrs("' joined the race.\n");
}
} else if (j->operator[]("msg") == "status" && j->operator[]("payload")["status"] == "countdown") {
lastRaceStart = time(0);
log->type(LOG_RACE);
log->wr("The race has started.\n");
lesson = j->operator[]("payload")["l"];
lessonLen = lesson.length();
lidx = 0;
log->type(LOG_INFO);
log->wr("Lesson length: ");
log->operator<<(lessonLen);
log->ln();
this_thread::sleep_for(chrono::milliseconds(50));
type(ws);
} else if (j->operator[]("msg") == "update" &&
j->operator[]("payload")["racers"][0] != nullptr &&
j->operator[]("payload")["racers"][0]["r"] != nullptr) {
// Race has finished for a client
if (recievedEndPacket == false) {
// Ensures its this client
recievedEndPacket = true;
handleRaceFinish(ws, j);
}
}
}
void NTClient::onMessage(WebSocket<CLIENT>* ws, char* msg, size_t len, OpCode opCode) {
if (opCode != OpCode::TEXT) {
cout << "The realtime server did not send a text packet for some reason, ignoring.\n";
return;
}
string smsg = string(msg, len);
if (smsg == "3probe") {
// Response to initial connection probe
ws->send("5", OpCode::TEXT);
// Join packet
this_thread::sleep_for(chrono::seconds(1));
string joinTo = getJoinPacket(20); // 20 WPM just to test
ws->send(joinTo.c_str(), OpCode::TEXT);
} else if (smsg.length() > 2 && smsg[0] == '4' && smsg[1] == '{') {
string rawJData = smsg.substr(1, smsg.length());
json jdata;
try {
jdata = json::parse(rawJData);
} catch (const exception& e) {
// Some error parsing real race data, something must be wrong
cout << "There was an issue parsing server data: " << e.what() << endl;
return;
}
handleData(ws, &jdata);
} else {
cout << "Recieved unknown WebSocket message: '" << smsg << "'\n";
}
}
void NTClient::onConnection(WebSocket<CLIENT>* wsocket, HttpRequest req) {
// Send a probe, which is required for connection
wsocket->send("2probe", OpCode::TEXT);
}
void NTClient::sendTypePacket(WebSocket<CLIENT>* ws, int idx, bool isRight) {
json p = {
{"stream", "race"},
{"msg", "update"},
{"payload", {}}
};
if (isRight) {
p["payload"]["t"] = idx;
} else {
p["payload"]["e"] = idx;
}
string packet = "4" + p.dump();
ws->send(packet.c_str(), OpCode::TEXT);
}
void NTClient::type(WebSocket<CLIENT>* ws) {
if (lidx > lessonLen) {
// All characters have been typed
return;
}
int low = typeIntervalMS - 10;
int high = typeIntervalMS + 10;
bool isRight = Utils::randBool(accuracy);
int sleepFor = Utils::randInt(low, high);
if (low < 10) {
low = 10;
}
if (lidx % 25 == 0) { // Display info every 25 characters
// Log race updated
log->type(LOG_INFO);
log->wr("I have finished ");
log->operator<<((((double)lidx) / ((double)lessonLen)) * 100.00);
log->wrs("% of the race (");
log->operator<<((int)lidx);
log->wrs(" / ");
log->operator<<((int)lessonLen);
log->wrs(" characters at ");
log->operator<<((int)wpm);
log->wrs(" WPM)");
log->ln();
}
// cout << "Typing with index: " << lidx << ", isRight: " << isRight << ", sleepFor: " << sleepFor << endl;
sendTypePacket(ws, lidx, isRight);
lidx++;
this_thread::sleep_for(chrono::milliseconds(sleepFor));
type(ws); // Call the function until the lesson has been "typed"
}
void NTClient::handleRaceFinish(WebSocket<CLIENT>* ws, json* j) {
int raceCompleteTime = time(0) - lastRaceStart;
log->type(LOG_RACE);
log->wr("The race has finished.\n");
log->type(LOG_INFO);
log->wr("The race took ");
log->operator<<(raceCompleteTime);
log->wrs(" seconds to complete\n");
this_thread::sleep_for(chrono::seconds(2)); // Sleep 2 seconds
log->type(LOG_CONN);
log->wr("Closing WebSocket...\n");
ws->close();
}<commit_msg>Wait longer before disconnecting from the realtime server<commit_after>#include "NTClient.h"
using namespace std;
NTClient::NTClient(int _wpm, double _accuracy) {
typeIntervalMS = 12000 / _wpm;
wpm = _wpm;
accuracy = _accuracy;
hasError = false;
firstConnect = true;
connected = false;
lessonLen = 0;
lidx = 0;
log = new NTLogger("(Not logged in)");
}
NTClient::~NTClient() {
delete log;
if (wsh != nullptr) {
delete wsh;
wsh = nullptr;
}
}
bool NTClient::login(string username, string password) {
log->type(LOG_HTTP);
log->wr("Logging into the NitroType account...\n");
log->setUsername(username);
uname = username;
pword = password;
bool ret = true;
string data = string("username=");
data += uname;
data += "&password=";
data += pword;
data += "&adb=1&tz=America%2FChicago"; // No need to have anything other than Chicago timezone
httplib::SSLClient loginReq(NITROTYPE_HOSTNAME, HTTPS_PORT);
shared_ptr<httplib::Response> res = loginReq.post(NT_LOGIN_ENDPOINT, data, "application/x-www-form-urlencoded; charset=UTF-8");
if (res) {
bool foundLoginCookie = false;
for (int i = 0; i < res->cookies.size(); ++i) {
string cookie = res->cookies.at(i);
addCookie(Utils::extractCKey(cookie), Utils::extractCValue(cookie));
if (cookie.find("ntuserrem=") == 0) {
foundLoginCookie = true;
token = Utils::extractCValue(cookie);
log->type(LOG_HTTP);
log->wr("Resolved ntuserrem login token.\n");
// addCookie("ntuserrem", token);
}
}
if (!foundLoginCookie) {
ret = false;
cout << "Unable to locate the login cookie. Maybe try a different account?\n";
}
} else {
ret = false;
cout << "Login request failed. This might be a network issue. Maybe try resetting your internet connection?\n";
}
if (ret == false) {
log->type(LOG_HTTP);
log->wr("Failed to log in. This account is most likely banned.\n");
} else {
bool success = getPrimusSID();
if (!success) return false;
}
return ret;
}
bool NTClient::connect() {
wsh = new Hub();
time_t tnow = time(0);
rawCookieStr = Utils::stringifyCookies(&cookies);
stringstream uristream;
uristream << "wss://realtime1.nitrotype.com:443/realtime/?_primuscb=" << tnow << "-0&EIO=3&transport=websocket&sid=" << primusSid << "&t=" << tnow << "&b64=1";
string wsURI = uristream.str();
log->type(LOG_CONN);
log->wr("Attempting to open a WebSocket on NitroType realtime server...\n");
if (firstConnect) {
addListeners();
}
// cout << "Cookies: " << rawCookieStr << endl << endl;
// Create override headers
customHeaders["Cookie"] = rawCookieStr;
customHeaders["Origin"] = "https://www.nitrotype.com";
customHeaders["User-Agent"] = "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Ubuntu Chromium/55.0.2883.87 Chrome/55.0.2883.87 Safari/537.36";
// customHeaders["Host"] = "realtime1.nitrotype.com";
wsh->connect(wsURI, (void*)this, customHeaders, 7000);
// wsh->connect(wsURI);
if (firstConnect) {
wsh->run();
firstConnect = false;
}
return true;
}
void NTClient::addCookie(string key, string val) {
SPair sp = SPair(key, val);
cookies.push_back(sp);
}
bool NTClient::getPrimusSID() {
time_t tnow = time(0);
log->type(LOG_HTTP);
log->wr("Resolving Primus SID...\n");
rawCookieStr = Utils::stringifyCookies(&cookies);
stringstream squery;
squery << "?_primuscb=" << tnow << "-0&EIO=3&transport=polling&t=" << tnow << "-0&b64=1";
string queryStr = squery.str();
httplib::SSLClient loginReq(NT_REALTIME_HOST, HTTPS_PORT);
string path = NT_PRIMUS_ENDPOINT + queryStr;
shared_ptr<httplib::Response> res = loginReq.get(path.c_str(), rawCookieStr.c_str());
if (res) {
json jres = json::parse(res->body.substr(4, res->body.length()));
primusSid = jres["sid"];
log->type(LOG_HTTP);
log->wr("Resolved Primus SID successfully.\n");
// addCookie("io", primusSid);
} else {
cout << "Error retrieving primus handshake data.\n";
return false;
}
return true;
}
string NTClient::getJoinPacket(int avgSpeed) {
stringstream ss;
ss << "4{\"stream\":\"race\",\"msg\":\"join\",\"payload\":{\"debugging\":false,\"avgSpeed\":"
<< avgSpeed
<< ",\"forceEarlyPlace\":true,\"track\":\"desert\",\"music\":\"city_nights\"}}";
return ss.str();
}
void NTClient::addListeners() {
assert(wsh != nullptr);
wsh->onError([this](void* udata) {
cout << "Failed to connect to WebSocket server." << endl;
hasError = true;
});
wsh->onConnection([this](WebSocket<CLIENT>* wsocket, HttpRequest req) {
log->type(LOG_CONN);
log->wr("Established a WebSocket connection with the realtime server.\n");
onConnection(wsocket, req);
});
wsh->onDisconnection([this](WebSocket<CLIENT>* wsocket, int code, char* msg, size_t len) {
log->type(LOG_CONN);
log->wr("Disconnected from the realtime server.\n");
onDisconnection(wsocket, code, msg, len);
});
wsh->onMessage([this](WebSocket<CLIENT>* ws, char* msg, size_t len, OpCode opCode) {
onMessage(ws, msg, len, opCode);
});
}
void NTClient::onDisconnection(WebSocket<CLIENT>* wsocket, int code, char* msg, size_t len) {
/*
cout << "Disconn message: " << string(msg, len) << endl;
cout << "Disconn code: " << code << endl;
*/
log->type(LOG_CONN);
log->wr("Reconnecting to the realtime server...\n");
getPrimusSID();
rawCookieStr = Utils::stringifyCookies(&cookies);
stringstream uristream;
uristream << "wss://realtime1.nitrotype.com:443/realtime/?_primuscb=" << time(0) << "-0&EIO=3&transport=websocket&sid=" << primusSid << "&t=" << time(0) << "&b64=1";
string wsURI = uristream.str();
wsh->connect(wsURI, (void*)this, customHeaders, 7000);
}
void NTClient::handleData(WebSocket<CLIENT>* ws, json* j) {
// Uncomment to dump all raw JSON packets
// cout << "Recieved json data:" << endl << j->dump(4) << endl;
if (j->operator[]("msg") == "setup") {
log->type(LOG_RACE);
log->wr("I joined a new race.\n");
recievedEndPacket = false;
} else if (j->operator[]("msg") == "joined") {
string joinedName = j->operator[]("payload")["profile"]["username"];
string dispName;
try {
dispName = j->operator[]("payload")["profile"]["displayName"];
} catch (const exception& e) {
dispName = "[None]";
}
log->type(LOG_RACE);
if (joinedName == "bot") {
log->wr("Bot user '");
log->wrs(dispName);
log->wrs("' joined the race.\n");
} else {
log->wr("Human user '");
log->wrs(joinedName);
log->wrs("' joined the race.\n");
}
} else if (j->operator[]("msg") == "status" && j->operator[]("payload")["status"] == "countdown") {
lastRaceStart = time(0);
log->type(LOG_RACE);
log->wr("The race has started.\n");
lesson = j->operator[]("payload")["l"];
lessonLen = lesson.length();
lidx = 0;
log->type(LOG_INFO);
log->wr("Lesson length: ");
log->operator<<(lessonLen);
log->ln();
this_thread::sleep_for(chrono::milliseconds(50));
type(ws);
} else if (j->operator[]("msg") == "update" &&
j->operator[]("payload")["racers"][0] != nullptr &&
j->operator[]("payload")["racers"][0]["r"] != nullptr) {
// Race has finished for a client
if (recievedEndPacket == false) {
// Ensures its this client
recievedEndPacket = true;
handleRaceFinish(ws, j);
}
}
}
void NTClient::onMessage(WebSocket<CLIENT>* ws, char* msg, size_t len, OpCode opCode) {
if (opCode != OpCode::TEXT) {
cout << "The realtime server did not send a text packet for some reason, ignoring.\n";
return;
}
string smsg = string(msg, len);
if (smsg == "3probe") {
// Response to initial connection probe
ws->send("5", OpCode::TEXT);
// Join packet
this_thread::sleep_for(chrono::seconds(1));
string joinTo = getJoinPacket(20); // 20 WPM just to test
ws->send(joinTo.c_str(), OpCode::TEXT);
} else if (smsg.length() > 2 && smsg[0] == '4' && smsg[1] == '{') {
string rawJData = smsg.substr(1, smsg.length());
json jdata;
try {
jdata = json::parse(rawJData);
} catch (const exception& e) {
// Some error parsing real race data, something must be wrong
cout << "There was an issue parsing server data: " << e.what() << endl;
return;
}
handleData(ws, &jdata);
} else {
cout << "Recieved unknown WebSocket message: '" << smsg << "'\n";
}
}
void NTClient::onConnection(WebSocket<CLIENT>* wsocket, HttpRequest req) {
// Send a probe, which is required for connection
wsocket->send("2probe", OpCode::TEXT);
}
void NTClient::sendTypePacket(WebSocket<CLIENT>* ws, int idx, bool isRight) {
json p = {
{"stream", "race"},
{"msg", "update"},
{"payload", {}}
};
if (isRight) {
p["payload"]["t"] = idx;
} else {
p["payload"]["e"] = idx;
}
string packet = "4" + p.dump();
ws->send(packet.c_str(), OpCode::TEXT);
}
void NTClient::type(WebSocket<CLIENT>* ws) {
if (lidx > lessonLen) {
// All characters have been typed
return;
}
int low = typeIntervalMS - 10;
int high = typeIntervalMS + 10;
bool isRight = Utils::randBool(accuracy);
int sleepFor = Utils::randInt(low, high);
if (low < 10) {
low = 10;
}
if (lidx % 25 == 0) { // Display info every 25 characters
// Log race updated
log->type(LOG_INFO);
log->wr("I have finished ");
log->operator<<((((double)lidx) / ((double)lessonLen)) * 100.00);
log->wrs("% of the race (");
log->operator<<((int)lidx);
log->wrs(" / ");
log->operator<<((int)lessonLen);
log->wrs(" characters at ");
log->operator<<((int)wpm);
log->wrs(" WPM)");
log->ln();
}
// cout << "Typing with index: " << lidx << ", isRight: " << isRight << ", sleepFor: " << sleepFor << endl;
sendTypePacket(ws, lidx, isRight);
lidx++;
this_thread::sleep_for(chrono::milliseconds(sleepFor));
type(ws); // Call the function until the lesson has been "typed"
}
void NTClient::handleRaceFinish(WebSocket<CLIENT>* ws, json* j) {
int raceCompleteTime = time(0) - lastRaceStart;
log->type(LOG_RACE);
log->wr("The race has finished.\n");
log->type(LOG_INFO);
log->wr("The race took ");
log->operator<<(raceCompleteTime);
log->wrs(" seconds to complete\n");
this_thread::sleep_for(chrono::seconds(10)); // Sleep 2 seconds
log->type(LOG_CONN);
log->wr("Closing WebSocket...\n");
ws->close();
}<|endoftext|>
|
<commit_before>/* This file is part of the KDE project
Copyright (C) 2006 Matthias Kretz <[email protected]>
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Library General Public
License version 2 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
Library General Public License for more details.
You should have received a copy of the GNU Library General Public License
along with this library; see the file COPYING.LIB. If not, write to
the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
Boston, MA 02110-1301, USA.
*/
#include "volumeslider.h"
#include "volumeslider_p.h"
#include "../audiooutput.h"
#include <klocale.h>
namespace Phonon
{
VolumeSlider::VolumeSlider( QWidget* parent )
: QWidget( parent ),
d_ptr( new VolumeSliderPrivate( this ) )
{
setToolTip( i18n( "Volume: %1%", 100 ) );
setWhatsThis( i18n( "Use this slider to adjust the volume. The leftmost position is 0%, the rightmost is %1%", 100 ) );
}
VolumeSlider::~VolumeSlider()
{
delete d_ptr;
}
bool VolumeSlider::isMuteVisible() const
{
return d_ptr->muteButton.isVisible();
}
void VolumeSlider::setMuteVisible(bool visible)
{
d_ptr->muteButton.setVisible(visible);
}
QSize VolumeSlider::iconSize() const
{
return d_ptr->muteButton.iconSize();
}
void VolumeSlider::setIconSize(const QSize &iconSize)
{
kDebug(602) << k_funcinfo << iconSize << endl;
d_ptr->muteButton.setIconSize(iconSize);
}
float VolumeSlider::maximumVolume() const
{
return d_ptr->slider.maximum() * 0.01;
}
void VolumeSlider::setMaximumVolume( float volume )
{
int max = static_cast<int>( volume * 100 );
d_ptr->slider.setMaximum(max);
setWhatsThis( i18n( "Use this slider to adjust the volume. The leftmost position is 0%, the rightmost is %1%" , max ) );
}
Qt::Orientation VolumeSlider::orientation() const
{
return d_ptr->slider.orientation();
}
void VolumeSlider::setOrientation(Qt::Orientation o)
{
Q_D(VolumeSlider);
Qt::Alignment align = (o == Qt::Horizontal ? Qt::AlignVCenter : Qt::AlignHCenter);
d->layout.setAlignment(&d->muteButton, align);
d->layout.setAlignment(&d->slider, align);
d->layout.setDirection(o == Qt::Horizontal ? QBoxLayout::LeftToRight : QBoxLayout::TopToBottom);
d->slider.setOrientation(o);
}
void VolumeSlider::setAudioOutput(AudioOutput *output)
{
if (!output) {
return;
}
Q_D(VolumeSlider);
d->output = output;
d->slider.setValue(qRound(100 * output->volume()));
d->slider.setEnabled(true);
connect(output, SIGNAL(destroyed()), SLOT(_k_outputDestroyed()));
connect(&d->slider, SIGNAL(valueChanged(int)), SLOT(_k_sliderChanged(int)));
connect(&d->muteButton, SIGNAL(clicked()), SLOT(_k_buttonClicked()));
connect(output, SIGNAL(volumeChanged(float)), SLOT(_k_volumeChanged(float)));
connect(output, SIGNAL(mutedChanged(bool)), SLOT(_k_mutedChanged(bool)));
}
void VolumeSliderPrivate::_k_buttonClicked()
{
if (output) {
output->setMuted(!output->isMuted());
}
}
void VolumeSliderPrivate::_k_mutedChanged(bool muted)
{
if (muted) {
muteButton.setIcon(mutedIcon);
} else {
muteButton.setIcon(volumeIcon);
}
}
void VolumeSliderPrivate::_k_sliderChanged(int value)
{
Q_Q(VolumeSlider);
q->setToolTip(i18n("Volume: %1%", value));
if (output) {
ignoreVolumeChange = true;
output->setVolume((static_cast<float>(value)) * 0.01);
ignoreVolumeChange = false;
}
}
void VolumeSliderPrivate::_k_volumeChanged(float value)
{
if (!ignoreVolumeChange) {
slider.setValue(qRound(100 * value));
}
}
void VolumeSliderPrivate::_k_outputDestroyed()
{
output = 0;
slider.setValue(100);
slider.setEnabled(false);
}
bool VolumeSlider::hasTracking() const
{
return d_ptr->slider.hasTracking();
}
void VolumeSlider::setTracking(bool tracking)
{
d_ptr->slider.setTracking(tracking);
}
int VolumeSlider::pageStep() const
{
return d_ptr->slider.pageStep();
}
void VolumeSlider::setPageStep(int milliseconds)
{
d_ptr->slider.setPageStep(milliseconds);
}
int VolumeSlider::singleStep() const
{
return d_ptr->slider.singleStep();
}
void VolumeSlider::setSingleStep(int milliseconds)
{
d_ptr->slider.setSingleStep(milliseconds);
}
} // namespace Phonon
#include "volumeslider.moc"
// vim: sw=4 et
<commit_msg>correct tooltip when muted<commit_after>/* This file is part of the KDE project
Copyright (C) 2006 Matthias Kretz <[email protected]>
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Library General Public
License version 2 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
Library General Public License for more details.
You should have received a copy of the GNU Library General Public License
along with this library; see the file COPYING.LIB. If not, write to
the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
Boston, MA 02110-1301, USA.
*/
#include "volumeslider.h"
#include "volumeslider_p.h"
#include "../audiooutput.h"
#include <klocale.h>
namespace Phonon
{
VolumeSlider::VolumeSlider( QWidget* parent )
: QWidget( parent ),
d_ptr( new VolumeSliderPrivate( this ) )
{
setToolTip( i18n( "Volume: %1%", 100 ) );
setWhatsThis( i18n( "Use this slider to adjust the volume. The leftmost position is 0%, the rightmost is %1%", 100 ) );
}
VolumeSlider::~VolumeSlider()
{
delete d_ptr;
}
bool VolumeSlider::isMuteVisible() const
{
return d_ptr->muteButton.isVisible();
}
void VolumeSlider::setMuteVisible(bool visible)
{
d_ptr->muteButton.setVisible(visible);
}
QSize VolumeSlider::iconSize() const
{
return d_ptr->muteButton.iconSize();
}
void VolumeSlider::setIconSize(const QSize &iconSize)
{
kDebug(602) << k_funcinfo << iconSize << endl;
d_ptr->muteButton.setIconSize(iconSize);
}
float VolumeSlider::maximumVolume() const
{
return d_ptr->slider.maximum() * 0.01;
}
void VolumeSlider::setMaximumVolume( float volume )
{
int max = static_cast<int>( volume * 100 );
d_ptr->slider.setMaximum(max);
setWhatsThis( i18n( "Use this slider to adjust the volume. The leftmost position is 0%, the rightmost is %1%" , max ) );
}
Qt::Orientation VolumeSlider::orientation() const
{
return d_ptr->slider.orientation();
}
void VolumeSlider::setOrientation(Qt::Orientation o)
{
Q_D(VolumeSlider);
Qt::Alignment align = (o == Qt::Horizontal ? Qt::AlignVCenter : Qt::AlignHCenter);
d->layout.setAlignment(&d->muteButton, align);
d->layout.setAlignment(&d->slider, align);
d->layout.setDirection(o == Qt::Horizontal ? QBoxLayout::LeftToRight : QBoxLayout::TopToBottom);
d->slider.setOrientation(o);
}
void VolumeSlider::setAudioOutput(AudioOutput *output)
{
if (!output) {
return;
}
Q_D(VolumeSlider);
d->output = output;
d->slider.setValue(qRound(100 * output->volume()));
d->slider.setEnabled(true);
connect(output, SIGNAL(destroyed()), SLOT(_k_outputDestroyed()));
connect(&d->slider, SIGNAL(valueChanged(int)), SLOT(_k_sliderChanged(int)));
connect(&d->muteButton, SIGNAL(clicked()), SLOT(_k_buttonClicked()));
connect(output, SIGNAL(volumeChanged(float)), SLOT(_k_volumeChanged(float)));
connect(output, SIGNAL(mutedChanged(bool)), SLOT(_k_mutedChanged(bool)));
}
void VolumeSliderPrivate::_k_buttonClicked()
{
if (output) {
output->setMuted(!output->isMuted());
}
}
void VolumeSliderPrivate::_k_mutedChanged(bool muted)
{
Q_Q(VolumeSlider);
if (muted) {
q->setToolTip(i18n("Muted"));
muteButton.setIcon(mutedIcon);
} else {
q->setToolTip(i18n("Volume: %1%", static_cast<int>(output->volume() * 100.0f)));
muteButton.setIcon(volumeIcon);
}
}
void VolumeSliderPrivate::_k_sliderChanged(int value)
{
Q_Q(VolumeSlider);
if (!output->isMuted()) {
q->setToolTip(i18n("Volume: %1%", value));
}
if (output) {
ignoreVolumeChange = true;
output->setVolume((static_cast<float>(value)) * 0.01f);
ignoreVolumeChange = false;
}
}
void VolumeSliderPrivate::_k_volumeChanged(float value)
{
if (!ignoreVolumeChange) {
slider.setValue(qRound(100 * value));
}
}
void VolumeSliderPrivate::_k_outputDestroyed()
{
output = 0;
slider.setValue(100);
slider.setEnabled(false);
}
bool VolumeSlider::hasTracking() const
{
return d_ptr->slider.hasTracking();
}
void VolumeSlider::setTracking(bool tracking)
{
d_ptr->slider.setTracking(tracking);
}
int VolumeSlider::pageStep() const
{
return d_ptr->slider.pageStep();
}
void VolumeSlider::setPageStep(int milliseconds)
{
d_ptr->slider.setPageStep(milliseconds);
}
int VolumeSlider::singleStep() const
{
return d_ptr->slider.singleStep();
}
void VolumeSlider::setSingleStep(int milliseconds)
{
d_ptr->slider.setSingleStep(milliseconds);
}
} // namespace Phonon
#include "volumeslider.moc"
// vim: sw=4 et
<|endoftext|>
|
<commit_before>//=======================================================================
// Copyright Baptiste Wicht 2011.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
//=======================================================================
#include <string>
#include <iostream>
#include "Options.hpp"
using namespace eddic;
bool eddic::OptimizeIntegers;
bool eddic::OptimizeStrings;
bool eddic::WarningUnused;
po::variables_map eddic::options;
po::options_description desc("Usage : edic [options]");
bool eddic::parseOptions(int argc, const char* argv[]) {
try {
desc.add_options()
("help,h", "Generate this help message")
("assembly,S", "Generate only the assembly")
("version", "Print the version of eddic")
("output,o", po::value<std::string>()->default_value("a.out"), "Set the name of the executable")
("optimize-all", "Enable all optimizations")
("optimize-strings", po::bool_switch(&OptimizeStrings), "Enable the optimizations on strings")
("optimize-integers", po::bool_switch(&OptimizeIntegers), "Enable the optimizations on integers")
("warning-all,Wall", "Enable all the warnings")
("warning-unused,Wunused", po::bool_switch(&WarningUnused), "Enable warnings for unused variables, parameters and functions")
("input", po::value<std::string>(), "Input file");
po::positional_options_description p;
p.add("input", -1);
po::store(po::command_line_parser(argc, argv).options(desc).positional(p).run(), options);
po::notify(options);
if(options.count("optimize-all")){
OptimizeStrings = OptimizeIntegers = true;
}
if(options.count("warning-all")){
WarningUnused = true;
}
} catch (const po::ambiguous_option& e) {
std::cout << "Invalid command line options : " << e.what() << std::endl;
return false;
} catch (const po::unknown_option& e) {
std::cout << "Invalid command line options : " << e.what() << std::endl;
return false;
} catch (const po::multiple_occurrences& e) {
std::cout << "Only one file can be compiled" << std::endl;
return false;
}
return true;
}
void eddic::printHelp(){
std::cout << desc << std::endl;
}
void eddic::printVersion(){
std::cout << "eddic version 0.5.1" << std::endl;
}
<commit_msg>Apparently, upper case option cannot be used like that<commit_after>//=======================================================================
// Copyright Baptiste Wicht 2011.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
//=======================================================================
#include <string>
#include <iostream>
#include "Options.hpp"
using namespace eddic;
bool eddic::OptimizeIntegers;
bool eddic::OptimizeStrings;
bool eddic::WarningUnused;
po::variables_map eddic::options;
po::options_description desc("Usage : edic [options]");
bool eddic::parseOptions(int argc, const char* argv[]) {
try {
desc.add_options()
("help,h", "Generate this help message")
("assembly,S", "Generate only the assembly")
("version", "Print the version of eddic")
("output,o", po::value<std::string>()->default_value("a.out"), "Set the name of the executable")
("optimize-all", "Enable all optimizations")
("optimize-strings", po::bool_switch(&OptimizeStrings), "Enable the optimizations on strings")
("optimize-integers", po::bool_switch(&OptimizeIntegers), "Enable the optimizations on integers")
("warning-all", "Enable all the warnings")
("warning-unused", po::bool_switch(&WarningUnused), "Enable warnings for unused variables, parameters and functions")
("input", po::value<std::string>(), "Input file");
po::positional_options_description p;
p.add("input", -1);
po::store(po::command_line_parser(argc, argv).options(desc).positional(p).run(), options);
po::notify(options);
if(options.count("optimize-all")){
OptimizeStrings = OptimizeIntegers = true;
}
if(options.count("warning-all")){
WarningUnused = true;
}
} catch (const po::ambiguous_option& e) {
std::cout << "Invalid command line options : " << e.what() << std::endl;
return false;
} catch (const po::unknown_option& e) {
std::cout << "Invalid command line options : " << e.what() << std::endl;
return false;
} catch (const po::multiple_occurrences& e) {
std::cout << "Only one file can be compiled" << std::endl;
return false;
}
return true;
}
void eddic::printHelp(){
std::cout << desc << std::endl;
}
void eddic::printVersion(){
std::cout << "eddic version 0.5.1" << std::endl;
}
<|endoftext|>
|
<commit_before>/****************************************************************************
*
* (c) 2009-2016 QGROUNDCONTROL PROJECT <http://www.qgroundcontrol.org>
*
* QGroundControl is licensed according to the terms in the file
* COPYING.md in the root of the source code directory.
*
****************************************************************************/
// We keep the list of all unit tests in a global location so it's easier to see which
// ones are enabled/disabled
#include "FactSystemTestGeneric.h"
#include "FactSystemTestPX4.h"
#include "FileDialogTest.h"
#include "FlightGearTest.h"
#include "GeoTest.h"
#include "LinkManagerTest.h"
#include "MessageBoxTest.h"
#include "MissionItemTest.h"
#include "SimpleMissionItemTest.h"
#include "ComplexMissionItemTest.h"
#include "MissionControllerTest.h"
#include "MissionManagerTest.h"
#include "RadioConfigTest.h"
#include "MavlinkLogTest.h"
#include "MainWindowTest.h"
#include "FileManagerTest.h"
#include "TCPLinkTest.h"
#include "ParameterManagerTest.h"
#include "MissionCommandTreeTest.h"
#include "LogDownloadTest.h"
UT_REGISTER_TEST(FactSystemTestGeneric)
UT_REGISTER_TEST(FactSystemTestPX4)
UT_REGISTER_TEST(FileDialogTest)
UT_REGISTER_TEST(FlightGearUnitTest)
UT_REGISTER_TEST(GeoTest)
UT_REGISTER_TEST(LinkManagerTest)
UT_REGISTER_TEST(MavlinkLogTest)
UT_REGISTER_TEST(MessageBoxTest)
UT_REGISTER_TEST(MissionItemTest)
UT_REGISTER_TEST(SimpleMissionItemTest)
UT_REGISTER_TEST(ComplexMissionItemTest)
UT_REGISTER_TEST(MissionControllerTest)
UT_REGISTER_TEST(MissionManagerTest)
UT_REGISTER_TEST(RadioConfigTest)
UT_REGISTER_TEST(TCPLinkTest)
UT_REGISTER_TEST(FileManagerTest)
UT_REGISTER_TEST(ParameterManagerTest)
UT_REGISTER_TEST(MissionCommandTreeTest)
UT_REGISTER_TEST(LogDownloadTest)
// List of unit test which are currently disabled.
// If disabling a new test, include reason in comment.
// FIXME: Temporarily disabled until this can be stabilized
//UT_REGISTER_TEST(MainWindowTest)
<commit_msg>Remove FileManager unit test<commit_after>/****************************************************************************
*
* (c) 2009-2016 QGROUNDCONTROL PROJECT <http://www.qgroundcontrol.org>
*
* QGroundControl is licensed according to the terms in the file
* COPYING.md in the root of the source code directory.
*
****************************************************************************/
// We keep the list of all unit tests in a global location so it's easier to see which
// ones are enabled/disabled
#include "FactSystemTestGeneric.h"
#include "FactSystemTestPX4.h"
#include "FileDialogTest.h"
#include "FlightGearTest.h"
#include "GeoTest.h"
#include "LinkManagerTest.h"
#include "MessageBoxTest.h"
#include "MissionItemTest.h"
#include "SimpleMissionItemTest.h"
#include "ComplexMissionItemTest.h"
#include "MissionControllerTest.h"
#include "MissionManagerTest.h"
#include "RadioConfigTest.h"
#include "MavlinkLogTest.h"
#include "MainWindowTest.h"
#include "FileManagerTest.h"
#include "TCPLinkTest.h"
#include "ParameterManagerTest.h"
#include "MissionCommandTreeTest.h"
#include "LogDownloadTest.h"
UT_REGISTER_TEST(FactSystemTestGeneric)
UT_REGISTER_TEST(FactSystemTestPX4)
UT_REGISTER_TEST(FileDialogTest)
UT_REGISTER_TEST(FlightGearUnitTest)
UT_REGISTER_TEST(GeoTest)
UT_REGISTER_TEST(LinkManagerTest)
UT_REGISTER_TEST(MavlinkLogTest)
UT_REGISTER_TEST(MessageBoxTest)
UT_REGISTER_TEST(MissionItemTest)
UT_REGISTER_TEST(SimpleMissionItemTest)
UT_REGISTER_TEST(ComplexMissionItemTest)
UT_REGISTER_TEST(MissionControllerTest)
UT_REGISTER_TEST(MissionManagerTest)
UT_REGISTER_TEST(RadioConfigTest)
UT_REGISTER_TEST(TCPLinkTest)
UT_REGISTER_TEST(ParameterManagerTest)
UT_REGISTER_TEST(MissionCommandTreeTest)
UT_REGISTER_TEST(LogDownloadTest)
// List of unit test which are currently disabled.
// If disabling a new test, include reason in comment.
// FIXME: Temporarily disabled until this can be stabilized
//UT_REGISTER_TEST(MainWindowTest)
// Onboard file support has been removed until it can be make to work correctly
//UT_REGISTER_TEST(FileManagerTest)
<|endoftext|>
|
<commit_before>// Copyright (c) 2021 The PIVX developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or https://www.opensource.org/licenses/mit-license.php.
#include "qt/pivx/governancemodel.h"
#include "budget/budgetmanager.h"
#include "budget/budgetutil.h"
#include "destination_io.h"
#include "guiconstants.h"
#include "masternode-sync.h"
#include "script/standard.h"
#include "qt/transactiontablemodel.h"
#include "qt/transactionrecord.h"
#include "qt/pivx/mnmodel.h"
#include "utilmoneystr.h"
#include "utilstrencodings.h"
#include "walletmodel.h"
#include <algorithm>
#include <QTimer>
std::string ProposalInfo::statusToStr() const
{
switch(status) {
case WAITING_FOR_APPROVAL:
return _("Waiting");
case PASSING:
return _("Passing");
case PASSING_NOT_FUNDED:
return _("Passing not funded");
case NOT_PASSING:
return _("Not Passing");
case FINISHED:
return _("Finished");
}
return "";
}
GovernanceModel::GovernanceModel(ClientModel* _clientModel, MNModel* _mnModel) : clientModel(_clientModel), mnModel(_mnModel) {}
GovernanceModel::~GovernanceModel() {}
void GovernanceModel::setWalletModel(WalletModel* _walletModel)
{
walletModel = _walletModel;
connect(walletModel->getTransactionTableModel(), &TransactionTableModel::txLoaded, this, &GovernanceModel::txLoaded);
}
ProposalInfo GovernanceModel::buildProposalInfo(const CBudgetProposal* prop, bool isPassing, bool isPending)
{
CTxDestination recipient;
ExtractDestination(prop->GetPayee(), recipient);
// Calculate status
int votesYes = prop->GetYeas();
int votesNo = prop->GetNays();
int remainingPayments = prop->GetRemainingPaymentCount(clientModel->getLastBlockProcessedHeight());
ProposalInfo::Status status;
if (isPending) {
// Proposal waiting for confirmation to be broadcasted.
status = ProposalInfo::WAITING_FOR_APPROVAL;
} else {
if (remainingPayments <= 0) {
status = ProposalInfo::FINISHED;
} else if (isPassing) {
status = ProposalInfo::PASSING;
} else if (votesYes > votesNo) {
status = ProposalInfo::PASSING_NOT_FUNDED;
} else {
status = ProposalInfo::NOT_PASSING;
}
}
return ProposalInfo(prop->GetHash(),
prop->GetName(),
prop->GetURL(),
votesYes,
votesNo,
Standard::EncodeDestination(recipient),
prop->GetAmount(),
prop->GetTotalPaymentCount(),
remainingPayments,
status,
prop->GetBlockStart(),
prop->GetBlockEnd());
}
std::list<ProposalInfo> GovernanceModel::getProposals(const ProposalInfo::Status* filterByStatus, bool filterFinished)
{
if (!clientModel) return {};
std::list<ProposalInfo> ret;
std::vector<CBudgetProposal> budget = g_budgetman.GetBudget();
allocatedAmount = 0;
for (const auto& prop : g_budgetman.GetAllProposalsOrdered()) {
bool isPassing = std::find(budget.begin(), budget.end(), *prop) != budget.end();
ProposalInfo propInfo = buildProposalInfo(prop, isPassing, false);
if (filterFinished && propInfo.isFinished()) continue;
if (!filterByStatus || propInfo.status == *filterByStatus) {
ret.emplace_back(propInfo);
}
if (isPassing) allocatedAmount += prop->GetAmount();
}
// Add pending proposals
for (const auto& prop : waitingPropsForConfirmations) {
ProposalInfo propInfo = buildProposalInfo(&prop, false, true);
if (!filterByStatus || propInfo.status == *filterByStatus) {
ret.emplace_back(propInfo);
}
}
return ret;
}
bool GovernanceModel::hasProposals()
{
return g_budgetman.HasAnyProposal() || !waitingPropsForConfirmations.empty();
}
CAmount GovernanceModel::getMaxAvailableBudgetAmount() const
{
return g_budgetman.GetTotalBudget(clientModel->getNumBlocks());
}
int GovernanceModel::getNumBlocksPerBudgetCycle() const
{
return Params().GetConsensus().nBudgetCycleBlocks;
}
int GovernanceModel::getProposalVoteUpdateMinTime() const
{
return BUDGET_VOTE_UPDATE_MIN;
}
int GovernanceModel::getPropMaxPaymentsCount() const
{
return Params().GetConsensus().nMaxProposalPayments;
}
CAmount GovernanceModel::getProposalFeeAmount() const
{
return PROPOSAL_FEE_TX;
}
int GovernanceModel::getNextSuperblockHeight() const
{
const int nBlocksPerCycle = getNumBlocksPerBudgetCycle();
const int chainHeight = clientModel->getNumBlocks();
return chainHeight - chainHeight % nBlocksPerCycle + nBlocksPerCycle;
}
std::vector<VoteInfo> GovernanceModel::getLocalMNsVotesForProposal(const ProposalInfo& propInfo)
{
// First, get the local masternodes
std::vector<std::pair<COutPoint, std::string>> vecLocalMn;
for (int i = 0; i < mnModel->rowCount(); ++i) {
vecLocalMn.emplace_back(std::make_pair(
COutPoint(uint256S(mnModel->index(i, MNModel::COLLATERAL_ID, QModelIndex()).data().toString().toStdString()),
mnModel->index(i, MNModel::COLLATERAL_OUT_INDEX, QModelIndex()).data().toInt()),
mnModel->index(i, MNModel::ALIAS, QModelIndex()).data().toString().toStdString())
);
}
std::vector<VoteInfo> localVotes;
{
LOCK(g_budgetman.cs_proposals); // future: encapsulate this mutex lock.
// Get the budget proposal, get the votes, then loop over it and return the ones that correspond to the local masternodes here.
CBudgetProposal* prop = g_budgetman.FindProposal(propInfo.id);
const auto& mapVotes = prop->GetVotes();
for (const auto& it : mapVotes) {
for (const auto& mn : vecLocalMn) {
if (it.first == mn.first && it.second.IsValid()) {
localVotes.emplace_back(mn.first, (VoteInfo::VoteDirection) it.second.GetDirection(), mn.second, it.second.GetTime());
break;
}
}
}
}
return localVotes;
}
OperationResult GovernanceModel::validatePropURL(const QString& url) const
{
std::string strError;
return {validateURL(url.toStdString(), strError, PROP_URL_MAX_SIZE), strError};
}
OperationResult GovernanceModel::validatePropAmount(CAmount amount) const
{
if (amount < PROPOSAL_MIN_AMOUNT) { // Future: move constant to a budget interface.
return {false, strprintf("Amount below the minimum of %s PIV", FormatMoney(PROPOSAL_MIN_AMOUNT))};
}
if (amount > getMaxAvailableBudgetAmount()) {
return {false, strprintf("Amount exceeding the maximum available of %s PIV", FormatMoney(getMaxAvailableBudgetAmount()))};
}
return {true};
}
OperationResult GovernanceModel::validatePropPaymentCount(int paymentCount) const
{
if (paymentCount < 1) return { false, "Invalid payment count, must be greater than zero."};
int nMaxPayments = getPropMaxPaymentsCount();
if (paymentCount > nMaxPayments) {
return { false, strprintf("Invalid payment count, cannot be greater than %d", nMaxPayments)};
}
return {true};
}
bool GovernanceModel::isTierTwoSync()
{
return masternodeSync.IsBlockchainSynced();
}
OperationResult GovernanceModel::createProposal(const std::string& strProposalName,
const std::string& strURL,
int nPaymentCount,
CAmount nAmount,
const std::string& strPaymentAddr)
{
// First get the next superblock height
int nBlockStart = getNextSuperblockHeight();
// Parse address
const CTxDestination* dest = Standard::GetTransparentDestination(Standard::DecodeDestination(strPaymentAddr));
if (!dest) return {false, "invalid recipient address for the proposal"};
CScript scriptPubKey = GetScriptForDestination(*dest);
// Validate proposal
CBudgetProposal proposal(strProposalName, strURL, nPaymentCount, scriptPubKey, nAmount, nBlockStart, UINT256_ZERO);
if (!proposal.IsWellFormed(g_budgetman.GetTotalBudget(proposal.GetBlockStart()))) {
return {false, strprintf("Proposal is not valid %s", proposal.IsInvalidReason())};
}
// Craft and send transaction.
auto opRes = walletModel->createAndSendProposalFeeTx(proposal);
if (!opRes) return opRes;
scheduleBroadcast(proposal);
return {true};
}
OperationResult GovernanceModel::voteForProposal(const ProposalInfo& prop,
bool isVotePositive,
const std::vector<std::string>& mnVotingAlias)
{
UniValue ret; // future: don't use UniValue here.
for (const auto& mnAlias : mnVotingAlias) {
bool fLegacyMN = true; // For now, only legacy MNs
ret = mnBudgetVoteInner(nullptr,
fLegacyMN,
prop.id,
false,
isVotePositive ? CBudgetVote::VoteDirection::VOTE_YES : CBudgetVote::VoteDirection::VOTE_NO,
mnAlias);
if (ret.exists("detail") && ret["detail"].isArray()) {
const UniValue& obj = ret["detail"].get_array()[0];
if (obj["result"].getValStr() != "success") {
return {false, obj["error"].getValStr()};
}
}
}
// add more information with ret["overall"]
return {true};
}
void GovernanceModel::scheduleBroadcast(const CBudgetProposal& proposal)
{
// Cache the proposal to be sent as soon as it gets the minimum required confirmations
// without requiring user interaction
waitingPropsForConfirmations.emplace_back(proposal);
// Launch timer if it's not already running
if (!pollTimer) pollTimer = new QTimer(this);
if (!pollTimer->isActive()) {
connect(pollTimer, &QTimer::timeout, this, &GovernanceModel::pollGovernanceChanged);
pollTimer->start(MODEL_UPDATE_DELAY * 60 * (walletModel->isTestNetwork() ? 0.5 : 3.5)); // Every 3.5 minutes
}
}
void GovernanceModel::pollGovernanceChanged()
{
if (!isTierTwoSync()) return;
int chainHeight = clientModel->getNumBlocks();
// Try to broadcast any pending for confirmations proposal
auto it = waitingPropsForConfirmations.begin();
while (it != waitingPropsForConfirmations.end()) {
// Remove expired proposals
if (it->IsExpired(clientModel->getNumBlocks())) {
it = waitingPropsForConfirmations.erase(it);
continue;
}
// Try to add it
if (!g_budgetman.AddProposal(*it)) {
LogPrint(BCLog::QT, "Cannot broadcast budget proposal - %s", it->IsInvalidReason());
// Remove proposals who due a reorg lost their fee tx
if (it->IsInvalidReason().find("Can't find collateral tx") != std::string::npos) {
// future: notify the user about it.
it = waitingPropsForConfirmations.erase(it);
continue;
}
// Check if the proposal didn't exceed the superblock start height
if (chainHeight > it->GetBlockStart()) {
// Edge case, the proposal was never broadcasted before the next superblock, can be removed.
// future: notify the user about it.
it = waitingPropsForConfirmations.erase(it);
} else {
it++;
}
continue;
}
it->Relay();
it = waitingPropsForConfirmations.erase(it);
}
// If there are no more waiting proposals, turn the timer off.
if (waitingPropsForConfirmations.empty()) {
pollTimer->stop();
}
}
void GovernanceModel::stop()
{
if (pollTimer && pollTimer->isActive()) {
pollTimer->stop();
}
}
void GovernanceModel::txLoaded(const QString& id, const int txType, const int txStatus)
{
if (txType == TransactionRecord::SendToNobody) {
// If the tx is not longer available in the mainchain, drop it.
if (txStatus == TransactionStatus::Conflicted ||
txStatus == TransactionStatus::NotAccepted) {
return;
}
// If this is a proposal fee, parse it.
const auto& wtx = walletModel->getTx(uint256S(id.toStdString()));
assert(wtx);
const auto& it = wtx->mapValue.find("proposal");
if (it != wtx->mapValue.end()) {
const std::vector<unsigned char> vec = ParseHex(it->second);
if (vec.empty()) return;
CDataStream ss(vec, SER_DISK, CLIENT_VERSION);
CBudgetProposal proposal;
ss >> proposal;
if (!g_budgetman.HaveProposal(proposal.GetHash()) &&
!proposal.IsExpired(clientModel->getNumBlocks()) &&
proposal.GetBlockStart() < clientModel->getNumBlocks()) {
scheduleBroadcast(proposal);
}
}
}
}
<commit_msg>Bugfix GUI: proposal broadcast should be scheduled only if the block start has not passed yet<commit_after>// Copyright (c) 2021 The PIVX developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or https://www.opensource.org/licenses/mit-license.php.
#include "qt/pivx/governancemodel.h"
#include "budget/budgetmanager.h"
#include "budget/budgetutil.h"
#include "destination_io.h"
#include "guiconstants.h"
#include "masternode-sync.h"
#include "script/standard.h"
#include "qt/transactiontablemodel.h"
#include "qt/transactionrecord.h"
#include "qt/pivx/mnmodel.h"
#include "utilmoneystr.h"
#include "utilstrencodings.h"
#include "walletmodel.h"
#include <algorithm>
#include <QTimer>
std::string ProposalInfo::statusToStr() const
{
switch(status) {
case WAITING_FOR_APPROVAL:
return _("Waiting");
case PASSING:
return _("Passing");
case PASSING_NOT_FUNDED:
return _("Passing not funded");
case NOT_PASSING:
return _("Not Passing");
case FINISHED:
return _("Finished");
}
return "";
}
GovernanceModel::GovernanceModel(ClientModel* _clientModel, MNModel* _mnModel) : clientModel(_clientModel), mnModel(_mnModel) {}
GovernanceModel::~GovernanceModel() {}
void GovernanceModel::setWalletModel(WalletModel* _walletModel)
{
walletModel = _walletModel;
connect(walletModel->getTransactionTableModel(), &TransactionTableModel::txLoaded, this, &GovernanceModel::txLoaded);
}
ProposalInfo GovernanceModel::buildProposalInfo(const CBudgetProposal* prop, bool isPassing, bool isPending)
{
CTxDestination recipient;
ExtractDestination(prop->GetPayee(), recipient);
// Calculate status
int votesYes = prop->GetYeas();
int votesNo = prop->GetNays();
int remainingPayments = prop->GetRemainingPaymentCount(clientModel->getLastBlockProcessedHeight());
ProposalInfo::Status status;
if (isPending) {
// Proposal waiting for confirmation to be broadcasted.
status = ProposalInfo::WAITING_FOR_APPROVAL;
} else {
if (remainingPayments <= 0) {
status = ProposalInfo::FINISHED;
} else if (isPassing) {
status = ProposalInfo::PASSING;
} else if (votesYes > votesNo) {
status = ProposalInfo::PASSING_NOT_FUNDED;
} else {
status = ProposalInfo::NOT_PASSING;
}
}
return ProposalInfo(prop->GetHash(),
prop->GetName(),
prop->GetURL(),
votesYes,
votesNo,
Standard::EncodeDestination(recipient),
prop->GetAmount(),
prop->GetTotalPaymentCount(),
remainingPayments,
status,
prop->GetBlockStart(),
prop->GetBlockEnd());
}
std::list<ProposalInfo> GovernanceModel::getProposals(const ProposalInfo::Status* filterByStatus, bool filterFinished)
{
if (!clientModel) return {};
std::list<ProposalInfo> ret;
std::vector<CBudgetProposal> budget = g_budgetman.GetBudget();
allocatedAmount = 0;
for (const auto& prop : g_budgetman.GetAllProposalsOrdered()) {
bool isPassing = std::find(budget.begin(), budget.end(), *prop) != budget.end();
ProposalInfo propInfo = buildProposalInfo(prop, isPassing, false);
if (filterFinished && propInfo.isFinished()) continue;
if (!filterByStatus || propInfo.status == *filterByStatus) {
ret.emplace_back(propInfo);
}
if (isPassing) allocatedAmount += prop->GetAmount();
}
// Add pending proposals
for (const auto& prop : waitingPropsForConfirmations) {
ProposalInfo propInfo = buildProposalInfo(&prop, false, true);
if (!filterByStatus || propInfo.status == *filterByStatus) {
ret.emplace_back(propInfo);
}
}
return ret;
}
bool GovernanceModel::hasProposals()
{
return g_budgetman.HasAnyProposal() || !waitingPropsForConfirmations.empty();
}
CAmount GovernanceModel::getMaxAvailableBudgetAmount() const
{
return g_budgetman.GetTotalBudget(clientModel->getNumBlocks());
}
int GovernanceModel::getNumBlocksPerBudgetCycle() const
{
return Params().GetConsensus().nBudgetCycleBlocks;
}
int GovernanceModel::getProposalVoteUpdateMinTime() const
{
return BUDGET_VOTE_UPDATE_MIN;
}
int GovernanceModel::getPropMaxPaymentsCount() const
{
return Params().GetConsensus().nMaxProposalPayments;
}
CAmount GovernanceModel::getProposalFeeAmount() const
{
return PROPOSAL_FEE_TX;
}
int GovernanceModel::getNextSuperblockHeight() const
{
const int nBlocksPerCycle = getNumBlocksPerBudgetCycle();
const int chainHeight = clientModel->getNumBlocks();
return chainHeight - chainHeight % nBlocksPerCycle + nBlocksPerCycle;
}
std::vector<VoteInfo> GovernanceModel::getLocalMNsVotesForProposal(const ProposalInfo& propInfo)
{
// First, get the local masternodes
std::vector<std::pair<COutPoint, std::string>> vecLocalMn;
for (int i = 0; i < mnModel->rowCount(); ++i) {
vecLocalMn.emplace_back(std::make_pair(
COutPoint(uint256S(mnModel->index(i, MNModel::COLLATERAL_ID, QModelIndex()).data().toString().toStdString()),
mnModel->index(i, MNModel::COLLATERAL_OUT_INDEX, QModelIndex()).data().toInt()),
mnModel->index(i, MNModel::ALIAS, QModelIndex()).data().toString().toStdString())
);
}
std::vector<VoteInfo> localVotes;
{
LOCK(g_budgetman.cs_proposals); // future: encapsulate this mutex lock.
// Get the budget proposal, get the votes, then loop over it and return the ones that correspond to the local masternodes here.
CBudgetProposal* prop = g_budgetman.FindProposal(propInfo.id);
const auto& mapVotes = prop->GetVotes();
for (const auto& it : mapVotes) {
for (const auto& mn : vecLocalMn) {
if (it.first == mn.first && it.second.IsValid()) {
localVotes.emplace_back(mn.first, (VoteInfo::VoteDirection) it.second.GetDirection(), mn.second, it.second.GetTime());
break;
}
}
}
}
return localVotes;
}
OperationResult GovernanceModel::validatePropURL(const QString& url) const
{
std::string strError;
return {validateURL(url.toStdString(), strError, PROP_URL_MAX_SIZE), strError};
}
OperationResult GovernanceModel::validatePropAmount(CAmount amount) const
{
if (amount < PROPOSAL_MIN_AMOUNT) { // Future: move constant to a budget interface.
return {false, strprintf("Amount below the minimum of %s PIV", FormatMoney(PROPOSAL_MIN_AMOUNT))};
}
if (amount > getMaxAvailableBudgetAmount()) {
return {false, strprintf("Amount exceeding the maximum available of %s PIV", FormatMoney(getMaxAvailableBudgetAmount()))};
}
return {true};
}
OperationResult GovernanceModel::validatePropPaymentCount(int paymentCount) const
{
if (paymentCount < 1) return { false, "Invalid payment count, must be greater than zero."};
int nMaxPayments = getPropMaxPaymentsCount();
if (paymentCount > nMaxPayments) {
return { false, strprintf("Invalid payment count, cannot be greater than %d", nMaxPayments)};
}
return {true};
}
bool GovernanceModel::isTierTwoSync()
{
return masternodeSync.IsBlockchainSynced();
}
OperationResult GovernanceModel::createProposal(const std::string& strProposalName,
const std::string& strURL,
int nPaymentCount,
CAmount nAmount,
const std::string& strPaymentAddr)
{
// First get the next superblock height
int nBlockStart = getNextSuperblockHeight();
// Parse address
const CTxDestination* dest = Standard::GetTransparentDestination(Standard::DecodeDestination(strPaymentAddr));
if (!dest) return {false, "invalid recipient address for the proposal"};
CScript scriptPubKey = GetScriptForDestination(*dest);
// Validate proposal
CBudgetProposal proposal(strProposalName, strURL, nPaymentCount, scriptPubKey, nAmount, nBlockStart, UINT256_ZERO);
if (!proposal.IsWellFormed(g_budgetman.GetTotalBudget(proposal.GetBlockStart()))) {
return {false, strprintf("Proposal is not valid %s", proposal.IsInvalidReason())};
}
// Craft and send transaction.
auto opRes = walletModel->createAndSendProposalFeeTx(proposal);
if (!opRes) return opRes;
scheduleBroadcast(proposal);
return {true};
}
OperationResult GovernanceModel::voteForProposal(const ProposalInfo& prop,
bool isVotePositive,
const std::vector<std::string>& mnVotingAlias)
{
UniValue ret; // future: don't use UniValue here.
for (const auto& mnAlias : mnVotingAlias) {
bool fLegacyMN = true; // For now, only legacy MNs
ret = mnBudgetVoteInner(nullptr,
fLegacyMN,
prop.id,
false,
isVotePositive ? CBudgetVote::VoteDirection::VOTE_YES : CBudgetVote::VoteDirection::VOTE_NO,
mnAlias);
if (ret.exists("detail") && ret["detail"].isArray()) {
const UniValue& obj = ret["detail"].get_array()[0];
if (obj["result"].getValStr() != "success") {
return {false, obj["error"].getValStr()};
}
}
}
// add more information with ret["overall"]
return {true};
}
void GovernanceModel::scheduleBroadcast(const CBudgetProposal& proposal)
{
// Cache the proposal to be sent as soon as it gets the minimum required confirmations
// without requiring user interaction
waitingPropsForConfirmations.emplace_back(proposal);
// Launch timer if it's not already running
if (!pollTimer) pollTimer = new QTimer(this);
if (!pollTimer->isActive()) {
connect(pollTimer, &QTimer::timeout, this, &GovernanceModel::pollGovernanceChanged);
pollTimer->start(MODEL_UPDATE_DELAY * 60 * (walletModel->isTestNetwork() ? 0.5 : 3.5)); // Every 3.5 minutes
}
}
void GovernanceModel::pollGovernanceChanged()
{
if (!isTierTwoSync()) return;
int chainHeight = clientModel->getNumBlocks();
// Try to broadcast any pending for confirmations proposal
auto it = waitingPropsForConfirmations.begin();
while (it != waitingPropsForConfirmations.end()) {
// Remove expired proposals
if (it->IsExpired(clientModel->getNumBlocks())) {
it = waitingPropsForConfirmations.erase(it);
continue;
}
// Try to add it
if (!g_budgetman.AddProposal(*it)) {
LogPrint(BCLog::QT, "Cannot broadcast budget proposal - %s", it->IsInvalidReason());
// Remove proposals which due a reorg lost their fee tx
if (it->IsInvalidReason().find("Can't find collateral tx") != std::string::npos) {
// future: notify the user about it.
it = waitingPropsForConfirmations.erase(it);
continue;
}
// Check if the proposal didn't exceed the superblock start height
if (chainHeight >= it->GetBlockStart()) {
// Edge case, the proposal was never broadcasted before the next superblock, can be removed.
// future: notify the user about it.
it = waitingPropsForConfirmations.erase(it);
} else {
it++;
}
continue;
}
it->Relay();
it = waitingPropsForConfirmations.erase(it);
}
// If there are no more waiting proposals, turn the timer off.
if (waitingPropsForConfirmations.empty()) {
pollTimer->stop();
}
}
void GovernanceModel::stop()
{
if (pollTimer && pollTimer->isActive()) {
pollTimer->stop();
}
}
void GovernanceModel::txLoaded(const QString& id, const int txType, const int txStatus)
{
if (txType == TransactionRecord::SendToNobody) {
// If the tx is not longer available in the mainchain, drop it.
if (txStatus == TransactionStatus::Conflicted ||
txStatus == TransactionStatus::NotAccepted) {
return;
}
// If this is a proposal fee, parse it.
const auto& wtx = walletModel->getTx(uint256S(id.toStdString()));
assert(wtx);
const auto& it = wtx->mapValue.find("proposal");
if (it != wtx->mapValue.end()) {
const std::vector<unsigned char> vec = ParseHex(it->second);
if (vec.empty()) return;
CDataStream ss(vec, SER_DISK, CLIENT_VERSION);
CBudgetProposal proposal;
ss >> proposal;
if (!g_budgetman.HaveProposal(proposal.GetHash()) &&
!proposal.IsExpired(clientModel->getNumBlocks()) &&
proposal.GetBlockStart() > clientModel->getNumBlocks()) {
scheduleBroadcast(proposal);
}
}
}
}
<|endoftext|>
|
<commit_before>#include "Printer.hpp"
#include "TerminalInfo.hpp"
#include <cstring>
namespace yb {
void Printer::deleteRows(int rows) {
output_ << std::string(rows, ' ');
cursor_backward(rows);
output_ << std::flush;
}
void Printer::clearTerminalLine() {
int pos, width;
if (!(pos = TerminalInfo::getCursorPosition())) return;
width = TerminalInfo::getWidth();
deleteRows(width - pos);
}
void Printer::printInColor(const char *buffer, Color color) {
output_ << "\e[" << static_cast<int>(color) << 'm' << buffer << "\e[0m";
}
void Printer::print(const char *text, Color color, int offset) {
clearTerminalLine();
if (offset)
cursor_forward(offset);
printInColor(text, color);
cursor_backward(std::strlen(text) + offset);
output_ << std::flush;
}
} // namespace yb
<commit_msg>Dummy checking if the output is a stdout<commit_after>#include "Printer.hpp"
#include "TerminalInfo.hpp"
#include <cstring>
#include <iostream>
// TODO: change "if (&output_ == &std::cout)" to something more convenient or move it out
namespace yb {
void Printer::deleteRows(int rows) {
output_ << std::string(rows, ' ');
cursor_backward(rows);
output_ << std::flush;
}
void Printer::clearTerminalLine() {
int pos, width;
if (!(pos = TerminalInfo::getCursorPosition())) return;
width = TerminalInfo::getWidth();
deleteRows(width - pos);
}
void Printer::printInColor(const char *buffer, Color color) {
if (&output_ == &std::cout)
output_ << "\e[" << static_cast<int>(color) << 'm';
output_ << buffer;
if (&output_ == &std::cout)
output_ << "\e[0m";
}
void Printer::print(const char *text, Color color, int offset) {
if (&output_ == &std::cout) {
clearTerminalLine();
if (offset)
cursor_forward(offset);
}
printInColor(text, color);
if (&output_ == &std::cout) {
cursor_backward(std::strlen(text) + offset);
}
output_ << std::flush;
}
} // namespace yb
<|endoftext|>
|
<commit_before>/*=========================================================================
Program: Visualization Library
Module: Renderer.cc
Language: C++
Date: $Date$
Version: $Revision$
This file is part of the Visualization Library. No part of this file or its
contents may be copied, reproduced or altered in any way without the express
written consent of the authors.
Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen 1993, 1994
=========================================================================*/
#include <stdlib.h>
#include <string.h>
#include <math.h>
#include "Renderer.hh"
#include "RenderW.hh"
vlRenderer::vlRenderer()
{
this->ActiveCamera = NULL;
this->Ambient[0] = 1;
this->Ambient[1] = 1;
this->Ambient[2] = 1;
this->Background[0] = 0;
this->Background[1] = 0;
this->Background[2] = 0;
this->DisplayPoint[0] = 0;
this->DisplayPoint[1] = 0;
this->DisplayPoint[2] = 0;
this->ViewPoint[0] = 0;
this->ViewPoint[1] = 0;
this->ViewPoint[2] = 0;
this->Viewport[0] = 0;
this->Viewport[1] = 0;
this->Viewport[2] = 1;
this->Viewport[3] = 1;
this->BackLight = 1;
this->Erase = 1;
this->StereoRender = 0;
this->Aspect[0] = this->Aspect[1] = 1.0;
}
void vlRenderer::SetActiveCamera(vlCamera *cam)
{
this->ActiveCamera = cam;
}
vlCamera *vlRenderer::GetActiveCamera()
{
return this->ActiveCamera;
}
void vlRenderer::AddLights(vlLight *light)
{
this->Lights.AddMember(light);
}
void vlRenderer::AddActors(vlActor *actor)
{
this->Actors.AddMember(actor);
}
void vlRenderer::DoLights()
{
vlLight *light1;
if (!this->UpdateLights())
{
cerr << this->GetClassName() << " : No lights are on, creating one.\n";
light1 = this->RenderWindow->MakeLight();
this->AddLights(light1);
light1->SetPosition(this->ActiveCamera->GetPosition());
light1->SetFocalPoint(this->ActiveCamera->GetFocalPoint());
this->UpdateLights();
}
}
void vlRenderer::DoCameras()
{
vlCamera *cam1;
if (!this->UpdateCameras())
{
cerr << this->GetClassName() << " : No cameras are on, creating one.\n";
cam1 = this->RenderWindow->MakeCamera();
this->SetActiveCamera(cam1);
this->ResetCamera();
this->UpdateCameras();
}
}
void vlRenderer::DoActors()
{
if (!this->UpdateActors())
{
cerr << "No actors are on.\n";
}
}
void vlRenderer::ResetCamera()
{
vlActor *anActor;
int num;
float *bounds;
float all_bounds[6];
float center[3];
float distance;
float width;
all_bounds[0] = all_bounds[2] = all_bounds[4] = LARGE_FLOAT;
all_bounds[1] = all_bounds[3] = all_bounds[5] = -LARGE_FLOAT;
// loop through actors
for (num = 0; num < this->Actors.GetNumberOfMembers(); num++)
{
anActor = this->Actors.GetMember(num);
// if it's invisible, we can skip the rest
if ( anActor->GetVisibility() )
{
bounds = anActor->GetBounds();
if (bounds[0] < all_bounds[0]) all_bounds[0] = bounds[0];
if (bounds[1] > all_bounds[1]) all_bounds[1] = bounds[1];
if (bounds[2] < all_bounds[2]) all_bounds[2] = bounds[2];
if (bounds[3] > all_bounds[3]) all_bounds[3] = bounds[3];
if (bounds[4] < all_bounds[4]) all_bounds[4] = bounds[4];
if (bounds[5] > all_bounds[5]) all_bounds[5] = bounds[5];
}
}
// now we have the bounds for all actors
center[0] = (all_bounds[0] + all_bounds[1])/2.0;
center[1] = (all_bounds[2] + all_bounds[3])/2.0;
center[2] = (all_bounds[4] + all_bounds[5])/2.0;
width = all_bounds[3] - all_bounds[2];
if (width < (all_bounds[1] - all_bounds[0]))
{
width = all_bounds[1] - all_bounds[0];
}
distance = 0.8*width/tan(this->ActiveCamera->GetViewAngle()*M_PI/360.0);
distance = distance + (all_bounds[5] - all_bounds[4])/2.0;
// update the camera
this->ActiveCamera->SetFocalPoint(center);
this->ActiveCamera->SetPosition(center[0],center[1],center[2]+distance);
this->ActiveCamera->SetViewUp(0,1,0);
this->ActiveCamera->SetClippingRange(distance/10.0,distance*5.0);
}
void vlRenderer::SetRenderWindow(vlRenderWindow *renwin)
{
this->RenderWindow = renwin;
}
void vlRenderer::DisplayToView()
{
float vx,vy,vz;
int sizex,sizey;
int *size;
/* get physical window dimensions */
size = this->RenderWindow->GetSize();
sizex = size[0];
sizey = size[1];
vx = 2.0 * (this->DisplayPoint[0] - sizex*this->Viewport[0])/
(sizex*(this->Viewport[2]-this->Viewport[0])) - 1.0;
vy = 2.0 * (this->DisplayPoint[1] - sizey*this->Viewport[1])/
(sizey*(this->Viewport[3]-this->Viewport[1])) - 1.0;
vz = this->DisplayPoint[2];
this->SetViewPoint(vx*this->Aspect[0],vy*this->Aspect[1],vz);
}
void vlRenderer::ViewToDisplay()
{
int dx,dy;
int sizex,sizey;
int *size;
/* get physical window dimensions */
size = this->RenderWindow->GetSize();
sizex = size[0];
sizey = size[1];
dx = (int)((this->ViewPoint[0]/this->Aspect[0] + 1.0) *
(sizex*(this->Viewport[2]-this->Viewport[0])) / 2.0 + 0.5 +
sizex*this->Viewport[0]);
dy = (int)((this->ViewPoint[1]/this->Aspect[1] + 1.0) *
(sizey*(this->Viewport[3]-this->Viewport[1])) / 2.0 + 0.5 +
sizey*this->Viewport[1]);
this->SetDisplayPoint(dx,dy,this->ViewPoint[2]);
}
void vlRenderer::ViewToWorld()
{
vlMatrix4x4 mat;
float result[4];
// get the perspective transformation from the active camera
mat = this->ActiveCamera->GetPerspectiveTransform();
// use the inverse matrix
mat.Invert();
// Transform point to world coordinates
result[0] = this->ViewPoint[0];
result[1] = this->ViewPoint[1];
result[2] = this->ViewPoint[2];
result[3] = 1.0;
mat.VectorMultiply(result,result);
// Get the transformed vector & set WorldPoint
this->SetWorldPoint(result);
}
void vlRenderer::WorldToView()
{
vlMatrix4x4 matrix;
float view[4];
float *world;
// get the perspective transformation from the active camera
matrix = this->ActiveCamera->GetPerspectiveTransform();
world = this->WorldPoint;
view[0] = world[0]*matrix[0][0] + world[1]*matrix[1][0] +
world[2]*matrix[2][0] + world[3]*matrix[3][0];
view[1] = world[0]*matrix[0][1] + world[1]*matrix[1][1] +
world[2]*matrix[2][1] + world[3]*matrix[3][1];
view[2] = world[0]*matrix[0][2] + world[1]*matrix[1][2] +
world[2]*matrix[2][2] + world[3]*matrix[3][2];
view[3] = world[0]*matrix[0][3] + world[1]*matrix[1][3] +
world[2]*matrix[2][3] + world[3]*matrix[3][3];
if (view[3] != 0.0)
{
this->SetViewPoint(view[0]/view[3],
view[1]/view[3],
view[2]/view[3]);
}
}
void vlRenderer::PrintSelf(ostream& os, vlIndent indent)
{
if (this->ShouldIPrint(vlRenderer::GetClassName()))
{
this->vlObject::PrintSelf(os,indent);
os << indent << "Actors:\n";
this->Actors.PrintSelf(os,indent.GetNextIndent());
os << indent << "Ambient: (" << this->Ambient[0] << ", "
<< this->Ambient[1] << ", " << this->Ambient[2] << ")\n";
os << indent << "Aspect: (" << this->Aspect[0] << ", "
<< this->Aspect[1] << ")\n";
os << indent << "Background: (" << this->Background[0] << ", "
<< this->Background[1] << ", " << this->Background[2] << ")\n";
os << indent << "Back Light: " << (this->BackLight ? "On\n" : "Off\n");
os << indent << "DisplayPoint: (" << this->DisplayPoint[0] << ", "
<< this->DisplayPoint[1] << ", " << this->DisplayPoint[2] << ")\n";
os << indent << "Erase: " << (this->Erase ? "On\n" : "Off\n");
os << indent << "Lights:\n";
this->Lights.PrintSelf(os,indent.GetNextIndent());
os << indent << "Stereo Render: "
<< (this->StereoRender ? "On\n":"Off\n");
os << indent << "ViewPoint: (" << this->ViewPoint[0] << ", "
<< this->ViewPoint[1] << ", " << this->ViewPoint[2] << ")\n";
os << indent << "Viewport: (" << this->Viewport[0] << ", "
<< this->Viewport[1] << ", " << this->Viewport[2] << ", "
<< this->Viewport[3] << ")\n";
}
}
<commit_msg>Minor indexing problem in reset camera<commit_after>/*=========================================================================
Program: Visualization Library
Module: Renderer.cc
Language: C++
Date: $Date$
Version: $Revision$
This file is part of the Visualization Library. No part of this file or its
contents may be copied, reproduced or altered in any way without the express
written consent of the authors.
Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen 1993, 1994
=========================================================================*/
#include <stdlib.h>
#include <string.h>
#include <math.h>
#include "Renderer.hh"
#include "RenderW.hh"
vlRenderer::vlRenderer()
{
this->ActiveCamera = NULL;
this->Ambient[0] = 1;
this->Ambient[1] = 1;
this->Ambient[2] = 1;
this->Background[0] = 0;
this->Background[1] = 0;
this->Background[2] = 0;
this->DisplayPoint[0] = 0;
this->DisplayPoint[1] = 0;
this->DisplayPoint[2] = 0;
this->ViewPoint[0] = 0;
this->ViewPoint[1] = 0;
this->ViewPoint[2] = 0;
this->Viewport[0] = 0;
this->Viewport[1] = 0;
this->Viewport[2] = 1;
this->Viewport[3] = 1;
this->BackLight = 1;
this->Erase = 1;
this->StereoRender = 0;
this->Aspect[0] = this->Aspect[1] = 1.0;
}
void vlRenderer::SetActiveCamera(vlCamera *cam)
{
this->ActiveCamera = cam;
}
vlCamera *vlRenderer::GetActiveCamera()
{
return this->ActiveCamera;
}
void vlRenderer::AddLights(vlLight *light)
{
this->Lights.AddMember(light);
}
void vlRenderer::AddActors(vlActor *actor)
{
this->Actors.AddMember(actor);
}
void vlRenderer::DoLights()
{
vlLight *light1;
if (!this->UpdateLights())
{
cerr << this->GetClassName() << " : No lights are on, creating one.\n";
light1 = this->RenderWindow->MakeLight();
this->AddLights(light1);
light1->SetPosition(this->ActiveCamera->GetPosition());
light1->SetFocalPoint(this->ActiveCamera->GetFocalPoint());
this->UpdateLights();
}
}
void vlRenderer::DoCameras()
{
vlCamera *cam1;
if (!this->UpdateCameras())
{
cerr << this->GetClassName() << " : No cameras are on, creating one.\n";
cam1 = this->RenderWindow->MakeCamera();
this->SetActiveCamera(cam1);
this->ResetCamera();
this->UpdateCameras();
}
}
void vlRenderer::DoActors()
{
if (!this->UpdateActors())
{
cerr << "No actors are on.\n";
}
}
void vlRenderer::ResetCamera()
{
vlActor *anActor;
int num;
float *bounds;
float all_bounds[6];
float center[3];
float distance;
float width;
all_bounds[0] = all_bounds[2] = all_bounds[4] = LARGE_FLOAT;
all_bounds[1] = all_bounds[3] = all_bounds[5] = -LARGE_FLOAT;
// loop through actors
for (num = 1; num <= this->Actors.GetNumberOfMembers(); num++)
{
anActor = this->Actors.GetMember(num);
// if it's invisible, we can skip the rest
if ( anActor->GetVisibility() )
{
bounds = anActor->GetBounds();
if (bounds[0] < all_bounds[0]) all_bounds[0] = bounds[0];
if (bounds[1] > all_bounds[1]) all_bounds[1] = bounds[1];
if (bounds[2] < all_bounds[2]) all_bounds[2] = bounds[2];
if (bounds[3] > all_bounds[3]) all_bounds[3] = bounds[3];
if (bounds[4] < all_bounds[4]) all_bounds[4] = bounds[4];
if (bounds[5] > all_bounds[5]) all_bounds[5] = bounds[5];
}
}
// now we have the bounds for all actors
center[0] = (all_bounds[0] + all_bounds[1])/2.0;
center[1] = (all_bounds[2] + all_bounds[3])/2.0;
center[2] = (all_bounds[4] + all_bounds[5])/2.0;
width = all_bounds[3] - all_bounds[2];
if (width < (all_bounds[1] - all_bounds[0]))
{
width = all_bounds[1] - all_bounds[0];
}
distance = 0.8*width/tan(this->ActiveCamera->GetViewAngle()*M_PI/360.0);
distance = distance + (all_bounds[5] - all_bounds[4])/2.0;
// update the camera
this->ActiveCamera->SetFocalPoint(center);
this->ActiveCamera->SetPosition(center[0],center[1],center[2]+distance);
this->ActiveCamera->SetViewUp(0,1,0);
this->ActiveCamera->SetClippingRange(distance/10.0,distance*5.0);
}
void vlRenderer::SetRenderWindow(vlRenderWindow *renwin)
{
this->RenderWindow = renwin;
}
void vlRenderer::DisplayToView()
{
float vx,vy,vz;
int sizex,sizey;
int *size;
/* get physical window dimensions */
size = this->RenderWindow->GetSize();
sizex = size[0];
sizey = size[1];
vx = 2.0 * (this->DisplayPoint[0] - sizex*this->Viewport[0])/
(sizex*(this->Viewport[2]-this->Viewport[0])) - 1.0;
vy = 2.0 * (this->DisplayPoint[1] - sizey*this->Viewport[1])/
(sizey*(this->Viewport[3]-this->Viewport[1])) - 1.0;
vz = this->DisplayPoint[2];
this->SetViewPoint(vx*this->Aspect[0],vy*this->Aspect[1],vz);
}
void vlRenderer::ViewToDisplay()
{
int dx,dy;
int sizex,sizey;
int *size;
/* get physical window dimensions */
size = this->RenderWindow->GetSize();
sizex = size[0];
sizey = size[1];
dx = (int)((this->ViewPoint[0]/this->Aspect[0] + 1.0) *
(sizex*(this->Viewport[2]-this->Viewport[0])) / 2.0 + 0.5 +
sizex*this->Viewport[0]);
dy = (int)((this->ViewPoint[1]/this->Aspect[1] + 1.0) *
(sizey*(this->Viewport[3]-this->Viewport[1])) / 2.0 + 0.5 +
sizey*this->Viewport[1]);
this->SetDisplayPoint(dx,dy,this->ViewPoint[2]);
}
void vlRenderer::ViewToWorld()
{
vlMatrix4x4 mat;
float result[4];
// get the perspective transformation from the active camera
mat = this->ActiveCamera->GetPerspectiveTransform();
// use the inverse matrix
mat.Invert();
// Transform point to world coordinates
result[0] = this->ViewPoint[0];
result[1] = this->ViewPoint[1];
result[2] = this->ViewPoint[2];
result[3] = 1.0;
mat.VectorMultiply(result,result);
// Get the transformed vector & set WorldPoint
this->SetWorldPoint(result);
}
void vlRenderer::WorldToView()
{
vlMatrix4x4 matrix;
float view[4];
float *world;
// get the perspective transformation from the active camera
matrix = this->ActiveCamera->GetPerspectiveTransform();
world = this->WorldPoint;
view[0] = world[0]*matrix[0][0] + world[1]*matrix[1][0] +
world[2]*matrix[2][0] + world[3]*matrix[3][0];
view[1] = world[0]*matrix[0][1] + world[1]*matrix[1][1] +
world[2]*matrix[2][1] + world[3]*matrix[3][1];
view[2] = world[0]*matrix[0][2] + world[1]*matrix[1][2] +
world[2]*matrix[2][2] + world[3]*matrix[3][2];
view[3] = world[0]*matrix[0][3] + world[1]*matrix[1][3] +
world[2]*matrix[2][3] + world[3]*matrix[3][3];
if (view[3] != 0.0)
{
this->SetViewPoint(view[0]/view[3],
view[1]/view[3],
view[2]/view[3]);
}
}
void vlRenderer::PrintSelf(ostream& os, vlIndent indent)
{
if (this->ShouldIPrint(vlRenderer::GetClassName()))
{
this->vlObject::PrintSelf(os,indent);
os << indent << "Actors:\n";
this->Actors.PrintSelf(os,indent.GetNextIndent());
os << indent << "Ambient: (" << this->Ambient[0] << ", "
<< this->Ambient[1] << ", " << this->Ambient[2] << ")\n";
os << indent << "Aspect: (" << this->Aspect[0] << ", "
<< this->Aspect[1] << ")\n";
os << indent << "Background: (" << this->Background[0] << ", "
<< this->Background[1] << ", " << this->Background[2] << ")\n";
os << indent << "Back Light: " << (this->BackLight ? "On\n" : "Off\n");
os << indent << "DisplayPoint: (" << this->DisplayPoint[0] << ", "
<< this->DisplayPoint[1] << ", " << this->DisplayPoint[2] << ")\n";
os << indent << "Erase: " << (this->Erase ? "On\n" : "Off\n");
os << indent << "Lights:\n";
this->Lights.PrintSelf(os,indent.GetNextIndent());
os << indent << "Stereo Render: "
<< (this->StereoRender ? "On\n":"Off\n");
os << indent << "ViewPoint: (" << this->ViewPoint[0] << ", "
<< this->ViewPoint[1] << ", " << this->ViewPoint[2] << ")\n";
os << indent << "Viewport: (" << this->Viewport[0] << ", "
<< this->Viewport[1] << ", " << this->Viewport[2] << ", "
<< this->Viewport[3] << ")\n";
}
}
<|endoftext|>
|
<commit_before>/*****************************************************************************
*
* This file is part of Mapnik (c++ mapping toolkit)
*
* Copyright (C) 2011 Artem Pavlenko
* 2013 Oleksandr Novychenko
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*
*****************************************************************************/
#include "mongodb_datasource.hpp"
#include "mongodb_featureset.hpp"
#include "connection_manager.hpp"
// mapnik
#include <mapnik/debug.hpp>
#include <mapnik/global.hpp>
#include <mapnik/boolean.hpp>
#include <mapnik/sql_utils.hpp>
#include <mapnik/util/conversions.hpp>
#include <mapnik/timer.hpp>
#include <mapnik/value_types.hpp>
// boost
#include <boost/algorithm/string.hpp>
#include <boost/tokenizer.hpp>
#include <boost/make_shared.hpp>
// stl
#include <string>
#include <algorithm>
#include <set>
#include <sstream>
#include <iomanip>
DATASOURCE_PLUGIN(mongodb_datasource)
using boost::shared_ptr;
using mapnik::attribute_descriptor;
mongodb_datasource::mongodb_datasource(parameters const& params)
: datasource(params),
desc_(*params.get<std::string>("type"), "utf-8"),
type_(datasource::Vector),
creator_(params.get<std::string>("host", "localhost"),
params.get<std::string>("port", "27017"),
params.get<std::string>("dbname", "gis"),
params.get<std::string>("collection"),
params.get<std::string>("user"),
params.get<std::string>("password")),
persist_connection_(*params.get<mapnik::boolean>("persist_connection", true)),
extent_initialized_(false) {
boost::optional<std::string> ext = params.get<std::string>("extent");
if (ext && !ext->empty())
extent_initialized_ = extent_.from_string(*ext);
boost::optional<int> initial_size = params.get<int>("initial_size", 1);
boost::optional<int> max_size = params.get<int>("max_size", 10);
ConnectionManager::instance().registerPool(creator_, *initial_size, *max_size);
}
mongodb_datasource::~mongodb_datasource() {
if (!persist_connection_) {
shared_ptr< Pool<Connection, ConnectionCreator> > pool = ConnectionManager::instance().getPool(creator_.id());
if (pool) {
shared_ptr<Connection> conn = pool->borrowObject();
if (conn)
conn->close();
}
}
}
const char *mongodb_datasource::name() {
return "mongodb";
}
mapnik::datasource::datasource_t mongodb_datasource::type() const {
return type_;
}
layer_descriptor mongodb_datasource::get_descriptor() const {
return desc_;
}
std::string mongodb_datasource::json_bbox(const box2d<double> &env) const {
std::ostringstream lookup;
lookup << "{ geometry: { \"$geoWithin\": { \"$box\": [ [ "
<< std::setprecision(16)
<< env.minx() << ", " << env.miny() << " ], [ "
<< env.maxx() << ", " << env.maxy() << " ] ] } } }";
return lookup.str();
}
featureset_ptr mongodb_datasource::features(const query &q) const {
const box2d<double> &box = q.get_bbox();
shared_ptr< Pool<Connection, ConnectionCreator> > pool = ConnectionManager::instance().getPool(creator_.id());
if (pool) {
shared_ptr<Connection> conn = pool->borrowObject();
if (!conn)
return featureset_ptr();
if (conn && conn->isOK()) {
mapnik::context_ptr ctx = boost::make_shared<mapnik::context_type>();
boost::shared_ptr<mongo::DBClientCursor> rs(conn->query(json_bbox(box)));
return boost::make_shared<mongodb_featureset>(rs, ctx, desc_.get_encoding());
}
}
return featureset_ptr();
}
featureset_ptr mongodb_datasource::features_at_point(const coord2d &pt, double tol) const {
shared_ptr< Pool<Connection, ConnectionCreator> > pool = ConnectionManager::instance().getPool(creator_.id());
if (pool) {
shared_ptr<Connection> conn = pool->borrowObject();
if (!conn)
return featureset_ptr();
if (conn->isOK()) {
mapnik::context_ptr ctx = boost::make_shared<mapnik::context_type>();
box2d<double> box(pt.x - tol, pt.y - tol, pt.x + tol, pt.y + tol);
boost::shared_ptr<mongo::DBClientCursor> rs(conn->query(json_bbox(box)));
return boost::make_shared<mongodb_featureset>(rs, ctx, desc_.get_encoding());
}
}
return featureset_ptr();
}
box2d<double> mongodb_datasource::envelope() const {
if (extent_initialized_)
return extent_;
else {
// a dumb way :-/
extent_.init(-180.0, -90.0, 180.0, 90.0);
extent_initialized_ = true;
}
// shared_ptr< Pool<Connection, ConnectionCreator> > pool = ConnectionManager::instance().getPool(creator_.id());
// if (pool) {
// shared_ptr<Connection> conn = pool->borrowObject();
// if (!conn)
// return extent_;
// if (conn->isOK()) {
// // query
// }
// }
return extent_;
}
boost::optional<mapnik::datasource::geometry_t> mongodb_datasource::get_geometry_type() const {
boost::optional<mapnik::datasource::geometry_t> result;
shared_ptr< Pool<Connection,ConnectionCreator> > pool = ConnectionManager::instance().getPool(creator_.id());
if (pool) {
shared_ptr<Connection> conn = pool->borrowObject();
if (!conn)
return result;
if (conn->isOK()) {
boost::shared_ptr <mongo::DBClientCursor> rs(conn->query("{ geometry: { \"$exists\": true } }", 1));
try {
if (rs->more()) {
mongo::BSONObj bson = rs->next();
std::string type = bson["geometry"]["type"].String();
if (type == "Point")
result.reset(mapnik::datasource::Point);
else if (type == "LineString")
result.reset(mapnik::datasource::LineString);
else if (type == "Polygon")
result.reset(mapnik::datasource::Polygon);
}
} catch(mongo::DBException &de) {
std::string err_msg = "Mongodb Plugin: ";
err_msg += de.toString();
err_msg += "\n";
throw mapnik::datasource_exception(err_msg);
}
}
}
return result;
}
<commit_msg>added checking collection definition<commit_after>/*****************************************************************************
*
* This file is part of Mapnik (c++ mapping toolkit)
*
* Copyright (C) 2011 Artem Pavlenko
* 2013 Oleksandr Novychenko
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*
*****************************************************************************/
#include "mongodb_datasource.hpp"
#include "mongodb_featureset.hpp"
#include "connection_manager.hpp"
// mapnik
#include <mapnik/debug.hpp>
#include <mapnik/global.hpp>
#include <mapnik/boolean.hpp>
#include <mapnik/sql_utils.hpp>
#include <mapnik/util/conversions.hpp>
#include <mapnik/timer.hpp>
#include <mapnik/value_types.hpp>
// boost
#include <boost/algorithm/string.hpp>
#include <boost/tokenizer.hpp>
#include <boost/make_shared.hpp>
// stl
#include <string>
#include <algorithm>
#include <set>
#include <sstream>
#include <iomanip>
DATASOURCE_PLUGIN(mongodb_datasource)
using boost::shared_ptr;
using mapnik::attribute_descriptor;
mongodb_datasource::mongodb_datasource(parameters const& params)
: datasource(params),
desc_(*params.get<std::string>("type"), "utf-8"),
type_(datasource::Vector),
creator_(params.get<std::string>("host", "localhost"),
params.get<std::string>("port", "27017"),
params.get<std::string>("dbname", "gis"),
params.get<std::string>("collection"),
params.get<std::string>("user"),
params.get<std::string>("password")),
persist_connection_(*params.get<mapnik::boolean>("persist_connection", true)),
extent_initialized_(false) {
if (!params.get<std::string>("collection"))
throw mapnik::datasource_exception("MongoDB Plugin: missing <collection> parameter");
boost::optional<std::string> ext = params.get<std::string>("extent");
if (ext && !ext->empty())
extent_initialized_ = extent_.from_string(*ext);
boost::optional<int> initial_size = params.get<int>("initial_size", 1);
boost::optional<int> max_size = params.get<int>("max_size", 10);
ConnectionManager::instance().registerPool(creator_, *initial_size, *max_size);
}
mongodb_datasource::~mongodb_datasource() {
if (!persist_connection_) {
shared_ptr< Pool<Connection, ConnectionCreator> > pool = ConnectionManager::instance().getPool(creator_.id());
if (pool) {
shared_ptr<Connection> conn = pool->borrowObject();
if (conn)
conn->close();
}
}
}
const char *mongodb_datasource::name() {
return "mongodb";
}
mapnik::datasource::datasource_t mongodb_datasource::type() const {
return type_;
}
layer_descriptor mongodb_datasource::get_descriptor() const {
return desc_;
}
std::string mongodb_datasource::json_bbox(const box2d<double> &env) const {
std::ostringstream lookup;
lookup << "{ geometry: { \"$geoWithin\": { \"$box\": [ [ "
<< std::setprecision(16)
<< env.minx() << ", " << env.miny() << " ], [ "
<< env.maxx() << ", " << env.maxy() << " ] ] } } }";
return lookup.str();
}
featureset_ptr mongodb_datasource::features(const query &q) const {
const box2d<double> &box = q.get_bbox();
shared_ptr< Pool<Connection, ConnectionCreator> > pool = ConnectionManager::instance().getPool(creator_.id());
if (pool) {
shared_ptr<Connection> conn = pool->borrowObject();
if (!conn)
return featureset_ptr();
if (conn && conn->isOK()) {
mapnik::context_ptr ctx = boost::make_shared<mapnik::context_type>();
boost::shared_ptr<mongo::DBClientCursor> rs(conn->query(json_bbox(box)));
return boost::make_shared<mongodb_featureset>(rs, ctx, desc_.get_encoding());
}
}
return featureset_ptr();
}
featureset_ptr mongodb_datasource::features_at_point(const coord2d &pt, double tol) const {
shared_ptr< Pool<Connection, ConnectionCreator> > pool = ConnectionManager::instance().getPool(creator_.id());
if (pool) {
shared_ptr<Connection> conn = pool->borrowObject();
if (!conn)
return featureset_ptr();
if (conn->isOK()) {
mapnik::context_ptr ctx = boost::make_shared<mapnik::context_type>();
box2d<double> box(pt.x - tol, pt.y - tol, pt.x + tol, pt.y + tol);
boost::shared_ptr<mongo::DBClientCursor> rs(conn->query(json_bbox(box)));
return boost::make_shared<mongodb_featureset>(rs, ctx, desc_.get_encoding());
}
}
return featureset_ptr();
}
box2d<double> mongodb_datasource::envelope() const {
if (extent_initialized_)
return extent_;
else {
// a dumb way :-/
extent_.init(-180.0, -90.0, 180.0, 90.0);
extent_initialized_ = true;
}
// shared_ptr< Pool<Connection, ConnectionCreator> > pool = ConnectionManager::instance().getPool(creator_.id());
// if (pool) {
// shared_ptr<Connection> conn = pool->borrowObject();
// if (!conn)
// return extent_;
// if (conn->isOK()) {
// // query
// }
// }
return extent_;
}
boost::optional<mapnik::datasource::geometry_t> mongodb_datasource::get_geometry_type() const {
boost::optional<mapnik::datasource::geometry_t> result;
shared_ptr< Pool<Connection,ConnectionCreator> > pool = ConnectionManager::instance().getPool(creator_.id());
if (pool) {
shared_ptr<Connection> conn = pool->borrowObject();
if (!conn)
return result;
if (conn->isOK()) {
boost::shared_ptr <mongo::DBClientCursor> rs(conn->query("{ geometry: { \"$exists\": true } }", 1));
try {
if (rs->more()) {
mongo::BSONObj bson = rs->next();
std::string type = bson["geometry"]["type"].String();
if (type == "Point")
result.reset(mapnik::datasource::Point);
else if (type == "LineString")
result.reset(mapnik::datasource::LineString);
else if (type == "Polygon")
result.reset(mapnik::datasource::Polygon);
}
} catch(mongo::DBException &de) {
std::string err_msg = "Mongodb Plugin: ";
err_msg += de.toString();
err_msg += "\n";
throw mapnik::datasource_exception(err_msg);
}
}
}
return result;
}
<|endoftext|>
|
<commit_before>/*
* Copyright (c) 2016-2017, The OpenThread Authors.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* 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 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.
*/
/**
* @file
* This file implements common methods for manipulating MeshCoP Datasets.
*
*/
#include "dataset_local.hpp"
#include <stdio.h>
#include "common/code_utils.hpp"
#include "common/instance.hpp"
#include "common/locator_getters.hpp"
#include "common/log.hpp"
#include "common/settings.hpp"
#include "crypto/storage.hpp"
#include "meshcop/dataset.hpp"
#include "meshcop/meshcop_tlvs.hpp"
#include "thread/mle_tlvs.hpp"
namespace ot {
namespace MeshCoP {
RegisterLogModule("DatasetLocal");
DatasetLocal::DatasetLocal(Instance &aInstance, Dataset::Type aType)
: InstanceLocator(aInstance)
, mUpdateTime(0)
, mType(aType)
, mTimestampPresent(false)
, mSaved(false)
{
mTimestamp.Clear();
}
void DatasetLocal::Clear(void)
{
#if OPENTHREAD_CONFIG_PLATFORM_KEY_REFERENCES_ENABLE
DestroySecurelyStoredKeys();
#endif
IgnoreError(Get<Settings>().DeleteOperationalDataset(IsActive()));
mTimestamp.Clear();
mTimestampPresent = false;
mSaved = false;
}
Error DatasetLocal::Restore(Dataset &aDataset)
{
Error error;
mTimestampPresent = false;
error = Read(aDataset);
SuccessOrExit(error);
mSaved = true;
mTimestampPresent = (aDataset.GetTimestamp(mType, mTimestamp) == kErrorNone);
exit:
return error;
}
Error DatasetLocal::Read(Dataset &aDataset) const
{
DelayTimerTlv *delayTimer;
uint32_t elapsed;
Error error;
error = Get<Settings>().ReadOperationalDataset(IsActive(), aDataset);
VerifyOrExit(error == kErrorNone, aDataset.mLength = 0);
#if OPENTHREAD_CONFIG_PLATFORM_KEY_REFERENCES_ENABLE
EmplaceSecurelyStoredKeys(aDataset);
#endif
if (mType == Dataset::kActive)
{
aDataset.RemoveTlv(Tlv::kPendingTimestamp);
aDataset.RemoveTlv(Tlv::kDelayTimer);
}
else
{
delayTimer = aDataset.GetTlv<DelayTimerTlv>();
VerifyOrExit(delayTimer);
elapsed = TimerMilli::GetNow() - mUpdateTime;
if (delayTimer->GetDelayTimer() > elapsed)
{
delayTimer->SetDelayTimer(delayTimer->GetDelayTimer() - elapsed);
}
else
{
delayTimer->SetDelayTimer(0);
}
}
aDataset.mUpdateTime = TimerMilli::GetNow();
exit:
return error;
}
Error DatasetLocal::Read(Dataset::Info &aDatasetInfo) const
{
Dataset dataset;
Error error;
aDatasetInfo.Clear();
SuccessOrExit(error = Read(dataset));
dataset.ConvertTo(aDatasetInfo);
exit:
return error;
}
Error DatasetLocal::Read(otOperationalDatasetTlvs &aDataset) const
{
Dataset dataset;
Error error;
memset(&aDataset, 0, sizeof(aDataset));
SuccessOrExit(error = Read(dataset));
dataset.ConvertTo(aDataset);
exit:
return error;
}
Error DatasetLocal::Save(const Dataset::Info &aDatasetInfo)
{
Error error;
Dataset dataset;
SuccessOrExit(error = dataset.SetFrom(aDatasetInfo));
SuccessOrExit(error = Save(dataset));
exit:
return error;
}
Error DatasetLocal::Save(const otOperationalDatasetTlvs &aDataset)
{
Dataset dataset;
dataset.SetFrom(aDataset);
return Save(dataset);
}
Error DatasetLocal::Save(const Dataset &aDataset)
{
Error error = kErrorNone;
#if OPENTHREAD_CONFIG_PLATFORM_KEY_REFERENCES_ENABLE
DestroySecurelyStoredKeys();
#endif
if (aDataset.GetSize() == 0)
{
// do not propagate error back
IgnoreError(Get<Settings>().DeleteOperationalDataset(IsActive()));
mSaved = false;
LogInfo("%s dataset deleted", Dataset::TypeToString(mType));
}
else
{
#if OPENTHREAD_CONFIG_PLATFORM_KEY_REFERENCES_ENABLE
// Store the network key and PSKC in the secure storage instead of settings.
Dataset dataset;
dataset.Set(GetType(), aDataset);
MoveKeysToSecureStorage(dataset);
SuccessOrExit(error = Get<Settings>().SaveOperationalDataset(IsActive(), dataset));
#else
SuccessOrExit(error = Get<Settings>().SaveOperationalDataset(IsActive(), aDataset));
#endif
mSaved = true;
LogInfo("%s dataset set", Dataset::TypeToString(mType));
}
mTimestampPresent = (aDataset.GetTimestamp(mType, mTimestamp) == kErrorNone);
mUpdateTime = TimerMilli::GetNow();
exit:
return error;
}
#if OPENTHREAD_CONFIG_PLATFORM_KEY_REFERENCES_ENABLE
void DatasetLocal::DestroySecurelyStoredKeys(void) const
{
using namespace Crypto::Storage;
KeyRef networkKeyRef = IsActive() ? kActiveDatasetNetworkKeyRef : kPendingDatasetNetworkKeyRef;
KeyRef pskcRef = IsActive() ? kActiveDatasetPskcRef : kPendingDatasetPskcRef;
// Destroy securely stored keys associated with the given operational dataset type.
DestroyKey(networkKeyRef);
DestroyKey(pskcRef);
}
void DatasetLocal::MoveKeysToSecureStorage(Dataset &aDataset) const
{
using namespace Crypto::Storage;
KeyRef networkKeyRef = IsActive() ? kActiveDatasetNetworkKeyRef : kPendingDatasetNetworkKeyRef;
KeyRef pskcRef = IsActive() ? kActiveDatasetPskcRef : kPendingDatasetPskcRef;
NetworkKeyTlv *networkKeyTlv = aDataset.GetTlv<NetworkKeyTlv>();
PskcTlv * pskcTlv = aDataset.GetTlv<PskcTlv>();
if (networkKeyTlv != nullptr)
{
// If the dataset contains a network key, put it in the secure storage
// and zero the corresponding TLV element.
NetworkKey networkKey;
SuccessOrAssert(ImportKey(networkKeyRef, kKeyTypeRaw, kKeyAlgorithmVendor, kUsageExport, kTypePersistent,
networkKeyTlv->GetNetworkKey().m8, NetworkKey::kSize));
networkKey.Clear();
networkKeyTlv->SetNetworkKey(networkKey);
}
if (pskcTlv != nullptr)
{
// If the dataset contains a PSKC, put it in the secure storage and zero
// the corresponding TLV element.
Pskc pskc;
SuccessOrAssert(ImportKey(pskcRef, kKeyTypeRaw, kKeyAlgorithmVendor, kUsageExport, kTypePersistent,
pskcTlv->GetPskc().m8, Pskc::kSize));
pskc.Clear();
pskcTlv->SetPskc(pskc);
}
}
void DatasetLocal::EmplaceSecurelyStoredKeys(Dataset &aDataset) const
{
using namespace Crypto::Storage;
KeyRef networkKeyRef = IsActive() ? kActiveDatasetNetworkKeyRef : kPendingDatasetNetworkKeyRef;
KeyRef pskcRef = IsActive() ? kActiveDatasetPskcRef : kPendingDatasetPskcRef;
NetworkKeyTlv *networkKeyTlv = aDataset.GetTlv<NetworkKeyTlv>();
PskcTlv * pskcTlv = aDataset.GetTlv<PskcTlv>();
size_t keyLen;
if (networkKeyTlv != nullptr)
{
// If the dataset contains a network key, its real value must have been moved to
// the secure storage upon saving the dataset, so restore it back now.
NetworkKey networkKey;
SuccessOrAssert(ExportKey(networkKeyRef, networkKey.m8, NetworkKey::kSize, keyLen));
OT_ASSERT(keyLen == NetworkKey::kSize);
networkKeyTlv->SetNetworkKey(networkKey);
}
if (pskcTlv != nullptr)
{
// If the dataset contains a PSKC, its real value must have been moved to
// the secure storage upon saving the dataset, so restore it back now.
Pskc pskc;
SuccessOrAssert(ExportKey(pskcRef, pskc.m8, Pskc::kSize, keyLen));
OT_ASSERT(keyLen == Pskc::kSize);
pskcTlv->SetPskc(pskc);
}
}
#endif
} // namespace MeshCoP
} // namespace ot
<commit_msg>[crypto] update emplace method to expect read failure during key export (#7559)<commit_after>/*
* Copyright (c) 2016-2017, The OpenThread Authors.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* 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 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.
*/
/**
* @file
* This file implements common methods for manipulating MeshCoP Datasets.
*
*/
#include "dataset_local.hpp"
#include <stdio.h>
#include "common/code_utils.hpp"
#include "common/instance.hpp"
#include "common/locator_getters.hpp"
#include "common/log.hpp"
#include "common/settings.hpp"
#include "crypto/storage.hpp"
#include "meshcop/dataset.hpp"
#include "meshcop/meshcop_tlvs.hpp"
#include "thread/mle_tlvs.hpp"
namespace ot {
namespace MeshCoP {
RegisterLogModule("DatasetLocal");
DatasetLocal::DatasetLocal(Instance &aInstance, Dataset::Type aType)
: InstanceLocator(aInstance)
, mUpdateTime(0)
, mType(aType)
, mTimestampPresent(false)
, mSaved(false)
{
mTimestamp.Clear();
}
void DatasetLocal::Clear(void)
{
#if OPENTHREAD_CONFIG_PLATFORM_KEY_REFERENCES_ENABLE
DestroySecurelyStoredKeys();
#endif
IgnoreError(Get<Settings>().DeleteOperationalDataset(IsActive()));
mTimestamp.Clear();
mTimestampPresent = false;
mSaved = false;
}
Error DatasetLocal::Restore(Dataset &aDataset)
{
Error error;
mTimestampPresent = false;
error = Read(aDataset);
SuccessOrExit(error);
mSaved = true;
mTimestampPresent = (aDataset.GetTimestamp(mType, mTimestamp) == kErrorNone);
exit:
return error;
}
Error DatasetLocal::Read(Dataset &aDataset) const
{
DelayTimerTlv *delayTimer;
uint32_t elapsed;
Error error;
error = Get<Settings>().ReadOperationalDataset(IsActive(), aDataset);
VerifyOrExit(error == kErrorNone, aDataset.mLength = 0);
#if OPENTHREAD_CONFIG_PLATFORM_KEY_REFERENCES_ENABLE
EmplaceSecurelyStoredKeys(aDataset);
#endif
if (mType == Dataset::kActive)
{
aDataset.RemoveTlv(Tlv::kPendingTimestamp);
aDataset.RemoveTlv(Tlv::kDelayTimer);
}
else
{
delayTimer = aDataset.GetTlv<DelayTimerTlv>();
VerifyOrExit(delayTimer);
elapsed = TimerMilli::GetNow() - mUpdateTime;
if (delayTimer->GetDelayTimer() > elapsed)
{
delayTimer->SetDelayTimer(delayTimer->GetDelayTimer() - elapsed);
}
else
{
delayTimer->SetDelayTimer(0);
}
}
aDataset.mUpdateTime = TimerMilli::GetNow();
exit:
return error;
}
Error DatasetLocal::Read(Dataset::Info &aDatasetInfo) const
{
Dataset dataset;
Error error;
aDatasetInfo.Clear();
SuccessOrExit(error = Read(dataset));
dataset.ConvertTo(aDatasetInfo);
exit:
return error;
}
Error DatasetLocal::Read(otOperationalDatasetTlvs &aDataset) const
{
Dataset dataset;
Error error;
memset(&aDataset, 0, sizeof(aDataset));
SuccessOrExit(error = Read(dataset));
dataset.ConvertTo(aDataset);
exit:
return error;
}
Error DatasetLocal::Save(const Dataset::Info &aDatasetInfo)
{
Error error;
Dataset dataset;
SuccessOrExit(error = dataset.SetFrom(aDatasetInfo));
SuccessOrExit(error = Save(dataset));
exit:
return error;
}
Error DatasetLocal::Save(const otOperationalDatasetTlvs &aDataset)
{
Dataset dataset;
dataset.SetFrom(aDataset);
return Save(dataset);
}
Error DatasetLocal::Save(const Dataset &aDataset)
{
Error error = kErrorNone;
#if OPENTHREAD_CONFIG_PLATFORM_KEY_REFERENCES_ENABLE
DestroySecurelyStoredKeys();
#endif
if (aDataset.GetSize() == 0)
{
// do not propagate error back
IgnoreError(Get<Settings>().DeleteOperationalDataset(IsActive()));
mSaved = false;
LogInfo("%s dataset deleted", Dataset::TypeToString(mType));
}
else
{
#if OPENTHREAD_CONFIG_PLATFORM_KEY_REFERENCES_ENABLE
// Store the network key and PSKC in the secure storage instead of settings.
Dataset dataset;
dataset.Set(GetType(), aDataset);
MoveKeysToSecureStorage(dataset);
SuccessOrExit(error = Get<Settings>().SaveOperationalDataset(IsActive(), dataset));
#else
SuccessOrExit(error = Get<Settings>().SaveOperationalDataset(IsActive(), aDataset));
#endif
mSaved = true;
LogInfo("%s dataset set", Dataset::TypeToString(mType));
}
mTimestampPresent = (aDataset.GetTimestamp(mType, mTimestamp) == kErrorNone);
mUpdateTime = TimerMilli::GetNow();
exit:
return error;
}
#if OPENTHREAD_CONFIG_PLATFORM_KEY_REFERENCES_ENABLE
void DatasetLocal::DestroySecurelyStoredKeys(void) const
{
using namespace Crypto::Storage;
KeyRef networkKeyRef = IsActive() ? kActiveDatasetNetworkKeyRef : kPendingDatasetNetworkKeyRef;
KeyRef pskcRef = IsActive() ? kActiveDatasetPskcRef : kPendingDatasetPskcRef;
// Destroy securely stored keys associated with the given operational dataset type.
DestroyKey(networkKeyRef);
DestroyKey(pskcRef);
}
void DatasetLocal::MoveKeysToSecureStorage(Dataset &aDataset) const
{
using namespace Crypto::Storage;
KeyRef networkKeyRef = IsActive() ? kActiveDatasetNetworkKeyRef : kPendingDatasetNetworkKeyRef;
KeyRef pskcRef = IsActive() ? kActiveDatasetPskcRef : kPendingDatasetPskcRef;
NetworkKeyTlv *networkKeyTlv = aDataset.GetTlv<NetworkKeyTlv>();
PskcTlv * pskcTlv = aDataset.GetTlv<PskcTlv>();
if (networkKeyTlv != nullptr)
{
// If the dataset contains a network key, put it in the secure storage
// and zero the corresponding TLV element.
NetworkKey networkKey;
SuccessOrAssert(ImportKey(networkKeyRef, kKeyTypeRaw, kKeyAlgorithmVendor, kUsageExport, kTypePersistent,
networkKeyTlv->GetNetworkKey().m8, NetworkKey::kSize));
networkKey.Clear();
networkKeyTlv->SetNetworkKey(networkKey);
}
if (pskcTlv != nullptr)
{
// If the dataset contains a PSKC, put it in the secure storage and zero
// the corresponding TLV element.
Pskc pskc;
SuccessOrAssert(ImportKey(pskcRef, kKeyTypeRaw, kKeyAlgorithmVendor, kUsageExport, kTypePersistent,
pskcTlv->GetPskc().m8, Pskc::kSize));
pskc.Clear();
pskcTlv->SetPskc(pskc);
}
}
void DatasetLocal::EmplaceSecurelyStoredKeys(Dataset &aDataset) const
{
using namespace Crypto::Storage;
KeyRef networkKeyRef = IsActive() ? kActiveDatasetNetworkKeyRef : kPendingDatasetNetworkKeyRef;
KeyRef pskcRef = IsActive() ? kActiveDatasetPskcRef : kPendingDatasetPskcRef;
NetworkKeyTlv *networkKeyTlv = aDataset.GetTlv<NetworkKeyTlv>();
PskcTlv * pskcTlv = aDataset.GetTlv<PskcTlv>();
bool moveKeys = false;
size_t keyLen;
Error error;
if (networkKeyTlv != nullptr)
{
// If the dataset contains a network key, its real value must have been moved to
// the secure storage upon saving the dataset, so restore it back now.
NetworkKey networkKey;
error = ExportKey(networkKeyRef, networkKey.m8, NetworkKey::kSize, keyLen);
if (error != kErrorNone)
{
// If ExportKey fails, key is not in secure storage and is stored in settings
moveKeys = true;
}
else
{
OT_ASSERT(keyLen == NetworkKey::kSize);
networkKeyTlv->SetNetworkKey(networkKey);
}
}
if (pskcTlv != nullptr)
{
// If the dataset contains a PSKC, its real value must have been moved to
// the secure storage upon saving the dataset, so restore it back now.
Pskc pskc;
error = ExportKey(pskcRef, pskc.m8, Pskc::kSize, keyLen);
if (error != kErrorNone)
{
// If ExportKey fails, key is not in secure storage and is stored in settings
moveKeys = true;
}
else
{
OT_ASSERT(keyLen == Pskc::kSize);
pskcTlv->SetPskc(pskc);
}
}
if (moveKeys)
{
// Clear the networkkey and Pskc stored in the settings and move them to secure storage.
// Store the network key and PSKC in the secure storage instead of settings.
Dataset dataset;
dataset.Set(GetType(), aDataset);
MoveKeysToSecureStorage(dataset);
SuccessOrAssert(error = Get<Settings>().SaveOperationalDataset(IsActive(), dataset));
}
}
#endif
} // namespace MeshCoP
} // namespace ot
<|endoftext|>
|
<commit_before>#include "API.hpp"
#include "APICamera.hpp"
#include "ros/ros.h"
#include <ros/console.h>
#include <map>
//messages
#include "api_application/System.h"
#include "api_application/SetFormation.h"
#include "api_application/MoveFormation.h"
#include "control_application/SetQuadcopters.h"
#include "control_application/Rotation.h"
using namespace kitrokopter;
/**
* This is only a dummy formation
*/
APIFormation dummyFormation() {
std::vector<Vector> positions;
positions.push_back(Vector(0.0, 0.0, 0.0));
return APIFormation(positions, 1);
}
/**
* Initializes the API which means starting the announcement service.
*
* @param argc remapping arguments from the command line for ros
* @param argv remapping arguments from the command line for ros
* @param sync whether to do blocking ROS spinning
*/
API::API(int argc, char **argv, bool sync)
{
//TODO this is only a dummy
this->formation = dummyFormation();
this->idCounter = 0;
//this->formation = NULL;
this->controllerIds = std::vector<int>(1);
this->positionIds = std::vector<int>(5);
this->cameraSystem = APICameraSystem();
ros::init(argc, argv, "api_server");
ros::NodeHandle nodeHandle;
announceService = nodeHandle.advertiseService("announce", &API::announce, this);
ROS_INFO("Ready to deliver IDs.");
formationPublisher = nodeHandle.advertise<api_application::SetFormation>("SetFormation", 1);
ROS_INFO("Ready to send a formation.");
formationMovementPublisher = nodeHandle.advertise<api_application::MoveFormation>("MoveFormation", 1);
ROS_INFO("Ready to move a formation.");
systemPublisher = nodeHandle.advertise<api_application::System>("System", 1);
ROS_INFO("Ready to send system signals.");
if (sync) {
ros::spin();
} else {
spinner = new ros::AsyncSpinner(1);
spinner->start();
}
}
/**
* Destructs the API, stopping the ROS spinner.
*/
API::~API()
{
delete spinner;
}
/**
* Start the system
*/
void API::startSystem() {
this->sendSystemSignal(STARTUP);
}
/**
* Shutdown the system
*/
void API::shutdownSystem() {
this->sendSystemSignal(SHUTDOWN);
}
/**
* Send a system signal.
*
* @param signal the signal to send
*/
void API::sendSystemSignal(uint8_t signal) {
api_application::System message;
message.header.stamp = ros::Time::now();
message.command = signal;
this->systemPublisher.publish(message);
}
/**
* Get a pointer to the APIQuadcopter with the corresponding id
* or a null pointer if there is no such APIQuadcopter.
*
* @param id the APIQuadcopter's id
* @return the APIQuadcopter with this id or a null pointer if there is no such APIQuadcopter
*/
APIQuadcopter* API::getQuadcopter(int id) {
if (this->quadcopters.find(id) != this->quadcopters.end()) {
return &this->quadcopters[id];
} else {
return NULL;
}
}
/**
* Removes the APIQuadcopter with the corresponding id.
*
* @param id the APIQuadcopter's id
* @return whether there was a APIQuadcopter with this id to remove
*/
bool API::removeQuadcopter(int id) {
if (this->quadcopters.find(id) != this->quadcopters.end()) {
quadcopters.erase(id);
return true;
} else {
return false;
}
}
/**
* Get all channels where a quadcopter is online.
*
* @return array of channels
*/
std::vector<uint8_t> API::scanChannels() {
if (this->quadcopters.size() == 0) {
throw new std::runtime_error("no quadcopter module to scan with");
}
return this->quadcopters.begin()->second.scanChannels();
}
/**
* Scan for all available quadcopters and distribute them to the quadcopter modules.
*
* @return whether the function was able to distribute all quadcopter channels or or give all quadcopter modules a channel.
*/
bool API::initializeQuadcopters() {
if (this->quadcopters.size() == 0) {
return false;
}
std::vector<uint8_t> channels = this->scanChannels();
if (channels.size() == 0){
return false;
}
int max;
if (this->quadcopters.size() > channels.size()) {
max = channels.size();
} else {
max = this->quadcopters.size();
}
std::map<uint32_t, APIQuadcopter>::iterator quadIt = this->quadcopters.begin();
for (int i = 0; i < max; i++)
{
if (quadIt->second.connectOnChannel(channels[i]) == false)
{
return false;
}
quadIt++;
}
sendQuadcoptersToController();
return true;
}
/**
* Initialize the controller
*/
void API::sendQuadcoptersToController() {
/**
* since the service does not provide a good way
* to deal with quadcopters not selected for flight
* send only "selected for flight" quadcopters
*/
ros::NodeHandle nodeHandle;
ros::ServiceClient client = nodeHandle.serviceClient<control_application::SetQuadcopters>("SetQuadcopters");
control_application::SetQuadcopters srv;
srv.request.header.stamp = ros::Time::now();
std::vector<APIQuadcopter*> result;
for (std::map<uint32_t, APIQuadcopter>::iterator it =
this->quadcopters.begin(); it != this->quadcopters.end(); ++it)
{
srv.request.quadcoptersId.push_back(it->first);
}
srv.request.amount = srv.request.quadcoptersId.size();
if (!client.call(srv)) {
ROS_ERROR("Could not call StartCalibration service.");
throw new std::runtime_error("Could not call StartCalibration service.");
}
}
/**
* Initializes the cameras
*/
void API::initializeCameras() {
this->cameraSystem.initializeCameras(this->quadcopters);
}
/**
* Function to be called when the announce service is invoked.
*/
bool API::announce(api_application::Announce::Request &req, api_application::Announce::Response &res)
{
res.id = idCounter++;
switch (req.type) {
case 0:
this->cameraSystem.addCamera(APICamera(res.id));
break;
case 1:
this->quadcopters[res.id] = APIQuadcopter(res.id);
this->quadcopters[res.id].listen();
break;
case 2:
this->controllerIds.push_back(res.id);
break;
case 3:
this->positionIds.push_back(res.id);
break;
default:
ROS_ERROR("Malformed register attempt!");
res.id = -1;
return false;
}
ROS_INFO("Registered new module with type %d and id %d", req.type, res.id);
return true;
}
/**
* Initializes the controller
*/
void API::initializeController() {
}
/**
* Sets a new formation.
*
* @param newFormation th enew formation
*/
void API::setFormation(APIFormation newFormation) {
this->formation = newFormation;
sendFormation();
}
/**
* Send the formation to the controller
*/
void API::sendFormation() {
api_application::SetFormation msg;
msg.header.stamp = ros::Time::now();
msg.distance = this->formation.getMinimumDistance();
msg.amount = this->formation.getQuadcopterAmount();
auto positions = this->formation.getQuadcopterPositions();
for (auto& pos : *positions)
{
msg.xPositions.push_back(pos.getX());
msg.yPositions.push_back(pos.getY());
msg.zPositions.push_back(pos.getZ());
}
}
/**
* Get a pointer to the formation.
*
* @return the formation
*/
APIFormation* API::getFormation() {
return &this->formation;
}
/**
* Get a pointer to the camera system
*
* @return the pointer
*/
APICameraSystem* API::getCameraSystem()
{
return &cameraSystem;
}
/**
* Get a vector of all quadcopters.
*
* @return vector of all quadcopters
*/
std::vector<APIQuadcopter*> API::getQuadcopters() {
std::vector<APIQuadcopter*> result;
for (std::map<uint32_t, APIQuadcopter>::iterator it =
this->quadcopters.begin(); it != this->quadcopters.end(); ++it)
{
result.push_back(&it->second);
}
return result;
}
/**
* Get all quadcopters which are selected to fly in formation.
*
* @return a vector of pointers to the quadcopters
*/
std::vector<APIQuadcopter*> API::getQuadcoptersSelectedForFlight() {
std::vector<APIQuadcopter*> result;
for (std::map<uint32_t, APIQuadcopter>::iterator it =
this->quadcopters.begin(); it != this->quadcopters.end(); ++it)
{
if (it->second.isSelectedForFlight())
{
result.push_back(&it->second);
}
}
return result;
}
/**
* Get all quadcopters which are selected to fly in formation.
*
* @return a vector of pointers to the quadcopters
*/
std::vector<APIQuadcopter*> API::getQuadcoptersNotSelectedForFlight() {
std::vector<APIQuadcopter*> result;
for (std::map<uint32_t, APIQuadcopter>::iterator it =
this->quadcopters.begin(); it != this->quadcopters.end(); ++it)
{
if (!it->second.isSelectedForFlight())
{
result.push_back(&it->second);
}
}
return result;
}
/**
* Get all quadcopters which are selected to fly in formation.
*
* @return a vector of pointers to the quadcopters
*/
std::vector<APICamera*> API::getCameras() {
return this->cameraSystem.getCamerasAsVector();
}
/**
* Move the formation by a vector
*
* @param vector the vector for moving the formation
*/
void API::moveFormation(Vector vector) {
api_application::MoveFormation message;
message.header.stamp = ros::Time::now();
message.xMovement = vector.getX();
message.yMovement = vector.getY();
message.zMovement = vector.getZ();
this->systemPublisher.publish(message);
}
/**
* Send a rotate formation signal to the controller
* TODO the controller needs to provide a proper rotate functionality
* to make the formation turn by a choosable angle
*/
void API::rotateFormation()
{
ros::NodeHandle nodeHandle;
ros::ServiceClient client = nodeHandle.serviceClient<control_application::Rotation>("Rotation");
control_application::Rotation srv;
srv.request.header.stamp = ros::Time::now();
if (!client.call(srv)) {
ROS_ERROR("Could not call Rotate service.");
throw new std::runtime_error("Could not call Rotate service.");
}
}
<commit_msg>Changed error message when setquadcopters is not available<commit_after>#include "API.hpp"
#include "APICamera.hpp"
#include "ros/ros.h"
#include <ros/console.h>
#include <map>
//messages
#include "api_application/System.h"
#include "api_application/SetFormation.h"
#include "api_application/MoveFormation.h"
#include "control_application/SetQuadcopters.h"
#include "control_application/Rotation.h"
using namespace kitrokopter;
/**
* This is only a dummy formation
*/
APIFormation dummyFormation() {
std::vector<Vector> positions;
positions.push_back(Vector(0.0, 0.0, 0.0));
return APIFormation(positions, 1);
}
/**
* Initializes the API which means starting the announcement service.
*
* @param argc remapping arguments from the command line for ros
* @param argv remapping arguments from the command line for ros
* @param sync whether to do blocking ROS spinning
*/
API::API(int argc, char **argv, bool sync)
{
//TODO this is only a dummy
this->formation = dummyFormation();
this->idCounter = 0;
//this->formation = NULL;
this->controllerIds = std::vector<int>(1);
this->positionIds = std::vector<int>(5);
this->cameraSystem = APICameraSystem();
ros::init(argc, argv, "api_server");
ros::NodeHandle nodeHandle;
announceService = nodeHandle.advertiseService("announce", &API::announce, this);
ROS_INFO("Ready to deliver IDs.");
formationPublisher = nodeHandle.advertise<api_application::SetFormation>("SetFormation", 1);
ROS_INFO("Ready to send a formation.");
formationMovementPublisher = nodeHandle.advertise<api_application::MoveFormation>("MoveFormation", 1);
ROS_INFO("Ready to move a formation.");
systemPublisher = nodeHandle.advertise<api_application::System>("System", 1);
ROS_INFO("Ready to send system signals.");
if (sync) {
ros::spin();
} else {
spinner = new ros::AsyncSpinner(1);
spinner->start();
}
}
/**
* Destructs the API, stopping the ROS spinner.
*/
API::~API()
{
delete spinner;
}
/**
* Start the system
*/
void API::startSystem() {
this->sendSystemSignal(STARTUP);
}
/**
* Shutdown the system
*/
void API::shutdownSystem() {
this->sendSystemSignal(SHUTDOWN);
}
/**
* Send a system signal.
*
* @param signal the signal to send
*/
void API::sendSystemSignal(uint8_t signal) {
api_application::System message;
message.header.stamp = ros::Time::now();
message.command = signal;
this->systemPublisher.publish(message);
}
/**
* Get a pointer to the APIQuadcopter with the corresponding id
* or a null pointer if there is no such APIQuadcopter.
*
* @param id the APIQuadcopter's id
* @return the APIQuadcopter with this id or a null pointer if there is no such APIQuadcopter
*/
APIQuadcopter* API::getQuadcopter(int id) {
if (this->quadcopters.find(id) != this->quadcopters.end()) {
return &this->quadcopters[id];
} else {
return NULL;
}
}
/**
* Removes the APIQuadcopter with the corresponding id.
*
* @param id the APIQuadcopter's id
* @return whether there was a APIQuadcopter with this id to remove
*/
bool API::removeQuadcopter(int id) {
if (this->quadcopters.find(id) != this->quadcopters.end()) {
quadcopters.erase(id);
return true;
} else {
return false;
}
}
/**
* Get all channels where a quadcopter is online.
*
* @return array of channels
*/
std::vector<uint8_t> API::scanChannels() {
if (this->quadcopters.size() == 0) {
throw new std::runtime_error("no quadcopter module to scan with");
}
return this->quadcopters.begin()->second.scanChannels();
}
/**
* Scan for all available quadcopters and distribute them to the quadcopter modules.
*
* @return whether the function was able to distribute all quadcopter channels or or give all quadcopter modules a channel.
*/
bool API::initializeQuadcopters() {
if (this->quadcopters.size() == 0) {
return false;
}
std::vector<uint8_t> channels = this->scanChannels();
if (channels.size() == 0){
return false;
}
int max;
if (this->quadcopters.size() > channels.size()) {
max = channels.size();
} else {
max = this->quadcopters.size();
}
std::map<uint32_t, APIQuadcopter>::iterator quadIt = this->quadcopters.begin();
for (int i = 0; i < max; i++)
{
if (quadIt->second.connectOnChannel(channels[i]) == false)
{
return false;
}
quadIt++;
}
sendQuadcoptersToController();
return true;
}
/**
* Initialize the controller
*/
void API::sendQuadcoptersToController() {
/**
* since the service does not provide a good way
* to deal with quadcopters not selected for flight
* send only "selected for flight" quadcopters
*/
ros::NodeHandle nodeHandle;
ros::ServiceClient client = nodeHandle.serviceClient<control_application::SetQuadcopters>("SetQuadcopters");
control_application::SetQuadcopters srv;
srv.request.header.stamp = ros::Time::now();
std::vector<APIQuadcopter*> result;
for (std::map<uint32_t, APIQuadcopter>::iterator it =
this->quadcopters.begin(); it != this->quadcopters.end(); ++it)
{
srv.request.quadcoptersId.push_back(it->first);
}
srv.request.amount = srv.request.quadcoptersId.size();
if (!client.call(srv)) {
ROS_ERROR("Could not call SetQuadcopters service.");
throw new std::runtime_error("Could not call SetQuadcopters service.");
}
}
/**
* Initializes the cameras
*/
void API::initializeCameras() {
this->cameraSystem.initializeCameras(this->quadcopters);
}
/**
* Function to be called when the announce service is invoked.
*/
bool API::announce(api_application::Announce::Request &req, api_application::Announce::Response &res)
{
res.id = idCounter++;
switch (req.type) {
case 0:
this->cameraSystem.addCamera(APICamera(res.id));
break;
case 1:
this->quadcopters[res.id] = APIQuadcopter(res.id);
this->quadcopters[res.id].listen();
break;
case 2:
this->controllerIds.push_back(res.id);
break;
case 3:
this->positionIds.push_back(res.id);
break;
default:
ROS_ERROR("Malformed register attempt!");
res.id = -1;
return false;
}
ROS_INFO("Registered new module with type %d and id %d", req.type, res.id);
return true;
}
/**
* Initializes the controller
*/
void API::initializeController() {
}
/**
* Sets a new formation.
*
* @param newFormation th enew formation
*/
void API::setFormation(APIFormation newFormation) {
this->formation = newFormation;
sendFormation();
}
/**
* Send the formation to the controller
*/
void API::sendFormation() {
api_application::SetFormation msg;
msg.header.stamp = ros::Time::now();
msg.distance = this->formation.getMinimumDistance();
msg.amount = this->formation.getQuadcopterAmount();
auto positions = this->formation.getQuadcopterPositions();
for (auto& pos : *positions)
{
msg.xPositions.push_back(pos.getX());
msg.yPositions.push_back(pos.getY());
msg.zPositions.push_back(pos.getZ());
}
}
/**
* Get a pointer to the formation.
*
* @return the formation
*/
APIFormation* API::getFormation() {
return &this->formation;
}
/**
* Get a pointer to the camera system
*
* @return the pointer
*/
APICameraSystem* API::getCameraSystem()
{
return &cameraSystem;
}
/**
* Get a vector of all quadcopters.
*
* @return vector of all quadcopters
*/
std::vector<APIQuadcopter*> API::getQuadcopters() {
std::vector<APIQuadcopter*> result;
for (std::map<uint32_t, APIQuadcopter>::iterator it =
this->quadcopters.begin(); it != this->quadcopters.end(); ++it)
{
result.push_back(&it->second);
}
return result;
}
/**
* Get all quadcopters which are selected to fly in formation.
*
* @return a vector of pointers to the quadcopters
*/
std::vector<APIQuadcopter*> API::getQuadcoptersSelectedForFlight() {
std::vector<APIQuadcopter*> result;
for (std::map<uint32_t, APIQuadcopter>::iterator it =
this->quadcopters.begin(); it != this->quadcopters.end(); ++it)
{
if (it->second.isSelectedForFlight())
{
result.push_back(&it->second);
}
}
return result;
}
/**
* Get all quadcopters which are selected to fly in formation.
*
* @return a vector of pointers to the quadcopters
*/
std::vector<APIQuadcopter*> API::getQuadcoptersNotSelectedForFlight() {
std::vector<APIQuadcopter*> result;
for (std::map<uint32_t, APIQuadcopter>::iterator it =
this->quadcopters.begin(); it != this->quadcopters.end(); ++it)
{
if (!it->second.isSelectedForFlight())
{
result.push_back(&it->second);
}
}
return result;
}
/**
* Get all quadcopters which are selected to fly in formation.
*
* @return a vector of pointers to the quadcopters
*/
std::vector<APICamera*> API::getCameras() {
return this->cameraSystem.getCamerasAsVector();
}
/**
* Move the formation by a vector
*
* @param vector the vector for moving the formation
*/
void API::moveFormation(Vector vector) {
api_application::MoveFormation message;
message.header.stamp = ros::Time::now();
message.xMovement = vector.getX();
message.yMovement = vector.getY();
message.zMovement = vector.getZ();
this->systemPublisher.publish(message);
}
/**
* Send a rotate formation signal to the controller
* TODO the controller needs to provide a proper rotate functionality
* to make the formation turn by a choosable angle
*/
void API::rotateFormation()
{
ros::NodeHandle nodeHandle;
ros::ServiceClient client = nodeHandle.serviceClient<control_application::Rotation>("Rotation");
control_application::Rotation srv;
srv.request.header.stamp = ros::Time::now();
if (!client.call(srv)) {
ROS_ERROR("Could not call Rotate service.");
throw new std::runtime_error("Could not call Rotate service.");
}
}
<|endoftext|>
|
<commit_before>//************************************************************/
//
// Plot Implementation
//
// Implements the SPXPlot class, which connects all of the
// other non-configuration classes (non-steering/options) and
// manages the plotting, drawing, and ROOT objects
//
// @Author: J. Gibson, C. Embree, T. Carli - CERN ATLAS
// @Date: 13.10.2014
// @Email: [email protected]
//
//************************************************************/
#include <sstream>
#include "SPXPlot.h"
#include "SPXUtilities.h"
const std::string cn = "SPXPlot::";
//Must define the static debug variable in the implementation
bool SPXPlot::debug;
//Initialize all plots
void SPXPlot::Initialize(void) {
try {
InitializeData();
InitializeCrossSections();
NormalizeCrossSections();
} catch(const SPXException &e) {
throw;
}
}
void SPXPlot::Plot(void) {
std::string mn = "Plot:: ";
SPXPlotConfiguration &pc = steeringFile->GetPlotConfiguration(id);
std::ostringstream oss;
oss << "canvas" << id;
std::string canvasID = oss.str();
//@TODO Where should these come from? Or are they just initial values that are set later?
int wtopx = 200; //Window top x
int wtopy = 10; //Window top y
int ww = 700; //Window width
int wh = 500; //Window height
canvas = new TCanvas(canvasID.c_str(), pc.GetDescription().c_str(), wtopx, wtopy, ww, wh);
canvas->SetFillColor(0);
canvas->SetGrid();
if(debug) {
std::cout << cn << mn << "Canvas (" << canvasID << ") created for Plot ID " << id <<
" with dimensions: " << ww << " x " << wh << " and title: " << pc.GetDescription() << std::endl;
}
//@TODO Where should these come from?
double xMin; // = 0;
double xMax; // = 3000;
double yMin; // = 0;
double yMax; // = 0.003;
//Determine frame bounds by calculating the xmin, xmax, ymin, ymax from ALL graphs being drawn
std::vector<TGraphAsymmErrors *> graphs;
{
//Data graphs
for(int i = 0; i < data.size(); i++) {
graphs.push_back(data[i].GetStatisticalErrorGraph());
graphs.push_back(data[i].GetSystematicErrorGraph());
}
//Cross sections
for(int i = 0; i < crossSections.size(); i++) {
graphs.push_back(crossSections[i].GetPDFBandResults());
}
xMin = SPXGraphUtilities::GetXMin(graphs);
xMax = SPXGraphUtilities::GetXMax(graphs);
yMin = SPXGraphUtilities::GetYMin(graphs);
yMax = SPXGraphUtilities::GetYMax(graphs);
//Sanity check
if(xMin > xMax) {
throw SPXGraphException("xMin calculated to be larger than xMax");
}
if(yMin > yMax) {
throw SPXGraphException("yMin calculated to be larger than yMax");
}
}
//Draw the frame (xmin, ymin, xmax, ymax)
canvas->DrawFrame(xMin, yMin, xMax, yMax);
if(debug) {
std::cout << cn << mn << "Canvas (" << canvasID << ") frame drawn with dimensions: " << std::endl;
std::cout << "\t xMin = " << xMin << std::endl;
std::cout << "\t xMax = " << xMax << std::endl;
std::cout << "\t yMin = " << yMin << std::endl;
std::cout << "\t yMax = " << yMax << std::endl;
}
//Draw data graphs
for(int i = 0; i < data.size(); i++) {
data[i].GetSystematicErrorGraph()->Draw("P");
data[i].GetStatisticalErrorGraph()->Draw("||");
}
//Draw cross sections
for(int i = 0; i < crossSections.size(); i++) {
crossSections[i].GetPDFBandResults()->Draw("P");
}
//Update canvas
canvas->Update();
}
//@TODO Where do I normalize cross section???
void SPXPlot::InitializeCrossSections(void) {
std::string mn = "InitializeCrossSections: ";
//Create cross sections for each configuration instance (and each PDF)
for(int i = 0; i < steeringFile->GetNumberOfConfigurationInstances(id); i++) {
for(int j = 0; j < steeringFile->GetNumberOfPDFSteeringFiles(); j++) {
SPXPDFSteeringFile &psf = steeringFile->GetPDFSteeringFile(j);
SPXPlotConfigurationInstance &pci = steeringFile->GetPlotConfigurationInstance(id, i);
SPXCrossSection crossSectionInstance = SPXCrossSection(&psf, &pci);
try {
crossSectionInstance.Create();
crossSections.push_back(crossSectionInstance);
} catch(const SPXException &e) {
throw;
}
}
}
}
void SPXPlot::NormalizeCrossSections(void) {
for(int i = 0; i < crossSections.size(); i++) {
SPXPDFSteeringFile *psf = crossSections[i].GetPDFSteeringFile();
SPXPlotConfigurationInstance *pci = crossSections[i].GetPlotConfigurationInstance();
//@TODO WHERE DO I GET THE CS SCALE FROM????
double xScale = pci->dataSteeringFile.GetXScale();
double yScale = pci->dataSteeringFile.GetYScale();
bool normalizedToTotalSigma = false; //@TODO Where is this for the PDF/Grid/CS?
bool dividedByBinWidth = pci->gridSteeringFile.IsDividedByBinWidth();
SPXGraphUtilities::Normalize(crossSections[i].GetPDFBandResults(), xScale, yScale, true, dividedByBinWidth);
}
}
void SPXPlot::InitializeData(void) {
std::string mn = "InitializeData: ";
//Create data objects for each configuration instance of this plot and add them to vector
for(int i = 0; i < steeringFile->GetNumberOfConfigurationInstances(id); i++) {
SPXPlotConfigurationInstance &pci = steeringFile->GetPlotConfigurationInstance(id, i);
SPXData dataInstance = SPXData(pci);
try {
dataInstance.Parse();
dataInstance.Print();
data.push_back(dataInstance);
} catch(const SPXException &e) {
throw;
}
}
//Go through data objects and create graphs, modify settings, etc.
for(int i = 0; i < data.size(); i++) {
//Create graphs: once this function is called, it is safe to manipulate graphs
data[i].CreateGraphs();
//Obtain the graphs
TGraphAsymmErrors *statGraph = data[i].GetStatisticalErrorGraph();
TGraphAsymmErrors *systGraph = data[i].GetSystematicErrorGraph();
//Get settings
SPXPlotConfigurationInstance &pci = steeringFile->GetPlotConfigurationInstance(id, i);
//Normalize the graphs based on the settings
double xScale = pci.dataSteeringFile.GetXScale();
double yScale = pci.dataSteeringFile.GetYScale();
bool normalizedToTotalSigma = pci.dataSteeringFile.IsNormalizedToTotalSigma();
bool dividedByBinWidth = pci.dataSteeringFile.IsDividedByBinWidth();
if(debug) {
std::cout << cn << mn << "Normalizing with: " << std::endl;
std::cout << "\t X Scale = " << xScale << std::endl;
std::cout << "\t Y Scale = " << yScale << std::endl;
std::cout << "\t Normalized To Total Sigma? " << (normalizedToTotalSigma ? "YES" : "NO") << std::endl;
std::cout << "\t Divided By Bin Width? " << (dividedByBinWidth ? "YES" : "NO") << std::endl;
}
SPXGraphUtilities::Normalize(statGraph, xScale, yScale, normalizedToTotalSigma, dividedByBinWidth);
SPXGraphUtilities::Normalize(systGraph, xScale, yScale, normalizedToTotalSigma, dividedByBinWidth);
//Modify Data Graph styles
statGraph->SetMarkerStyle(pci.markerStyle);
systGraph->SetMarkerStyle(pci.markerStyle);
statGraph->SetMarkerColor(pci.markerColor);
systGraph->SetMarkerColor(pci.markerColor);
//@TODO Why is this not in the data steering file? Why is one larger?
statGraph->SetMarkerSize(1.0);
systGraph->SetMarkerSize(1.0);
statGraph->SetLineColor(4);
systGraph->SetLineColor(1);
statGraph->SetLineWidth(1);
systGraph->SetLineWidth(1);
}
}<commit_msg>Removed Normalization of data graphs (it was incorrect) and corrected normalization of CS<commit_after>//************************************************************/
//
// Plot Implementation
//
// Implements the SPXPlot class, which connects all of the
// other non-configuration classes (non-steering/options) and
// manages the plotting, drawing, and ROOT objects
//
// @Author: J. Gibson, C. Embree, T. Carli - CERN ATLAS
// @Date: 13.10.2014
// @Email: [email protected]
//
//************************************************************/
#include <sstream>
#include "SPXPlot.h"
#include "SPXUtilities.h"
const std::string cn = "SPXPlot::";
//Must define the static debug variable in the implementation
bool SPXPlot::debug;
//Initialize all plots
void SPXPlot::Initialize(void) {
try {
InitializeData();
InitializeCrossSections();
NormalizeCrossSections();
} catch(const SPXException &e) {
throw;
}
}
void SPXPlot::Plot(void) {
std::string mn = "Plot:: ";
SPXPlotConfiguration &pc = steeringFile->GetPlotConfiguration(id);
std::ostringstream oss;
oss << "canvas" << id;
std::string canvasID = oss.str();
//@TODO Where should these come from? Or are they just initial values that are set later?
int wtopx = 200; //Window top x
int wtopy = 10; //Window top y
int ww = 700; //Window width
int wh = 500; //Window height
canvas = new TCanvas(canvasID.c_str(), pc.GetDescription().c_str(), wtopx, wtopy, ww, wh);
canvas->SetFillColor(0);
canvas->SetGrid();
if(debug) {
std::cout << cn << mn << "Canvas (" << canvasID << ") created for Plot ID " << id <<
" with dimensions: " << ww << " x " << wh << " and title: " << pc.GetDescription() << std::endl;
}
//@TODO Where should these come from?
double xMin; // = 0;
double xMax; // = 3000;
double yMin; // = 0;
double yMax; // = 0.003;
//Determine frame bounds by calculating the xmin, xmax, ymin, ymax from ALL graphs being drawn
std::vector<TGraphAsymmErrors *> graphs;
{
//Data graphs
for(int i = 0; i < data.size(); i++) {
graphs.push_back(data[i].GetStatisticalErrorGraph());
graphs.push_back(data[i].GetSystematicErrorGraph());
}
//Cross sections
for(int i = 0; i < crossSections.size(); i++) {
graphs.push_back(crossSections[i].GetPDFBandResults());
}
xMin = SPXGraphUtilities::GetXMin(graphs);
xMax = SPXGraphUtilities::GetXMax(graphs);
yMin = SPXGraphUtilities::GetYMin(graphs);
yMax = SPXGraphUtilities::GetYMax(graphs);
//Sanity check
if(xMin > xMax) {
throw SPXGraphException("xMin calculated to be larger than xMax");
}
if(yMin > yMax) {
throw SPXGraphException("yMin calculated to be larger than yMax");
}
}
//Draw the frame (xmin, ymin, xmax, ymax)
canvas->DrawFrame(xMin, yMin, xMax, yMax);
if(debug) {
std::cout << cn << mn << "Canvas (" << canvasID << ") frame drawn with dimensions: " << std::endl;
std::cout << "\t xMin = " << xMin << std::endl;
std::cout << "\t xMax = " << xMax << std::endl;
std::cout << "\t yMin = " << yMin << std::endl;
std::cout << "\t yMax = " << yMax << std::endl;
}
//Draw data graphs
for(int i = 0; i < data.size(); i++) {
data[i].GetSystematicErrorGraph()->Draw("P");
data[i].GetStatisticalErrorGraph()->Draw("||");
}
//Draw cross sections
for(int i = 0; i < crossSections.size(); i++) {
crossSections[i].GetPDFBandResults()->Draw("P");
}
//Update canvas
canvas->Update();
}
//@TODO Where do I normalize cross section???
void SPXPlot::InitializeCrossSections(void) {
std::string mn = "InitializeCrossSections: ";
//Create cross sections for each configuration instance (and each PDF)
for(int i = 0; i < steeringFile->GetNumberOfConfigurationInstances(id); i++) {
for(int j = 0; j < steeringFile->GetNumberOfPDFSteeringFiles(); j++) {
SPXPDFSteeringFile &psf = steeringFile->GetPDFSteeringFile(j);
SPXPlotConfigurationInstance &pci = steeringFile->GetPlotConfigurationInstance(id, i);
SPXCrossSection crossSectionInstance = SPXCrossSection(&psf, &pci);
try {
crossSectionInstance.Create();
crossSections.push_back(crossSectionInstance);
} catch(const SPXException &e) {
throw;
}
}
}
}
void SPXPlot::NormalizeCrossSections(void) {
std::string mn = "NormalizeCrossSections: ";
for(int i = 0; i < crossSections.size(); i++) {
try {
if(debug) std::cout << cn << mn << "Normalizing Cross Section at index " << i << std::endl;
SPXPDFSteeringFile *psf = crossSections[i].GetPDFSteeringFile();
SPXPlotConfigurationInstance *pci = crossSections[i].GetPlotConfigurationInstance();
std::string masterXUnits = pci->dataSteeringFile.GetXUnits();
std::string slaveXUnits = pci->gridSteeringFile.GetXUnits();
std::string masterYUnits = pci->dataSteeringFile.GetYUnits();
std::string slaveYUnits = pci->gridSteeringFile.GetYUnits();
//Determine the scale from the unit difference between data and grid
double xScale = SPXGraphUtilities::GetXUnitsScale(masterXUnits, slaveXUnits);
double yScale = SPXGraphUtilities::GetYUnitsScale(masterYUnits, slaveYUnits);
if(debug) {
std::cout << cn << mn << "Scales determined from data/grid unit differential: " << std::endl;
std::cout << "\t Data X Units: " << masterXUnits << std::endl;
std::cout << "\t Grid X Units: " << slaveXUnits << std::endl << std::endl;
std::cout << "\t Data Y Units: " << masterYUnits << std::endl;
std::cout << "\t Grid Y Units: " << slaveYUnits << std::endl << std::endl;
std::cout << "\t ---> X Unit Scale Determined: " << xScale << std::endl;
std::cout << "\t ---> Y Unit Scale Determined: " << yScale << std::endl << std::endl;
}
//Also scale by the artificial scale from the plot configuration instance
xScale *= pci->xScale;
yScale *= pci->yScale;
SPXGraphUtilities::Scale(crossSections[i].GetPDFBandResults(), xScale, yScale);
if(debug) {
std::cout << cn << mn << "Additional artificial scale for Cross Section: " << std::endl;
std::cout << "\t X Scale: " << pci->xScale << std::endl;
std::cout << "\t Y Scale: " << pci->yScale << std::endl << std::endl;
}
//Normalized to total sigma from the DATA steering file
bool normalizeToTotalSigma = pci->dataSteeringFile.IsNormalizedToTotalSigma();
bool dataDividedByBinWidth = pci->dataSteeringFile.IsDividedByBinWidth();
bool gridDividedByBinWidth = pci->gridSteeringFile.IsDividedByBinWidth();
bool divideByBinWidth = false;
if(dataDividedByBinWidth && !gridDividedByBinWidth) {
if(debug) std::cout << cn << mn << "Data IS divided by bin width but the grid IS NOT. Will call Normalize with divideByBinWidth = true" << std::endl;
divideByBinWidth = true;
}
double yBinWidthScale = 1.0;
//If the data is divided by the bin width, then set the yBinWidthScale, which is the scaling of the Data's Y Bin Width Units to the Data's X Units
if(dataDividedByBinWidth) {
yBinWidthScale = SPXGraphUtilities::GetYBinWidthUnitsScale(pci->dataSteeringFile.GetXUnits(), pci->dataSteeringFile.GetYBinWidthUnits());
}
if(debug) std::cout << cn << mn << "Y Bin Width Scale = " << yBinWidthScale << std::endl;
if(debug) std::cout << cn << mn << "Normalize to Total Sigma is " << (normalizeToTotalSigma ? "ON" : "OFF") << std::endl;
if(debug) std::cout << cn << mn << "Divide by Bin Width is " << (divideByBinWidth ? "ON" : "OFF") << std::endl;
//Normalize the cross section
SPXGraphUtilities::Normalize(crossSections[i].GetPDFBandResults(), yBinWidthScale, normalizeToTotalSigma, divideByBinWidth);
if(debug) std::cout << cn << mn << "Sucessfully normalized Cross Section " << i << std::endl;
} catch(const SPXException &e) {
std::cerr << e.what() << std::endl;
throw SPXGraphException("SPXPlot::NormalizeCrossSections: Unable to obtain X/Y Scale based on Data/Grid Units");
}
}
}
void SPXPlot::InitializeData(void) {
std::string mn = "InitializeData: ";
//Create data objects for each configuration instance of this plot and add them to vector
for(int i = 0; i < steeringFile->GetNumberOfConfigurationInstances(id); i++) {
SPXPlotConfigurationInstance &pci = steeringFile->GetPlotConfigurationInstance(id, i);
SPXData dataInstance = SPXData(pci);
try {
dataInstance.Parse();
dataInstance.Print();
data.push_back(dataInstance);
} catch(const SPXException &e) {
throw;
}
}
//Go through data objects and create graphs, modify settings, etc.
for(int i = 0; i < data.size(); i++) {
//Create graphs: once this function is called, it is safe to manipulate graphs
data[i].CreateGraphs();
//Obtain the graphs
TGraphAsymmErrors *statGraph = data[i].GetStatisticalErrorGraph();
TGraphAsymmErrors *systGraph = data[i].GetSystematicErrorGraph();
//Get settings
SPXPlotConfigurationInstance &pci = steeringFile->GetPlotConfigurationInstance(id, i);
//Normalize the graphs based on the settings
double xScale = pci.xScale;
double yScale = pci.yScale;
if(debug) {
std::cout << cn << mn << "Scaling Data with: " << std::endl;
std::cout << "\t X Scale = " << xScale << std::endl;
std::cout << "\t Y Scale = " << yScale << std::endl;
}
SPXGraphUtilities::Scale(statGraph, xScale, yScale);
SPXGraphUtilities::Scale(systGraph, xScale, yScale);
//Modify Data Graph styles
statGraph->SetMarkerStyle(pci.markerStyle);
systGraph->SetMarkerStyle(pci.markerStyle);
statGraph->SetMarkerColor(pci.markerColor);
systGraph->SetMarkerColor(pci.markerColor);
statGraph->SetMarkerSize(1.0);
systGraph->SetMarkerSize(1.0);
statGraph->SetLineColor(4);
systGraph->SetLineColor(1);
statGraph->SetLineWidth(1);
systGraph->SetLineWidth(1);
}
}<|endoftext|>
|
<commit_before>
/* App.cpp
*
* Copyright (C) 2013 Michael Imamura
*
* 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 "StdAfx.h"
#include "Exception.h"
#include "FinalScene.h"
#include "ImageScene.h"
#include "InitScene.h"
#include "IntroScene.h"
#include "MainLoopScene.h"
#include "MiscScene.h"
#include "Player.h"
#include "PreloadScene.h"
#include "RenderScene.h"
#include "ResStr.h"
#include "Scene.h"
#include "TextInputScene.h"
#include "TtfScene.h"
#include "App.h"
namespace AISDL {
namespace {
struct UserEvent {
enum type {
FLASH_TIMER,
};
};
// Called by SDL_AddTimer.
Uint32 HandleFlashTimer(Uint32 interval, void *params)
{
// SDL_AddTimer runs callbacks on a separate thread, so to be safe
// we push an event so we actually handle it on the main thread.
// See App::OnUserEvent().
SDL_Event evt;
evt.type = SDL_USEREVENT;
evt.user.code = UserEvent::FLASH_TIMER;
SDL_PushEvent(&evt);
// Continue firing events on the same interval.
return interval;
}
}
/**
* Constructor.
* @param startingScene Index of the scene to start.
*/
App::App(int startingScene) :
SUPER(),
display(),
startingScene(startingScene), sceneIdx(-1),
clockDecor(display),
keyLeft(0), keyRight(0), keyUp(0), keyDown(0)
{
AddScene(std::make_shared<IntroScene>(*this, display));
AddScene(std::make_shared<InitScene>(*this, display));
AddScene(std::make_shared<MainLoopScene>(*this, display));
AddScene(std::make_shared<TextInputScene>(*this, display));
AddScene(std::make_shared<RenderScene>(*this, display));
AddScene(std::make_shared<ImageScene>(*this, display));
AddScene(std::make_shared<TtfScene>(*this, display));
AddScene(std::make_shared<MiscScene>(*this, display));
AddScene(std::make_shared<FinalScene>(*this, display));
// Create the main player.
players.emplace_back(std::make_shared<Player>());
}
App::~App()
{
}
/**
* Add a scene to the end of the scene list.
* @param scene The scene (may not be @c nullptr).
*/
void App::AddScene(std::shared_ptr<Scene> scene)
{
scenes.emplace_back(std::move(scene));
}
/**
* Attempt to attach a game controller.
* @param idx The joystick index.
* @return @c true if attached successfully, @c false otherwise.
*/
bool App::AttachController(int idx)
{
if (!SDL_IsGameController(idx)) return false;
SDL_GameController *controller = SDL_GameControllerOpen(idx);
if (!controller) {
SDL_Log("Could not open controller %d: %s", idx, SDL_GetError());
return false;
}
// Keep track of the instance ID of each controller so we can detach it
// later -- the detach event returns the instance ID, not the index!
int instanceId = SDL_JoystickInstanceID(
SDL_GameControllerGetJoystick(controller));
gameControllers[instanceId] = controller;
SDL_Log("Attached controller index=%d instance=%d (%s).",
idx, instanceId, SDL_GameControllerName(controller));
return true;
}
/**
* Attempt to detach a game controller.
* @param instanceId The joystick instance ID (not the index!).
* @return @c true if detached successfully, @c false otherwise.
*/
bool App::DetachController(int instanceId)
{
auto iter = gameControllers.find(instanceId);
if (iter == gameControllers.end()) {
SDL_Log("Unable to find controller for instance ID: %d", instanceId);
return false;
}
else {
SDL_GameControllerClose(iter->second);
gameControllers.erase(iter);
SDL_Log("Detached controller instance=%d.", instanceId);
return true;
}
}
/**
* Handle when a controller button is pressed.
* @param evt The button press event.
*/
void App::OnControllerButtonDown(SDL_ControllerButtonEvent &evt)
{
const SDL_GameControllerButton btn =
static_cast<SDL_GameControllerButton>(evt.button);
switch (btn) {
case SDL_CONTROLLER_BUTTON_A:
scene->OnAction();
break;
case SDL_CONTROLLER_BUTTON_B:
scene->OnCancel();
break;
case SDL_CONTROLLER_BUTTON_X:
scene->OnInteract();
break;
case SDL_CONTROLLER_BUTTON_LEFTSTICK:
ResStr::ReloadAll();
break;
case SDL_CONTROLLER_BUTTON_BACK:
clockDecor.Flash();
break;
case SDL_CONTROLLER_BUTTON_START:
//TODO: Switch to TOC (last scene in list).
break;
case SDL_CONTROLLER_BUTTON_LEFTSHOULDER:
RequestPrevScene();
break;
case SDL_CONTROLLER_BUTTON_RIGHTSHOULDER:
RequestNextScene();
break;
default:
// Ignore.
break;
}
}
/**
* Handle when a key is pressed.
* @param evt The key pressed event.
*/
void App::OnKeyDown(SDL_KeyboardEvent &evt)
{
switch (evt.keysym.sym) {
case SDLK_w:
case SDLK_UP:
keyUp = -1.0f;
break;
case SDLK_d:
case SDLK_RIGHT:
keyRight = 1.0f;
break;
case SDLK_s:
case SDLK_DOWN:
keyDown = 1.0f;
break;
case SDLK_a:
case SDLK_LEFT:
keyLeft = -1.0f;
break;
case SDLK_RETURN:
if (evt.keysym.mod & KMOD_ALT) {
// Alt+Enter - Toggle fullscreen.
display.ToggleFullscreen();
} else {
scene->OnAction();
}
break;
case SDLK_ESCAPE:
scene->OnCancel();
break;
case SDLK_e:
scene->OnInteract();
break;
case SDLK_q:
RequestShutdown();
break;
case SDLK_F5:
ResStr::ReloadAll();
scene->Reload();
break;
case SDLK_TAB:
clockDecor.Flash();
break;
case SDLK_HOME:
//TODO: Switch to TOC (last scene in list).
break;
case SDLK_PAGEUP:
RequestPrevScene();
break;
case SDLK_PAGEDOWN:
RequestNextScene();
break;
default:
// Ignore.
break;
}
}
/**
* Handle when a key is released.
* @param evt The key released event.
*/
void App::OnKeyUp(SDL_KeyboardEvent &evt)
{
switch (evt.keysym.sym) {
case SDLK_w:
case SDLK_UP:
keyUp = 0;
break;
case SDLK_d:
case SDLK_RIGHT:
keyRight = 0;
break;
case SDLK_s:
case SDLK_DOWN:
keyDown = 0;
break;
case SDLK_a:
case SDLK_LEFT:
keyLeft = 0;
break;
}
}
/**
* Handle when a user event is triggered.
* @param evt The event.
*/
void App::OnUserEvent(SDL_UserEvent &evt)
{
switch (evt.code) {
case UserEvent::FLASH_TIMER:
clockDecor.Flash();
break;
default:
SDL_Log("Unhandled user event: %d", evt.code);
}
}
/**
* Main loop.
*/
void App::Run()
{
bool quit = false;
SDL_Event evt;
Uint32 lastTick = 0;
// SDL automatically enables text input at startup.
// We only want to use it in TextInputScene, so we turn it off here.
SDL_StopTextInput();
// Always start with the preload scene.
// When the preloader finishes, it'll request to switch to the next scene.
scene = std::make_shared<PreloadScene>(*this, display);
// Attach all already-plugged-in controllers.
for (int i = 0; i < SDL_NumJoysticks(); i++) {
AttachController(i);
}
// Flash the clock every 15 minutes.
SDL_AddTimer(15 * 60 * 1000, &HandleFlashTimer, nullptr);
while (!quit) {
// Process all events that have been triggered since the last
// frame was rendered.
while (SDL_PollEvent(&evt) && !quit) {
switch (evt.type) {
case SDL_KEYDOWN:
OnKeyDown(evt.key);
break;
case SDL_KEYUP:
OnKeyUp(evt.key);
break;
// SDL_ControllerButtonEvent
case SDL_CONTROLLERBUTTONDOWN:
OnControllerButtonDown(evt.cbutton);
break;
// SDL_ControllerDeviceEvent
case SDL_CONTROLLERDEVICEADDED:
AttachController(evt.cdevice.which);
break;
case SDL_CONTROLLERDEVICEREMOVED:
DetachController(evt.cdevice.which);
break;
case SDL_CONTROLLERDEVICEREMAPPED:
//TODO
SDL_Log("Remapped controller: %d", evt.cdevice.which);
break;
// SDL_UserEvent
case SDL_USEREVENT:
OnUserEvent(evt.user);
break;
case SDL_QUIT:
quit = true;
break;
}
// Let the current scene have a chance at handling the event.
scene->HandleEvent(evt);
}
if (quit) break;
auto tick = SDL_GetTicks();
if (lastTick == 0) {
lastTick = tick;
}
RenderFrame(*scene, lastTick, tick);
lastTick = tick;
// If a new scene was requested, switch to it.
if (nextScene) {
// Shut down the old scene.
scene->Cleanup();
scene = nextScene;
nextScene.reset();
// Set up the new scene.
players.front()->Reset();
scene->Reset();
lastTick = 0;
}
}
// Detach all controllers.
while (!gameControllers.empty()) {
DetachController(gameControllers.begin()->first);
}
SDL_Log("Shutting down.");
}
void App::RenderFrame(Scene &scene, Uint32 lastTick, Uint32 tick)
{
scene.Advance(lastTick, tick);
clockDecor.Advance(tick);
// We let the scene decide how to clear the frame.
scene.Render();
clockDecor.Render();
SDL_RenderPresent(display.renderer);
}
void App::RequestPrevScene()
{
if (sceneIdx > 0) {
sceneIdx--;
nextScene = scenes[sceneIdx];
SDL_Log("Switching to %d: %s", sceneIdx, nextScene->title.c_str());
}
}
void App::RequestNextScene()
{
if (sceneIdx <= -1) {
// The scene at -1 is the preload scene; it's followed by the
// requested starting scene.
sceneIdx = startingScene;
if (startingScene < 0 || startingScene >= (int)scenes.size()) {
std::ostringstream oss;
oss << "Invalid starting scene index [" << startingScene << "] -- "
"Starting scene must be in range 0.." << (scenes.size() - 1) <<
" (inclusive)";
throw Exception(oss.str());
}
}
else if ((unsigned)sceneIdx == scenes.size() - 1) {
// At the final scene.
return;
}
else {
sceneIdx++;
}
nextScene = scenes[sceneIdx];
SDL_Log("Switching to %d: %s", sceneIdx, nextScene->title.c_str());
}
void App::RequestShutdown()
{
// Handle the shutdown in a calm and orderly fashion, when the
// main loop gets around to it.
SDL_Event evt;
evt.type = SDL_QUIT;
SDL_PushEvent(&evt);
}
std::shared_ptr<Player> App::GetMainPlayer() const
{
// The player at index zero is always the main player.
return players.front();
}
namespace {
const float DEAD_ZONE_MIN = -0.15f;
const float DEAD_ZONE_MAX = 0.15f;
}
float App::SampleControllerAxis(SDL_GameController *controller,
SDL_GameControllerAxis axis)
{
// Axis is reported in range -38768 to 38767.
auto a = static_cast<float>(
SDL_GameControllerGetAxis(controller, axis));
// Scale the axis to -1.0 to 1.0.
a = ((2.0f * (a + 32768.0f)) / 65535.0f) - 1.0f;
// Ignore if the axis is in the dead (resting) zone.
if (a > DEAD_ZONE_MIN && a < DEAD_ZONE_MAX) {
a = 0;
}
return a;
}
Director::MovementState App::SampleMovement() const
{
// For now, we just take the average of all controllers which are actually
// pushed in a direction.
float x = 0, y = 0;
float active = 0;
for (auto iter = gameControllers.cbegin();
iter != gameControllers.cend(); ++iter)
{
auto controller = iter->second;
auto ax = SampleControllerAxis(controller, SDL_CONTROLLER_AXIS_LEFTX);
auto ay = SampleControllerAxis(controller, SDL_CONTROLLER_AXIS_LEFTY);
if (ax != 0 || ay != 0) {
x += ax;
y += ay;
active++;
}
}
if (keyUp != 0 || keyRight != 0 || keyDown != 0 || keyLeft != 0) {
x += keyLeft + keyRight;
y += keyUp + keyDown;
active++;
}
if (active == 0) {
x = 0;
y = 0;
}
else {
x /= active;
y /= active;
}
return MovementState(x, y);
}
} // namespace AISDL
<commit_msg>Increase gamepad dead zone.<commit_after>
/* App.cpp
*
* Copyright (C) 2013 Michael Imamura
*
* 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 "StdAfx.h"
#include "Exception.h"
#include "FinalScene.h"
#include "ImageScene.h"
#include "InitScene.h"
#include "IntroScene.h"
#include "MainLoopScene.h"
#include "MiscScene.h"
#include "Player.h"
#include "PreloadScene.h"
#include "RenderScene.h"
#include "ResStr.h"
#include "Scene.h"
#include "TextInputScene.h"
#include "TtfScene.h"
#include "App.h"
namespace AISDL {
namespace {
struct UserEvent {
enum type {
FLASH_TIMER,
};
};
// Called by SDL_AddTimer.
Uint32 HandleFlashTimer(Uint32 interval, void *params)
{
// SDL_AddTimer runs callbacks on a separate thread, so to be safe
// we push an event so we actually handle it on the main thread.
// See App::OnUserEvent().
SDL_Event evt;
evt.type = SDL_USEREVENT;
evt.user.code = UserEvent::FLASH_TIMER;
SDL_PushEvent(&evt);
// Continue firing events on the same interval.
return interval;
}
}
/**
* Constructor.
* @param startingScene Index of the scene to start.
*/
App::App(int startingScene) :
SUPER(),
display(),
startingScene(startingScene), sceneIdx(-1),
clockDecor(display),
keyLeft(0), keyRight(0), keyUp(0), keyDown(0)
{
AddScene(std::make_shared<IntroScene>(*this, display));
AddScene(std::make_shared<InitScene>(*this, display));
AddScene(std::make_shared<MainLoopScene>(*this, display));
AddScene(std::make_shared<TextInputScene>(*this, display));
AddScene(std::make_shared<RenderScene>(*this, display));
AddScene(std::make_shared<ImageScene>(*this, display));
AddScene(std::make_shared<TtfScene>(*this, display));
AddScene(std::make_shared<MiscScene>(*this, display));
AddScene(std::make_shared<FinalScene>(*this, display));
// Create the main player.
players.emplace_back(std::make_shared<Player>());
}
App::~App()
{
}
/**
* Add a scene to the end of the scene list.
* @param scene The scene (may not be @c nullptr).
*/
void App::AddScene(std::shared_ptr<Scene> scene)
{
scenes.emplace_back(std::move(scene));
}
/**
* Attempt to attach a game controller.
* @param idx The joystick index.
* @return @c true if attached successfully, @c false otherwise.
*/
bool App::AttachController(int idx)
{
if (!SDL_IsGameController(idx)) return false;
SDL_GameController *controller = SDL_GameControllerOpen(idx);
if (!controller) {
SDL_Log("Could not open controller %d: %s", idx, SDL_GetError());
return false;
}
// Keep track of the instance ID of each controller so we can detach it
// later -- the detach event returns the instance ID, not the index!
int instanceId = SDL_JoystickInstanceID(
SDL_GameControllerGetJoystick(controller));
gameControllers[instanceId] = controller;
SDL_Log("Attached controller index=%d instance=%d (%s).",
idx, instanceId, SDL_GameControllerName(controller));
return true;
}
/**
* Attempt to detach a game controller.
* @param instanceId The joystick instance ID (not the index!).
* @return @c true if detached successfully, @c false otherwise.
*/
bool App::DetachController(int instanceId)
{
auto iter = gameControllers.find(instanceId);
if (iter == gameControllers.end()) {
SDL_Log("Unable to find controller for instance ID: %d", instanceId);
return false;
}
else {
SDL_GameControllerClose(iter->second);
gameControllers.erase(iter);
SDL_Log("Detached controller instance=%d.", instanceId);
return true;
}
}
/**
* Handle when a controller button is pressed.
* @param evt The button press event.
*/
void App::OnControllerButtonDown(SDL_ControllerButtonEvent &evt)
{
const SDL_GameControllerButton btn =
static_cast<SDL_GameControllerButton>(evt.button);
switch (btn) {
case SDL_CONTROLLER_BUTTON_A:
scene->OnAction();
break;
case SDL_CONTROLLER_BUTTON_B:
scene->OnCancel();
break;
case SDL_CONTROLLER_BUTTON_X:
scene->OnInteract();
break;
case SDL_CONTROLLER_BUTTON_LEFTSTICK:
ResStr::ReloadAll();
break;
case SDL_CONTROLLER_BUTTON_BACK:
clockDecor.Flash();
break;
case SDL_CONTROLLER_BUTTON_START:
//TODO: Switch to TOC (last scene in list).
break;
case SDL_CONTROLLER_BUTTON_LEFTSHOULDER:
RequestPrevScene();
break;
case SDL_CONTROLLER_BUTTON_RIGHTSHOULDER:
RequestNextScene();
break;
default:
// Ignore.
break;
}
}
/**
* Handle when a key is pressed.
* @param evt The key pressed event.
*/
void App::OnKeyDown(SDL_KeyboardEvent &evt)
{
switch (evt.keysym.sym) {
case SDLK_w:
case SDLK_UP:
keyUp = -1.0f;
break;
case SDLK_d:
case SDLK_RIGHT:
keyRight = 1.0f;
break;
case SDLK_s:
case SDLK_DOWN:
keyDown = 1.0f;
break;
case SDLK_a:
case SDLK_LEFT:
keyLeft = -1.0f;
break;
case SDLK_RETURN:
if (evt.keysym.mod & KMOD_ALT) {
// Alt+Enter - Toggle fullscreen.
display.ToggleFullscreen();
} else {
scene->OnAction();
}
break;
case SDLK_ESCAPE:
scene->OnCancel();
break;
case SDLK_e:
scene->OnInteract();
break;
case SDLK_q:
RequestShutdown();
break;
case SDLK_F5:
ResStr::ReloadAll();
scene->Reload();
break;
case SDLK_TAB:
clockDecor.Flash();
break;
case SDLK_HOME:
//TODO: Switch to TOC (last scene in list).
break;
case SDLK_PAGEUP:
RequestPrevScene();
break;
case SDLK_PAGEDOWN:
RequestNextScene();
break;
default:
// Ignore.
break;
}
}
/**
* Handle when a key is released.
* @param evt The key released event.
*/
void App::OnKeyUp(SDL_KeyboardEvent &evt)
{
switch (evt.keysym.sym) {
case SDLK_w:
case SDLK_UP:
keyUp = 0;
break;
case SDLK_d:
case SDLK_RIGHT:
keyRight = 0;
break;
case SDLK_s:
case SDLK_DOWN:
keyDown = 0;
break;
case SDLK_a:
case SDLK_LEFT:
keyLeft = 0;
break;
}
}
/**
* Handle when a user event is triggered.
* @param evt The event.
*/
void App::OnUserEvent(SDL_UserEvent &evt)
{
switch (evt.code) {
case UserEvent::FLASH_TIMER:
clockDecor.Flash();
break;
default:
SDL_Log("Unhandled user event: %d", evt.code);
}
}
/**
* Main loop.
*/
void App::Run()
{
bool quit = false;
SDL_Event evt;
Uint32 lastTick = 0;
// SDL automatically enables text input at startup.
// We only want to use it in TextInputScene, so we turn it off here.
SDL_StopTextInput();
// Always start with the preload scene.
// When the preloader finishes, it'll request to switch to the next scene.
scene = std::make_shared<PreloadScene>(*this, display);
// Attach all already-plugged-in controllers.
for (int i = 0; i < SDL_NumJoysticks(); i++) {
AttachController(i);
}
// Flash the clock every 15 minutes.
SDL_AddTimer(15 * 60 * 1000, &HandleFlashTimer, nullptr);
while (!quit) {
// Process all events that have been triggered since the last
// frame was rendered.
while (SDL_PollEvent(&evt) && !quit) {
switch (evt.type) {
case SDL_KEYDOWN:
OnKeyDown(evt.key);
break;
case SDL_KEYUP:
OnKeyUp(evt.key);
break;
// SDL_ControllerButtonEvent
case SDL_CONTROLLERBUTTONDOWN:
OnControllerButtonDown(evt.cbutton);
break;
// SDL_ControllerDeviceEvent
case SDL_CONTROLLERDEVICEADDED:
AttachController(evt.cdevice.which);
break;
case SDL_CONTROLLERDEVICEREMOVED:
DetachController(evt.cdevice.which);
break;
case SDL_CONTROLLERDEVICEREMAPPED:
//TODO
SDL_Log("Remapped controller: %d", evt.cdevice.which);
break;
// SDL_UserEvent
case SDL_USEREVENT:
OnUserEvent(evt.user);
break;
case SDL_QUIT:
quit = true;
break;
}
// Let the current scene have a chance at handling the event.
scene->HandleEvent(evt);
}
if (quit) break;
auto tick = SDL_GetTicks();
if (lastTick == 0) {
lastTick = tick;
}
RenderFrame(*scene, lastTick, tick);
lastTick = tick;
// If a new scene was requested, switch to it.
if (nextScene) {
// Shut down the old scene.
scene->Cleanup();
scene = nextScene;
nextScene.reset();
// Set up the new scene.
players.front()->Reset();
scene->Reset();
lastTick = 0;
}
}
// Detach all controllers.
while (!gameControllers.empty()) {
DetachController(gameControllers.begin()->first);
}
SDL_Log("Shutting down.");
}
void App::RenderFrame(Scene &scene, Uint32 lastTick, Uint32 tick)
{
scene.Advance(lastTick, tick);
clockDecor.Advance(tick);
// We let the scene decide how to clear the frame.
scene.Render();
clockDecor.Render();
SDL_RenderPresent(display.renderer);
}
void App::RequestPrevScene()
{
if (sceneIdx > 0) {
sceneIdx--;
nextScene = scenes[sceneIdx];
SDL_Log("Switching to %d: %s", sceneIdx, nextScene->title.c_str());
}
}
void App::RequestNextScene()
{
if (sceneIdx <= -1) {
// The scene at -1 is the preload scene; it's followed by the
// requested starting scene.
sceneIdx = startingScene;
if (startingScene < 0 || startingScene >= (int)scenes.size()) {
std::ostringstream oss;
oss << "Invalid starting scene index [" << startingScene << "] -- "
"Starting scene must be in range 0.." << (scenes.size() - 1) <<
" (inclusive)";
throw Exception(oss.str());
}
}
else if ((unsigned)sceneIdx == scenes.size() - 1) {
// At the final scene.
return;
}
else {
sceneIdx++;
}
nextScene = scenes[sceneIdx];
SDL_Log("Switching to %d: %s", sceneIdx, nextScene->title.c_str());
}
void App::RequestShutdown()
{
// Handle the shutdown in a calm and orderly fashion, when the
// main loop gets around to it.
SDL_Event evt;
evt.type = SDL_QUIT;
SDL_PushEvent(&evt);
}
std::shared_ptr<Player> App::GetMainPlayer() const
{
// The player at index zero is always the main player.
return players.front();
}
namespace {
const float DEAD_ZONE_MIN = -0.25f;
const float DEAD_ZONE_MAX = 0.25f;
}
float App::SampleControllerAxis(SDL_GameController *controller,
SDL_GameControllerAxis axis)
{
// Axis is reported in range -38768 to 38767.
auto a = static_cast<float>(
SDL_GameControllerGetAxis(controller, axis));
// Scale the axis to -1.0 to 1.0.
a = ((2.0f * (a + 32768.0f)) / 65535.0f) - 1.0f;
// Ignore if the axis is in the dead (resting) zone.
if (a > DEAD_ZONE_MIN && a < DEAD_ZONE_MAX) {
a = 0;
}
return a;
}
Director::MovementState App::SampleMovement() const
{
// For now, we just take the average of all controllers which are actually
// pushed in a direction.
float x = 0, y = 0;
float active = 0;
for (auto iter = gameControllers.cbegin();
iter != gameControllers.cend(); ++iter)
{
auto controller = iter->second;
auto ax = SampleControllerAxis(controller, SDL_CONTROLLER_AXIS_LEFTX);
auto ay = SampleControllerAxis(controller, SDL_CONTROLLER_AXIS_LEFTY);
if (ax != 0 || ay != 0) {
x += ax;
y += ay;
active++;
}
}
if (keyUp != 0 || keyRight != 0 || keyDown != 0 || keyLeft != 0) {
x += keyLeft + keyRight;
y += keyUp + keyDown;
active++;
}
if (active == 0) {
x = 0;
y = 0;
}
else {
x /= active;
y /= active;
}
return MovementState(x, y);
}
} // namespace AISDL
<|endoftext|>
|
<commit_before>// Copyright (c) 2014 Roberto Raggi <[email protected]>
//
// 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 "Symbols.h"
#include "Names.h"
#include <iostream>
#include <cassert>
namespace {
static std::string indent(int depth) {
return std::string(4 * depth, ' ');
}
TypeToString typeToString;
} // anonymous namespace
const Name* Symbol::unqualifiedName() const {
auto q = _name ? _name->asQualifiedName() : nullptr;
return q ? q->name() : _name;
}
const Name* Symbol::name() const {
return _name;
}
void Symbol::setName(const Name* name) {
_name = name;
}
QualType Symbol::type() const {
return _type;
}
void Symbol::setType(const QualType& type) {
_type = type;
}
Scope* Symbol::enclosingScope() const {
return _enclosingScope;
}
void Symbol::setEnclosingScope(Scope* enclosingScope) {
_enclosingScope = enclosingScope;
}
void NamespaceSymbol::dump(std::ostream& out, int depth) {
out << indent(depth) << "namespace";
if (auto n = unqualifiedName())
out << " " << n->toString();
out << " {";
out << std::endl;
for (auto sym: symbols()) {
sym->dump(out, depth + 1);
}
out << indent(depth) << "}";
out << std::endl;
}
void BaseClassSymbol::dump(std::ostream& out, int depth) {
assert(!"todo");
}
void ClassSymbol::dump(std::ostream& out, int depth) {
out << indent(depth) << "class";
if (auto n = unqualifiedName())
out << " " << n->toString();
bool first = true;
for (auto&& bc: _baseClasses) {
if (first) {
out << ": ";
first = false;
} else {
out << ", ";
}
out << bc->name()->toString();
}
out << " {";
out << std::endl;
for (auto sym: symbols()) {
sym->dump(out, depth + 1);
}
out << indent(depth) << "}";
out << ';' << std::endl;
}
void TemplateSymbol::dump(std::ostream& out, int depth) {
out << indent(depth) << "template <";
bool first = true;
for (auto sym: symbols()) {
if (first)
first = false;
else
out << ", ";
sym->dump(out, depth + 1);
}
out << ">" << std::endl;
if (auto decl = symbol())
decl->dump(out, depth + 1);
else
out << indent(depth + 1) << "@template-declaration" << std::endl;
}
void TemplateSymbol::addSymbol(Symbol* symbol) {
assert(! _symbol);
_symbol = symbol;
}
void FunctionSymbol::dump(std::ostream& out, int depth) {
auto funTy = type()->asFunctionType();
assert(funTy);
std::vector<const Name*> actuals;
for (auto&& arg: _arguments)
actuals.push_back(arg->name()); // ### this is a bit slow.
out << indent(depth) << typeToString(funTy->returnType(), name())
<< typeToString.prototype(funTy, actuals);
out << " {}" << std::endl;
}
unsigned FunctionSymbol::sourceLocation() const {
return _sourceLocation;
}
void FunctionSymbol::setSourceLocation(unsigned sourceLocation) {
_sourceLocation = sourceLocation;
}
StatementAST** FunctionSymbol::internalNode() const {
return _internalNode;
}
void FunctionSymbol::setInternalNode(StatementAST** internalNode) {
_internalNode = internalNode;
}
void BlockSymbol::dump(std::ostream& out, int depth) {
assert(!"todo");
}
void ArgumentSymbol::dump(std::ostream& out, int depth) {
out << typeToString(type(), name());
}
void DeclarationSymbol::dump(std::ostream& out, int depth) {
out << indent(depth) << typeToString(type(), name());
out << ';' << std::endl;
}
void TypeParameterSymbol::dump(std::ostream& out, int) {
out << "typename";
if (auto id = name())
out << " " << id->toString();
}
void TemplateTypeParameterSymbol::dump(std::ostream& out, int) {
out << "template <@...@> class";
if (auto id = name())
out << " " << id->toString();
}
NamespaceSymbol* Scope::findNamespace(const Name* name) const {
auto q = name ? name->asQualifiedName() : nullptr;
auto u = q ? q->name() : name;
for (auto sym: _symbols) {
if (sym->unqualifiedName() == u && sym->isNamespaceSymbol())
return sym->asNamespaceSymbol();
}
return nullptr;
}
<commit_msg>Show the specified class name instead of the unqualified name.<commit_after>// Copyright (c) 2014 Roberto Raggi <[email protected]>
//
// 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 "Symbols.h"
#include "Names.h"
#include <iostream>
#include <cassert>
namespace {
static std::string indent(int depth) {
return std::string(4 * depth, ' ');
}
TypeToString typeToString;
} // anonymous namespace
const Name* Symbol::unqualifiedName() const {
auto q = _name ? _name->asQualifiedName() : nullptr;
return q ? q->name() : _name;
}
const Name* Symbol::name() const {
return _name;
}
void Symbol::setName(const Name* name) {
_name = name;
}
QualType Symbol::type() const {
return _type;
}
void Symbol::setType(const QualType& type) {
_type = type;
}
Scope* Symbol::enclosingScope() const {
return _enclosingScope;
}
void Symbol::setEnclosingScope(Scope* enclosingScope) {
_enclosingScope = enclosingScope;
}
void NamespaceSymbol::dump(std::ostream& out, int depth) {
out << indent(depth) << "namespace";
if (auto n = unqualifiedName())
out << " " << n->toString();
out << " {";
out << std::endl;
for (auto sym: symbols()) {
sym->dump(out, depth + 1);
}
out << indent(depth) << "}";
out << std::endl;
}
void BaseClassSymbol::dump(std::ostream& out, int depth) {
assert(!"todo");
}
void ClassSymbol::dump(std::ostream& out, int depth) {
out << indent(depth) << "class";
if (auto n = name())
out << " " << n->toString();
bool first = true;
for (auto&& bc: _baseClasses) {
if (first) {
out << ": ";
first = false;
} else {
out << ", ";
}
out << bc->name()->toString();
}
out << " {";
out << std::endl;
for (auto sym: symbols()) {
sym->dump(out, depth + 1);
}
out << indent(depth) << "}";
out << ';' << std::endl;
}
void TemplateSymbol::dump(std::ostream& out, int depth) {
out << indent(depth) << "template <";
bool first = true;
for (auto sym: symbols()) {
if (first)
first = false;
else
out << ", ";
sym->dump(out, depth + 1);
}
out << ">" << std::endl;
if (auto decl = symbol())
decl->dump(out, depth + 1);
else
out << indent(depth + 1) << "@template-declaration" << std::endl;
}
void TemplateSymbol::addSymbol(Symbol* symbol) {
assert(! _symbol);
_symbol = symbol;
}
void FunctionSymbol::dump(std::ostream& out, int depth) {
auto funTy = type()->asFunctionType();
assert(funTy);
std::vector<const Name*> actuals;
for (auto&& arg: _arguments)
actuals.push_back(arg->name()); // ### this is a bit slow.
out << indent(depth) << typeToString(funTy->returnType(), name())
<< typeToString.prototype(funTy, actuals);
out << " {}" << std::endl;
}
unsigned FunctionSymbol::sourceLocation() const {
return _sourceLocation;
}
void FunctionSymbol::setSourceLocation(unsigned sourceLocation) {
_sourceLocation = sourceLocation;
}
StatementAST** FunctionSymbol::internalNode() const {
return _internalNode;
}
void FunctionSymbol::setInternalNode(StatementAST** internalNode) {
_internalNode = internalNode;
}
void BlockSymbol::dump(std::ostream& out, int depth) {
assert(!"todo");
}
void ArgumentSymbol::dump(std::ostream& out, int depth) {
out << typeToString(type(), name());
}
void DeclarationSymbol::dump(std::ostream& out, int depth) {
out << indent(depth) << typeToString(type(), name());
out << ';' << std::endl;
}
void TypeParameterSymbol::dump(std::ostream& out, int) {
out << "typename";
if (auto id = name())
out << " " << id->toString();
}
void TemplateTypeParameterSymbol::dump(std::ostream& out, int) {
out << "template <@...@> class";
if (auto id = name())
out << " " << id->toString();
}
NamespaceSymbol* Scope::findNamespace(const Name* name) const {
auto q = name ? name->asQualifiedName() : nullptr;
auto u = q ? q->name() : name;
for (auto sym: _symbols) {
if (sym->unqualifiedName() == u && sym->isNamespaceSymbol())
return sym->asNamespaceSymbol();
}
return nullptr;
}
<|endoftext|>
|
<commit_before>/*
* Copyright (C) 2011, Paul Tagliamonte <[email protected]>
*
* 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 <iostream>
#include <malloc.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <wait.h>
#include <pty.h>
#include "conf/term.hh"
#include "Exceptions.hh"
#include "Terminal.hh"
#include "Shibuya.hh"
void Terminal::_init_Terminal(int width, int height) {
this->width = width;
this->height = height;
this->cX = 0;
this->cY = 0;
this->cMode = 0x70; // XXX: Globalize
this->scroll_frame_bottom = this->height;
this->scroll_frame_top = 0;
this->pty = -1;
this->chars = (TerminalCell*)
malloc(sizeof(TerminalCell) * (width * height));
for ( int i = 0; i < ( height * width ); ++i ) {
this->chars[i].ch = ' ';
this->chars[i].attr = this->cMode;
}
}
Terminal::~Terminal() {
free( this->chars );
}
Terminal::Terminal() {
this->_init_Terminal(80, 25);
}
Terminal::Terminal( int width, int height ) {
this->_init_Terminal(width, height);
}
void Terminal::erase_to_from( int iX, int iY, int tX, int tY ) {
int from = GET_OFFSET(iX, iY);
int to = GET_OFFSET(tX, tY);
SDEBUG << "Erasing from/to: " << iX << ", " << iY << "(" << from
<< ") -> " << tX << ", " << tY
<< "(" << to << ")" << std::endl;
for ( int i = from; i <= to; ++i ) {
this->chars[i].ch = ' ';
this->chars[i].attr = 0x70;
}
}
void Terminal::scroll_up() {
for (
int iy = this->scroll_frame_top + 1;
iy < this->scroll_frame_bottom;
++iy
) {
for ( int ix = 0; ix < this->width; ++ix ) {
int thisChar = GET_OFFSET(ix, iy);
int lastChar = GET_OFFSET(ix, (iy - 1));
this->chars[lastChar].ch = this->chars[thisChar].ch;
this->chars[lastChar].attr = this->chars[thisChar].attr;
}
}
for ( int ix = 0; ix < this->width; ++ix ) {
int offset = GET_OFFSET( ix, (this->scroll_frame_bottom - 1) );
this->chars[offset].ch = ' ';
this->chars[offset].attr = 0x70;
}
}
void Terminal::scroll_down() {
/*
* ----------------------+--------------------+--------+
* A A A A A A A A A A A | Blank A line | Step 5 | < idex 0
* B B B B B B B B B B B | Copy A line over | Step 4 | < idex 1
* C C C C C C C C C C C | Copy B line over | Step 3 | < idex 2
* D D D D D D D D D D D | Copy C line over | Step 2 | < idex 3
* E E E E E E E E E E E | Copy D line over | Step 1 | < idex 4
* ----------------------+--------------------+--------+
*/
for (
int iy = this->scroll_frame_bottom - 1; // line "E"
iy > this->scroll_frame_top; // line "A"
--iy
) {
for ( int ix = 0; ix < this->width; ++ix ) {
int thisChar = GET_OFFSET(ix, (iy - 1)); // for "E" this is "D"
int lastChar = GET_OFFSET(ix, iy); // for "E" this is "E"
this->chars[lastChar].ch = this->chars[thisChar].ch;
this->chars[lastChar].attr = this->chars[thisChar].attr;
}
}
for ( int ix = 0; ix < this->width; ++ix ) {
int thisChar = GET_OFFSET(ix, this->scroll_frame_top);
this->chars[thisChar].ch = ' ';
this->chars[thisChar].attr = 0x70;
}
}
void Terminal::sigint() {
this->type( 0x03 );
}
pid_t Terminal::fork( const char * command ) {
struct winsize ws;
ws.ws_row = this->height;
ws.ws_col = this->width;
ws.ws_xpixel = 0;
ws.ws_ypixel = 0;
pid_t childpid = forkpty(&this->pty, NULL, NULL, &ws);
if (childpid < 0) return -1;
if (childpid == 0) {
setenv("TERM", TERMINAL_ENV_NAME, 1);
execl(command, command, NULL);
std::cerr << "Failed to fork." << std::endl;
exit(127);
}
/* if we got here we are the parent process */
this->childpid = childpid;
return childpid;
}
void Terminal::poke() {
/*
* A good deal of this was inspired by `librote'. Mad gangster-props to
* librote.
*/
fd_set ifs;
struct timeval tvzero;
char buf[512];
int bytesread;
int n = 5; // XXX: Fix?
int status;
if (this->pty < 0)
return;
pid_t result = waitpid(this->childpid, &status, WNOHANG);
switch ( result ) {
case 0:
/* If waitpid() was invoked with WNOHANG set in options, and there
* are children specified by pid for which status is not available,
* waitpid() returns 0 */
break;
case -1:
/* Otherwise, it returns -1 and sets errno to one of the following
* values */
SDEBUG << "Error in PID wait." << std::endl;
switch ( errno ) {
case ECHILD:
/* The process or process group specified by pid does not
* exist or is not a child of the calling process. */
SDEBUG << " => pid (" << this->childpid <<
") does not exist." << std::endl;
break;
case EFAULT:
/* stat_loc is not a writable address. */
SDEBUG << " => pid is out of our segment" << std::endl;
break;
case EINTR:
/* The function was interrupted by a signal. The value of
* the location pointed to by stat_loc is undefined. */
SDEBUG << " => wait() hit with a signal" << std::endl;
break;
case EINVAL:
/* The options argument is not valid. */
SDEBUG << " => wait() arguments not valid" << std::endl;
break;
case ENOSYS:
/* pid specifies a process group (0 or less than -1), which
* is not currently supported. */
SDEBUG << " => pid is less then 1" << std::endl;
break;
}
break;
default:
/* Our child died :'( */
SDEBUG << "Child PID: " << this->childpid << " has died."
<< std::endl;
throw new DeadChildException();
// ^^ This will force whatever else to clean up the mess
// ( if you will pardon the term )
break;
}
/* This bit here taken from librote almost directly */
while (n--) {
FD_ZERO(&ifs);
FD_SET(this->pty, &ifs);
tvzero.tv_sec = 0;
tvzero.tv_usec = 0;
if (select(this->pty + 1, &ifs, NULL, NULL, &tvzero) <= 0)
return;
bytesread = read(this->pty, buf, 512);
if (bytesread <= 0)
return;
for ( int i = 0; i < bytesread; ++i )
this->insert( buf[i] );
}
}
void Terminal::insert( unsigned char c ) {
switch ( c ) {
case '\n':
this->newline();
break;
case 8: /* Backspace */
SDEBUG << "Backspace" << this->cX << " -> ";
if ( this->cX > 0 )
--this->cX;
SDEBUG << this->cX << std::endl;
break;
case 9: /* Tab */
SDEBUG << "TAB!" << std::endl;
while ( ( this->cX % 8 ) != 0 )
this->insert(' ');
break;
}
/* No need to return above, because of below :) */
if ( c < 32 )
return;
/* Alright. We've got something printable. Let's deal with it. */
int ix = this->cX;
int iy = this->cY;
/*
* XXX: Why was the math using this->cX failing?
* for some reason we have to bring it into the local
* scope...
*/
int offset = GET_OFFSET(ix, iy);
this->chars[offset].ch = c;
this->chars[offset].attr = this->cMode;
this->cX++;
this->bounds_check();
}
void Terminal::type( char c ) {
write(this->pty, &c, 1);
}
void Terminal::newline() {
this->cX = 0;
this->cY++;
if ( this->scroll_frame_bottom <= this->cY ) {
this->cY = (this->scroll_frame_bottom - 1);
this->scroll_up();
}
}
void Terminal::bounds_check() {
if ( this->width < this->cX ) {
this->newline();
}
if ( this->cX < 0 ) {
this->cX = this->width;
this->cY = ( this->cY < 0 ) ? 0 : this->cY;
}
}
int Terminal::get_width() {
return this->width;
}
int Terminal::get_height() {
return this->height;
}
void Terminal::delete_line( int idex ) {
int oldfloor = scroll_frame_top;
this->scroll_frame_top = idex;
this->scroll_up();
scroll_frame_top = oldfloor;
}
void Terminal::insert_line( int idex ) {
int oldfloor = scroll_frame_top;
this->scroll_frame_top = idex;
this->scroll_down();
scroll_frame_top = oldfloor;
}
<commit_msg>Removing this bit for clarity<commit_after>/*
* Copyright (C) 2011, Paul Tagliamonte <[email protected]>
*
* 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 <iostream>
#include <malloc.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <wait.h>
#include <pty.h>
#include "conf/term.hh"
#include "Exceptions.hh"
#include "Terminal.hh"
#include "Shibuya.hh"
void Terminal::_init_Terminal(int width, int height) {
this->width = width;
this->height = height;
this->cX = 0;
this->cY = 0;
this->cMode = 0x70; // XXX: Globalize
this->scroll_frame_bottom = this->height;
this->scroll_frame_top = 0;
this->pty = -1;
this->chars = (TerminalCell*)
malloc(sizeof(TerminalCell) * (width * height));
for ( int i = 0; i < ( height * width ); ++i ) {
this->chars[i].ch = ' ';
this->chars[i].attr = this->cMode;
}
}
Terminal::~Terminal() {
free( this->chars );
}
Terminal::Terminal() {
this->_init_Terminal(80, 25);
}
Terminal::Terminal( int width, int height ) {
this->_init_Terminal(width, height);
}
void Terminal::erase_to_from( int iX, int iY, int tX, int tY ) {
int from = GET_OFFSET(iX, iY);
int to = GET_OFFSET(tX, tY);
SDEBUG << "Erasing from/to: " << iX << ", " << iY << "(" << from
<< ") -> " << tX << ", " << tY
<< "(" << to << ")" << std::endl;
for ( int i = from; i <= to; ++i ) {
this->chars[i].ch = ' ';
this->chars[i].attr = 0x70;
}
}
void Terminal::scroll_up() {
for (
int iy = this->scroll_frame_top + 1;
iy < this->scroll_frame_bottom;
++iy
) {
for ( int ix = 0; ix < this->width; ++ix ) {
int thisChar = GET_OFFSET(ix, iy);
int lastChar = GET_OFFSET(ix, (iy - 1));
this->chars[lastChar].ch = this->chars[thisChar].ch;
this->chars[lastChar].attr = this->chars[thisChar].attr;
}
}
for ( int ix = 0; ix < this->width; ++ix ) {
int offset = GET_OFFSET( ix, (this->scroll_frame_bottom - 1) );
this->chars[offset].ch = ' ';
this->chars[offset].attr = 0x70;
}
}
void Terminal::scroll_down() {
/*
* ----------------------+--------------------+--------+
* A A A A A A A A A A A | Blank A line | Step 5 | < idex 0
* B B B B B B B B B B B | Copy A line over | Step 4 | < idex 1
* C C C C C C C C C C C | Copy B line over | Step 3 | < idex 2
* D D D D D D D D D D D | Copy C line over | Step 2 | < idex 3
* E E E E E E E E E E E | Copy D line over | Step 1 | < idex 4
* ----------------------+--------------------+--------+
*/
for (
int iy = this->scroll_frame_bottom - 1; // line "E"
iy > this->scroll_frame_top; // line "A"
--iy
) {
for ( int ix = 0; ix < this->width; ++ix ) {
int thisChar = GET_OFFSET(ix, (iy - 1)); // for "E" this is "D"
int lastChar = GET_OFFSET(ix, iy); // for "E" this is "E"
this->chars[lastChar].ch = this->chars[thisChar].ch;
this->chars[lastChar].attr = this->chars[thisChar].attr;
}
}
for ( int ix = 0; ix < this->width; ++ix ) {
int thisChar = GET_OFFSET(ix, this->scroll_frame_top);
this->chars[thisChar].ch = ' ';
this->chars[thisChar].attr = 0x70;
}
}
void Terminal::sigint() {
this->type( 0x03 );
}
pid_t Terminal::fork( const char * command ) {
struct winsize ws;
ws.ws_row = this->height;
ws.ws_col = this->width;
ws.ws_xpixel = 0;
ws.ws_ypixel = 0;
pid_t childpid = forkpty(&this->pty, NULL, NULL, &ws);
if (childpid < 0) return -1;
if (childpid == 0) {
setenv("TERM", TERMINAL_ENV_NAME, 1);
execl(command, command, NULL);
std::cerr << "Failed to fork." << std::endl;
exit(127);
}
/* if we got here we are the parent process */
this->childpid = childpid;
return childpid;
}
void Terminal::poke() {
/*
* A good deal of this was inspired by `librote'. Mad gangster-props to
* librote.
*/
fd_set ifs;
struct timeval tvzero;
char buf[512];
int bytesread;
int n = 5; // XXX: Fix?
int status;
if (this->pty < 0)
return;
pid_t result = waitpid(this->childpid, &status, WNOHANG);
switch ( result ) {
case 0:
/* If waitpid() was invoked with WNOHANG set in options, and there
* are children specified by pid for which status is not available,
* waitpid() returns 0 */
break;
case -1:
/* Otherwise, it returns -1 and sets errno to one of the following
* values */
SDEBUG << "Error in PID wait." << std::endl;
switch ( errno ) {
case ECHILD:
/* The process or process group specified by pid does not
* exist or is not a child of the calling process. */
SDEBUG << " => pid (" << this->childpid <<
") does not exist." << std::endl;
break;
case EFAULT:
/* stat_loc is not a writable address. */
SDEBUG << " => pid is out of our segment" << std::endl;
break;
case EINTR:
/* The function was interrupted by a signal. The value of
* the location pointed to by stat_loc is undefined. */
SDEBUG << " => wait() hit with a signal" << std::endl;
break;
case EINVAL:
/* The options argument is not valid. */
SDEBUG << " => wait() arguments not valid" << std::endl;
break;
case ENOSYS:
/* pid specifies a process group (0 or less than -1), which
* is not currently supported. */
SDEBUG << " => pid is less then 1" << std::endl;
break;
}
break;
default:
/* Our child died :'( */
SDEBUG << "Child PID: " << this->childpid << " has died."
<< std::endl;
throw new DeadChildException();
// ^^ This will force whatever else to clean up the mess
// ( if you will pardon the term )
break;
}
/* This bit here taken from librote almost directly */
while (n--) {
FD_ZERO(&ifs);
FD_SET(this->pty, &ifs);
tvzero.tv_sec = 0;
tvzero.tv_usec = 0;
if (select(this->pty + 1, &ifs, NULL, NULL, &tvzero) <= 0)
return;
bytesread = read(this->pty, buf, 512);
if (bytesread <= 0)
return;
for ( int i = 0; i < bytesread; ++i )
this->insert( buf[i] );
}
}
void Terminal::insert( unsigned char c ) {
switch ( c ) {
case '\n':
this->newline();
break;
case 8: /* Backspace */
SDEBUG << "Backspace" << this->cX << " -> ";
if ( this->cX > 0 )
--this->cX;
SDEBUG << this->cX << std::endl;
break;
case 9: /* Tab */
SDEBUG << "TAB!" << std::endl;
while ( ( this->cX % 8 ) != 0 )
this->insert(' ');
break;
}
/* No need to return above, because of below :) */
if ( c < 32 )
return;
/* Alright. We've got something printable. Let's deal with it. */
int ix = this->cX;
int iy = this->cY;
/*
* XXX: Why was the math using this->cX failing?
* for some reason we have to bring it into the local
* scope...
*/
int offset = GET_OFFSET(ix, iy);
this->chars[offset].ch = c;
this->chars[offset].attr = this->cMode;
this->cX++;
this->bounds_check();
}
void Terminal::type( char c ) {
write(this->pty, &c, 1);
}
void Terminal::newline() {
this->cX = 0;
this->cY++;
if ( this->scroll_frame_bottom <= this->cY ) {
this->cY = (this->scroll_frame_bottom - 1);
this->scroll_up();
}
}
void Terminal::bounds_check() {
if ( this->width < this->cX ) {
this->newline();
}
/* if ( this->cX < 0 ) {
this->cX = this->width;
this->cY = ( this->cY < 0 ) ? 0 : this->cY;
} */
}
int Terminal::get_width() {
return this->width;
}
int Terminal::get_height() {
return this->height;
}
void Terminal::delete_line( int idex ) {
int oldfloor = scroll_frame_top;
this->scroll_frame_top = idex;
this->scroll_up();
scroll_frame_top = oldfloor;
}
void Terminal::insert_line( int idex ) {
int oldfloor = scroll_frame_top;
this->scroll_frame_top = idex;
this->scroll_down();
scroll_frame_top = oldfloor;
}
<|endoftext|>
|
<commit_before>/*
* The MIT License (MIT)
*
* Copyright (c) 2015 vmolsa <[email protected]> (http://github.com/vmolsa)
*
* 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 "uv.h"
#include "Core.h"
#ifdef WIN32
#include "webrtc/base/win32socketinit.h"
#endif
using namespace WebRTC;
rtc::scoped_refptr<webrtc::PeerConnectionFactoryInterface> _factory;
rtc::scoped_ptr<cricket::DeviceManagerInterface> _manager;
uv_check_t _msg;
static void ProcessMessages(uv_check_t* handle) {
rtc::Thread::Current()->ProcessMessages(0);
}
void Core::Init() {
#ifdef WIN32
rtc::EnsureWinsockInit();
#endif
uv_check_init(uv_default_loop(), &_msg);
uv_check_start(&_msg, ProcessMessages);
uv_unref(reinterpret_cast<uv_handle_t*>(&_msg));
rtc::InitializeSSL();
_factory = webrtc::CreatePeerConnectionFactory();
_manager.reset(cricket::DeviceManagerFactory::Create());
if (!_manager->Init()) {
_manager.release();
}
}
void Core::Dispose() {
uv_check_stop(&_msg);
_factory.release();
if (_manager.get()) {
_manager->Terminate();
}
_manager.release();
}
webrtc::PeerConnectionFactoryInterface* Core::GetFactory() {
return _factory.get();
}
cricket::DeviceManagerInterface* Core::GetManager() {
return _manager.get();
}<commit_msg>Use webrtc thread for signaling<commit_after>/*
* The MIT License (MIT)
*
* Copyright (c) 2015 vmolsa <[email protected]> (http://github.com/vmolsa)
*
* 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 "uv.h"
#include "Core.h"
#ifdef WIN32
#include "webrtc/base/win32socketinit.h"
#endif
using namespace WebRTC;
rtc::Thread *_signal, *_worker;
rtc::scoped_refptr<webrtc::PeerConnectionFactoryInterface> _factory;
rtc::scoped_ptr<cricket::DeviceManagerInterface> _manager;
//uv_check_t _msg;
/*
static void ProcessMessages(uv_check_t* handle) {
rtc::Thread::Current()->ProcessMessages(0);
}
*/
class ProcessMessages : public rtc::Runnable {
public:
virtual void Run(rtc::Thread* thread) {
thread->ProcessMessages(rtc::ThreadManager::kForever);
}
};
void Core::Init() {
ProcessMessages task;
#ifdef WIN32
rtc::EnsureWinsockInit();
#endif
//uv_check_init(uv_default_loop(), &_msg);
//uv_check_start(&_msg, ProcessMessages);
//uv_unref(reinterpret_cast<uv_handle_t*>(&_msg));
rtc::InitializeSSL();
_signal = new rtc::Thread();
_worker = new rtc::Thread();
_signal->Start(&task);
_worker->Start(&task);
_factory = webrtc::CreatePeerConnectionFactory(_signal, _worker, NULL, NULL, NULL);
_manager.reset(cricket::DeviceManagerFactory::Create());
if (!_manager->Init()) {
_manager.release();
}
}
void Core::Dispose() {
//uv_check_stop(&_msg);
_factory.release();
if (_manager.get()) {
_manager->Terminate();
}
_manager.release();
_signal->Stop();
_worker->Stop();
delete _signal;
delete _worker;
}
webrtc::PeerConnectionFactoryInterface* Core::GetFactory() {
return _factory.get();
}
cricket::DeviceManagerInterface* Core::GetManager() {
return _manager.get();
}<|endoftext|>
|
<commit_before>#include <string>
#include "nbind/api.h"
#include "control.h"
#include "ui.h"
class UiButton : public UiControl {
DEFINE_EVENT(onClicked)
public:
UiButton(std::string text);
UiButton();
DEFINE_CONTROL_METHODS()
void setText(std::string text);
std::string getText();
~UiButton();
void onDestroy(uiControl *control) override;
};
void UiButton::onDestroy(uiControl *control) {
/*
freeing event callbacks to allow JS to garbage collect this class
when there are no references to it left in JS code.
*/
DISPOSE_EVENT(onClicked);
}
UiButton::~UiButton() {
// printf("UiButton %p destroyed with wrapper %p.\n", getHandle(), this);
}
UiButton::UiButton(std::string text)
: UiControl(uiControl(uiNewButton(text.c_str()))) {}
UiButton::UiButton() : UiControl(uiControl(uiNewButton(""))) {}
INHERITS_CONTROL_METHODS(UiButton)
void UiButton::setText(std::string text) {
uiButtonSetText(uiButton(getHandle()), text.c_str());
}
std::string UiButton::getText() {
char *char_ptr = uiButtonText(uiButton(getHandle()));
std::string s(char_ptr);
uiFreeText(char_ptr);
return s;
}
IMPLEMENT_EVENT(UiButton, uiButton, onClicked, uiButtonOnClicked)
NBIND_CLASS(UiButton) {
construct<std::string>();
construct<>();
DECLARE_CHILD_CONTROL_METHODS()
getset(getText, setText);
method(getText);
method(setText);
method(onClicked);
}
<commit_msg>removed macro -> UiButton<commit_after>#include <string>
#include "nbind/api.h"
#include "control.h"
#include "ui.h"
class UiButton : public UiControl {
DEFINE_EVENT(onClicked)
public:
UiButton(std::string text);
UiButton();
void setText(std::string text);
std::string getText();
~UiButton();
void onDestroy(uiControl *control) override;
};
void UiButton::onDestroy(uiControl *control) {
/*
freeing event callbacks to allow JS to garbage collect this class
when there are no references to it left in JS code.
*/
DISPOSE_EVENT(onClicked);
}
UiButton::~UiButton() {
// printf("UiButton %p destroyed with wrapper %p.\n", getHandle(), this);
}
UiButton::UiButton(std::string text)
: UiControl(uiControl(uiNewButton(text.c_str()))) {}
UiButton::UiButton() : UiControl(uiControl(uiNewButton(""))) {}
void UiButton::setText(std::string text) {
uiButtonSetText(uiButton(getHandle()), text.c_str());
}
std::string UiButton::getText() {
char *char_ptr = uiButtonText(uiButton(getHandle()));
std::string s(char_ptr);
uiFreeText(char_ptr);
return s;
}
IMPLEMENT_EVENT(UiButton, uiButton, onClicked, uiButtonOnClicked)
NBIND_CLASS(UiButton) {
inherit(UiControl);
construct<std::string>();
construct<>();
getset(getText, setText);
method(getText);
method(setText);
method(onClicked);
}
<|endoftext|>
|
<commit_before>#include "clause.hpp"
#include "internal.hpp"
#include "iterator.hpp"
#include "macros.hpp"
#include "message.hpp"
#include "proof.hpp"
#include <algorithm>
#include <cmath>
namespace CaDiCaL {
// Code for conflict analysis, e.g., to generate the first UIP clause. The
// main function is 'analyze' below. It further uses 'minimize' to minimize
// the first UIP clause, which is in 'minimize.cpp'. An important side
// effect of conflict analysis is to update the decision queue by bumping
// variables. Similarly analyzed clauses are bumped to mark them as active.
/*------------------------------------------------------------------------*/
void Internal::learn_empty_clause () {
assert (!unsat);
LOG ("learned empty clause");
if (proof) proof->trace_empty_clause ();
unsat = true;
}
void Internal::learn_unit_clause (int lit) {
LOG ("learned unit clause %d", lit);
if (proof) proof->trace_unit_clause (lit);
stats.fixed++;
}
/*------------------------------------------------------------------------*/
// Important variables recently used in conflict analysis are 'bumped',
// which means to move them to the front of the VMTF decision queue. The
// 'bumped' time stamp is updated accordingly. It is used to determine
// whether the 'queue.assigned' pointer has to be moved in 'unassign'.
void Internal::bump_variable (int lit) {
const int idx = vidx (lit);
Link * l = ltab + idx;
if (!l->next) return;
queue.dequeue (ltab, l);
queue.enqueue (ltab, l);
btab[idx] = ++stats.bumped;
if (var (idx).level == level) stats.bumplast++;
LOG ("moved to front %d and bumped %ld", idx, btab[idx]);
if (!vals[idx]) update_queue_unassigned (idx);
}
struct bumped_earlier {
Internal * internal;
bumped_earlier (Internal * i) : internal (i) { }
bool operator () (int a, int b) {
return internal->bumped (a) < internal->bumped (b);
}
};
struct trail_bumped_smaller {
Internal * internal;
trail_bumped_smaller (Internal * i) : internal (i) { }
bool operator () (int a, int b) {
long c = internal->var (a).trail, s = internal->bumped (a) + c;
long d = internal->var (b).trail, t = internal->bumped (b) + d;
if (s < t) return true;
if (s > t) return false;
return c < d;
}
};
void Internal::bump_variables () {
START (bump);
if (opts.trailbump &&
relative (stats.propagations, stats.decisions) > opts.trailbumprops &&
percent (stats.bumplast, stats.bumped) > opts.trailbumplast) {
// There are some instances (for instance the 'newton...' instances),
// which have a very high number of propagations per decision if we try
// to maintain previous bump order as much as possible. They go through
// easily if more recent propagated variables are bumped last, which
// also reduces propagations per decision by two orders of magnitude.
// It seems that this is related to the high percentage of bumped
// variables on the highest decision level. So if this percentage is
// high and we have many propagations per decision, then we take the
// assignment order into account too by comparing with respect to the
// sum of bumped and trail order. For the instances mentioned above just
// comparing with respect to assignment order (e.g., trail height when
// assigned) would work too, but this is in general less robust and thus
// we use the sum instead with the trail height as (stable) tie-breaker.
sort (analyzed.begin (), analyzed.end (), trail_bumped_smaller (this));
stats.trailbumped++;
} else {
// Otherwise the default is to bump the variable in the order they are
// in the current decision queue. This maintains relative order between
// bumped variables in the queue and seems to work best for those
// instance with smaller number of bumped variables on the last decision
// level.
sort (analyzed.begin (), analyzed.end (), bumped_earlier (this));
}
for (const_int_iterator i = analyzed.begin (); i != analyzed.end (); i++)
bump_variable (*i);
STOP (bump);
}
/*------------------------------------------------------------------------*/
// Clause activity is replaced by a move-to-front scheme as well with
// 'analyzed' as time stamp. Only long and high glue clauses are stamped
// since small or low glue clauses are kept anyhow (and do not actually have
// a 'analyzed' field). We keep the relative order of bumped clauses by
// sorting them first.
void Internal::bump_analyzed_clauses () {
START (bump);
sort (resolved.begin (), resolved.end (), analyzed_earlier ());
for (const_clause_iterator i = resolved.begin (); i != resolved.end (); i++)
(*i)->analyzed () = ++stats.analyzed;
STOP (bump);
resolved.clear ();
}
inline void Internal::analyze_clause (Clause * c) {
if (!c->redundant) return;
if (c->size <= opts.keepsize) return;
if (c->glue <= opts.keepglue) return;
assert (c->extended);
resolved.push_back (c);
}
/*------------------------------------------------------------------------*/
// During conflict analysis literals not seen yet either become part of the
// first UIP clause (if on lower decision level), are dropped (if fixed),
// or are resolved away (if on the current decision level and different from
// the first UIP). At the same time we update the number of seen literals on
// a decision level. This helps conflict clause minimization. The number
// of seen levels is the glucose level (also called glue, or LBD).
inline void Internal::analyze_literal (int lit, int & open) {
assert (lit);
Flags & f = flags (lit);
if (f.seen ()) return;
Var & v = var (lit);
if (!v.level) return;
assert (val (lit) < 0);
if (v.level < level) clause.push_back (lit);
Level & l = control[v.level];
if (!l.seen++) {
LOG ("found new level %d contributing to conflict", v.level);
levels.push_back (v.level);
}
if (v.trail < l.trail) l.trail = v.trail;
f.set (SEEN);
analyzed.push_back (lit);
LOG ("analyzed literal %d assigned at level %d", lit, v.level);
if (v.level == level) open++;
}
inline void
Internal::analyze_reason (int lit, Clause * reason, int & open) {
assert (reason);
const const_literal_iterator end = reason->end ();
const_literal_iterator j = reason->begin ();
int other;
while (j != end)
if ((other = *j++) != lit)
analyze_literal (other, open);
}
/*------------------------------------------------------------------------*/
void Internal::clear_seen () {
for (const_int_iterator i = analyzed.begin (); i != analyzed.end (); i++) {
Flags & f = flags (*i);
assert (f.seen ());
f.clear (SEEN);
assert (!f);
}
analyzed.clear ();
}
void Internal::clear_levels () {
for (const_int_iterator i = levels.begin (); i != levels.end (); i++)
control[*i].reset ();
levels.clear ();
}
/*------------------------------------------------------------------------*/
void Internal::analyze () {
assert (conflict);
if (!level) { learn_empty_clause (); return; }
START (analyze);
// First derive the first UIP clause.
//
Clause * reason = conflict;
LOG (reason, "analyzing conflict");
int open = 0, uip = 0, other = 0;
const_int_iterator i = trail.end ();
for (;;) {
if (reason) analyze_reason (uip, reason, open);
else analyze_literal (other, open);
while (!flags (uip = *--i).seen ())
;
if (!--open) break;
Var & v = var (uip);
if (!(reason = v.reason)) other = v.other;
#ifdef LOGGING
if (reason) LOG (reason, "analyzing %d reason", uip);
else LOG ("analyzing %d binary reason %d %d", uip, uip, other);
#endif
}
LOG ("first UIP %d", uip);
clause.push_back (-uip);
check_clause ();
// Update glue statistics.
//
bump_analyzed_clauses ();
const int glue = (int) levels.size ();
LOG ("1st UIP clause of size %ld and glue %d",
(long) clause.size (), glue);
UPDATE_AVG (fast_glue_avg, glue);
UPDATE_AVG (slow_glue_avg, glue);
if (lim.decision_level_at_last_restart) {
double x = relative (level, lim.decision_level_at_last_restart);
LOG ("last restart effectiveness %.2f", x);
UPDATE_AVG (restarteff, x);
lim.decision_level_at_last_restart = 0;
}
int size = (int) clause.size ();
stats.learned += size;
if (size > 1) {
if (opts.minimize) minimize_clause ();
if (opts.shrink && size <= opts.shrinksize && glue <= opts.shrinkglue)
shrink_clause ();
size = (int) clause.size ();
}
stats.units += (size == 1);
stats.binaries += (size == 2);
UPDATE_AVG (size_avg, size);
if (size > 1 && opts.sublast) eagerly_subsume_last_learned ();
bump_variables (); // Update decision heuristics.
// Determine back jump level, backtrack and assign flipped literal.
//
Clause * driving_clause = 0;
int jump = 0;
if (size > 1) {
sort (clause.rbegin (), clause.rend (), trail_smaller (this));
driving_clause = new_learned_redundant_clause (glue);
jump = var (clause[1]).level;
} else iterating = true;
UPDATE_AVG (jump_avg, jump);
backtrack (jump);
assign (-uip, driving_clause);
// Clean up.
//
clear_seen ();
clause.clear ();
clear_levels ();
conflict = 0;
STOP (analyze);
}
// We wait reporting a learned unit until propagation of that unit is
// completed. Otherwise the 'i' report line might prematurely give the
// number of remaining variables.
void Internal::iterate () { iterating = false; report ('i'); }
};
<commit_msg>added back removed "analyze_clause" aka "resolve_clause"<commit_after>#include "clause.hpp"
#include "internal.hpp"
#include "iterator.hpp"
#include "macros.hpp"
#include "message.hpp"
#include "proof.hpp"
#include <algorithm>
#include <cmath>
namespace CaDiCaL {
// Code for conflict analysis, e.g., to generate the first UIP clause. The
// main function is 'analyze' below. It further uses 'minimize' to minimize
// the first UIP clause, which is in 'minimize.cpp'. An important side
// effect of conflict analysis is to update the decision queue by bumping
// variables. Similarly analyzed clauses are bumped to mark them as active.
/*------------------------------------------------------------------------*/
void Internal::learn_empty_clause () {
assert (!unsat);
LOG ("learned empty clause");
if (proof) proof->trace_empty_clause ();
unsat = true;
}
void Internal::learn_unit_clause (int lit) {
LOG ("learned unit clause %d", lit);
if (proof) proof->trace_unit_clause (lit);
stats.fixed++;
}
/*------------------------------------------------------------------------*/
// Important variables recently used in conflict analysis are 'bumped',
// which means to move them to the front of the VMTF decision queue. The
// 'bumped' time stamp is updated accordingly. It is used to determine
// whether the 'queue.assigned' pointer has to be moved in 'unassign'.
void Internal::bump_variable (int lit) {
const int idx = vidx (lit);
Link * l = ltab + idx;
if (!l->next) return;
queue.dequeue (ltab, l);
queue.enqueue (ltab, l);
btab[idx] = ++stats.bumped;
if (var (idx).level == level) stats.bumplast++;
LOG ("moved to front %d and bumped %ld", idx, btab[idx]);
if (!vals[idx]) update_queue_unassigned (idx);
}
struct bumped_earlier {
Internal * internal;
bumped_earlier (Internal * i) : internal (i) { }
bool operator () (int a, int b) {
return internal->bumped (a) < internal->bumped (b);
}
};
struct trail_bumped_smaller {
Internal * internal;
trail_bumped_smaller (Internal * i) : internal (i) { }
bool operator () (int a, int b) {
long c = internal->var (a).trail, s = internal->bumped (a) + c;
long d = internal->var (b).trail, t = internal->bumped (b) + d;
if (s < t) return true;
if (s > t) return false;
return c < d;
}
};
void Internal::bump_variables () {
START (bump);
if (opts.trailbump &&
relative (stats.propagations, stats.decisions) > opts.trailbumprops &&
percent (stats.bumplast, stats.bumped) > opts.trailbumplast) {
// There are some instances (for instance the 'newton...' instances),
// which have a very high number of propagations per decision if we try
// to maintain previous bump order as much as possible. They go through
// easily if more recent propagated variables are bumped last, which
// also reduces propagations per decision by two orders of magnitude.
// It seems that this is related to the high percentage of bumped
// variables on the highest decision level. So if this percentage is
// high and we have many propagations per decision, then we take the
// assignment order into account too by comparing with respect to the
// sum of bumped and trail order. For the instances mentioned above just
// comparing with respect to assignment order (e.g., trail height when
// assigned) would work too, but this is in general less robust and thus
// we use the sum instead with the trail height as (stable) tie-breaker.
sort (analyzed.begin (), analyzed.end (), trail_bumped_smaller (this));
stats.trailbumped++;
} else {
// Otherwise the default is to bump the variable in the order they are
// in the current decision queue. This maintains relative order between
// bumped variables in the queue and seems to work best for those
// instance with smaller number of bumped variables on the last decision
// level.
sort (analyzed.begin (), analyzed.end (), bumped_earlier (this));
}
for (const_int_iterator i = analyzed.begin (); i != analyzed.end (); i++)
bump_variable (*i);
STOP (bump);
}
/*------------------------------------------------------------------------*/
// Clause activity is replaced by a move-to-front scheme as well with
// 'analyzed' as time stamp. Only long and high glue clauses are stamped
// since small or low glue clauses are kept anyhow (and do not actually have
// a 'analyzed' field). We keep the relative order of bumped clauses by
// sorting them first.
void Internal::bump_analyzed_clauses () {
START (bump);
sort (resolved.begin (), resolved.end (), analyzed_earlier ());
for (const_clause_iterator i = resolved.begin (); i != resolved.end (); i++)
(*i)->analyzed () = ++stats.analyzed;
STOP (bump);
resolved.clear ();
}
inline void Internal::analyze_clause (Clause * c) {
if (!c->redundant) return;
if (c->size <= opts.keepsize) return;
if (c->glue <= opts.keepglue) return;
assert (c->extended);
resolved.push_back (c);
}
/*------------------------------------------------------------------------*/
// During conflict analysis literals not seen yet either become part of the
// first UIP clause (if on lower decision level), are dropped (if fixed),
// or are resolved away (if on the current decision level and different from
// the first UIP). At the same time we update the number of seen literals on
// a decision level. This helps conflict clause minimization. The number
// of seen levels is the glucose level (also called glue, or LBD).
inline void Internal::analyze_literal (int lit, int & open) {
assert (lit);
Flags & f = flags (lit);
if (f.seen ()) return;
Var & v = var (lit);
if (!v.level) return;
assert (val (lit) < 0);
if (v.level < level) clause.push_back (lit);
Level & l = control[v.level];
if (!l.seen++) {
LOG ("found new level %d contributing to conflict", v.level);
levels.push_back (v.level);
}
if (v.trail < l.trail) l.trail = v.trail;
f.set (SEEN);
analyzed.push_back (lit);
LOG ("analyzed literal %d assigned at level %d", lit, v.level);
if (v.level == level) open++;
}
inline void
Internal::analyze_reason (int lit, Clause * reason, int & open) {
assert (reason);
analyze_clause (reason);
const const_literal_iterator end = reason->end ();
const_literal_iterator j = reason->begin ();
int other;
while (j != end)
if ((other = *j++) != lit)
analyze_literal (other, open);
}
/*------------------------------------------------------------------------*/
void Internal::clear_seen () {
for (const_int_iterator i = analyzed.begin (); i != analyzed.end (); i++) {
Flags & f = flags (*i);
assert (f.seen ());
f.clear (SEEN);
assert (!f);
}
analyzed.clear ();
}
void Internal::clear_levels () {
for (const_int_iterator i = levels.begin (); i != levels.end (); i++)
control[*i].reset ();
levels.clear ();
}
/*------------------------------------------------------------------------*/
void Internal::analyze () {
assert (conflict);
if (!level) { learn_empty_clause (); return; }
START (analyze);
// First derive the first UIP clause.
//
Clause * reason = conflict;
LOG (reason, "analyzing conflict");
int open = 0, uip = 0, other = 0;
const_int_iterator i = trail.end ();
for (;;) {
if (reason) analyze_reason (uip, reason, open);
else analyze_literal (other, open);
while (!flags (uip = *--i).seen ())
;
if (!--open) break;
Var & v = var (uip);
if (!(reason = v.reason)) other = v.other;
#ifdef LOGGING
if (reason) LOG (reason, "analyzing %d reason", uip);
else LOG ("analyzing %d binary reason %d %d", uip, uip, other);
#endif
}
LOG ("first UIP %d", uip);
clause.push_back (-uip);
check_clause ();
// Update glue statistics.
//
bump_analyzed_clauses ();
const int glue = (int) levels.size ();
LOG ("1st UIP clause of size %ld and glue %d",
(long) clause.size (), glue);
UPDATE_AVG (fast_glue_avg, glue);
UPDATE_AVG (slow_glue_avg, glue);
if (lim.decision_level_at_last_restart) {
double x = relative (level, lim.decision_level_at_last_restart);
LOG ("last restart effectiveness %.2f", x);
UPDATE_AVG (restarteff, x);
lim.decision_level_at_last_restart = 0;
}
int size = (int) clause.size ();
stats.learned += size;
if (size > 1) {
if (opts.minimize) minimize_clause ();
if (opts.shrink && size <= opts.shrinksize && glue <= opts.shrinkglue)
shrink_clause ();
size = (int) clause.size ();
}
stats.units += (size == 1);
stats.binaries += (size == 2);
UPDATE_AVG (size_avg, size);
if (size > 1 && opts.sublast) eagerly_subsume_last_learned ();
bump_variables (); // Update decision heuristics.
// Determine back jump level, backtrack and assign flipped literal.
//
Clause * driving_clause = 0;
int jump = 0;
if (size > 1) {
sort (clause.rbegin (), clause.rend (), trail_smaller (this));
driving_clause = new_learned_redundant_clause (glue);
jump = var (clause[1]).level;
} else iterating = true;
UPDATE_AVG (jump_avg, jump);
backtrack (jump);
assign (-uip, driving_clause);
// Clean up.
//
clear_seen ();
clause.clear ();
clear_levels ();
conflict = 0;
STOP (analyze);
}
// We wait reporting a learned unit until propagation of that unit is
// completed. Otherwise the 'i' report line might prematurely give the
// number of remaining variables.
void Internal::iterate () { iterating = false; report ('i'); }
};
<|endoftext|>
|
<commit_before>#include <stdio.h>
#include <string>
#include <boost/python.hpp>
#include <sys/stat.h>
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <fcntl.h>
#include <sys/mman.h>
#include <string.h>
#include <math.h>
#include <vector>
#include <boost/random.hpp>
#include <boost/random/normal_distribution.hpp>
using namespace std;
using namespace boost;
template<typename T>
struct __attribute__((__packed__)) node {
/*
* We store a binary tree where each node has two things
* - A vector associated with it
* - Two children
* All nodes occupy the same amount of memory
* All nodes with n_descendants == 1 are leaf nodes.
* A memory optimization is that for nodes with 2 <= n_descendants <= K,
* we skip the vector. Instead we store a list of all descendants. K is
* determined by the number of items that fits in the same space.
* For nodes with n_descendants == 1 or > K, there is always a
* corresponding vector.
* Note that we can't really do sizeof(node<T>) because we cheat and allocate
* more memory to be able to fit the vector outside
*/
int n_descendants;
int children[2]; // Will possibly store more than 2
T v[0]; // Hack. We just allocate as much memory as we need and let this array overflow
};
template<typename T>
class AnnoyIndex {
/*
* We use random projection to build a forest of binary trees of all items.
* Basically just split the hyperspace into two sides by a hyperplane,
* then recursively split each of those subtrees etc.
* We create a tree like this q times. The default q is determined automatically
* in such a way that we at most use 2x as much memory as the vectors take.
*/
int _f;
size_t _s;
int _n_items;
mt19937 _rng;
normal_distribution<T> _nd;
variate_generator<mt19937&,
normal_distribution<T> > _var_nor;
void* _nodes; // Could either be mmapped, or point to a memory buffer that we reallocate
int _n_nodes;
int _nodes_size;
vector<int> _roots;
int _K;
bool _loaded;
public:
AnnoyIndex(int f) : _rng(), _nd(), _var_nor(_rng, _nd) {
_f = f;
_s = sizeof(node<T>) + sizeof(T) * f; // Size of each node
_n_items = 0;
_n_nodes = 0;
_nodes_size = 0;
_nodes = NULL;
_loaded = false;
_K = (sizeof(T) * f + sizeof(int) * 2) / sizeof(int);
}
~AnnoyIndex() {
if (!_loaded && _nodes) {
free(_nodes);
}
}
void add_item(int item, const python::list& v) {
_allocate_size(item+1);
node<T>* n = _get(item);
n->children[0] = 0;
n->children[1] = 0;
n->n_descendants = 1;
for (int z = 0; z < _f; z++)
n->v[z] = python::extract<T>(v[z]);
if (item >= _n_items)
_n_items = item + 1;
}
void build(int q) {
_n_nodes = _n_items;
while (1) {
if (q == -1 && _n_nodes >= _n_items * 2)
break;
if (q != -1 && _roots.size() >= (size_t)q)
break;
printf("pass %zd...\n", _roots.size());
vector<int> indices;
for (int i = 0; i < _n_items; i++)
indices.push_back(i);
_roots.push_back(_make_tree(indices));
}
printf("has %d nodes\n", _n_nodes);
}
void save(const string& filename) {
FILE *f = fopen(filename.c_str(), "w");
fwrite(_nodes, _s, _n_nodes, f);
fclose(f);
free(_nodes);
_n_items = 0;
_n_nodes = 0;
_nodes_size = 0;
_nodes = NULL;
_roots.clear();
load(filename);
}
void load(const string& filename) {
struct stat buf;
stat(filename.c_str(), &buf);
off_t size = buf.st_size;
printf("size = %jd\n", (intmax_t)size); // http://stackoverflow.com/questions/586928/how-should-i-print-types-like-off-t-and-size-t
int fd = open(filename.c_str(), O_RDONLY, (mode_t)0400);
printf("fd = %d\n", fd);
_nodes = (node<T>*)mmap(0, size, PROT_READ, MAP_SHARED, fd, 0);
int n = size / _s;
printf("%d nodes\n", n);
// Find the nodes with the largest number of descendants. These are the roots
int m = 0;
for (int i = 0; i < n; i++) {
if (_get(i)->n_descendants > m) {
_roots.clear();
m = _get(i)->n_descendants;
}
if (_get(i)->n_descendants == m) {
_roots.push_back(i);
}
}
_loaded = true;
printf("found %lu roots with degree %d\n", _roots.size(), m);
}
inline T _cos(const T* x, const T* y) {
T pp = 0, qq = 0, pq = 0;
for (int z = 0; z < _f; z++) {
pp += x[z] * x[z];
qq += y[z] * y[z];
pq += x[z] * y[z];
}
T ppqq = pp * qq;
if (ppqq > 0) return pq / sqrt(ppqq);
else return 0.0;
}
inline T cos(int i, int j) {
const T* x = _get(i)->v;
const T* y = _get(j)->v;
return _cos(x, y);
}
python::list get_nns_by_item(int item, int n) {
const node<T>* m = _get(item);
return _get_all_nns(m->v, n);
}
python::list get_nns_by_vector(python::list v, int n) {
vector<T> w(_f);
for (int z = 0; z < _f; z++)
w[z] = python::extract<T>(v[z]);
return _get_all_nns(&w[0], n);
}
private:
void _allocate_size(int n) {
if (n > _nodes_size) {
int new_nodes_size = (_nodes_size + 1) * 2;
if (n > new_nodes_size)
new_nodes_size = n;
printf("reallocating to %d nodes\n", new_nodes_size);
_nodes = realloc(_nodes, _s * new_nodes_size);
memset((char *)_nodes + (_nodes_size * _s)/sizeof(char), 0, (new_nodes_size - _nodes_size) * _s);
_nodes_size = new_nodes_size;
}
}
inline node<T>* _get(int i) {
return (node<T>*)((char *)_nodes + (_s * i)/sizeof(char));
}
int _make_tree(const vector<int >& indices) {
if (indices.size() == 1)
return indices[0];
_allocate_size(_n_nodes + 1);
int item = _n_nodes++;
node<T>* m = _get(item);
m->n_descendants = indices.size();
if (indices.size() <= (size_t)_K) {
for (size_t i = 0; i < indices.size(); i++)
m->children[i] = indices[i];
return item;
}
vector<int> children_indices[2];
for (int attempt = 0; attempt < 20; attempt ++) {
/*
* Create a random hyperplane.
* If all points end up on the same time, we try again.
* We could in principle *construct* a plane so that we split
* all items evenly, but I think that could violate the guarantees
* given by just picking a hyperplane at random
*/
for (int z = 0; z < _f; z++)
m->v[z] = _var_nor();
children_indices[0].clear();
children_indices[1].clear();
for (size_t i = 0; i < indices.size(); i++) {
int j = indices[i];
node<T>* n = _get(j);
if (!n) {
printf("node %d undef...\n", j);
continue;
}
T dot = 0;
for (int z = 0; z < _f; z++) {
dot += m->v[z] * n->v[z];
}
while (dot == 0)
dot = _var_nor();
children_indices[dot > 0].push_back(j);
}
if (children_indices[0].size() > 0 && children_indices[1].size() > 0) {
if (indices.size() > 100000)
printf("Split %lu items -> %lu, %lu (attempt %d)\n", indices.size(), children_indices[0].size(), children_indices[1].size(), attempt);
break;
}
}
while (children_indices[0].size() == 0 || children_indices[1].size() == 0) {
// If we didn't find a hyperplane, just randomize sides as a last option
if (indices.size() > 100000)
printf("Failed splitting %lu items\n", indices.size());
children_indices[0].clear();
children_indices[1].clear();
// Set the vector to 0.0
for (int z = 0; z < _f; z++)
m->v[z] = 0.0;
for (size_t i = 0; i < indices.size(); i++) {
int j = indices[i];
// Just randomize...
children_indices[_var_nor() > 0].push_back(j);
}
}
int children_0 = _make_tree(children_indices[0]);
int children_1 = _make_tree(children_indices[1]);
// We need to fetch m again because it might have been reallocated
m = _get(item);
m->children[0] = children_0;
m->children[1] = children_1;
return item;
}
void _get_nns(const T* v, int i, vector<int>* result, int limit) {
const node<T>* n = _get(i);
if (n->n_descendants == 0) {
// unknown item, nothing to do...
} else if (n->n_descendants == 1) {
result->push_back(i);
} else if (n->n_descendants <= _K) {
for (int j = 0; j < n->n_descendants; j++) {
result->push_back(n->children[j]);
}
} else {
T dot = 0;
for (int z = 0; z < _f; z++)
dot += v[z] * n->v[z];
while (dot == 0) // Randomize side if the dot product is zero
dot = _var_nor();
_get_nns(v, n->children[dot > 0], result, limit);
if (result->size() < (size_t)limit)
_get_nns(v, n->children[dot < 0], result, limit);
}
}
python::list _get_all_nns(const T* v, int n) {
vector<pair<T, int> > nns_cos;
for (size_t i = 0; i < _roots.size(); i++) {
vector<int> nns;
_get_nns(v, _roots[i], &nns, n);
for (size_t j = 0; j < nns.size(); j++) {
nns_cos.push_back(make_pair(_cos(v, _get(nns[j])->v), nns[j]));
}
}
sort(nns_cos.begin(), nns_cos.end());
int last = -1, length=0;
python::list l;
for (size_t i = nns_cos.size() - 1; i >= 0 && length < n; i--) {
if (nns_cos[i].second != last) {
l.append(nns_cos[i].second);
last = nns_cos[i].second;
length++;
}
}
return l;
}
};
BOOST_PYTHON_MODULE(annoylib)
{
python::class_<AnnoyIndex<float> >("AnnoyIndex", python::init<int>())
.def("add_item", &AnnoyIndex<float>::add_item)
.def("build", &AnnoyIndex<float>::build)
.def("save", &AnnoyIndex<float>::save)
.def("load", &AnnoyIndex<float>::load)
.def("cos", &AnnoyIndex<float>::cos)
.def("get_nns_by_item", &AnnoyIndex<float>::get_nns_by_item)
.def("get_nns_by_vector", &AnnoyIndex<float>::get_nns_by_vector);
}
<commit_msg>fixed broken int-size_t confusing causing a serious bug. removed some printfs<commit_after>#include <stdio.h>
#include <string>
#include <boost/python.hpp>
#include <sys/stat.h>
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <fcntl.h>
#include <sys/mman.h>
#include <string.h>
#include <math.h>
#include <vector>
#include <boost/random.hpp>
#include <boost/random/normal_distribution.hpp>
using namespace std;
using namespace boost;
template<typename T>
struct __attribute__((__packed__)) node {
/*
* We store a binary tree where each node has two things
* - A vector associated with it
* - Two children
* All nodes occupy the same amount of memory
* All nodes with n_descendants == 1 are leaf nodes.
* A memory optimization is that for nodes with 2 <= n_descendants <= K,
* we skip the vector. Instead we store a list of all descendants. K is
* determined by the number of items that fits in the same space.
* For nodes with n_descendants == 1 or > K, there is always a
* corresponding vector.
* Note that we can't really do sizeof(node<T>) because we cheat and allocate
* more memory to be able to fit the vector outside
*/
int n_descendants;
int children[2]; // Will possibly store more than 2
T v[0]; // Hack. We just allocate as much memory as we need and let this array overflow
};
template<typename T>
class AnnoyIndex {
/*
* We use random projection to build a forest of binary trees of all items.
* Basically just split the hyperspace into two sides by a hyperplane,
* then recursively split each of those subtrees etc.
* We create a tree like this q times. The default q is determined automatically
* in such a way that we at most use 2x as much memory as the vectors take.
*/
int _f;
size_t _s;
int _n_items;
mt19937 _rng;
normal_distribution<T> _nd;
variate_generator<mt19937&,
normal_distribution<T> > _var_nor;
void* _nodes; // Could either be mmapped, or point to a memory buffer that we reallocate
int _n_nodes;
int _nodes_size;
vector<int> _roots;
int _K;
bool _loaded;
public:
AnnoyIndex(int f) : _rng(), _nd(), _var_nor(_rng, _nd) {
_f = f;
_s = sizeof(node<T>) + sizeof(T) * f; // Size of each node
_n_items = 0;
_n_nodes = 0;
_nodes_size = 0;
_nodes = NULL;
_loaded = false;
_K = (sizeof(T) * f + sizeof(int) * 2) / sizeof(int);
}
~AnnoyIndex() {
if (!_loaded && _nodes) {
free(_nodes);
}
}
void add_item(int item, const python::list& v) {
_allocate_size(item+1);
node<T>* n = _get(item);
n->children[0] = 0;
n->children[1] = 0;
n->n_descendants = 1;
for (int z = 0; z < _f; z++)
n->v[z] = python::extract<T>(v[z]);
if (item >= _n_items)
_n_items = item + 1;
}
void build(int q) {
_n_nodes = _n_items;
while (1) {
if (q == -1 && _n_nodes >= _n_items * 2)
break;
if (q != -1 && _roots.size() >= (size_t)q)
break;
printf("pass %zd...\n", _roots.size());
vector<int> indices;
for (int i = 0; i < _n_items; i++)
indices.push_back(i);
_roots.push_back(_make_tree(indices));
}
printf("has %d nodes\n", _n_nodes);
}
void save(const string& filename) {
FILE *f = fopen(filename.c_str(), "w");
fwrite(_nodes, _s, _n_nodes, f);
fclose(f);
free(_nodes);
_n_items = 0;
_n_nodes = 0;
_nodes_size = 0;
_nodes = NULL;
_roots.clear();
load(filename);
}
void load(const string& filename) {
struct stat buf;
stat(filename.c_str(), &buf);
off_t size = buf.st_size;
int fd = open(filename.c_str(), O_RDONLY, (mode_t)0400);
_nodes = (node<T>*)mmap(0, size, PROT_READ, MAP_SHARED, fd, 0);
int n = size / _s;
// Find the nodes with the largest number of descendants. These are the roots
int m = 0;
for (int i = 0; i < n; i++) {
if (_get(i)->n_descendants > m) {
_roots.clear();
m = _get(i)->n_descendants;
}
if (_get(i)->n_descendants == m) {
_roots.push_back(i);
}
}
_loaded = true;
printf("found %lu roots with degree %d\n", _roots.size(), m);
}
inline T _cos(const T* x, const T* y) {
T pp = 0, qq = 0, pq = 0;
for (int z = 0; z < _f; z++) {
pp += x[z] * x[z];
qq += y[z] * y[z];
pq += x[z] * y[z];
}
T ppqq = pp * qq;
if (ppqq > 0) return pq / sqrt(ppqq);
else return 0.0;
}
inline T cos(int i, int j) {
const T* x = _get(i)->v;
const T* y = _get(j)->v;
return _cos(x, y);
}
python::list get_nns_by_item(int item, int n) {
const node<T>* m = _get(item);
return _get_all_nns(m->v, n);
}
python::list get_nns_by_vector(python::list v, int n) {
vector<T> w(_f);
for (int z = 0; z < _f; z++)
w[z] = python::extract<T>(v[z]);
return _get_all_nns(&w[0], n);
}
private:
void _allocate_size(int n) {
if (n > _nodes_size) {
int new_nodes_size = (_nodes_size + 1) * 2;
if (n > new_nodes_size)
new_nodes_size = n;
_nodes = realloc(_nodes, _s * new_nodes_size);
memset((char *)_nodes + (_nodes_size * _s)/sizeof(char), 0, (new_nodes_size - _nodes_size) * _s);
_nodes_size = new_nodes_size;
}
}
inline node<T>* _get(int i) {
return (node<T>*)((char *)_nodes + (_s * i)/sizeof(char));
}
int _make_tree(const vector<int >& indices) {
if (indices.size() == 1)
return indices[0];
_allocate_size(_n_nodes + 1);
int item = _n_nodes++;
node<T>* m = _get(item);
m->n_descendants = indices.size();
if (indices.size() <= (size_t)_K) {
for (size_t i = 0; i < indices.size(); i++)
m->children[i] = indices[i];
return item;
}
vector<int> children_indices[2];
for (int attempt = 0; attempt < 20; attempt ++) {
/*
* Create a random hyperplane.
* If all points end up on the same time, we try again.
* We could in principle *construct* a plane so that we split
* all items evenly, but I think that could violate the guarantees
* given by just picking a hyperplane at random
*/
for (int z = 0; z < _f; z++)
m->v[z] = _var_nor();
children_indices[0].clear();
children_indices[1].clear();
for (size_t i = 0; i < indices.size(); i++) {
int j = indices[i];
node<T>* n = _get(j);
if (!n) {
printf("node %d undef...\n", j);
continue;
}
T dot = 0;
for (int z = 0; z < _f; z++) {
dot += m->v[z] * n->v[z];
}
while (dot == 0)
dot = _var_nor();
children_indices[dot > 0].push_back(j);
}
if (children_indices[0].size() > 0 && children_indices[1].size() > 0) {
break;
}
}
while (children_indices[0].size() == 0 || children_indices[1].size() == 0) {
// If we didn't find a hyperplane, just randomize sides as a last option
if (indices.size() > 100000)
printf("Failed splitting %lu items\n", indices.size());
children_indices[0].clear();
children_indices[1].clear();
// Set the vector to 0.0
for (int z = 0; z < _f; z++)
m->v[z] = 0.0;
for (size_t i = 0; i < indices.size(); i++) {
int j = indices[i];
// Just randomize...
children_indices[_var_nor() > 0].push_back(j);
}
}
int children_0 = _make_tree(children_indices[0]);
int children_1 = _make_tree(children_indices[1]);
// We need to fetch m again because it might have been reallocated
m = _get(item);
m->children[0] = children_0;
m->children[1] = children_1;
return item;
}
void _get_nns(const T* v, int i, vector<int>* result, int limit) {
const node<T>* n = _get(i);
if (n->n_descendants == 0) {
// unknown item, nothing to do...
} else if (n->n_descendants == 1) {
result->push_back(i);
} else if (n->n_descendants <= _K) {
for (int j = 0; j < n->n_descendants; j++) {
result->push_back(n->children[j]);
}
} else {
T dot = 0;
for (int z = 0; z < _f; z++)
dot += v[z] * n->v[z];
while (dot == 0) // Randomize side if the dot product is zero
dot = _var_nor();
_get_nns(v, n->children[dot > 0], result, limit);
if (result->size() < (size_t)limit)
_get_nns(v, n->children[dot < 0], result, limit);
}
}
python::list _get_all_nns(const T* v, int n) {
vector<pair<T, int> > nns_cos;
for (size_t i = 0; i < _roots.size(); i++) {
vector<int> nns;
_get_nns(v, _roots[i], &nns, n);
for (size_t j = 0; j < nns.size(); j++) {
nns_cos.push_back(make_pair(_cos(v, _get(nns[j])->v), nns[j]));
}
}
sort(nns_cos.begin(), nns_cos.end());
int last = -1, length=0;
python::list l;
for (int i = (int)nns_cos.size() - 1; i >= 0 && length < n; i--) {
if (nns_cos[i].second != last) {
l.append(nns_cos[i].second);
last = nns_cos[i].second;
length++;
}
}
return l;
}
};
BOOST_PYTHON_MODULE(annoylib)
{
python::class_<AnnoyIndex<float> >("AnnoyIndex", python::init<int>())
.def("add_item", &AnnoyIndex<float>::add_item)
.def("build", &AnnoyIndex<float>::build)
.def("save", &AnnoyIndex<float>::save)
.def("load", &AnnoyIndex<float>::load)
.def("cos", &AnnoyIndex<float>::cos)
.def("get_nns_by_item", &AnnoyIndex<float>::get_nns_by_item)
.def("get_nns_by_vector", &AnnoyIndex<float>::get_nns_by_vector);
}
<|endoftext|>
|
<commit_before>#include "common.th"
// c <- multiplicand
// d <- multiplier
// b -> product
.global imul
imul:
#if IMUL_EARLY_EXITS
b <- c == 0
d <- d &~ b // d = (c == 0) ? 0 : d
b <- d == 0
p <- @+L_done & b + p
#endif
o <- o - 3
h -> [o + (3 - 0)]
i -> [o + (3 - 1)]
j -> [o + (3 - 2)]
b <- 0
h <- 1
j <- d >> 31 // save sign bit in j
d <- d ^ j // adjust multiplier
d <- d - j
L_top:
// use constant 1 in h to combine instructions
i <- d & h - 1
i <- c &~ i
b <- b + i
c <- c << 1
d <- d >> 1
i <- d == 0
p <- @+L_top &~ i + p
b <- b ^ j // adjust product for signed math
b <- b - j
o <- o + 3
j <- [o - 2]
i <- [o - 1]
h <- [o - 0]
L_done:
o <- o + 1
p <- [o]
<commit_msg>Remove optimization dependent on cpp<commit_after>#include "common.th"
// c <- multiplicand
// d <- multiplier
// b -> product
.global imul
imul:
o <- o - 3
h -> [o + (3 - 0)]
i -> [o + (3 - 1)]
j -> [o + (3 - 2)]
b <- 0
h <- 1
j <- d >> 31 // save sign bit in j
d <- d ^ j // adjust multiplier
d <- d - j
L_top:
// use constant 1 in h to combine instructions
i <- d & h - 1
i <- c &~ i
b <- b + i
c <- c << 1
d <- d >> 1
i <- d == 0
p <- @+L_top &~ i + p
b <- b ^ j // adjust product for signed math
b <- b - j
o <- o + 3
j <- [o - 2]
i <- [o - 1]
h <- [o - 0]
L_done:
o <- o + 1
p <- [o]
<|endoftext|>
|
<commit_before>/*=========================================================================
*
* Copyright Marius Staring, Stefan Klein, David Doria. 2011.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0.txt
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*=========================================================================*/
/** \file
\brief Perform PCA.
\verbinclude pca.help
*/
#include "itkCommandLineArgumentParser.h"
#include "CommandLineArgumentHelper.h"
#include <itksys/SystemTools.hxx>
#include <sstream>
#include "itkPCAImageToImageFilter.h"
#include "itkImageFileReader.h"
#include "itkImageFileWriter.h"
//-------------------------------------------------------------------------------------
/** run: A macro to call a function. */
#define run(function,type,dim) \
if ( componentType == #type && Dimension == dim ) \
{ \
typedef itk::Image< type, dim > OutputImageType; \
function< OutputImageType >( inputFileNames, outputDirectory, numberOfPCs ); \
supported = true; \
}
//-------------------------------------------------------------------------------------
/* Declare PerformPCA. */
template< class OutputImageType >
void PerformPCA(
const std::vector< std::string > & inputFileNames,
const std::string & outputDirectory,
unsigned int numberOfPCs );
/** Declare other functions. */
std::string GetHelpString( void );
//-------------------------------------------------------------------------------------
int main( int argc, char **argv )
{
/** Create a command line argument parser. */
itk::CommandLineArgumentParser::Pointer parser = itk::CommandLineArgumentParser::New();
parser->SetCommandLineArguments( argc, argv );
parser->SetProgramHelpText( GetHelpString() );
parser->MarkArgumentAsRequired( "-in", "The input filename." );
itk::CommandLineArgumentParser::ReturnValue validateArguments = parser->CheckForRequiredArguments();
if(validateArguments == itk::CommandLineArgumentParser::FAILED)
{
return EXIT_FAILURE;
}
else if(validateArguments == itk::CommandLineArgumentParser::HELPREQUESTED)
{
return EXIT_SUCCESS;
}
/** Get arguments. */
std::vector<std::string> inputFileNames( 0, "" );
parser->GetCommandLineArgument( "-in", inputFileNames );
std::string base = itksys::SystemTools::GetFilenamePath( inputFileNames[ 0 ] );
if ( base != "" ) base = base + "/";
std::string outputDirectory = base;
parser->GetCommandLineArgument( "-out", outputDirectory );
bool endslash = itksys::SystemTools::StringEndsWith( outputDirectory.c_str(), "/" );
if ( !endslash ) outputDirectory += "/";
unsigned int numberOfPCs = inputFileNames.size();
parser->GetCommandLineArgument( "-npc", numberOfPCs );
std::string componentType = "";
bool retpt = parser->GetCommandLineArgument( "-opct", componentType );
/** Check that numberOfOutputs <= numberOfInputs. */
if ( numberOfPCs > inputFileNames.size() )
{
std::cerr << "ERROR: you should specify less than " << inputFileNames.size() << " output pc's." << std::endl;
return 1;
}
/** Determine image properties. */
std::string ComponentTypeIn = "short";
std::string PixelType; //we don't use this
unsigned int Dimension = 3;
unsigned int NumberOfComponents = 1;
std::vector<unsigned int> imagesize( Dimension, 0 );
int retgip = GetImageProperties(
inputFileNames[ 0 ],
PixelType,
ComponentTypeIn,
Dimension,
NumberOfComponents,
imagesize );
if ( retgip != 0 )
{
return 1;
}
/** Check for vector images. */
if ( NumberOfComponents > 1 )
{
std::cerr << "ERROR: The NumberOfComponents is larger than 1!" << std::endl;
std::cerr << "Vector images are not supported." << std::endl;
return 1;
}
/** The default output is equal to the input, but can be overridden by
* specifying -pt in the command line.
*/
if ( !retpt ) componentType = ComponentTypeIn;
/** Get rid of the possible "_" in ComponentType. */
ReplaceUnderscoreWithSpace( componentType );
/** Run the program. */
bool supported = false;
try
{
run( PerformPCA, unsigned char, 2 );
run( PerformPCA, char, 2 );
run( PerformPCA, unsigned short, 2 );
run( PerformPCA, short, 2 );
run( PerformPCA, unsigned int, 2 );
run( PerformPCA, int, 2 );
run( PerformPCA, unsigned long, 2 );
run( PerformPCA, long, 2 );
run( PerformPCA, float, 2 );
run( PerformPCA, double, 2 );
run( PerformPCA, unsigned char, 3 );
run( PerformPCA, char, 3 );
run( PerformPCA, unsigned short, 3 );
run( PerformPCA, short, 3 );
run( PerformPCA, unsigned int, 3 );
run( PerformPCA, int, 3 );
run( PerformPCA, unsigned long, 3 );
run( PerformPCA, long, 3 );
run( PerformPCA, float, 3 );
run( PerformPCA, double, 3 );
}
catch( itk::ExceptionObject &e )
{
std::cerr << "Caught ITK exception: " << e << std::endl;
return 1;
}
if ( !supported )
{
std::cerr << "ERROR: this combination of pixeltype and dimension is not supported!" << std::endl;
std::cerr
<< "pixel (component) type = " << ComponentTypeIn
<< " ; dimension = " << Dimension
<< std::endl;
return 1;
}
/** End program. */
return 0;
} // end main()
/*
* ******************* PerformPCA *******************
*/
template< class OutputImageType >
void PerformPCA(
const std::vector< std::string > & inputFileNames,
const std::string & outputDirectory,
unsigned int numberOfPCs )
{
const unsigned int Dimension = OutputImageType::ImageDimension;
/** Typedefs. */
typedef itk::Image< double, Dimension > DoubleImageType;
typedef itk::PCAImageToImageFilter<
DoubleImageType, OutputImageType > PCAEstimatorType;
typedef typename PCAEstimatorType::VectorOfDoubleType VectorOfDoubleType;
typedef typename PCAEstimatorType::MatrixOfDoubleType MatrixOfDoubleType;
typedef itk::ImageFileReader< DoubleImageType > ReaderType;
typedef typename ReaderType::Pointer ReaderPointer;
typedef itk::ImageFileWriter< OutputImageType > WriterType;
typedef typename WriterType::Pointer WriterPointer;
/** Get some sizes. */
unsigned int noInputs = inputFileNames.size();
/** Create the PCA estimator. */
typename PCAEstimatorType::Pointer pcaEstimator = PCAEstimatorType::New();
pcaEstimator->SetNumberOfFeatureImages( noInputs );
pcaEstimator->SetNumberOfPrincipalComponentsRequired( numberOfPCs );
/** For all inputs... */
std::vector<ReaderPointer> readers( noInputs );
for ( unsigned int i = 0; i < noInputs; ++i )
{
/** Read in the input images. */
readers[ i ] = ReaderType::New();
readers[ i ]->SetFileName( inputFileNames[ i ] );
readers[ i ]->Update();
/** Setup PCA estimator. */
pcaEstimator->SetInput( i, readers[ i ]->GetOutput() );
}
/** Do the PCA analysis. */
pcaEstimator->Update();
/** Get eigenvalues and vectors, and print it to screen. */
//pcaEstimator->Print( std::cout );
VectorOfDoubleType vec = pcaEstimator->GetEigenValues();
MatrixOfDoubleType mat = pcaEstimator->GetEigenVectors();
std::cout << "Eigenvalues: " << std::endl;
for ( unsigned int i = 0; i < vec.size(); ++i )
{
std::cout << vec[ i ] << " ";
}
std::cout << std::endl;
std::cout << "Eigenvectors: " << std::endl;
for ( unsigned int i = 0; i < vec.size(); ++i )
{
std::cout << mat.get_row( i ) << std::endl;
}
/** Setup and process the pipeline. */
unsigned int noo = pcaEstimator->GetNumberOfOutputs();
std::vector<WriterPointer> writers( noo );
for ( unsigned int i = 0; i < noo; ++i )
{
/** Create output filename. */
std::ostringstream makeFileName( "" );
makeFileName << outputDirectory << "pc" << i << ".mhd";
/** Write principal components. */
writers[ i ] = WriterType::New();
writers[ i ]->SetFileName( makeFileName.str().c_str() );
writers[ i ]->SetInput( pcaEstimator->GetOutput( i ) );
writers[ i ]->Update();
}
} // end PerformPCA()
/**
* ******************* GetHelpString *******************
*/
std::string GetHelpString( void )
{
std::stringstream ss;
ss << "Usage:" << std::endl
<< "pxpca" << std::endl
<< " -in inputFilenames" << std::endl
<< " [-out] outputDirectory, default equal to the inputFilename directory" << std::endl
<< " [-opc] the number of principal components that you want to output, default all" << std::endl
<< " [-opct] output pixel component type, default derived from the input image" << std::endl
<< "Supported: 2D, 3D, (unsigned) char, (unsigned) short, (unsigned) int, (unsigned) long, float, double.";
return ss.str();
} // end GetHelpString()
<commit_msg>ENH: convert PCA to template<commit_after>/*=========================================================================
*
* Copyright Marius Staring, Stefan Klein, David Doria. 2011.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0.txt
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*=========================================================================*/
/** \file
\brief Perform PCA.
\verbinclude pca.help
*/
#include "itkCommandLineArgumentParser.h"
#include "CommandLineArgumentHelper.h"
#include <itksys/SystemTools.hxx>
#include <sstream>
#include "itkPCAImageToImageFilter.h"
#include "itkImageFileReader.h"
#include "itkImageFileWriter.h"
//-------------------------------------------------------------------------------------
/** PCA */
class PCABase : public itktools::ITKToolsBase
{
public:
PCABase(){};
~PCABase(){};
/** Input parameters */
std::vector< std::string > m_InputFileNames;
std::string m_OutputDirectory;
unsigned int m_NumberOfPCs;
}; // end ReplaceVoxelBase
template< class TComponentType, unsigned int VDimension >
class PCA : public PCABase
{
public:
typedef PCA Self;
PCA(){};
~PCA(){};
static Self * New( itktools::EnumComponentType componentType, unsigned int dim )
{
if ( itktools::IsType<TComponentType>( componentType ) && VDimension == dim )
{
return new Self;
}
return 0;
}
void Run(void)
{
/** Typedefs. */
typedef itk::Image< TComponentType, VDimension > OutputImageType;
typedef itk::Image< double, VDimension > DoubleImageType;
typedef itk::PCAImageToImageFilter<
DoubleImageType, OutputImageType > PCAEstimatorType;
typedef typename PCAEstimatorType::VectorOfDoubleType VectorOfDoubleType;
typedef typename PCAEstimatorType::MatrixOfDoubleType MatrixOfDoubleType;
typedef itk::ImageFileReader< DoubleImageType > ReaderType;
typedef typename ReaderType::Pointer ReaderPointer;
typedef itk::ImageFileWriter< OutputImageType > WriterType;
typedef typename WriterType::Pointer WriterPointer;
/** Get some sizes. */
unsigned int noInputs = m_InputFileNames.size();
/** Create the PCA estimator. */
typename PCAEstimatorType::Pointer pcaEstimator = PCAEstimatorType::New();
pcaEstimator->SetNumberOfFeatureImages( noInputs );
pcaEstimator->SetNumberOfPrincipalComponentsRequired( m_NumberOfPCs );
/** For all inputs... */
std::vector<ReaderPointer> readers( noInputs );
for ( unsigned int i = 0; i < noInputs; ++i )
{
/** Read in the input images. */
readers[ i ] = ReaderType::New();
readers[ i ]->SetFileName( m_InputFileNames[ i ] );
readers[ i ]->Update();
/** Setup PCA estimator. */
pcaEstimator->SetInput( i, readers[ i ]->GetOutput() );
}
/** Do the PCA analysis. */
pcaEstimator->Update();
/** Get eigenvalues and vectors, and print it to screen. */
//pcaEstimator->Print( std::cout );
VectorOfDoubleType vec = pcaEstimator->GetEigenValues();
MatrixOfDoubleType mat = pcaEstimator->GetEigenVectors();
std::cout << "Eigenvalues: " << std::endl;
for ( unsigned int i = 0; i < vec.size(); ++i )
{
std::cout << vec[ i ] << " ";
}
std::cout << std::endl;
std::cout << "Eigenvectors: " << std::endl;
for ( unsigned int i = 0; i < vec.size(); ++i )
{
std::cout << mat.get_row( i ) << std::endl;
}
/** Setup and process the pipeline. */
unsigned int noo = pcaEstimator->GetNumberOfOutputs();
std::vector<WriterPointer> writers( noo );
for ( unsigned int i = 0; i < noo; ++i )
{
/** Create output filename. */
std::ostringstream makeFileName( "" );
makeFileName << m_OutputDirectory << "pc" << i << ".mhd";
/** Write principal components. */
writers[ i ] = WriterType::New();
writers[ i ]->SetFileName( makeFileName.str().c_str() );
writers[ i ]->SetInput( pcaEstimator->GetOutput( i ) );
writers[ i ]->Update();
}
}
}; // end PCA
//-------------------------------------------------------------------------------------
/* Declare PerformPCA. */
template< class OutputImageType >
void PerformPCA(
const std::vector< std::string > & inputFileNames,
const std::string & outputDirectory,
unsigned int numberOfPCs );
/** Declare other functions. */
std::string GetHelpString( void );
//-------------------------------------------------------------------------------------
int main( int argc, char **argv )
{
/** Create a command line argument parser. */
itk::CommandLineArgumentParser::Pointer parser = itk::CommandLineArgumentParser::New();
parser->SetCommandLineArguments( argc, argv );
parser->SetProgramHelpText( GetHelpString() );
parser->MarkArgumentAsRequired( "-in", "The input filename." );
itk::CommandLineArgumentParser::ReturnValue validateArguments = parser->CheckForRequiredArguments();
if(validateArguments == itk::CommandLineArgumentParser::FAILED)
{
return EXIT_FAILURE;
}
else if(validateArguments == itk::CommandLineArgumentParser::HELPREQUESTED)
{
return EXIT_SUCCESS;
}
/** Get arguments. */
std::vector<std::string> inputFileNames( 0, "" );
parser->GetCommandLineArgument( "-in", inputFileNames );
std::string base = itksys::SystemTools::GetFilenamePath( inputFileNames[ 0 ] );
if ( base != "" ) base = base + "/";
std::string outputDirectory = base;
parser->GetCommandLineArgument( "-out", outputDirectory );
bool endslash = itksys::SystemTools::StringEndsWith( outputDirectory.c_str(), "/" );
if ( !endslash ) outputDirectory += "/";
unsigned int numberOfPCs = inputFileNames.size();
parser->GetCommandLineArgument( "-npc", numberOfPCs );
std::string componentTypeString = "";
bool retpt = parser->GetCommandLineArgument( "-opct", componentTypeString );
/** Check that numberOfOutputs <= numberOfInputs. */
if ( numberOfPCs > inputFileNames.size() )
{
std::cerr << "ERROR: you should specify less than " << inputFileNames.size() << " output pc's." << std::endl;
return 1;
}
unsigned int numberOfComponents = 0;
GetImageNumberOfComponents(inputFileNames[0], numberOfComponents);
/** Check for vector images. */
if ( numberOfComponents > 1 )
{
std::cerr << "ERROR: The NumberOfComponents is larger than 1!" << std::endl;
std::cerr << "Vector images are not supported." << std::endl;
return 1;
}
/** The default output is equal to the input, but can be overridden by
* specifying -pt in the command line.
*/
itktools::EnumComponentType componentType = itktools::GetImageComponentType(inputFileNames[0]);
if ( !retpt )
{
componentType = itktools::EnumComponentTypeFromString(componentTypeString);
}
/** Class that does the work */
PCABase * pca = 0;
unsigned int imageDimension = 0;
GetImageDimension(inputFileNames[0], imageDimension);
std::cout << "Detected component type: " <<
componentType << std::endl;
try
{
// now call all possible template combinations.
if (!pca) pca = PCA< unsigned char, 2 >::New( componentType, imageDimension );
if (!pca) pca = PCA< char, 2 >::New( componentType, imageDimension );
if (!pca) pca = PCA< unsigned short, 2 >::New( componentType, imageDimension );
if (!pca) pca = PCA< short, 2 >::New( componentType, imageDimension );
if (!pca) pca = PCA< unsigned int, 2 >::New( componentType, imageDimension );
if (!pca) pca = PCA< int, 2 >::New( componentType, imageDimension );
if (!pca) pca = PCA< unsigned long, 2 >::New( componentType, imageDimension );
if (!pca) pca = PCA< long, 2 >::New( componentType, imageDimension );
if (!pca) pca = PCA< float, 2 >::New( componentType, imageDimension );
if (!pca) pca = PCA< double, 2 >::New( componentType, imageDimension );
#ifdef ITKTOOLS_3D_SUPPORT
if (!pca) pca = PCA< unsigned char, 3 >::New( componentType, imageDimension );
if (!pca) pca = PCA< char, 3 >::New( componentType, imageDimension );
if (!pca) pca = PCA< unsigned short, 3 >::New( componentType, imageDimension );
if (!pca) pca = PCA< short, 3 >::New( componentType, imageDimension );
if (!pca) pca = PCA< unsigned int, 3 >::New( componentType, imageDimension );
if (!pca) pca = PCA< int, 3 >::New( componentType, imageDimension );
if (!pca) pca = PCA< unsigned long, 3 >::New( componentType, imageDimension );
if (!pca) pca = PCA< long, 3 >::New( componentType, imageDimension );
if (!pca) pca = PCA< float, 3 >::New( componentType, imageDimension );
if (!pca) pca = PCA< double, 3 >::New( componentType, imageDimension );
#endif
if (!pca)
{
std::cerr << "ERROR: this combination of pixeltype and dimension is not supported!" << std::endl;
std::cerr
<< "pixel (component) type = " << componentType
<< " ; dimension = " << imageDimension
<< std::endl;
return 1;
}
pca->m_InputFileNames = inputFileNames;
pca->m_OutputDirectory = outputDirectory;
pca->m_NumberOfPCs = numberOfPCs;
pca->Run();
delete pca;
}
catch( itk::ExceptionObject &e )
{
std::cerr << "Caught ITK exception: " << e << std::endl;
delete pca;
return 1;
}
/** End program. */
return 0;
} // end main()
/**
* ******************* GetHelpString *******************
*/
std::string GetHelpString( void )
{
std::stringstream ss;
ss << "Usage:" << std::endl
<< "pxpca" << std::endl
<< " -in inputFilenames" << std::endl
<< " [-out] outputDirectory, default equal to the inputFilename directory" << std::endl
<< " [-opc] the number of principal components that you want to output, default all" << std::endl
<< " [-opct] output pixel component type, default derived from the input image" << std::endl
<< "Supported: 2D, 3D, (unsigned) char, (unsigned) short, (unsigned) int, (unsigned) long, float, double.";
return ss.str();
} // end GetHelpString()
<|endoftext|>
|
<commit_before>/*************** <auto-copyright.pl BEGIN do not edit this line> **************
*
* VR Juggler is (C) Copyright 1998-2002 by Iowa State University
*
* Original Authors:
* Allen Bierbaum, Christopher Just,
* Patrick Hartling, Kevin Meinert,
* Carolina Cruz-Neira, Albert Baker
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public
* License along with this library; if not, write to the
* Free Software Foundation, Inc., 59 Temple Place - Suite 330,
* Boston, MA 02111-1307, USA.
*
* -----------------------------------------------------------------
* File: $RCSfile$
* Date modified: $Date$
* Version: $Revision$
* -----------------------------------------------------------------
*
*************** <auto-copyright.pl END do not edit this line> ***************/
#include <vrj/vrjConfig.h>
#include <jccl/Config/ConfigChunk.h>
#include <vrj/Display/DisplayManager.h>
#include <vrj/Display/Display.h>
#include <vrj/Display/SurfaceViewport.h>
#include <vrj/Display/SimViewport.h>
#include <vrj/Draw/DrawManager.h>
#include <vrj/Kernel/Kernel.h>
namespace vrj
{
//vjDisplayManager* DisplayManager::_instance = NULL;
vprSingletonImp(DisplayManager);
std::vector<Display*> DisplayManager::getAllDisplays()
{
std::vector<Display*> ret_val;
ret_val.insert(ret_val.end(), mActiveDisplays.begin(), mActiveDisplays.end());
ret_val.insert(ret_val.end(), mInactiveDisplays.begin(), mInactiveDisplays.end());
return ret_val;
}
jccl::ConfigChunkPtr DisplayManager::getDisplaySystemChunk()
{
if ( mDisplaySystemChunk.get() == NULL )
{
jccl::ConfigManager* cfg_mgr = jccl::ConfigManager::instance();
cfg_mgr->lockActive();
{
std::vector<jccl::ConfigChunkPtr>::iterator i;
for(i=cfg_mgr->getActiveBegin(); i != cfg_mgr->getActiveEnd();++i)
{
if((*i)->getDescToken() == std::string("displaySystem"))
{
mDisplaySystemChunk = *i;
break; // This guarantees that we get the first displaySystem chunk.
}
}
}
cfg_mgr->unlockActive();
// vprASSERT(mDisplaySystemChunk.get() != NULL && "No Display Manager chunk found!");
}
return mDisplaySystemChunk;
}
void DisplayManager::setDrawManager(DrawManager* drawMgr)
{
vprDEBUG(vrjDBG_DISP_MGR,3) << "vjDisplayManager: Setting draw manager.\n" << vprDEBUG_FLUSH;
// set the draw manager
mDrawManager = drawMgr;
// Alert the draw manager about all the active windows currently configured
if(mDrawManager != NULL)
{
for(unsigned int i=0;i<mActiveDisplays.size();i++)
{
mDrawManager->addDisplay(mActiveDisplays[i]);
}
}
}
/**
* Adds the chunk to the configuration.
* @pre configCanHandle(chunk) == true
*/
bool DisplayManager::configAdd(jccl::ConfigChunkPtr chunk)
{
vprASSERT(configCanHandle(chunk));
std::string chunk_type = chunk->getDescToken();
if( (chunk_type == std::string("surfaceDisplay"))
|| (chunk_type == std::string("simDisplay")) )
{
vprDEBUG(vprDBG_ALL,0) << "Chunk of type: " << chunk_type << " is no longer supported. Use displayWindow type instead.\n" << vprDEBUG_FLUSH;
return false;
}
else if( (chunk_type == std::string("displayWindow")))
{
return configAddDisplay(chunk);
}
else if(chunk_type == std::string("displaySystem"))
{
// XXX: Put signal here to tell draw manager to lookup new stuff
mDisplaySystemChunk = chunk; // Keep track of the display system chunk
return true; // We successfully configured.
// This tell processPending to add it to the active config
}
return false;
}
/**
* Removes the chunk from the current configuration.
* @pre configCanHandle(chunk) == true
*/
bool DisplayManager::configRemove(jccl::ConfigChunkPtr chunk)
{
vprASSERT(configCanHandle(chunk));
std::string chunk_type = chunk->getDescToken();
if( (chunk_type == std::string("surfaceDisplay"))
|| (chunk_type == std::string("simDisplay")) )
{
vprDEBUG(vprDBG_ALL,0) << "Chunk of type: " << chunk_type << " is no longer supported. Use displayWindow type instead.\n" << vprDEBUG_FLUSH;
return false;
}
else if(chunk_type == std::string("displayWindow"))
{
return configRemoveDisplay(chunk);
}
else if(chunk_type == std::string("displaySystem"))
{
// XXX: Put signal here to tell draw manager to lookup new stuff
mDisplaySystemChunk.reset(); // Keep track of the display system chunk
return true; // We successfully configured.
// This tell processPending to remove it to the active config
}
else
{ return false; }
}
/**
* Is it a display chunk?
*
* @return true if we have a display chunk; false if we don't.
*/
bool DisplayManager::configCanHandle(jccl::ConfigChunkPtr chunk)
{
return ( (chunk->getDescToken() == std::string("surfaceDisplay"))
|| (chunk->getDescToken() == std::string("simDisplay"))
|| (chunk->getDescToken() == std::string("displaySystem"))
|| (chunk->getDescToken() == std::string("displayWindow"))
);
}
/**
* Adds the chunk to the configuration.
*
* @pre configCanHandle(chunk) == true
* @post (display of same name already loaded) ==> old display closed, new one opened<br>
* (display is new) ==> (new display is added)<br>
* Draw Manager is notified of the display change.
*/
bool DisplayManager::configAddDisplay(jccl::ConfigChunkPtr chunk)
{
vprASSERT(configCanHandle(chunk)); // We must be able to handle it first of all
vprDEBUG_BEGIN(vrjDBG_DISP_MGR,vprDBG_STATE_LVL) << "------- DisplayManager::configAddDisplay -------\n" << vprDEBUG_FLUSH;
// Find out if we already have a window of this name
// If so, then close it before we open a new one of the same name
// This basically allows re-configuration of a window
Display* cur_disp = findDisplayNamed(chunk->getName());
if(cur_disp != NULL) // We have an old display
{
vprDEBUG(vrjDBG_DISP_MGR,vprDBG_CONFIG_LVL) << "Removing old window: " << cur_disp->getName().c_str() << vprDEBUG_FLUSH;
closeDisplay(cur_disp,true); // Close the display and notify the draw manager to close the window
}
// --- Add a display (of the correct type) ---- //
if(chunk->getDescToken() == std::string("displayWindow")) // Display window
{
Display* newDisp = new Display(); // Create the display
newDisp->config(chunk);
addDisplay(newDisp,true); // Add it
vprDEBUG(vrjDBG_DISP_MGR,vprDBG_STATE_LVL) << "Adding display: " << newDisp->getName().c_str() << std::endl << vprDEBUG_FLUSH;
vprDEBUG(vrjDBG_DISP_MGR,vprDBG_STATE_LVL) << "Display: " << newDisp << std::endl << vprDEBUG_FLUSH;
}
vprDEBUG_END(vrjDBG_DISP_MGR,vprDBG_STATE_LVL) << "------- DisplayManager::configAddDisplay Done. --------\n" << vprDEBUG_FLUSH;
return true;
}
/**
* Removes the chunk from the current configuration.
*
* @pre configCanHandle(chunk) == true
* @return success
*/
bool DisplayManager::configRemoveDisplay(jccl::ConfigChunkPtr chunk)
{
vprASSERT(configCanHandle(chunk)); // We must be able to handle it first of all
vprDEBUG_BEGIN(vrjDBG_DISP_MGR,vprDBG_STATE_LVL) << "------- DisplayManager::configRemoveDisplay -------\n" << vprDEBUG_FLUSH;
bool success_flag(false);
if(chunk->getDescToken() == std::string("displayWindow")) // It is a display
{
Display* remove_disp = findDisplayNamed(chunk->getName());
if(remove_disp != NULL)
{
closeDisplay(remove_disp, true); // Remove it
success_flag = true;
}
}
vprDEBUG_END(vrjDBG_DISP_MGR,vprDBG_STATE_LVL) << "------- DisplayManager::configRemoveDisplay done. --------\n" << vprDEBUG_FLUSH;
return success_flag;
}
// notifyDrawMgr = 0; Defaults to 0
int DisplayManager::addDisplay(Display* disp, bool notifyDrawMgr)
{
vprDEBUG(vrjDBG_DISP_MGR,4) << "vjDisplayManager::addDisplay \n" << vprDEBUG_FLUSH;
// Test if active or not, to determine correct list
// The place it in the list
// --- Update Local Display structures
if(disp->isActive())
mActiveDisplays.push_back(disp);
else
mInactiveDisplays.push_back(disp);
// If we are supposed to notify about, and valid draw mgr, and disp is active
if((notifyDrawMgr) && (mDrawManager != NULL) && (disp->isActive()))
mDrawManager->addDisplay(disp);; // Tell Draw Manager to add dislay;
return 1;
}
/**
* Closes the given display.
*
* @pre disp is a display we know about.
* @post disp has been removed from the list of displays
* (notifyDrawMgr == true) && (drawMgr != NULL) && (disp is active)
* ==> Draw manager has been told to clode the window for the display
*/
int DisplayManager::closeDisplay(Display* disp, bool notifyDrawMgr)
{
vprASSERT(isMemberDisplay(disp)); // Make sure that display actually exists
vprDEBUG_BEGIN(vrjDBG_DISP_MGR,vprDBG_STATE_LVL) << "closeDisplay: Closing display named: " << disp->getName() << std::endl<< vprDEBUG_FLUSH;
// Notify the draw manager to get rid of it
// Note: if it is not active, then the draw manager doesn't know about it
if((notifyDrawMgr) && (mDrawManager != NULL) && (disp->isActive()))
mDrawManager->removeDisplay(disp);
// Remove it from local data structures
unsigned int num_before_close = mActiveDisplays.size() + mInactiveDisplays.size();
mActiveDisplays.erase( std::remove(mActiveDisplays.begin(), mActiveDisplays.end(), disp),
mActiveDisplays.end());
mInactiveDisplays.erase( std::remove(mInactiveDisplays.begin(), mInactiveDisplays.end(), disp),
mInactiveDisplays.end());
vprASSERT(num_before_close == (1+mActiveDisplays.size() + mInactiveDisplays.size()));
// Delete the object
// XXX: Memory leak. Can't delete display here because the draw manager
// may need access to it when the draw manager closes the window up.
// ex: the glDrawManager window has ref to the display to get current user, etc.
//XXX//delete disp;
return 1;
}
// Is the display a member of the display manager
bool DisplayManager::isMemberDisplay(Display* disp)
{
std::vector<Display*>::iterator i;
i = std::find(mActiveDisplays.begin(),mActiveDisplays.end(),disp);
if(i != mActiveDisplays.end())
return true;
i = std::find(mInactiveDisplays.begin(),mInactiveDisplays.end(),disp);
if(i != mInactiveDisplays.end())
return true;
return false; // Didn't find any
}
/**
* Finds a display given the display name.
* @return NULL if nothing found
*/
Display* DisplayManager::findDisplayNamed(std::string name)
{
std::vector<Display*>::iterator i;
for(i = mActiveDisplays.begin();i!=mActiveDisplays.end();i++)
if((*i)->getName() == name)
return (*i);
for(i = mInactiveDisplays.begin();i!=mInactiveDisplays.end();i++)
if((*i)->getName() == name)
return (*i);
return NULL; // Didn't find any
}
void DisplayManager::updateProjections()
{
// for (all displays) update the projections
for (std::vector<Display*>::iterator i = mActiveDisplays.begin(); i != mActiveDisplays.end(); i++)
(*i)->updateProjections();
for (std::vector<Display*>::iterator j = mInactiveDisplays.begin(); j != mInactiveDisplays.end(); j++)
(*j)->updateProjections();
if(mDrawManager != NULL)
mDrawManager->updateProjections();
}
};
<commit_msg>Do not depend on header file pollution to get jccl/RTRC/ConfigManager.h.<commit_after>/*************** <auto-copyright.pl BEGIN do not edit this line> **************
*
* VR Juggler is (C) Copyright 1998-2002 by Iowa State University
*
* Original Authors:
* Allen Bierbaum, Christopher Just,
* Patrick Hartling, Kevin Meinert,
* Carolina Cruz-Neira, Albert Baker
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public
* License along with this library; if not, write to the
* Free Software Foundation, Inc., 59 Temple Place - Suite 330,
* Boston, MA 02111-1307, USA.
*
* -----------------------------------------------------------------
* File: $RCSfile$
* Date modified: $Date$
* Version: $Revision$
* -----------------------------------------------------------------
*
*************** <auto-copyright.pl END do not edit this line> ***************/
#include <vrj/vrjConfig.h>
#include <jccl/Config/ConfigChunk.h>
#include <jccl/RTRC/ConfigManager.h>
#include <vrj/Display/Display.h>
#include <vrj/Display/SurfaceViewport.h>
#include <vrj/Display/SimViewport.h>
#include <vrj/Draw/DrawManager.h>
#include <vrj/Kernel/Kernel.h>
#include <vrj/Display/DisplayManager.h>
namespace vrj
{
//vjDisplayManager* DisplayManager::_instance = NULL;
vprSingletonImp(DisplayManager);
std::vector<Display*> DisplayManager::getAllDisplays()
{
std::vector<Display*> ret_val;
ret_val.insert(ret_val.end(), mActiveDisplays.begin(), mActiveDisplays.end());
ret_val.insert(ret_val.end(), mInactiveDisplays.begin(), mInactiveDisplays.end());
return ret_val;
}
jccl::ConfigChunkPtr DisplayManager::getDisplaySystemChunk()
{
if ( mDisplaySystemChunk.get() == NULL )
{
jccl::ConfigManager* cfg_mgr = jccl::ConfigManager::instance();
cfg_mgr->lockActive();
{
std::vector<jccl::ConfigChunkPtr>::iterator i;
for(i=cfg_mgr->getActiveBegin(); i != cfg_mgr->getActiveEnd();++i)
{
if((*i)->getDescToken() == std::string("displaySystem"))
{
mDisplaySystemChunk = *i;
break; // This guarantees that we get the first displaySystem chunk.
}
}
}
cfg_mgr->unlockActive();
// vprASSERT(mDisplaySystemChunk.get() != NULL && "No Display Manager chunk found!");
}
return mDisplaySystemChunk;
}
void DisplayManager::setDrawManager(DrawManager* drawMgr)
{
vprDEBUG(vrjDBG_DISP_MGR,3) << "vjDisplayManager: Setting draw manager.\n" << vprDEBUG_FLUSH;
// set the draw manager
mDrawManager = drawMgr;
// Alert the draw manager about all the active windows currently configured
if(mDrawManager != NULL)
{
for(unsigned int i=0;i<mActiveDisplays.size();i++)
{
mDrawManager->addDisplay(mActiveDisplays[i]);
}
}
}
/**
* Adds the chunk to the configuration.
* @pre configCanHandle(chunk) == true
*/
bool DisplayManager::configAdd(jccl::ConfigChunkPtr chunk)
{
vprASSERT(configCanHandle(chunk));
std::string chunk_type = chunk->getDescToken();
if( (chunk_type == std::string("surfaceDisplay"))
|| (chunk_type == std::string("simDisplay")) )
{
vprDEBUG(vprDBG_ALL,0) << "Chunk of type: " << chunk_type << " is no longer supported. Use displayWindow type instead.\n" << vprDEBUG_FLUSH;
return false;
}
else if( (chunk_type == std::string("displayWindow")))
{
return configAddDisplay(chunk);
}
else if(chunk_type == std::string("displaySystem"))
{
// XXX: Put signal here to tell draw manager to lookup new stuff
mDisplaySystemChunk = chunk; // Keep track of the display system chunk
return true; // We successfully configured.
// This tell processPending to add it to the active config
}
return false;
}
/**
* Removes the chunk from the current configuration.
* @pre configCanHandle(chunk) == true
*/
bool DisplayManager::configRemove(jccl::ConfigChunkPtr chunk)
{
vprASSERT(configCanHandle(chunk));
std::string chunk_type = chunk->getDescToken();
if( (chunk_type == std::string("surfaceDisplay"))
|| (chunk_type == std::string("simDisplay")) )
{
vprDEBUG(vprDBG_ALL,0) << "Chunk of type: " << chunk_type << " is no longer supported. Use displayWindow type instead.\n" << vprDEBUG_FLUSH;
return false;
}
else if(chunk_type == std::string("displayWindow"))
{
return configRemoveDisplay(chunk);
}
else if(chunk_type == std::string("displaySystem"))
{
// XXX: Put signal here to tell draw manager to lookup new stuff
mDisplaySystemChunk.reset(); // Keep track of the display system chunk
return true; // We successfully configured.
// This tell processPending to remove it to the active config
}
else
{ return false; }
}
/**
* Is it a display chunk?
*
* @return true if we have a display chunk; false if we don't.
*/
bool DisplayManager::configCanHandle(jccl::ConfigChunkPtr chunk)
{
return ( (chunk->getDescToken() == std::string("surfaceDisplay"))
|| (chunk->getDescToken() == std::string("simDisplay"))
|| (chunk->getDescToken() == std::string("displaySystem"))
|| (chunk->getDescToken() == std::string("displayWindow"))
);
}
/**
* Adds the chunk to the configuration.
*
* @pre configCanHandle(chunk) == true
* @post (display of same name already loaded) ==> old display closed, new one opened<br>
* (display is new) ==> (new display is added)<br>
* Draw Manager is notified of the display change.
*/
bool DisplayManager::configAddDisplay(jccl::ConfigChunkPtr chunk)
{
vprASSERT(configCanHandle(chunk)); // We must be able to handle it first of all
vprDEBUG_BEGIN(vrjDBG_DISP_MGR,vprDBG_STATE_LVL) << "------- DisplayManager::configAddDisplay -------\n" << vprDEBUG_FLUSH;
// Find out if we already have a window of this name
// If so, then close it before we open a new one of the same name
// This basically allows re-configuration of a window
Display* cur_disp = findDisplayNamed(chunk->getName());
if(cur_disp != NULL) // We have an old display
{
vprDEBUG(vrjDBG_DISP_MGR,vprDBG_CONFIG_LVL) << "Removing old window: " << cur_disp->getName().c_str() << vprDEBUG_FLUSH;
closeDisplay(cur_disp,true); // Close the display and notify the draw manager to close the window
}
// --- Add a display (of the correct type) ---- //
if(chunk->getDescToken() == std::string("displayWindow")) // Display window
{
Display* newDisp = new Display(); // Create the display
newDisp->config(chunk);
addDisplay(newDisp,true); // Add it
vprDEBUG(vrjDBG_DISP_MGR,vprDBG_STATE_LVL) << "Adding display: " << newDisp->getName().c_str() << std::endl << vprDEBUG_FLUSH;
vprDEBUG(vrjDBG_DISP_MGR,vprDBG_STATE_LVL) << "Display: " << newDisp << std::endl << vprDEBUG_FLUSH;
}
vprDEBUG_END(vrjDBG_DISP_MGR,vprDBG_STATE_LVL) << "------- DisplayManager::configAddDisplay Done. --------\n" << vprDEBUG_FLUSH;
return true;
}
/**
* Removes the chunk from the current configuration.
*
* @pre configCanHandle(chunk) == true
* @return success
*/
bool DisplayManager::configRemoveDisplay(jccl::ConfigChunkPtr chunk)
{
vprASSERT(configCanHandle(chunk)); // We must be able to handle it first of all
vprDEBUG_BEGIN(vrjDBG_DISP_MGR,vprDBG_STATE_LVL) << "------- DisplayManager::configRemoveDisplay -------\n" << vprDEBUG_FLUSH;
bool success_flag(false);
if(chunk->getDescToken() == std::string("displayWindow")) // It is a display
{
Display* remove_disp = findDisplayNamed(chunk->getName());
if(remove_disp != NULL)
{
closeDisplay(remove_disp, true); // Remove it
success_flag = true;
}
}
vprDEBUG_END(vrjDBG_DISP_MGR,vprDBG_STATE_LVL) << "------- DisplayManager::configRemoveDisplay done. --------\n" << vprDEBUG_FLUSH;
return success_flag;
}
// notifyDrawMgr = 0; Defaults to 0
int DisplayManager::addDisplay(Display* disp, bool notifyDrawMgr)
{
vprDEBUG(vrjDBG_DISP_MGR,4) << "vjDisplayManager::addDisplay \n" << vprDEBUG_FLUSH;
// Test if active or not, to determine correct list
// The place it in the list
// --- Update Local Display structures
if(disp->isActive())
mActiveDisplays.push_back(disp);
else
mInactiveDisplays.push_back(disp);
// If we are supposed to notify about, and valid draw mgr, and disp is active
if((notifyDrawMgr) && (mDrawManager != NULL) && (disp->isActive()))
mDrawManager->addDisplay(disp);; // Tell Draw Manager to add dislay;
return 1;
}
/**
* Closes the given display.
*
* @pre disp is a display we know about.
* @post disp has been removed from the list of displays
* (notifyDrawMgr == true) && (drawMgr != NULL) && (disp is active)
* ==> Draw manager has been told to clode the window for the display
*/
int DisplayManager::closeDisplay(Display* disp, bool notifyDrawMgr)
{
vprASSERT(isMemberDisplay(disp)); // Make sure that display actually exists
vprDEBUG_BEGIN(vrjDBG_DISP_MGR,vprDBG_STATE_LVL) << "closeDisplay: Closing display named: " << disp->getName() << std::endl<< vprDEBUG_FLUSH;
// Notify the draw manager to get rid of it
// Note: if it is not active, then the draw manager doesn't know about it
if((notifyDrawMgr) && (mDrawManager != NULL) && (disp->isActive()))
mDrawManager->removeDisplay(disp);
// Remove it from local data structures
unsigned int num_before_close = mActiveDisplays.size() + mInactiveDisplays.size();
mActiveDisplays.erase( std::remove(mActiveDisplays.begin(), mActiveDisplays.end(), disp),
mActiveDisplays.end());
mInactiveDisplays.erase( std::remove(mInactiveDisplays.begin(), mInactiveDisplays.end(), disp),
mInactiveDisplays.end());
vprASSERT(num_before_close == (1+mActiveDisplays.size() + mInactiveDisplays.size()));
// Delete the object
// XXX: Memory leak. Can't delete display here because the draw manager
// may need access to it when the draw manager closes the window up.
// ex: the glDrawManager window has ref to the display to get current user, etc.
//XXX//delete disp;
return 1;
}
// Is the display a member of the display manager
bool DisplayManager::isMemberDisplay(Display* disp)
{
std::vector<Display*>::iterator i;
i = std::find(mActiveDisplays.begin(),mActiveDisplays.end(),disp);
if(i != mActiveDisplays.end())
return true;
i = std::find(mInactiveDisplays.begin(),mInactiveDisplays.end(),disp);
if(i != mInactiveDisplays.end())
return true;
return false; // Didn't find any
}
/**
* Finds a display given the display name.
* @return NULL if nothing found
*/
Display* DisplayManager::findDisplayNamed(std::string name)
{
std::vector<Display*>::iterator i;
for(i = mActiveDisplays.begin();i!=mActiveDisplays.end();i++)
if((*i)->getName() == name)
return (*i);
for(i = mInactiveDisplays.begin();i!=mInactiveDisplays.end();i++)
if((*i)->getName() == name)
return (*i);
return NULL; // Didn't find any
}
void DisplayManager::updateProjections()
{
// for (all displays) update the projections
for (std::vector<Display*>::iterator i = mActiveDisplays.begin(); i != mActiveDisplays.end(); i++)
(*i)->updateProjections();
for (std::vector<Display*>::iterator j = mInactiveDisplays.begin(); j != mInactiveDisplays.end(); j++)
(*j)->updateProjections();
if(mDrawManager != NULL)
mDrawManager->updateProjections();
}
};
<|endoftext|>
|
<commit_before>// Copyright 2010, Camilo Aguilar. Cloudescape, LLC.
#include "bindings.h"
/* size of the event structure, not counting name */
#define EVENT_SIZE (sizeof (struct inotify_event))
/* reasonable guess as to size of 1024 events */
#define BUF_LEN (1024 * (EVENT_SIZE + 16))
namespace NodeInotify {
static Persistent<String> path_sym;
static Persistent<String> watch_for_sym;
static Persistent<String> callback_sym;
static Persistent<String> persistent_sym;
static Persistent<String> watch_sym;
static Persistent<String> mask_sym;
static Persistent<String> cookie_sym;
static Persistent<String> name_sym;
void Inotify::Initialize(Handle<Object> target) {
Local<FunctionTemplate> t = FunctionTemplate::New(Inotify::New);
t->Inherit(EventEmitter::constructor_template);
t->InstanceTemplate()->SetInternalFieldCount(1);
NODE_SET_PROTOTYPE_METHOD(t, "addWatch",
Inotify::AddWatch);
NODE_SET_PROTOTYPE_METHOD(t, "removeWatch",
Inotify::RemoveWatch);
NODE_SET_PROTOTYPE_METHOD(t, "close",
Inotify::Close);
//Constants initialization
NODE_DEFINE_CONSTANT(t, IN_ACCESS); //File was accessed (read)
NODE_DEFINE_CONSTANT(t, IN_ATTRIB); //Metadata changed, e.g., permissions, timestamps,
//extended attributes, link count (since Linux 2.6.25),
//UID, GID, etc.
NODE_DEFINE_CONSTANT(t, IN_CLOSE_WRITE); //File opened for writing was closed
NODE_DEFINE_CONSTANT(t, IN_CLOSE_NOWRITE); //File not opened for writing was closed
NODE_DEFINE_CONSTANT(t, IN_CREATE); //File/directory created in watched directory
NODE_DEFINE_CONSTANT(t, IN_DELETE); //File/directory deleted from watched directory
NODE_DEFINE_CONSTANT(t, IN_DELETE_SELF); //Watched file/directory was itself deleted
NODE_DEFINE_CONSTANT(t, IN_MODIFY); //File was modified
NODE_DEFINE_CONSTANT(t, IN_MOVE_SELF); //Watched file/directory was itself moved
NODE_DEFINE_CONSTANT(t, IN_MOVED_FROM); //File moved out of watched directory
NODE_DEFINE_CONSTANT(t, IN_MOVED_TO); //File moved into watched directory
NODE_DEFINE_CONSTANT(t, IN_OPEN); //File was opened
NODE_DEFINE_CONSTANT(t, IN_IGNORED); // Watch was removed explicitly (inotify.watch.rm) or
//automatically (file was deleted, or file system was
//unmounted)
NODE_DEFINE_CONSTANT(t, IN_ISDIR); //Subject of this event is a directory
NODE_DEFINE_CONSTANT(t, IN_Q_OVERFLOW); //Event queue overflowed (wd is -1 for this event)
NODE_DEFINE_CONSTANT(t, IN_UNMOUNT); //File system containing watched object was unmounted
NODE_DEFINE_CONSTANT(t, IN_ALL_EVENTS);
NODE_DEFINE_CONSTANT(t, IN_ONLYDIR); // Only watch the path if it is a directory.
NODE_DEFINE_CONSTANT(t, IN_DONT_FOLLOW); // Do not follow a sym link
NODE_DEFINE_CONSTANT(t, IN_ONESHOT); // Only send event once
NODE_DEFINE_CONSTANT(t, IN_MASK_ADD); //Add (OR) events to watch mask for this pathname if it
//already exists (instead of replacing mask).
NODE_DEFINE_CONSTANT(t, IN_CLOSE); // (IN_CLOSE_WRITE | IN_CLOSE_NOWRITE) Close
NODE_DEFINE_CONSTANT(t, IN_MOVE); // (IN_MOVED_FROM | IN_MOVED_TO) Moves
path_sym = NODE_PSYMBOL("path");
watch_for_sym = NODE_PSYMBOL("watch_for");
callback_sym = NODE_PSYMBOL("callback");
persistent_sym = NODE_PSYMBOL("persistent");
watch_sym = NODE_PSYMBOL("watch");
mask_sym = NODE_PSYMBOL("mask");
cookie_sym = NODE_PSYMBOL("cookie");
name_sym = NODE_PSYMBOL("name");
Local<ObjectTemplate> object_tmpl = t->InstanceTemplate();
object_tmpl->SetAccessor(persistent_sym, Inotify::GetPersistent);
t->SetClassName(String::NewSymbol("Inotify"));
target->Set(String::NewSymbol("Inotify"), t->GetFunction());
}
Inotify::Inotify() : EventEmitter() {
ev_init(&read_watcher, Inotify::Callback);
read_watcher.data = this; //preserving my reference to use it inside Inotify::Callback
persistent = true;
}
Inotify::Inotify(bool nonpersistent) : EventEmitter() {
ev_init(&read_watcher, Inotify::Callback);
read_watcher.data = this; //preserving my reference to use it inside Inotify::Callback
persistent = nonpersistent;
}
Inotify::~Inotify() {
if(!persistent) {
ev_ref(EV_DEFAULT_UC);
}
ev_io_stop(EV_DEFAULT_UC_ &read_watcher);
assert(!ev_is_active(&read_watcher));
assert(!ev_is_pending(&read_watcher));
}
Handle<Value> Inotify::New(const Arguments& args) {
HandleScope scope;
Inotify *inotify = NULL;
if(args.Length() == 1 && args[0]->IsBoolean()) {
inotify = new Inotify(args[0]->IsTrue());
} else {
inotify = new Inotify();
}
inotify->fd = inotify_init1(IN_NONBLOCK | IN_CLOEXEC); //nonblock
//inotify->fd = inotify_init1(IN_CLOEXEC); //block
if(inotify->fd == -1) {
ThrowException(String::New(strerror(errno)));
return Null();
}
ev_io_set(&inotify->read_watcher, inotify->fd, EV_READ);
ev_io_start(EV_DEFAULT_UC_ &inotify->read_watcher);
Local<Object> obj = args.This();
inotify->Wrap(obj);
if(!inotify->persistent) {
ev_unref(EV_DEFAULT_UC);
}
/*Increment object references to avoid be GCed while
I'm waiting for inotify events in th ev_pool.
Also, the object is not weak anymore */
inotify->Ref();
return scope.Close(obj);
}
Handle<Value> Inotify::AddWatch(const Arguments& args) {
HandleScope scope;
uint32_t mask = 0;
int watch_descriptor = 0;
if(args.Length() < 1 || !args[0]->IsObject()) {
return ThrowException(Exception::TypeError(
String::New("You must specify an object as first argument")));
}
Local<Object> args_ = args[0]->ToObject();
if(!args_->Has(path_sym)) {
return ThrowException(Exception::TypeError(
String::New("You must specify a path to watch for events")));
}
if(!args_->Has(callback_sym) ||
!args_->Get(callback_sym)->IsFunction()) {
return ThrowException(Exception::TypeError(
String::New("You must specify a callback function")));
}
if(!args_->Has(watch_for_sym)) {
mask |= IN_ALL_EVENTS;
} else {
if(!args_->Get(watch_for_sym)->IsInt32()) {
return ThrowException(Exception::TypeError(
String::New("You must specify OR'ed set of events")));
}
mask |= args_->Get(watch_for_sym)->Int32Value();
if(mask == 0) {
return ThrowException(Exception::TypeError(
String::New("You must specify OR'ed set of events")));
}
}
String::Utf8Value path(args_->Get(path_sym));
Inotify *inotify = ObjectWrap::Unwrap<Inotify>(args.This());
/* add watch */
watch_descriptor = inotify_add_watch(inotify->fd, (const char *) *path, mask);
Local<Integer> descriptor = Integer::New(watch_descriptor);
//Local<Function> callback = Local<Function>::Cast(args_->Get(callback_sym));
inotify->handle_->Set(descriptor, args_->Get(callback_sym));
return scope.Close(descriptor);
}
Handle<Value> Inotify::RemoveWatch(const Arguments& args) {
HandleScope scope;
uint32_t watch = 0;
int ret = -1;
if(args.Length() == 0 || !args[0]->IsInt32()) {
return ThrowException(Exception::TypeError(
String::New("You must specify a valid watcher descriptor as argument")));
}
watch = args[0]->Int32Value();
Inotify *inotify = ObjectWrap::Unwrap<Inotify>(args.This());
ret = inotify_rm_watch(inotify->fd, watch);
if(ret == -1) {
ThrowException(String::New(strerror(errno)));
return False();
}
return True();
}
Handle<Value> Inotify::Close(const Arguments& args) {
HandleScope scope;
int ret = -1;
Inotify *inotify = ObjectWrap::Unwrap<Inotify>(args.This());
ret = close(inotify->fd);
if(ret == -1) {
ThrowException(String::New(strerror(errno)));
return False();
}
if(!inotify->persistent) {
ev_ref(EV_DEFAULT_UC);
}
ev_io_stop(EV_DEFAULT_UC_ &inotify->read_watcher);
/*Eliminating reference created inside of Inotify::New.
The object is also weak again.
Now v8 can do its stuff and GC the object.
*/
inotify->Unref();
return True();
}
void Inotify::Callback(EV_P_ ev_io *watcher, int revents) {
HandleScope scope;
Inotify *inotify = static_cast<Inotify*>(watcher->data);
assert(watcher == &inotify->read_watcher);
char buffer[BUF_LEN];
int length = read(inotify->fd, buffer, BUF_LEN);
Local<Value> argv[1];
TryCatch try_catch;
int i = 0;
while (i < length) {
struct inotify_event *event;
event = (struct inotify_event *) &buffer[i];
Local<Object> obj = Object::New();
obj->Set(watch_sym, Integer::New(event->wd));
obj->Set(mask_sym, Integer::New(event->mask));
obj->Set(cookie_sym, Integer::New(event->cookie));
if(event->len) {
obj->Set(name_sym, String::New(event->name));
}
argv[0] = obj;
inotify->Ref();
Local<Value> callback_ = inotify->handle_->Get(Integer::New(event->wd));
Local<Function> callback = Local<Function>::Cast(callback_);
callback->Call(inotify->handle_, 1, argv);
inotify->Unref();
if(event->mask & IN_IGNORED) {
//deleting callback because the watch was removed
printf("entrooo");
Local<Value> wd = Integer::New(event->wd);
inotify->handle_->Delete(wd->ToString());
}
if (try_catch.HasCaught()) {
FatalException(try_catch);
}
i += EVENT_SIZE + event->len;
}
}
Handle<Value> Inotify::GetPersistent(Local<String> property,
const AccessorInfo& info) {
Inotify *inotify = ObjectWrap::Unwrap<Inotify>(info.This());
return inotify->persistent ? True() : False();
}
}//namespace NodeInotify
<commit_msg>delete javascript callback when the watch is removed<commit_after>// Copyright 2010, Camilo Aguilar. Cloudescape, LLC.
#include "bindings.h"
/* size of the event structure, not counting name */
#define EVENT_SIZE (sizeof (struct inotify_event))
/* reasonable guess as to size of 1024 events */
#define BUF_LEN (1024 * (EVENT_SIZE + 16))
namespace NodeInotify {
static Persistent<String> path_sym;
static Persistent<String> watch_for_sym;
static Persistent<String> callback_sym;
static Persistent<String> persistent_sym;
static Persistent<String> watch_sym;
static Persistent<String> mask_sym;
static Persistent<String> cookie_sym;
static Persistent<String> name_sym;
void Inotify::Initialize(Handle<Object> target) {
Local<FunctionTemplate> t = FunctionTemplate::New(Inotify::New);
t->Inherit(EventEmitter::constructor_template);
t->InstanceTemplate()->SetInternalFieldCount(1);
NODE_SET_PROTOTYPE_METHOD(t, "addWatch",
Inotify::AddWatch);
NODE_SET_PROTOTYPE_METHOD(t, "removeWatch",
Inotify::RemoveWatch);
NODE_SET_PROTOTYPE_METHOD(t, "close",
Inotify::Close);
//Constants initialization
NODE_DEFINE_CONSTANT(t, IN_ACCESS); //File was accessed (read)
NODE_DEFINE_CONSTANT(t, IN_ATTRIB); //Metadata changed, e.g., permissions, timestamps,
//extended attributes, link count (since Linux 2.6.25),
//UID, GID, etc.
NODE_DEFINE_CONSTANT(t, IN_CLOSE_WRITE); //File opened for writing was closed
NODE_DEFINE_CONSTANT(t, IN_CLOSE_NOWRITE); //File not opened for writing was closed
NODE_DEFINE_CONSTANT(t, IN_CREATE); //File/directory created in watched directory
NODE_DEFINE_CONSTANT(t, IN_DELETE); //File/directory deleted from watched directory
NODE_DEFINE_CONSTANT(t, IN_DELETE_SELF); //Watched file/directory was itself deleted
NODE_DEFINE_CONSTANT(t, IN_MODIFY); //File was modified
NODE_DEFINE_CONSTANT(t, IN_MOVE_SELF); //Watched file/directory was itself moved
NODE_DEFINE_CONSTANT(t, IN_MOVED_FROM); //File moved out of watched directory
NODE_DEFINE_CONSTANT(t, IN_MOVED_TO); //File moved into watched directory
NODE_DEFINE_CONSTANT(t, IN_OPEN); //File was opened
NODE_DEFINE_CONSTANT(t, IN_IGNORED); // Watch was removed explicitly (inotify.watch.rm) or
//automatically (file was deleted, or file system was
//unmounted)
NODE_DEFINE_CONSTANT(t, IN_ISDIR); //Subject of this event is a directory
NODE_DEFINE_CONSTANT(t, IN_Q_OVERFLOW); //Event queue overflowed (wd is -1 for this event)
NODE_DEFINE_CONSTANT(t, IN_UNMOUNT); //File system containing watched object was unmounted
NODE_DEFINE_CONSTANT(t, IN_ALL_EVENTS);
NODE_DEFINE_CONSTANT(t, IN_ONLYDIR); // Only watch the path if it is a directory.
NODE_DEFINE_CONSTANT(t, IN_DONT_FOLLOW); // Do not follow a sym link
NODE_DEFINE_CONSTANT(t, IN_ONESHOT); // Only send event once
NODE_DEFINE_CONSTANT(t, IN_MASK_ADD); //Add (OR) events to watch mask for this pathname if it
//already exists (instead of replacing mask).
NODE_DEFINE_CONSTANT(t, IN_CLOSE); // (IN_CLOSE_WRITE | IN_CLOSE_NOWRITE) Close
NODE_DEFINE_CONSTANT(t, IN_MOVE); // (IN_MOVED_FROM | IN_MOVED_TO) Moves
path_sym = NODE_PSYMBOL("path");
watch_for_sym = NODE_PSYMBOL("watch_for");
callback_sym = NODE_PSYMBOL("callback");
persistent_sym = NODE_PSYMBOL("persistent");
watch_sym = NODE_PSYMBOL("watch");
mask_sym = NODE_PSYMBOL("mask");
cookie_sym = NODE_PSYMBOL("cookie");
name_sym = NODE_PSYMBOL("name");
Local<ObjectTemplate> object_tmpl = t->InstanceTemplate();
object_tmpl->SetAccessor(persistent_sym, Inotify::GetPersistent);
t->SetClassName(String::NewSymbol("Inotify"));
target->Set(String::NewSymbol("Inotify"), t->GetFunction());
}
Inotify::Inotify() : EventEmitter() {
ev_init(&read_watcher, Inotify::Callback);
read_watcher.data = this; //preserving my reference to use it inside Inotify::Callback
persistent = true;
}
Inotify::Inotify(bool nonpersistent) : EventEmitter() {
ev_init(&read_watcher, Inotify::Callback);
read_watcher.data = this; //preserving my reference to use it inside Inotify::Callback
persistent = nonpersistent;
}
Inotify::~Inotify() {
if(!persistent) {
ev_ref(EV_DEFAULT_UC);
}
ev_io_stop(EV_DEFAULT_UC_ &read_watcher);
assert(!ev_is_active(&read_watcher));
assert(!ev_is_pending(&read_watcher));
}
Handle<Value> Inotify::New(const Arguments& args) {
HandleScope scope;
Inotify *inotify = NULL;
if(args.Length() == 1 && args[0]->IsBoolean()) {
inotify = new Inotify(args[0]->IsTrue());
} else {
inotify = new Inotify();
}
inotify->fd = inotify_init1(IN_NONBLOCK | IN_CLOEXEC); //nonblock
//inotify->fd = inotify_init1(IN_CLOEXEC); //block
if(inotify->fd == -1) {
ThrowException(String::New(strerror(errno)));
return Null();
}
ev_io_set(&inotify->read_watcher, inotify->fd, EV_READ);
ev_io_start(EV_DEFAULT_UC_ &inotify->read_watcher);
Local<Object> obj = args.This();
inotify->Wrap(obj);
if(!inotify->persistent) {
ev_unref(EV_DEFAULT_UC);
}
/*Increment object references to avoid be GCed while
I'm waiting for inotify events in th ev_pool.
Also, the object is not weak anymore */
inotify->Ref();
return scope.Close(obj);
}
Handle<Value> Inotify::AddWatch(const Arguments& args) {
HandleScope scope;
uint32_t mask = 0;
int watch_descriptor = 0;
if(args.Length() < 1 || !args[0]->IsObject()) {
return ThrowException(Exception::TypeError(
String::New("You must specify an object as first argument")));
}
Local<Object> args_ = args[0]->ToObject();
if(!args_->Has(path_sym)) {
return ThrowException(Exception::TypeError(
String::New("You must specify a path to watch for events")));
}
if(!args_->Has(callback_sym) ||
!args_->Get(callback_sym)->IsFunction()) {
return ThrowException(Exception::TypeError(
String::New("You must specify a callback function")));
}
if(!args_->Has(watch_for_sym)) {
mask |= IN_ALL_EVENTS;
} else {
if(!args_->Get(watch_for_sym)->IsInt32()) {
return ThrowException(Exception::TypeError(
String::New("You must specify OR'ed set of events")));
}
mask |= args_->Get(watch_for_sym)->Int32Value();
if(mask == 0) {
return ThrowException(Exception::TypeError(
String::New("You must specify OR'ed set of events")));
}
}
String::Utf8Value path(args_->Get(path_sym));
Inotify *inotify = ObjectWrap::Unwrap<Inotify>(args.This());
/* add watch */
watch_descriptor = inotify_add_watch(inotify->fd, (const char *) *path, mask);
Local<Integer> descriptor = Integer::New(watch_descriptor);
//Local<Function> callback = Local<Function>::Cast(args_->Get(callback_sym));
inotify->handle_->Set(descriptor, args_->Get(callback_sym));
return scope.Close(descriptor);
}
Handle<Value> Inotify::RemoveWatch(const Arguments& args) {
HandleScope scope;
uint32_t watch = 0;
int ret = -1;
if(args.Length() == 0 || !args[0]->IsInt32()) {
return ThrowException(Exception::TypeError(
String::New("You must specify a valid watcher descriptor as argument")));
}
watch = args[0]->Int32Value();
Inotify *inotify = ObjectWrap::Unwrap<Inotify>(args.This());
ret = inotify_rm_watch(inotify->fd, watch);
if(ret == -1) {
ThrowException(String::New(strerror(errno)));
return False();
}
return True();
}
Handle<Value> Inotify::Close(const Arguments& args) {
HandleScope scope;
int ret = -1;
Inotify *inotify = ObjectWrap::Unwrap<Inotify>(args.This());
ret = close(inotify->fd);
if(ret == -1) {
ThrowException(String::New(strerror(errno)));
return False();
}
if(!inotify->persistent) {
ev_ref(EV_DEFAULT_UC);
}
ev_io_stop(EV_DEFAULT_UC_ &inotify->read_watcher);
/*Eliminating reference created inside of Inotify::New.
The object is also weak again.
Now v8 can do its stuff and GC the object.
*/
inotify->Unref();
return True();
}
void Inotify::Callback(EV_P_ ev_io *watcher, int revents) {
HandleScope scope;
Inotify *inotify = static_cast<Inotify*>(watcher->data);
assert(watcher == &inotify->read_watcher);
char buffer[BUF_LEN];
int length = read(inotify->fd, buffer, BUF_LEN);
Local<Value> argv[1];
TryCatch try_catch;
int i = 0;
while (i < length) {
struct inotify_event *event;
event = (struct inotify_event *) &buffer[i];
Local<Object> obj = Object::New();
obj->Set(watch_sym, Integer::New(event->wd));
obj->Set(mask_sym, Integer::New(event->mask));
obj->Set(cookie_sym, Integer::New(event->cookie));
if(event->len) {
obj->Set(name_sym, String::New(event->name));
}
argv[0] = obj;
inotify->Ref();
Local<Value> callback_ = inotify->handle_->Get(Integer::New(event->wd));
Local<Function> callback = Local<Function>::Cast(callback_);
callback->Call(inotify->handle_, 1, argv);
inotify->Unref();
if(event->mask & IN_IGNORED) {
//deleting callback because the watch was removed
Local<Value> wd = Integer::New(event->wd);
inotify->handle_->Delete(wd->ToString());
}
if (try_catch.HasCaught()) {
FatalException(try_catch);
}
i += EVENT_SIZE + event->len;
}
}
Handle<Value> Inotify::GetPersistent(Local<String> property,
const AccessorInfo& info) {
Inotify *inotify = ObjectWrap::Unwrap<Inotify>(info.This());
return inotify->persistent ? True() : False();
}
}//namespace NodeInotify
<|endoftext|>
|
<commit_before>#include <jni.h>
#include <string>
extern "C" JNIEXPORT jstring
JNICALL
Java_cn_vip_ldcr_SDLActivity_stringFromJNI(
JNIEnv *env,
jobject /* this */) {
std::string hello = "Hello from C++";
return env->NewStringUTF(hello.c_str());
}
<commit_msg>PREF 3guohero 3gyj-android 三国志英杰android //移除CPP 试了 3.2.1gradle as3.6.2 几个NDK版本 sync仍然莫名报错 https://www.jianshu.com/p/fdb8b83cc07f 去年写的好好的项目,今天 clone 下来根本跑不起来,编译直接报错:SIMPLE: Error configuring;https://blog.csdn.net/tklwj/article/details/87260414 Android studio 同步工程失败:External Native Build Issues: Error configuring;https://github.com/gongxp/sdlapp 这个还是2.3当年也能用·· GOOGLE的AS真是不敢恭维·<commit_after><|endoftext|>
|
<commit_before>#include "HM_base.h"
namespace kai
{
HM_base::HM_base()
{
m_pCAN = NULL;
m_pCMD = NULL;
m_pGPS = NULL;
m_strCMD = "";
m_rpmL = 0;
m_rpmR = 0;
m_motorRpmW = 0;
m_bSpeaker = false;
m_bMute = false;
m_canAddrStation = 0x301;
m_maxRpmT = 65535;
m_maxRpmW = 2500;
m_ctrlB0 = 0;
m_ctrlB1 = 0;
m_defaultRpmT = 3000;
m_wheelR = 0.1;
m_treadW = 0.4;
m_pinLEDwork = 0;
m_pinLEDrth = 0;
m_pinLEDfollow = 0;
m_dT.init();
m_dRot.init();
}
HM_base::~HM_base()
{
}
bool HM_base::init(void* pKiss)
{
IF_F(!this->ActionBase::init(pKiss));
Kiss* pK = (Kiss*)pKiss;
pK->m_pInst = this;
F_INFO(pK->v("maxSpeedT", &m_maxRpmT));
F_INFO(pK->v("maxSpeedW", &m_maxRpmW));
F_INFO(pK->v("motorRpmW", &m_motorRpmW));
F_INFO(pK->v("defaultRpmT", &m_defaultRpmT));
F_INFO(pK->v("wheelR", &m_wheelR));
F_INFO(pK->v("treadW", &m_treadW));
F_INFO(pK->v("bMute", &m_bMute));
F_INFO(pK->v("canAddrStation", &m_canAddrStation));
F_INFO(pK->v("pinLEDwork", (int*)&m_pinLEDwork));
F_INFO(pK->v("pinLEDrth", (int*)&m_pinLEDrth));
F_INFO(pK->v("pinLEDfollow", (int*)&m_pinLEDfollow));
Kiss* pI = pK->o("cmd");
IF_T(pI->empty());
m_pCMD = new TCP();
F_ERROR_F(m_pCMD->init(pI));
return true;
}
bool HM_base::link(void)
{
IF_F(!this->ActionBase::link());
Kiss* pK = (Kiss*)m_pKiss;
string iName;
iName = "";
F_ERROR_F(pK->v("_Canbus", &iName));
m_pCAN = (_Canbus*) (pK->root()->getChildInstByName(&iName));
iName = "";
F_ERROR_F(pK->v("_GPS", &iName));
m_pGPS = (_GPS*) (pK->root()->getChildInstByName(&iName));
return true;
}
void HM_base::update(void)
{
this->ActionBase::update();
NULL_(m_pAM);
NULL_(m_pCMD);
updateGPS();
updateCAN();
string* pStateName = m_pAM->getCurrentStateName();
if(*pStateName == "HM_STANDBY" || *pStateName == "HM_STATION" || *pStateName=="HM_FOLLOWME")
{
m_rpmL = 0;
m_rpmR = 0;
}
else
{
m_rpmL = m_defaultRpmT;
m_rpmR = m_defaultRpmT;
}
m_motorRpmW = 0;
m_bSpeaker = false;
cmd();
}
void HM_base::updateGPS(void)
{
NULL_(m_pGPS);
const static double tBase = 1.0/(USEC_1SEC*60.0);
//force rpm to only rot or translation at a time
if(abs(m_rpmL) != abs(m_rpmR))
{
int mid = (m_rpmL + m_rpmR)/2;
int absRpm = abs(m_rpmL - mid);
if(m_rpmL > m_rpmR)
{
m_rpmL = absRpm;
m_rpmR = -absRpm;
}
else
{
m_rpmL = -absRpm;
m_rpmR = absRpm;
}
m_dT.m_z = 0.0;
m_dRot.m_x = 360.0 * (((double)m_rpmL) * tBase * m_wheelR * 2 * PI) / (m_treadW * PI);
}
else if(m_rpmL != m_rpmR)
{
m_dT.m_z = 0.0;
m_dRot.m_x = 360.0 * (((double)m_rpmL) * tBase * m_wheelR * 2 * PI) / (m_treadW * PI);
}
else
{
m_dT.m_z = ((double)m_rpmL) * tBase * m_wheelR * 2 * PI;
m_dRot.m_x = 0.0;
}
//TODO:Temporal
m_dT.m_z *= 1000000;
m_pGPS->setSpeed(&m_dT,&m_dRot);
LOG_I("dZ="<<m_dT.m_z<<" dYaw="<<m_dRot.m_x);
}
void HM_base::cmd(void)
{
if (!m_pCMD->isOpen())
{
m_pCMD->open();
return;
}
char buf;
while (m_pCMD->read((uint8_t*) &buf, 1) > 0)
{
if (buf == ',')break;
IF_CONT(buf==LF);
IF_CONT(buf==CR);
m_strCMD += buf;
}
IF_(buf!=',');
LOG_I("CMD: "<<m_strCMD);
string stateName;
if(m_strCMD=="start")
{
stateName = *m_pAM->getCurrentStateName();
if(stateName=="HM_STATION")
{
stateName = "HM_KICKBACK";
m_pAM->transit(&stateName);
}
else if(stateName=="HM_STANDBY")
{
m_pAM->transit(m_pAM->getLastStateIdx());
}
}
else if(m_strCMD=="stop")
{
stateName = "HM_STANDBY";
m_pAM->transit(&stateName);
}
else if(m_strCMD=="work")
{
stateName = "HM_WORK";
m_pAM->transit(&stateName);
}
else if(m_strCMD=="back_to_home")
{
stateName = "HM_RTH";
m_pAM->transit(&stateName);
}
else if(m_strCMD=="follow_me")
{
stateName = "HM_FOLLOWME";
m_pAM->transit(&stateName);
}
else if(m_strCMD=="station")
{
stateName = "HM_STATION";
m_pGPS->reset();
m_pAM->transit(&stateName);
}
m_strCMD = "";
}
void HM_base::updateCAN(void)
{
NULL_(m_pCAN);
//send
if(m_bMute)m_bSpeaker = false;
unsigned long addr = 0x113;
unsigned char cmd[8];
m_ctrlB0 = 0;
m_ctrlB0 |= (m_rpmR<0)?(1 << 4):0;
m_ctrlB0 |= (m_rpmL<0)?(1 << 5):0;
m_ctrlB0 |= (m_motorRpmW<0)?(1 << 6):0;
uint16_t motorPwmL = abs(constrain(m_rpmL, m_maxRpmT, -m_maxRpmT));
uint16_t motorPwmR = abs(constrain(m_rpmR, m_maxRpmT, -m_maxRpmT));
uint16_t motorPwmW = abs(constrain(m_motorRpmW, m_maxRpmW, -m_maxRpmW));
m_ctrlB1 = 0;
m_ctrlB1 |= 1; //tracktion motor relay
m_ctrlB1 |= (1 << 1); //working motor relay
m_ctrlB1 |= (m_bSpeaker)?(1 << 5):0;//speaker
m_ctrlB1 |= (1 << 6); //external command
m_ctrlB1 |= (1 << 7); //0:pwm, 1:rpm
uint16_t bFilter = 0x00ff;
cmd[0] = m_ctrlB0;
cmd[1] = m_ctrlB1;
cmd[2] = motorPwmL & bFilter;
cmd[3] = (motorPwmL>>8) & bFilter;
cmd[4] = motorPwmR & bFilter;
cmd[5] = (motorPwmR>>8) & bFilter;
cmd[6] = motorPwmW & bFilter;
cmd[7] = (motorPwmW>>8) & bFilter;
m_pCAN->send(addr, 8, cmd);
//status LED
string stateName = *m_pAM->getCurrentStateName();
if(stateName=="HM_WORK")
{
m_pCAN->pinOut(m_pinLEDwork,1);
m_pCAN->pinOut(m_pinLEDrth,0);
m_pCAN->pinOut(m_pinLEDfollow,0);
}
else if(stateName=="HM_RTH")
{
m_pCAN->pinOut(m_pinLEDwork,0);
m_pCAN->pinOut(m_pinLEDrth,1);
m_pCAN->pinOut(m_pinLEDfollow,0);
}
else if(stateName=="HM_FOLLOW")
{
m_pCAN->pinOut(m_pinLEDwork,0);
m_pCAN->pinOut(m_pinLEDrth,0);
m_pCAN->pinOut(m_pinLEDfollow,1);
}
else if(stateName=="HM_KICKBACK")
{
m_pCAN->pinOut(m_pinLEDwork,1);
m_pCAN->pinOut(m_pinLEDrth,1);
m_pCAN->pinOut(m_pinLEDfollow,1);
}
else
{
m_pCAN->pinOut(m_pinLEDwork,0);
m_pCAN->pinOut(m_pinLEDrth,0);
m_pCAN->pinOut(m_pinLEDfollow,0);
}
//receive
uint8_t* pCanData = m_pCAN->get(m_canAddrStation);
NULL_(pCanData);
//CAN-ID301h 1byte 4bit "AC-input"
//1:ON-Docking/0:OFF-area
IF_(!((pCanData[1] >> 4) & 1));
IF_(stateName == "HM_KICKBACK");
stateName = "HM_STATION";
m_pGPS->reset();
m_pAM->transit(&stateName);
}
bool HM_base::draw(void)
{
IF_F(!this->ActionBase::draw());
Window* pWin = (Window*) this->m_pWindow;
Mat* pMat = pWin->getFrame()->getCMat();
NULL_F(pMat);
IF_F(pMat->empty());
string msg = *this->getName() + ": rpmL=" + i2str(m_rpmL)
+ ", rpmR=" + i2str(m_rpmR);
pWin->addMsg(&msg);
return true;
}
}
<commit_msg>Fixed HM follow_me LED<commit_after>#include "HM_base.h"
namespace kai
{
HM_base::HM_base()
{
m_pCAN = NULL;
m_pCMD = NULL;
m_pGPS = NULL;
m_strCMD = "";
m_rpmL = 0;
m_rpmR = 0;
m_motorRpmW = 0;
m_bSpeaker = false;
m_bMute = false;
m_canAddrStation = 0x301;
m_maxRpmT = 65535;
m_maxRpmW = 2500;
m_ctrlB0 = 0;
m_ctrlB1 = 0;
m_defaultRpmT = 3000;
m_wheelR = 0.1;
m_treadW = 0.4;
m_pinLEDwork = 0;
m_pinLEDrth = 0;
m_pinLEDfollow = 0;
m_dT.init();
m_dRot.init();
}
HM_base::~HM_base()
{
}
bool HM_base::init(void* pKiss)
{
IF_F(!this->ActionBase::init(pKiss));
Kiss* pK = (Kiss*)pKiss;
pK->m_pInst = this;
F_INFO(pK->v("maxSpeedT", &m_maxRpmT));
F_INFO(pK->v("maxSpeedW", &m_maxRpmW));
F_INFO(pK->v("motorRpmW", &m_motorRpmW));
F_INFO(pK->v("defaultRpmT", &m_defaultRpmT));
F_INFO(pK->v("wheelR", &m_wheelR));
F_INFO(pK->v("treadW", &m_treadW));
F_INFO(pK->v("bMute", &m_bMute));
F_INFO(pK->v("canAddrStation", &m_canAddrStation));
F_INFO(pK->v("pinLEDwork", (int*)&m_pinLEDwork));
F_INFO(pK->v("pinLEDrth", (int*)&m_pinLEDrth));
F_INFO(pK->v("pinLEDfollow", (int*)&m_pinLEDfollow));
Kiss* pI = pK->o("cmd");
IF_T(pI->empty());
m_pCMD = new TCP();
F_ERROR_F(m_pCMD->init(pI));
return true;
}
bool HM_base::link(void)
{
IF_F(!this->ActionBase::link());
Kiss* pK = (Kiss*)m_pKiss;
string iName;
iName = "";
F_ERROR_F(pK->v("_Canbus", &iName));
m_pCAN = (_Canbus*) (pK->root()->getChildInstByName(&iName));
iName = "";
F_ERROR_F(pK->v("_GPS", &iName));
m_pGPS = (_GPS*) (pK->root()->getChildInstByName(&iName));
return true;
}
void HM_base::update(void)
{
this->ActionBase::update();
NULL_(m_pAM);
NULL_(m_pCMD);
updateGPS();
updateCAN();
string* pStateName = m_pAM->getCurrentStateName();
if(*pStateName == "HM_STANDBY" || *pStateName == "HM_STATION" || *pStateName=="HM_FOLLOWME")
{
m_rpmL = 0;
m_rpmR = 0;
}
else
{
m_rpmL = m_defaultRpmT;
m_rpmR = m_defaultRpmT;
}
m_motorRpmW = 0;
m_bSpeaker = false;
cmd();
}
void HM_base::updateGPS(void)
{
NULL_(m_pGPS);
const static double tBase = 1.0/(USEC_1SEC*60.0);
//force rpm to only rot or translation at a time
if(abs(m_rpmL) != abs(m_rpmR))
{
int mid = (m_rpmL + m_rpmR)/2;
int absRpm = abs(m_rpmL - mid);
if(m_rpmL > m_rpmR)
{
m_rpmL = absRpm;
m_rpmR = -absRpm;
}
else
{
m_rpmL = -absRpm;
m_rpmR = absRpm;
}
m_dT.m_z = 0.0;
m_dRot.m_x = 360.0 * (((double)m_rpmL) * tBase * m_wheelR * 2 * PI) / (m_treadW * PI);
}
else if(m_rpmL != m_rpmR)
{
m_dT.m_z = 0.0;
m_dRot.m_x = 360.0 * (((double)m_rpmL) * tBase * m_wheelR * 2 * PI) / (m_treadW * PI);
}
else
{
m_dT.m_z = ((double)m_rpmL) * tBase * m_wheelR * 2 * PI;
m_dRot.m_x = 0.0;
}
//TODO:Temporal
m_dT.m_z *= 1000000;
m_pGPS->setSpeed(&m_dT,&m_dRot);
LOG_I("dZ="<<m_dT.m_z<<" dYaw="<<m_dRot.m_x);
}
void HM_base::cmd(void)
{
if (!m_pCMD->isOpen())
{
m_pCMD->open();
return;
}
char buf;
while (m_pCMD->read((uint8_t*) &buf, 1) > 0)
{
if (buf == ',')break;
IF_CONT(buf==LF);
IF_CONT(buf==CR);
m_strCMD += buf;
}
IF_(buf!=',');
LOG_I("CMD: "<<m_strCMD);
string stateName;
if(m_strCMD=="start")
{
stateName = *m_pAM->getCurrentStateName();
if(stateName=="HM_STATION")
{
stateName = "HM_KICKBACK";
m_pAM->transit(&stateName);
}
else if(stateName=="HM_STANDBY")
{
m_pAM->transit(m_pAM->getLastStateIdx());
}
}
else if(m_strCMD=="stop")
{
stateName = "HM_STANDBY";
m_pAM->transit(&stateName);
}
else if(m_strCMD=="work")
{
stateName = "HM_WORK";
m_pAM->transit(&stateName);
}
else if(m_strCMD=="back_to_home")
{
stateName = "HM_RTH";
m_pAM->transit(&stateName);
}
else if(m_strCMD=="follow_me")
{
stateName = "HM_FOLLOWME";
m_pAM->transit(&stateName);
}
else if(m_strCMD=="station")
{
stateName = "HM_STATION";
m_pGPS->reset();
m_pAM->transit(&stateName);
}
m_strCMD = "";
}
void HM_base::updateCAN(void)
{
NULL_(m_pCAN);
//send
if(m_bMute)m_bSpeaker = false;
unsigned long addr = 0x113;
unsigned char cmd[8];
m_ctrlB0 = 0;
m_ctrlB0 |= (m_rpmR<0)?(1 << 4):0;
m_ctrlB0 |= (m_rpmL<0)?(1 << 5):0;
m_ctrlB0 |= (m_motorRpmW<0)?(1 << 6):0;
uint16_t motorPwmL = abs(constrain(m_rpmL, m_maxRpmT, -m_maxRpmT));
uint16_t motorPwmR = abs(constrain(m_rpmR, m_maxRpmT, -m_maxRpmT));
uint16_t motorPwmW = abs(constrain(m_motorRpmW, m_maxRpmW, -m_maxRpmW));
m_ctrlB1 = 0;
m_ctrlB1 |= 1; //tracktion motor relay
m_ctrlB1 |= (1 << 1); //working motor relay
m_ctrlB1 |= (m_bSpeaker)?(1 << 5):0;//speaker
m_ctrlB1 |= (1 << 6); //external command
m_ctrlB1 |= (1 << 7); //0:pwm, 1:rpm
uint16_t bFilter = 0x00ff;
cmd[0] = m_ctrlB0;
cmd[1] = m_ctrlB1;
cmd[2] = motorPwmL & bFilter;
cmd[3] = (motorPwmL>>8) & bFilter;
cmd[4] = motorPwmR & bFilter;
cmd[5] = (motorPwmR>>8) & bFilter;
cmd[6] = motorPwmW & bFilter;
cmd[7] = (motorPwmW>>8) & bFilter;
m_pCAN->send(addr, 8, cmd);
//status LED
string stateName = *m_pAM->getCurrentStateName();
if(stateName=="HM_WORK")
{
m_pCAN->pinOut(m_pinLEDwork,1);
m_pCAN->pinOut(m_pinLEDrth,0);
m_pCAN->pinOut(m_pinLEDfollow,0);
}
else if(stateName=="HM_RTH")
{
m_pCAN->pinOut(m_pinLEDwork,0);
m_pCAN->pinOut(m_pinLEDrth,1);
m_pCAN->pinOut(m_pinLEDfollow,0);
}
else if(stateName=="HM_FOLLOWME")
{
m_pCAN->pinOut(m_pinLEDwork,0);
m_pCAN->pinOut(m_pinLEDrth,0);
m_pCAN->pinOut(m_pinLEDfollow,1);
}
else if(stateName=="HM_KICKBACK")
{
m_pCAN->pinOut(m_pinLEDwork,1);
m_pCAN->pinOut(m_pinLEDrth,1);
m_pCAN->pinOut(m_pinLEDfollow,1);
}
else
{
m_pCAN->pinOut(m_pinLEDwork,0);
m_pCAN->pinOut(m_pinLEDrth,0);
m_pCAN->pinOut(m_pinLEDfollow,0);
}
//receive
uint8_t* pCanData = m_pCAN->get(m_canAddrStation);
NULL_(pCanData);
//CAN-ID301h 1byte 4bit "AC-input"
//1:ON-Docking/0:OFF-area
IF_(!((pCanData[1] >> 4) & 1));
IF_(stateName == "HM_KICKBACK");
stateName = "HM_STATION";
m_pGPS->reset();
m_pAM->transit(&stateName);
}
bool HM_base::draw(void)
{
IF_F(!this->ActionBase::draw());
Window* pWin = (Window*) this->m_pWindow;
Mat* pMat = pWin->getFrame()->getCMat();
NULL_F(pMat);
IF_F(pMat->empty());
string msg = *this->getName() + ": rpmL=" + i2str(m_rpmL)
+ ", rpmR=" + i2str(m_rpmR);
pWin->addMsg(&msg);
return true;
}
}
<|endoftext|>
|
<commit_before>/****************************************************************************
**
** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation ([email protected])
**
** This file is part of the Qt Mobility Components.
**
** $QT_BEGIN_LICENSE:LGPL$
** No Commercial Usage
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions
** contained in the Technology Preview License Agreement accompanying
** this package.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights. These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** If you have questions regarding the use of this file, please contact
** Nokia at [email protected].
**
**
**
**
**
**
**
**
** $QT_END_LICENSE$
**
****************************************************************************/
//Symbian
#include <e32std.h>
#include <rrsensorapi.h>
// Local
#include "qs60sensorapiaccelerometer.h"
// Constants
const int KAccelerometerSensorUID = 0x10273024;
const char *QS60SensorApiAccelerometer::id("s60sensorapi.accelerometer");
QS60SensorApiAccelerometer::QS60SensorApiAccelerometer(QSensor *sensor)
: QSensorBackend(sensor)
, m_nativeSensor(NULL)
, m_sampleFactor(0.0f)
{
TRAPD(err, findAndCreateNativeSensorL());
if(err != KErrNone) {
sensorStopped();
sensorError(err);
}
setReading<QAccelerometerReading>(&m_reading);
// http://www.st.com/stonline/products/literature/ds/12726/lis302dl.pdf
// That 3D accelerometer inside N95 , N93i or N82 is from STMicroelectronics (type LIS302DL).
// http://wiki.forum.nokia.com/index.php/Nokia_Sensor_APIs.
// Sensor is set to 100Hz 2G mode and no public interface to switch it to 8G
// 2G - mode
addDataRate(100, 100);
addOutputRange(-22.418, 22.418, 0.17651);
setDescription(QLatin1String("lis302dl"));
//Synbian interface gives values between -680 - 680
m_sampleFactor = this->sensor()->outputRanges()[0].maximum / 680.0f;
}
QS60SensorApiAccelerometer::~QS60SensorApiAccelerometer()
{
stop();
delete m_nativeSensor;
m_nativeSensor = NULL;
}
void QS60SensorApiAccelerometer::start()
{
if(!m_nativeSensor)
return;
m_nativeSensor->AddDataListener(this);
}
void QS60SensorApiAccelerometer::stop()
{
if(!m_nativeSensor)
return;
m_nativeSensor->RemoveDataListener();
}
void QS60SensorApiAccelerometer::poll()
{
//empty implementation
}
void QS60SensorApiAccelerometer::HandleDataEventL(TRRSensorInfo aSensor, TRRSensorEvent aEvent)
{
if (aSensor.iSensorId != KAccelerometerSensorUID)
return;
TTime time;
time.UniversalTime();
m_reading.setTimestamp(time.Int64());
m_reading.setX((qreal)aEvent.iSensorData2 * m_sampleFactor);
m_reading.setY((qreal)aEvent.iSensorData1 * -m_sampleFactor);
m_reading.setZ((qreal)aEvent.iSensorData3 * -m_sampleFactor);
newReadingAvailable();
}
void QS60SensorApiAccelerometer::findAndCreateNativeSensorL()
{
if(m_nativeSensor)
return;
RArray<TRRSensorInfo> sensorList;
CRRSensorApi::FindSensorsL(sensorList);
CleanupClosePushL(sensorList);
TInt index = 0;
do {
if (sensorList[index].iSensorId == KAccelerometerSensorUID)
m_nativeSensor = CRRSensorApi::NewL(sensorList[index]);
} while(!m_nativeSensor && ++index < sensorList.Count());
if (!m_nativeSensor)
User::Leave(KErrHardwareNotAvailable);
CleanupStack::PopAndDestroy(&sensorList);
}
<commit_msg>Set the default rate so this doesn't warn.<commit_after>/****************************************************************************
**
** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation ([email protected])
**
** This file is part of the Qt Mobility Components.
**
** $QT_BEGIN_LICENSE:LGPL$
** No Commercial Usage
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions
** contained in the Technology Preview License Agreement accompanying
** this package.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights. These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** If you have questions regarding the use of this file, please contact
** Nokia at [email protected].
**
**
**
**
**
**
**
**
** $QT_END_LICENSE$
**
****************************************************************************/
//Symbian
#include <e32std.h>
#include <rrsensorapi.h>
// Local
#include "qs60sensorapiaccelerometer.h"
// Constants
const int KAccelerometerSensorUID = 0x10273024;
const char *QS60SensorApiAccelerometer::id("s60sensorapi.accelerometer");
QS60SensorApiAccelerometer::QS60SensorApiAccelerometer(QSensor *sensor)
: QSensorBackend(sensor)
, m_nativeSensor(NULL)
, m_sampleFactor(0.0f)
{
TRAPD(err, findAndCreateNativeSensorL());
if(err != KErrNone) {
sensorStopped();
sensorError(err);
}
setReading<QAccelerometerReading>(&m_reading);
// http://www.st.com/stonline/products/literature/ds/12726/lis302dl.pdf
// That 3D accelerometer inside N95 , N93i or N82 is from STMicroelectronics (type LIS302DL).
// http://wiki.forum.nokia.com/index.php/Nokia_Sensor_APIs.
// Sensor is set to 100Hz 2G mode and no public interface to switch it to 8G
// 2G - mode
addDataRate(100, 100);
sensor->setDataRate(100);
addOutputRange(-22.418, 22.418, 0.17651);
setDescription(QLatin1String("lis302dl"));
//Synbian interface gives values between -680 - 680
m_sampleFactor = this->sensor()->outputRanges()[0].maximum / 680.0f;
}
QS60SensorApiAccelerometer::~QS60SensorApiAccelerometer()
{
stop();
delete m_nativeSensor;
m_nativeSensor = NULL;
}
void QS60SensorApiAccelerometer::start()
{
if(!m_nativeSensor)
return;
m_nativeSensor->AddDataListener(this);
}
void QS60SensorApiAccelerometer::stop()
{
if(!m_nativeSensor)
return;
m_nativeSensor->RemoveDataListener();
}
void QS60SensorApiAccelerometer::poll()
{
//empty implementation
}
void QS60SensorApiAccelerometer::HandleDataEventL(TRRSensorInfo aSensor, TRRSensorEvent aEvent)
{
if (aSensor.iSensorId != KAccelerometerSensorUID)
return;
TTime time;
time.UniversalTime();
m_reading.setTimestamp(time.Int64());
m_reading.setX((qreal)aEvent.iSensorData2 * m_sampleFactor);
m_reading.setY((qreal)aEvent.iSensorData1 * -m_sampleFactor);
m_reading.setZ((qreal)aEvent.iSensorData3 * -m_sampleFactor);
newReadingAvailable();
}
void QS60SensorApiAccelerometer::findAndCreateNativeSensorL()
{
if(m_nativeSensor)
return;
RArray<TRRSensorInfo> sensorList;
CRRSensorApi::FindSensorsL(sensorList);
CleanupClosePushL(sensorList);
TInt index = 0;
do {
if (sensorList[index].iSensorId == KAccelerometerSensorUID)
m_nativeSensor = CRRSensorApi::NewL(sensorList[index]);
} while(!m_nativeSensor && ++index < sensorList.Count());
if (!m_nativeSensor)
User::Leave(KErrHardwareNotAvailable);
CleanupStack::PopAndDestroy(&sensorList);
}
<|endoftext|>
|
<commit_before>#include "socket.h"
class Plaintext : public Socket {
public:
Plaintext();
~Plaintext();
unsigned int apiVersion();
void connectServer(std::string server, std::string port, std::string bindAddr = "");
std::string receive(bool* reset);
void sendData(std::string line);
void closeConnection();
};
Plaintext::Plaintext() : Socket() {}
Plaintext::~Plaintext() {
closeConnection();
}
unsigned int Plaintext::apiVersion() {
return 3000;
}
void Plaintext::connectServer(std::string server, std::string port, std::string bindAddr) {
addrinfo* addrInfoList;
addrinfo hints;
hints.ai_family = PF_UNSPEC; // Don't specify either IPv4 or IPv6
hints.ai_socktype = SOCK_STREAM; // IRC uses TCP, which is streaming
hints.ai_protocol = IPPROTO_TCP;
hints.ai_flags = AI_ADDRCONFIG | AI_NUMERICHOST; // AI_ADDRCONFIG doesn't allow IPv4 when the machine doesn't have IPv4, same with IPv6; AI_NUMERICHOST signals a numeric port
int status = getaddrinfo(server.c_str(), port.c_str(), &hints, &addrInfoList);
if (status != 0) {
std::cerr << "An error occurred getting hosts for the server " << server << " on port " << port << "." << std::endl;
return;
}
for (addrinfo* thisAddr = addrInfoList; thisAddr != NULL; thisAddr = thisAddr->ai_next) {
socketfd = socket(thisAddr->ai_family, thisAddr->ai_socktype | SOCK_NONBLOCK, thisAddr->ai_protocol);
if (socketfd == -1)
continue;
if (bindAddr != "") {
status = bind(socketfd, bindAddr.c_str(), bindAddr.size());
if (status == -1) {
close(socketfd);
socketfd = -1;
continue;
}
}
status = connect(socketfd, thisAddr->ai_addr, thisAddr->ai_addrlen);
if (status != 0 && errno != EINPROGRESS) {
close(socketfd);
socketfd = -1;
continue;
}
break; // If we haven't continued out yet, we're connected and the socket is suitable.
}
freeaddrinfo(addrInfoList);
if (socketfd == -1) {
std::cerr << "No suitable host was found for the server " << server << " on port " << port << "." << std::endl;
return;
}
connected = true;
}
std::string Plaintext::receive(bool* reset) {
char inputBuffer[2];
std::string incomingMsg = "";
bool shouldSleep;
int status;
while (true) {
shouldSleep = false;
do {
if (reset)
return "";
if (shouldSleep)
usleep(50000);
status = recv(socketfd, &inputBuffer, 1, 0);
shouldSleep = true;
} while (status < 0 && (errno == EAGAIN || errno == EWOULDBLOCK));
if (status <= 0) {
close(socketfd);
connected = false;
return "";
}
if (inputBuffer[0] == '\r')
continue;
if (inputBuffer[0] == '\n')
break;
incomingMsg += inputBuffer[0];
}
return incomingMsg;
}
void Plaintext::sendData(std::string line) {
line += "\r\n";
int status;
do
status = send(socketfd, line.c_str(), line.size(), 0);
while (status != line.size() && (errno == EAGAIN || errno == EWOULDBLOCK));
}
void Plaintext::closeConnection() {
close(socketfd);
connected = false;
}
SOCKET_SPAWN(Plaintext)<commit_msg>Check the value, not the pointer, duh.<commit_after>#include "socket.h"
class Plaintext : public Socket {
public:
Plaintext();
~Plaintext();
unsigned int apiVersion();
void connectServer(std::string server, std::string port, std::string bindAddr = "");
std::string receive(bool* reset);
void sendData(std::string line);
void closeConnection();
};
Plaintext::Plaintext() : Socket() {}
Plaintext::~Plaintext() {
closeConnection();
}
unsigned int Plaintext::apiVersion() {
return 3000;
}
void Plaintext::connectServer(std::string server, std::string port, std::string bindAddr) {
addrinfo* addrInfoList;
addrinfo hints;
hints.ai_family = PF_UNSPEC; // Don't specify either IPv4 or IPv6
hints.ai_socktype = SOCK_STREAM; // IRC uses TCP, which is streaming
hints.ai_protocol = IPPROTO_TCP;
hints.ai_flags = AI_ADDRCONFIG | AI_NUMERICHOST; // AI_ADDRCONFIG doesn't allow IPv4 when the machine doesn't have IPv4, same with IPv6; AI_NUMERICHOST signals a numeric port
int status = getaddrinfo(server.c_str(), port.c_str(), &hints, &addrInfoList);
if (status != 0) {
std::cerr << "An error occurred getting hosts for the server " << server << " on port " << port << "." << std::endl;
return;
}
for (addrinfo* thisAddr = addrInfoList; thisAddr != NULL; thisAddr = thisAddr->ai_next) {
socketfd = socket(thisAddr->ai_family, thisAddr->ai_socktype | SOCK_NONBLOCK, thisAddr->ai_protocol);
if (socketfd == -1)
continue;
if (bindAddr != "") {
status = bind(socketfd, bindAddr.c_str(), bindAddr.size());
if (status == -1) {
close(socketfd);
socketfd = -1;
continue;
}
}
status = connect(socketfd, thisAddr->ai_addr, thisAddr->ai_addrlen);
if (status != 0 && errno != EINPROGRESS) {
close(socketfd);
socketfd = -1;
continue;
}
break; // If we haven't continued out yet, we're connected and the socket is suitable.
}
freeaddrinfo(addrInfoList);
if (socketfd == -1) {
std::cerr << "No suitable host was found for the server " << server << " on port " << port << "." << std::endl;
return;
}
connected = true;
}
std::string Plaintext::receive(bool* reset) {
char inputBuffer[2];
std::string incomingMsg = "";
bool shouldSleep;
int status;
while (true) {
shouldSleep = false;
do {
if (*reset)
return "";
if (shouldSleep)
usleep(50000);
status = recv(socketfd, &inputBuffer, 1, 0);
shouldSleep = true;
} while (status < 0 && (errno == EAGAIN || errno == EWOULDBLOCK));
if (status <= 0) {
close(socketfd);
connected = false;
return "";
}
if (inputBuffer[0] == '\r')
continue;
if (inputBuffer[0] == '\n')
break;
incomingMsg += inputBuffer[0];
}
return incomingMsg;
}
void Plaintext::sendData(std::string line) {
line += "\r\n";
int status;
do
status = send(socketfd, line.c_str(), line.size(), 0);
while (status != line.size() && (errno == EAGAIN || errno == EWOULDBLOCK));
}
void Plaintext::closeConnection() {
close(socketfd);
connected = false;
}
SOCKET_SPAWN(Plaintext)<|endoftext|>
|
<commit_before>#include <fstream>
#include "GlobalLexicalModel.h"
#include "StaticData.h"
#include "InputFileStream.h"
#include "UserMessage.h"
using namespace std;
namespace Moses
{
GlobalLexicalModel::GlobalLexicalModel(const string &filePath,
const float weight,
const vector< FactorType >& inFactors,
const vector< FactorType >& outFactors)
{
std::cerr << "Creating global lexical model...\n";
// register as score producer
const_cast<ScoreIndexManager&>(StaticData::Instance().GetScoreIndexManager()).AddScoreProducer(this);
std::vector< float > weights;
weights.push_back( weight );
const_cast<StaticData&>(StaticData::Instance()).SetWeightsForScoreProducer(this, weights);
// load model
LoadData( filePath, inFactors, outFactors );
// define bias word
FactorCollection &factorCollection = FactorCollection::Instance();
m_bias = new Word();
const Factor* factor = factorCollection.AddFactor( Input, inFactors[0], "**BIAS**" );
m_bias->SetFactor( inFactors[0], factor );
}
GlobalLexicalModel::~GlobalLexicalModel()
{
// delete words in the hash data structure
DoubleHash::const_iterator iter;
for(iter = m_hash.begin(); iter != m_hash.end(); iter++ ) {
map< const Word*, float, WordComparer >::const_iterator iter2;
for(iter2 = iter->second.begin(); iter2 != iter->second.end(); iter2++ ) {
delete iter2->first; // delete input word
}
delete iter->first; // delete output word
}
// if (m_cache != NULL) delete m_cache;
}
void GlobalLexicalModel::LoadData(const string &filePath,
const vector< FactorType >& inFactors,
const vector< FactorType >& outFactors)
{
FactorCollection &factorCollection = FactorCollection::Instance();
const std::string& factorDelimiter = StaticData::Instance().GetFactorDelimiter();
VERBOSE(2, "Loading global lexical model from file " << filePath << endl);
m_inputFactors = FactorMask(inFactors);
m_outputFactors = FactorMask(outFactors);
InputFileStream inFile(filePath);
// reading in data one line at a time
size_t lineNum = 0;
string line;
while(getline(inFile, line)) {
++lineNum;
vector<string> token = Tokenize<string>(line, " ");
if (token.size() != 3) { // format checking
stringstream errorMessage;
errorMessage << "Syntax error at " << filePath << ":" << lineNum << endl << line << endl;
UserMessage::Add(errorMessage.str());
abort();
}
// create the output word
Word *outWord = new Word();
vector<string> factorString = Tokenize( token[0], factorDelimiter );
for (size_t i=0 ; i < outFactors.size() ; i++) {
const FactorDirection& direction = Output;
const FactorType& factorType = outFactors[i];
const Factor* factor = factorCollection.AddFactor( direction, factorType, factorString[i] );
outWord->SetFactor( factorType, factor );
}
// create the input word
Word *inWord = new Word();
factorString = Tokenize( token[1], factorDelimiter );
for (size_t i=0 ; i < inFactors.size() ; i++) {
const FactorDirection& direction = Input;
const FactorType& factorType = inFactors[i];
const Factor* factor = factorCollection.AddFactor( direction, factorType, factorString[i] );
inWord->SetFactor( factorType, factor );
}
// maximum entropy feature score
float score = Scan<float>(token[2]);
// std::cerr << "storing word " << *outWord << " " << *inWord << " " << score << endl;
// store feature in hash
DoubleHash::iterator keyOutWord = m_hash.find( outWord );
if( keyOutWord == m_hash.end() ) {
m_hash[outWord][inWord] = score;
} else { // already have hash for outword, delete the word to avoid leaks
(keyOutWord->second)[inWord] = score;
delete outWord;
}
}
}
void GlobalLexicalModel::InitializeForInput( Sentence const& in )
{
m_local.reset(new ThreadLocalStorage);
m_local->input = ∈
}
float GlobalLexicalModel::ScorePhrase( const TargetPhrase& targetPhrase ) const
{
const Sentence& input = *(m_local->input);
float score = 0;
for(size_t targetIndex = 0; targetIndex < targetPhrase.GetSize(); targetIndex++ ) {
float sum = 0;
const Word& targetWord = targetPhrase.GetWord( targetIndex );
VERBOSE(2,"glm " << targetWord << ": ");
const DoubleHash::const_iterator targetWordHash = m_hash.find( &targetWord );
if( targetWordHash != m_hash.end() ) {
SingleHash::const_iterator inputWordHash = targetWordHash->second.find( m_bias );
if( inputWordHash != targetWordHash->second.end() ) {
VERBOSE(2,"*BIAS* " << inputWordHash->second);
sum += inputWordHash->second;
}
set< const Word*, WordComparer > alreadyScored; // do not score a word twice
for(size_t inputIndex = 0; inputIndex < input.GetSize(); inputIndex++ ) {
const Word& inputWord = input.GetWord( inputIndex );
if ( alreadyScored.find( &inputWord ) == alreadyScored.end() ) {
SingleHash::const_iterator inputWordHash = targetWordHash->second.find( &inputWord );
if( inputWordHash != targetWordHash->second.end() ) {
VERBOSE(2," " << inputWord << " " << inputWordHash->second);
sum += inputWordHash->second;
}
alreadyScored.insert( &inputWord );
}
}
}
// Hal Daume says: 1/( 1 + exp [ - sum_i w_i * f_i ] )
VERBOSE(2," p=" << FloorScore( log(1/(1+exp(-sum))) ) << endl);
score += FloorScore( log(1/(1+exp(-sum))) );
}
return score;
}
float GlobalLexicalModel::GetFromCacheOrScorePhrase( const TargetPhrase& targetPhrase ) const
{
LexiconCache& m_cache = m_local->cache;
map< const TargetPhrase*, float >::const_iterator query = m_cache.find( &targetPhrase );
if ( query != m_cache.end() ) {
return query->second;
}
float score = ScorePhrase( targetPhrase );
m_cache.insert( pair<const TargetPhrase*, float>(&targetPhrase, score) );
std::cerr << "add to cache " << targetPhrase << ": " << score << endl;
return score;
}
void GlobalLexicalModel::Evaluate(const TargetPhrase& targetPhrase, ScoreComponentCollection* accumulator) const
{
accumulator->PlusEquals( this, GetFromCacheOrScorePhrase( targetPhrase ) );
}
}
<commit_msg>less debug output in GlobalLexicalModel<commit_after>#include <fstream>
#include "GlobalLexicalModel.h"
#include "StaticData.h"
#include "InputFileStream.h"
#include "UserMessage.h"
using namespace std;
namespace Moses
{
GlobalLexicalModel::GlobalLexicalModel(const string &filePath,
const float weight,
const vector< FactorType >& inFactors,
const vector< FactorType >& outFactors)
{
std::cerr << "Creating global lexical model...\n";
// register as score producer
const_cast<ScoreIndexManager&>(StaticData::Instance().GetScoreIndexManager()).AddScoreProducer(this);
std::vector< float > weights;
weights.push_back( weight );
const_cast<StaticData&>(StaticData::Instance()).SetWeightsForScoreProducer(this, weights);
// load model
LoadData( filePath, inFactors, outFactors );
// define bias word
FactorCollection &factorCollection = FactorCollection::Instance();
m_bias = new Word();
const Factor* factor = factorCollection.AddFactor( Input, inFactors[0], "**BIAS**" );
m_bias->SetFactor( inFactors[0], factor );
}
GlobalLexicalModel::~GlobalLexicalModel()
{
// delete words in the hash data structure
DoubleHash::const_iterator iter;
for(iter = m_hash.begin(); iter != m_hash.end(); iter++ ) {
map< const Word*, float, WordComparer >::const_iterator iter2;
for(iter2 = iter->second.begin(); iter2 != iter->second.end(); iter2++ ) {
delete iter2->first; // delete input word
}
delete iter->first; // delete output word
}
// if (m_cache != NULL) delete m_cache;
}
void GlobalLexicalModel::LoadData(const string &filePath,
const vector< FactorType >& inFactors,
const vector< FactorType >& outFactors)
{
FactorCollection &factorCollection = FactorCollection::Instance();
const std::string& factorDelimiter = StaticData::Instance().GetFactorDelimiter();
VERBOSE(2, "Loading global lexical model from file " << filePath << endl);
m_inputFactors = FactorMask(inFactors);
m_outputFactors = FactorMask(outFactors);
InputFileStream inFile(filePath);
// reading in data one line at a time
size_t lineNum = 0;
string line;
while(getline(inFile, line)) {
++lineNum;
vector<string> token = Tokenize<string>(line, " ");
if (token.size() != 3) { // format checking
stringstream errorMessage;
errorMessage << "Syntax error at " << filePath << ":" << lineNum << endl << line << endl;
UserMessage::Add(errorMessage.str());
abort();
}
// create the output word
Word *outWord = new Word();
vector<string> factorString = Tokenize( token[0], factorDelimiter );
for (size_t i=0 ; i < outFactors.size() ; i++) {
const FactorDirection& direction = Output;
const FactorType& factorType = outFactors[i];
const Factor* factor = factorCollection.AddFactor( direction, factorType, factorString[i] );
outWord->SetFactor( factorType, factor );
}
// create the input word
Word *inWord = new Word();
factorString = Tokenize( token[1], factorDelimiter );
for (size_t i=0 ; i < inFactors.size() ; i++) {
const FactorDirection& direction = Input;
const FactorType& factorType = inFactors[i];
const Factor* factor = factorCollection.AddFactor( direction, factorType, factorString[i] );
inWord->SetFactor( factorType, factor );
}
// maximum entropy feature score
float score = Scan<float>(token[2]);
// std::cerr << "storing word " << *outWord << " " << *inWord << " " << score << endl;
// store feature in hash
DoubleHash::iterator keyOutWord = m_hash.find( outWord );
if( keyOutWord == m_hash.end() ) {
m_hash[outWord][inWord] = score;
} else { // already have hash for outword, delete the word to avoid leaks
(keyOutWord->second)[inWord] = score;
delete outWord;
}
}
}
void GlobalLexicalModel::InitializeForInput( Sentence const& in )
{
m_local.reset(new ThreadLocalStorage);
m_local->input = ∈
}
float GlobalLexicalModel::ScorePhrase( const TargetPhrase& targetPhrase ) const
{
const Sentence& input = *(m_local->input);
float score = 0;
for(size_t targetIndex = 0; targetIndex < targetPhrase.GetSize(); targetIndex++ ) {
float sum = 0;
const Word& targetWord = targetPhrase.GetWord( targetIndex );
VERBOSE(2,"glm " << targetWord << ": ");
const DoubleHash::const_iterator targetWordHash = m_hash.find( &targetWord );
if( targetWordHash != m_hash.end() ) {
SingleHash::const_iterator inputWordHash = targetWordHash->second.find( m_bias );
if( inputWordHash != targetWordHash->second.end() ) {
VERBOSE(2,"*BIAS* " << inputWordHash->second);
sum += inputWordHash->second;
}
set< const Word*, WordComparer > alreadyScored; // do not score a word twice
for(size_t inputIndex = 0; inputIndex < input.GetSize(); inputIndex++ ) {
const Word& inputWord = input.GetWord( inputIndex );
if ( alreadyScored.find( &inputWord ) == alreadyScored.end() ) {
SingleHash::const_iterator inputWordHash = targetWordHash->second.find( &inputWord );
if( inputWordHash != targetWordHash->second.end() ) {
VERBOSE(2," " << inputWord << " " << inputWordHash->second);
sum += inputWordHash->second;
}
alreadyScored.insert( &inputWord );
}
}
}
// Hal Daume says: 1/( 1 + exp [ - sum_i w_i * f_i ] )
VERBOSE(2," p=" << FloorScore( log(1/(1+exp(-sum))) ) << endl);
score += FloorScore( log(1/(1+exp(-sum))) );
}
return score;
}
float GlobalLexicalModel::GetFromCacheOrScorePhrase( const TargetPhrase& targetPhrase ) const
{
LexiconCache& m_cache = m_local->cache;
map< const TargetPhrase*, float >::const_iterator query = m_cache.find( &targetPhrase );
if ( query != m_cache.end() ) {
return query->second;
}
float score = ScorePhrase( targetPhrase );
m_cache.insert( pair<const TargetPhrase*, float>(&targetPhrase, score) );
//VERBOSE(2, "add to cache " << targetPhrase << ": " << score << endl);
return score;
}
void GlobalLexicalModel::Evaluate(const TargetPhrase& targetPhrase, ScoreComponentCollection* accumulator) const
{
accumulator->PlusEquals( this, GetFromCacheOrScorePhrase( targetPhrase ) );
}
}
<|endoftext|>
|
<commit_before>/*
This file is part of Android File Transfer For Linux.
Copyright (C) 2015 Vladimir Menshakov
Android File Transfer For Linux is free software: you can redistribute
it and/or modify it under the terms of the GNU General Public License
as published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
Android File Transfer For Linux 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 Android File Transfer For Linux.
If not, see <http://www.gnu.org/licenses/>.
*/
#include <usb/Device.h>
#include <usb/Exception.h>
#include <mtp/usb/TimeoutException.h>
#include <mtp/usb/DeviceBusyException.h>
#include <mtp/usb/DeviceNotFoundException.h>
#include <mtp/ByteArray.h>
#include <unistd.h>
#include <sys/ioctl.h>
#include <poll.h>
#include <sys/time.h>
#include "linux/usbdevice_fs.h"
#define IOCTL(...) do \
{ \
int r = ioctl(__VA_ARGS__); \
if (r < 0) \
{ \
if (errno == EBUSY) \
throw DeviceBusyException(); \
else if (errno == ENODEV) \
throw DeviceNotFoundException(); \
else \
throw Exception("ioctl(" #__VA_ARGS__ ")"); \
} \
} while(false)
namespace mtp { namespace usb
{
FileHandler::~FileHandler()
{ close(_fd); }
InterfaceToken::InterfaceToken(int fd, unsigned interfaceNumber): _fd(fd), _interfaceNumber(interfaceNumber)
{
IOCTL(_fd, USBDEVFS_CLAIMINTERFACE, &interfaceNumber);
}
InterfaceToken::~InterfaceToken()
{
ioctl(_fd, USBDEVFS_RELEASEINTERFACE, &_interfaceNumber);
}
#define PRINT_CAP(CAP, NAME) \
if (capabilities & (CAP)) \
{ \
printf(NAME " "); \
capabilities &= ~(CAP); \
}
Device::Device(int fd, const EndpointPtr &controlEp): _fd(fd), _capabilities(0), _controlEp(controlEp)
{
try { IOCTL(_fd.Get(), USBDEVFS_GET_CAPABILITIES, &_capabilities); }
catch(const std::exception &ex)
{ fprintf(stderr, "get usbfs capabilities failed: %s\n", ex.what()); }
printf("capabilities = 0x%02x: ", (unsigned)_capabilities);
if (_capabilities)
{
u32 capabilities = _capabilities;
PRINT_CAP(USBDEVFS_CAP_ZERO_PACKET, "<zero>");
PRINT_CAP(USBDEVFS_CAP_BULK_CONTINUATION, "<bulk-continuation>");
PRINT_CAP(USBDEVFS_CAP_NO_PACKET_SIZE_LIM, "<no-packet-size-limit>");
PRINT_CAP(USBDEVFS_CAP_BULK_SCATTER_GATHER, "<bulk-scatter-gather>");
PRINT_CAP(USBDEVFS_CAP_REAP_AFTER_DISCONNECT, "<reap-after-disconnect>");
if (capabilities)
printf("<unknown capability 0x%02x>", capabilities);
printf("\n");
}
else
printf("[none]\n");
}
Device::~Device()
{ }
int Device::GetConfiguration() const
{
return 0;
}
void Device::SetConfiguration(int idx)
{
fprintf(stderr, "SetConfiguration(%d): not implemented", idx);
}
struct Device::Urb : Noncopyable
{
int Fd;
ByteArray Buffer;
usbdevfs_urb KernelUrb;
static size_t PacketsPerBuffer(u8 type)
#if 0
//this will cause sudden freezes, almost every input transfer freezes on 4.3
{ return type == USBDEVFS_URB_TYPE_BULK? 2048: 1; }
#else
{ return 1; }
#endif
Urb(int fd, u8 type, const EndpointPtr & ep): Fd(fd), Buffer(PacketsPerBuffer(type) * ep->GetMaxPacketSize()), KernelUrb()
{
KernelUrb.type = type;
KernelUrb.endpoint = ep->GetAddress();
KernelUrb.buffer = Buffer.data();
KernelUrb.buffer_length = Buffer.size();
}
size_t GetTransferSize() const
{ return Buffer.size(); }
void Submit()
{
IOCTL(Fd, USBDEVFS_SUBMITURB, &KernelUrb);
}
void Discard()
{
int r = ioctl(Fd, USBDEVFS_DISCARDURB, &KernelUrb);
if (r != 0)
{
perror("ioctl(USBDEVFS_DISCARDURB)");
}
}
size_t Send(const IObjectInputStreamPtr &inputStream)
{
size_t r = inputStream->Read(Buffer.data(), Buffer.size());
//HexDump("write", ByteArray(Buffer.data(), Buffer.data() + r));
KernelUrb.buffer_length = r;
return r;
}
size_t Send(const ByteArray &inputData)
{
size_t r = std::min(Buffer.size(), inputData.size());
std::copy(inputData.data(), inputData.data() + r, Buffer.data());
KernelUrb.buffer_length = r;
return r;
}
size_t Recv(const IObjectOutputStreamPtr &outputStream)
{
//HexDump("read", ByteArray(Buffer.data(), Buffer.data() + KernelUrb.actual_length));
return outputStream->Write(Buffer.data(), KernelUrb.actual_length);
}
ByteArray Recv()
{ return ByteArray(Buffer.begin(), Buffer.begin() + KernelUrb.actual_length); }
template<unsigned Flag>
void SetFlag(bool value)
{
if (value)
KernelUrb.flags |= Flag;
else
KernelUrb.flags &= ~Flag;
}
void SetContinuationFlag(bool continuation)
{ SetFlag<USBDEVFS_URB_BULK_CONTINUATION>(continuation); }
void SetZeroPacketFlag(bool zero)
{ SetFlag<USBDEVFS_URB_ZERO_PACKET>(zero); }
};
void * Device::Reap(int timeout)
{
timeval started = {};
if (gettimeofday(&started, NULL) == -1)
throw usb::Exception("gettimeofday");
pollfd fd = {};
fd.fd = _fd.Get();
fd.events = POLLOUT;
int r = poll(&fd, 1, timeout);
timeval now = {};
if (gettimeofday(&now, NULL) == -1)
throw usb::Exception("gettimeofday");
if (r < 0)
throw Exception("poll");
if (r == 0 && timeout > 0)
{
int ms = (now.tv_sec - started.tv_sec) * 1000 + (now.tv_usec - started.tv_usec) / 1000;
fprintf(stderr, "%d ms since the last poll call\n", ms);
}
usbdevfs_urb *urb;
r = ioctl(_fd.Get(), USBDEVFS_REAPURBNDELAY, &urb);
if (r == 0)
return urb;
else if (errno == EAGAIN)
throw TimeoutException("timeout reaping usb urb");
else
throw Exception("ioctl");
}
void Device::ClearHalt(const EndpointPtr & ep)
{
try
{ unsigned index = ep->GetAddress(); IOCTL(_fd.Get(), USBDEVFS_CLEAR_HALT, &index); }
catch(const std::exception &ex)
{ fprintf(stderr, "clearing halt status for ep %02x: %s\n", (unsigned)ep->GetAddress(), ex.what()); }
}
void Device::Submit(const UrbPtr &urb, int timeout)
{
urb->Submit();
{
scoped_mutex_lock l(_mutex);
_urbs.insert(std::make_pair(&urb->KernelUrb, urb));
}
try
{
while(true)
{
UrbPtr completedUrb;
{
void *completedKernelUrb = Reap(timeout);
scoped_mutex_lock l(_mutex);
auto urbIt = _urbs.find(completedKernelUrb);
if (urbIt == _urbs.end())
{
fprintf(stderr, "got unknown urb: %p\n", completedKernelUrb);
continue;
}
completedUrb = urbIt->second;
_urbs.erase(urbIt);
}
if (completedUrb == urb)
break;
}
}
catch(const TimeoutException &ex)
{
urb->Discard();
throw;
}
catch(const std::exception &ex)
{
fprintf(stderr, "error while submitting urb: %s\n", ex.what());
urb->Discard();
throw;
}
}
void Device::WriteBulk(const EndpointPtr & ep, const IObjectInputStreamPtr &inputStream, int timeout)
{
UrbPtr urb = std::make_shared<Urb>(_fd.Get(), USBDEVFS_URB_TYPE_BULK, ep);
size_t transferSize = urb->GetTransferSize();
size_t r;
bool continuation = false;
do
{
r = urb->Send(inputStream);
urb->SetZeroPacketFlag(r != transferSize);
urb->SetContinuationFlag(continuation);
continuation = true;
Submit(urb, timeout);
ProcessControl();
}
while(r == transferSize);
}
void Device::ReadBulk(const EndpointPtr & ep, const IObjectOutputStreamPtr &outputStream, int timeout)
{
UrbPtr urb = std::make_shared<Urb>(_fd.Get(), USBDEVFS_URB_TYPE_BULK, ep);
size_t transferSize = urb->GetTransferSize();
size_t r;
bool continuation = false;
do
{
urb->SetContinuationFlag(continuation);
continuation = true;
Submit(urb, timeout);
ProcessControl();
r = urb->Recv(outputStream);
}
while(r == transferSize);
}
u8 Device::TransactionType(const EndpointPtr &ep)
{
EndpointType type = ep->GetType();
switch(type)
{
case EndpointType::Control:
return USBDEVFS_URB_TYPE_CONTROL;
case EndpointType::Isochronous:
return USBDEVFS_URB_TYPE_ISO;
case EndpointType::Bulk:
return USBDEVFS_URB_TYPE_BULK;
case EndpointType::Interrupt:
return USBDEVFS_URB_TYPE_INTERRUPT;
default:
throw std::runtime_error("invalid endpoint type");
}
}
void Device::ReadControl(u8 type, u8 req, u16 value, u16 index, ByteArray &data, int timeout)
{
printf("read control %02x %02x %04x %04x\n", type, req, value, index);
usbdevfs_ctrltransfer ctrl = { };
ctrl.bRequestType = type;
ctrl.bRequest = req;
ctrl.wValue = value;
ctrl.wIndex = index;
ctrl.wLength = data.size();
ctrl.data = const_cast<u8 *>(data.data());
ctrl.timeout = timeout;
int fd = _fd.Get();
int r = ioctl(fd, USBDEVFS_CONTROL, &ctrl);
if (r >= 0)
data.resize(r);
else if (errno == EAGAIN)
throw TimeoutException("timeout sending control transfer");
else
throw Exception("ioctl");
}
void Device::WriteControl(u8 type, u8 req, u16 value, u16 index, const ByteArray &data, bool interruptCurrentTransaction, int timeout)
{
printf("write control %02x %02x %04x %04x\n", type, req, value, index);
usbdevfs_ctrltransfer ctrl = { };
ctrl.bRequestType = type;
ctrl.bRequest = req;
ctrl.wValue = value;
ctrl.wIndex = index;
ctrl.wLength = data.size();
ctrl.data = const_cast<u8 *>(data.data());
ctrl.timeout = timeout;
int fd = _fd.Get();
_controls.push(
[fd, ctrl, interruptCurrentTransaction]()
{
int r = ioctl(fd, USBDEVFS_CONTROL, &ctrl);
if (r >= 0)
{
if (interruptCurrentTransaction)
throw std::runtime_error("transaction aborted");
else
return;
}
else if (errno == EAGAIN)
throw TimeoutException("timeout sending control transfer");
else
throw Exception("ioctl");
});
}
void Device::ProcessControl()
{
scoped_mutex_lock l(_mutex);
while(!_controls.empty())
{
try { _controls.front()(); } catch(const std::exception &ex) { _controls.pop(); throw; }
_controls.pop();
}
}
}}
<commit_msg>removed any large buffers, use single page, scatter gathering seems to be broken in kernel for ages<commit_after>/*
This file is part of Android File Transfer For Linux.
Copyright (C) 2015 Vladimir Menshakov
Android File Transfer For Linux is free software: you can redistribute
it and/or modify it under the terms of the GNU General Public License
as published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
Android File Transfer For Linux 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 Android File Transfer For Linux.
If not, see <http://www.gnu.org/licenses/>.
*/
#include <usb/Device.h>
#include <usb/Exception.h>
#include <mtp/usb/TimeoutException.h>
#include <mtp/usb/DeviceBusyException.h>
#include <mtp/usb/DeviceNotFoundException.h>
#include <mtp/ByteArray.h>
#include <unistd.h>
#include <sys/ioctl.h>
#include <poll.h>
#include <sys/time.h>
#include "linux/usbdevice_fs.h"
#define IOCTL(...) do \
{ \
int r = ioctl(__VA_ARGS__); \
if (r < 0) \
{ \
if (errno == EBUSY) \
throw DeviceBusyException(); \
else if (errno == ENODEV) \
throw DeviceNotFoundException(); \
else \
throw Exception("ioctl(" #__VA_ARGS__ ")"); \
} \
} while(false)
namespace mtp { namespace usb
{
FileHandler::~FileHandler()
{ close(_fd); }
InterfaceToken::InterfaceToken(int fd, unsigned interfaceNumber): _fd(fd), _interfaceNumber(interfaceNumber)
{
IOCTL(_fd, USBDEVFS_CLAIMINTERFACE, &interfaceNumber);
}
InterfaceToken::~InterfaceToken()
{
ioctl(_fd, USBDEVFS_RELEASEINTERFACE, &_interfaceNumber);
}
#define PRINT_CAP(CAP, NAME) \
if (capabilities & (CAP)) \
{ \
printf(NAME " "); \
capabilities &= ~(CAP); \
}
Device::Device(int fd, const EndpointPtr &controlEp): _fd(fd), _capabilities(0), _controlEp(controlEp)
{
try { IOCTL(_fd.Get(), USBDEVFS_GET_CAPABILITIES, &_capabilities); }
catch(const std::exception &ex)
{ fprintf(stderr, "get usbfs capabilities failed: %s\n", ex.what()); }
printf("capabilities = 0x%02x: ", (unsigned)_capabilities);
if (_capabilities)
{
u32 capabilities = _capabilities;
PRINT_CAP(USBDEVFS_CAP_ZERO_PACKET, "<zero>");
PRINT_CAP(USBDEVFS_CAP_BULK_CONTINUATION, "<bulk-continuation>");
PRINT_CAP(USBDEVFS_CAP_NO_PACKET_SIZE_LIM, "<no-packet-size-limit>");
PRINT_CAP(USBDEVFS_CAP_BULK_SCATTER_GATHER, "<bulk-scatter-gather>");
PRINT_CAP(USBDEVFS_CAP_REAP_AFTER_DISCONNECT, "<reap-after-disconnect>");
if (capabilities)
printf("<unknown capability 0x%02x>", capabilities);
printf("\n");
}
else
printf("[none]\n");
}
Device::~Device()
{ }
int Device::GetConfiguration() const
{
return 0;
}
void Device::SetConfiguration(int idx)
{
fprintf(stderr, "SetConfiguration(%d): not implemented", idx);
}
struct Device::Urb : Noncopyable
{
int Fd;
ByteArray Buffer;
usbdevfs_urb KernelUrb;
Urb(int fd, u8 type, const EndpointPtr & ep): Fd(fd), Buffer(4096), KernelUrb()
{
KernelUrb.type = type;
KernelUrb.endpoint = ep->GetAddress();
KernelUrb.buffer = Buffer.data();
KernelUrb.buffer_length = Buffer.size();
}
size_t GetTransferSize() const
{ return Buffer.size(); }
void Submit()
{
IOCTL(Fd, USBDEVFS_SUBMITURB, &KernelUrb);
}
void Discard()
{
int r = ioctl(Fd, USBDEVFS_DISCARDURB, &KernelUrb);
if (r != 0)
{
perror("ioctl(USBDEVFS_DISCARDURB)");
}
}
size_t Send(const IObjectInputStreamPtr &inputStream)
{
size_t r = inputStream->Read(Buffer.data(), Buffer.size());
//HexDump("write", ByteArray(Buffer.data(), Buffer.data() + r));
KernelUrb.buffer_length = r;
return r;
}
size_t Send(const ByteArray &inputData)
{
size_t r = std::min(Buffer.size(), inputData.size());
std::copy(inputData.data(), inputData.data() + r, Buffer.data());
KernelUrb.buffer_length = r;
return r;
}
size_t Recv(const IObjectOutputStreamPtr &outputStream)
{
//HexDump("read", ByteArray(Buffer.data(), Buffer.data() + KernelUrb.actual_length));
return outputStream->Write(Buffer.data(), KernelUrb.actual_length);
}
ByteArray Recv()
{ return ByteArray(Buffer.begin(), Buffer.begin() + KernelUrb.actual_length); }
template<unsigned Flag>
void SetFlag(bool value)
{
if (value)
KernelUrb.flags |= Flag;
else
KernelUrb.flags &= ~Flag;
}
void SetContinuationFlag(bool continuation)
{ SetFlag<USBDEVFS_URB_BULK_CONTINUATION>(continuation); }
void SetZeroPacketFlag(bool zero)
{ SetFlag<USBDEVFS_URB_ZERO_PACKET>(zero); }
};
void * Device::Reap(int timeout)
{
timeval started = {};
if (gettimeofday(&started, NULL) == -1)
throw usb::Exception("gettimeofday");
pollfd fd = {};
fd.fd = _fd.Get();
fd.events = POLLOUT;
int r = poll(&fd, 1, timeout);
timeval now = {};
if (gettimeofday(&now, NULL) == -1)
throw usb::Exception("gettimeofday");
if (r < 0)
throw Exception("poll");
if (r == 0 && timeout > 0)
{
int ms = (now.tv_sec - started.tv_sec) * 1000 + (now.tv_usec - started.tv_usec) / 1000;
fprintf(stderr, "%d ms since the last poll call\n", ms);
}
usbdevfs_urb *urb;
r = ioctl(_fd.Get(), USBDEVFS_REAPURBNDELAY, &urb);
if (r == 0)
return urb;
else if (errno == EAGAIN)
throw TimeoutException("timeout reaping usb urb");
else
throw Exception("ioctl");
}
void Device::ClearHalt(const EndpointPtr & ep)
{
try
{ unsigned index = ep->GetAddress(); IOCTL(_fd.Get(), USBDEVFS_CLEAR_HALT, &index); }
catch(const std::exception &ex)
{ fprintf(stderr, "clearing halt status for ep %02x: %s\n", (unsigned)ep->GetAddress(), ex.what()); }
}
void Device::Submit(const UrbPtr &urb, int timeout)
{
urb->Submit();
{
scoped_mutex_lock l(_mutex);
_urbs.insert(std::make_pair(&urb->KernelUrb, urb));
}
try
{
while(true)
{
UrbPtr completedUrb;
{
void *completedKernelUrb = Reap(timeout);
scoped_mutex_lock l(_mutex);
auto urbIt = _urbs.find(completedKernelUrb);
if (urbIt == _urbs.end())
{
fprintf(stderr, "got unknown urb: %p\n", completedKernelUrb);
continue;
}
completedUrb = urbIt->second;
_urbs.erase(urbIt);
}
if (completedUrb == urb)
break;
}
}
catch(const TimeoutException &ex)
{
urb->Discard();
throw;
}
catch(const std::exception &ex)
{
fprintf(stderr, "error while submitting urb: %s\n", ex.what());
urb->Discard();
throw;
}
}
void Device::WriteBulk(const EndpointPtr & ep, const IObjectInputStreamPtr &inputStream, int timeout)
{
UrbPtr urb = std::make_shared<Urb>(_fd.Get(), USBDEVFS_URB_TYPE_BULK, ep);
size_t transferSize = urb->GetTransferSize();
size_t r;
bool continuation = false;
do
{
r = urb->Send(inputStream);
urb->SetZeroPacketFlag(r != transferSize);
urb->SetContinuationFlag(continuation);
continuation = true;
Submit(urb, timeout);
ProcessControl();
}
while(r == transferSize);
}
void Device::ReadBulk(const EndpointPtr & ep, const IObjectOutputStreamPtr &outputStream, int timeout)
{
UrbPtr urb = std::make_shared<Urb>(_fd.Get(), USBDEVFS_URB_TYPE_BULK, ep);
size_t transferSize = urb->GetTransferSize();
size_t r;
bool continuation = false;
do
{
urb->SetContinuationFlag(continuation);
continuation = true;
Submit(urb, timeout);
ProcessControl();
r = urb->Recv(outputStream);
}
while(r == transferSize);
}
u8 Device::TransactionType(const EndpointPtr &ep)
{
EndpointType type = ep->GetType();
switch(type)
{
case EndpointType::Control:
return USBDEVFS_URB_TYPE_CONTROL;
case EndpointType::Isochronous:
return USBDEVFS_URB_TYPE_ISO;
case EndpointType::Bulk:
return USBDEVFS_URB_TYPE_BULK;
case EndpointType::Interrupt:
return USBDEVFS_URB_TYPE_INTERRUPT;
default:
throw std::runtime_error("invalid endpoint type");
}
}
void Device::ReadControl(u8 type, u8 req, u16 value, u16 index, ByteArray &data, int timeout)
{
printf("read control %02x %02x %04x %04x\n", type, req, value, index);
usbdevfs_ctrltransfer ctrl = { };
ctrl.bRequestType = type;
ctrl.bRequest = req;
ctrl.wValue = value;
ctrl.wIndex = index;
ctrl.wLength = data.size();
ctrl.data = const_cast<u8 *>(data.data());
ctrl.timeout = timeout;
int fd = _fd.Get();
int r = ioctl(fd, USBDEVFS_CONTROL, &ctrl);
if (r >= 0)
data.resize(r);
else if (errno == EAGAIN)
throw TimeoutException("timeout sending control transfer");
else
throw Exception("ioctl");
}
void Device::WriteControl(u8 type, u8 req, u16 value, u16 index, const ByteArray &data, bool interruptCurrentTransaction, int timeout)
{
printf("write control %02x %02x %04x %04x\n", type, req, value, index);
usbdevfs_ctrltransfer ctrl = { };
ctrl.bRequestType = type;
ctrl.bRequest = req;
ctrl.wValue = value;
ctrl.wIndex = index;
ctrl.wLength = data.size();
ctrl.data = const_cast<u8 *>(data.data());
ctrl.timeout = timeout;
int fd = _fd.Get();
_controls.push(
[fd, ctrl, interruptCurrentTransaction]()
{
int r = ioctl(fd, USBDEVFS_CONTROL, &ctrl);
if (r >= 0)
{
if (interruptCurrentTransaction)
throw std::runtime_error("transaction aborted");
else
return;
}
else if (errno == EAGAIN)
throw TimeoutException("timeout sending control transfer");
else
throw Exception("ioctl");
});
}
void Device::ProcessControl()
{
scoped_mutex_lock l(_mutex);
while(!_controls.empty())
{
try { _controls.front()(); } catch(const std::exception &ex) { _controls.pop(); throw; }
_controls.pop();
}
}
}}
<|endoftext|>
|
<commit_before>/**
* Chimera - a tool to convert c++ headers into Boost.Python bindings.
*/
#include "chimera/configuration.h"
#include "chimera/frontend_action.h"
#include <clang/Tooling/CommonOptionsParser.h>
#include <clang/Tooling/Tooling.h>
#include <llvm/Support/CommandLine.h>
#include <memory>
#include <string>
using namespace clang;
using namespace clang::tooling;
using namespace llvm;
// Apply a custom category to all command-line options so that they are the
// only ones displayed.
static cl::OptionCategory ChimeraCategory("Chimera options");
// Option for specifying output binding filename.
static cl::opt<std::string> OutputPath(
"o", cl::cat(ChimeraCategory),
cl::desc("Specify output C++ binding directory"),
cl::value_desc("directory"));
// Option for specifying YAML configuration filename.
static cl::opt<std::string> ConfigFilename(
"c", cl::cat(ChimeraCategory),
cl::desc("Specify YAML configuration filename"),
cl::value_desc("filename"));
// CommonOptionsParser declares HelpMessage with a description of the common
// command-line options related to the compilation database and input files.
// It's nice to have this help message in all tools.
static cl::extrahelp CommonHelp(CommonOptionsParser::HelpMessage);
// Add a footer to the help text.
static cl::extrahelp MoreHelp(
"\n"
"Chimera is a tool to convert C++ headers into Boost.Python bindings.\n"
"\n"
);
int main(int argc, const char **argv)
{
// Create parser that handles clang options.
CommonOptionsParser OptionsParser(argc, argv, ChimeraCategory);
// Parse the YAML configuration file if it exists, otherwise initialize it
// to an empty node.
if (!ConfigFilename.empty())
chimera::Configuration::GetInstance().LoadFile(ConfigFilename);
// If an output path was specified, initialize configuration to use it.
if (!OutputPath.empty())
chimera::Configuration::GetInstance().SetOutputPath(OutputPath);
// Create tool that uses the command-line options.
ClangTool Tool(OptionsParser.getCompilations(),
OptionsParser.getSourcePathList());
// Run the instantiated tool on the Chimera frontend.
return Tool.run(newFrontendActionFactory<chimera::FrontendAction>().get());
}
<commit_msg>Removed extraneous help messages.<commit_after>/**
* Chimera - a tool to convert c++ headers into Boost.Python bindings.
*/
#include "chimera/configuration.h"
#include "chimera/frontend_action.h"
#include <clang/Tooling/CommonOptionsParser.h>
#include <clang/Tooling/Tooling.h>
#include <llvm/Support/CommandLine.h>
#include <memory>
#include <string>
using namespace clang;
using namespace clang::tooling;
using namespace llvm;
// Apply a custom category to all command-line options so that they are the
// only ones displayed.
static cl::OptionCategory ChimeraCategory("Chimera options");
// Option for specifying output binding filename.
static cl::opt<std::string> OutputPath(
"o", cl::cat(ChimeraCategory),
cl::desc("Specify output C++ binding directory"),
cl::value_desc("directory"));
// Option for specifying YAML configuration filename.
static cl::opt<std::string> ConfigFilename(
"c", cl::cat(ChimeraCategory),
cl::desc("Specify YAML configuration filename"),
cl::value_desc("filename"));
// Add a footer to the help text.
static cl::extrahelp MoreHelp(
"\n"
"Chimera is a tool to convert C++ headers into Boost.Python bindings.\n"
"\n"
);
int main(int argc, const char **argv)
{
// Create parser that handles clang options.
CommonOptionsParser OptionsParser(argc, argv, ChimeraCategory);
// Parse the YAML configuration file if it exists, otherwise initialize it
// to an empty node.
if (!ConfigFilename.empty())
chimera::Configuration::GetInstance().LoadFile(ConfigFilename);
// If an output path was specified, initialize configuration to use it.
if (!OutputPath.empty())
chimera::Configuration::GetInstance().SetOutputPath(OutputPath);
// Create tool that uses the command-line options.
ClangTool Tool(OptionsParser.getCompilations(),
OptionsParser.getSourcePathList());
// Run the instantiated tool on the Chimera frontend.
return Tool.run(newFrontendActionFactory<chimera::FrontendAction>().get());
}
<|endoftext|>
|
<commit_before>/** \copyright
* Copyright (c) 2013, Balazs Racz
* 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.
*
* 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.
*
* \file AsyncIfImpl.cxx
*
* Implementation details for the asynchronous NMRAnet interfaces. This file
* should only be needed in hardware interface implementations.
*
* @author Balazs Racz
* @date 4 Dec 2013
*/
#include "nmranet/AsyncIfImpl.hxx"
namespace NMRAnet
{
StateFlowBase::Action WriteFlowBase::addressed_entry()
{
if (nmsg()->dst.id)
{
nmsg()->dstNode = async_if()->lookup_local_node(nmsg()->dst.id);
if (nmsg()->dstNode)
{
async_if()->dispatcher()->send(transfer_message(), priority());
return call_immediately(STATE(send_finished));
}
}
return send_to_hardware();
}
StateFlowBase::Action WriteFlowBase::global_entry()
{
async_if()->dispatcher()->send(transfer_message());
return release_and_exit();
}
} // namespace NMRAnet
<commit_msg>Makes loopback global packets ignore the done callback, because it causes deadlock in the event handler concept.<commit_after>/** \copyright
* Copyright (c) 2013, Balazs Racz
* 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.
*
* 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.
*
* \file AsyncIfImpl.cxx
*
* Implementation details for the asynchronous NMRAnet interfaces. This file
* should only be needed in hardware interface implementations.
*
* @author Balazs Racz
* @date 4 Dec 2013
*/
#include "nmranet/AsyncIfImpl.hxx"
namespace NMRAnet
{
StateFlowBase::Action WriteFlowBase::addressed_entry()
{
if (nmsg()->dst.id)
{
nmsg()->dstNode = async_if()->lookup_local_node(nmsg()->dst.id);
if (nmsg()->dstNode)
{
async_if()->dispatcher()->send(transfer_message(), priority());
return call_immediately(STATE(send_finished));
}
}
return send_to_hardware();
}
StateFlowBase::Action WriteFlowBase::global_entry()
{
// We do not pass on the done notifiable with the loopbacked message.
BarrierNotifiable* d = message()->new_child();
if (d) {
// This is abuse of the barriernotifiable code, because we assume that
// notifying the child twice will cause the parent to be notified once.
d->notify();
d->notify();
message()->set_done(nullptr);
}
async_if()->dispatcher()->send(transfer_message());
return release_and_exit();
}
} // namespace NMRAnet
<|endoftext|>
|
<commit_before>#include <packets/Packet.h>
#include "packets/server/BlockHelloPacket.h"
#include "Poco/Crypto/RSAKey.h"
#include "Poco/Crypto/Cipher.h"
#include "Poco/Crypto/CipherKey.h"
#include "Poco/Crypto/CipherFactory.h"
#include <string.h>
#include <packets/server/SystemMessagePacket.h>
#include <packets/FixedLengthPacket.h>
#include <fstream>
#include <ctime>
#include "PolarisConnection.h"
#include "PolarisClient.h"
#include "Poco/Util/Application.h"
#include "Poco/File.h"
#include "Poco/FileStream.h"
#include "RandomHelper.h"
PolarisConnection::PolarisConnection(const StreamSocket& socket, SocketReactor& reactor):
socket(socket),
reactor(reactor),
bufferPtr(new uint8_t[BUFFER_SIZE]),
bufferPosition(0),
outputTransform(0), inputTransform(0)
{
this->client = new PolarisClient(this);
reactor.addEventHandler(socket, NObserver<PolarisConnection, ReadableNotification>(*this, &PolarisConnection::onReadable));
reactor.addEventHandler(socket, NObserver<PolarisConnection, ShutdownNotification>(*this, &PolarisConnection::onShutdown));
Poco::Util::Application::instance().logger().information("New client connected, saying hello!");
BlockHelloPacket hello(201); // TODO Dynamic block pls
PacketData helloData = hello.build();
sendPacket(helloData);
}
PolarisConnection::~PolarisConnection() {
delete this->client;
delete[] this->bufferPtr;
reactor.removeEventHandler(socket, NObserver<PolarisConnection, ReadableNotification>(*this, &PolarisConnection::onReadable));
reactor.removeEventHandler(socket, NObserver<PolarisConnection, ShutdownNotification>(*this, &PolarisConnection::onShutdown));
delete outputTransform;
delete inputTransform;
}
void PolarisConnection::onShutdown(AutoPtr<ShutdownNotification> const ¬ification) {
delete this;
}
void PolarisConnection::onReadable(AutoPtr<ReadableNotification> const ¬ification) {
/*
1. Check if buffer already has data, if so deal with that
2. No data, new packet, read header
3. ...things?
*/
// Fill up the buffer, as much as possible
int readAmount;
if (inputTransform) {
uint8_t encrypted[BUFFER_SIZE];
readAmount = socket.receiveBytes(encrypted, BUFFER_SIZE - bufferPosition);
inputTransform->transform(encrypted, readAmount, &bufferPtr[bufferPosition], readAmount);
} else {
readAmount = socket.receiveBytes(&bufferPtr[bufferPosition], BUFFER_SIZE - bufferPosition);
}
bufferPosition += readAmount;
if (readAmount <= 0) {
// Connection failed
delete this;
return;
}
// Enough to process?
int position = 0;
while ((position + 4) <= bufferPosition) {
uint32_t packetSize = *((uint32_t *)&bufferPtr[position]);
if ((position + packetSize) > bufferPosition) {
// This packet is unfinished, bail out
break;
}
handlePacket(&bufferPtr[position]);
position += packetSize;
}
// If we handled any packets, we must remove their data from the buffer
if (position > 0) {
if (position >= bufferPosition) {
// End was reached, just empty the thing out.
bufferPosition = 0;
} else {
// Some data remains, move it to the beginning
memmove(bufferPtr, &bufferPtr[position], bufferPosition - position);
bufferPosition -= position;
}
}
}
void PolarisConnection::sendPacket(PacketData &data) {
PacketHeader *header = (PacketHeader *)data.getData();
Poco::Util::Application::instance().logger().information(Polaris::string_format("[Sending packet : %d bytes, type %x-%x]\n", header->length, header->command, header->subcommand));
if (outputTransform) {
uint8_t *encoded = new uint8_t[data.getSize()];
this->outputTransform->transform(data.getData(), data.getSize(), encoded, data.getSize());
this->socket.sendBytes(encoded, data.getSize());
delete[] encoded;
} else {
this->socket.sendBytes(data.getData(), data.getSize());
}
}
void PolarisConnection::handlePacket(uint8_t *packet) {
PacketHeader *header = (PacketHeader *)packet;
// Incomplete (corrupted/malicious?) packet
if (header->length < 8)
return;
Poco::Util::Application::instance().logger().information(Polaris::string_format("[Received packet : %d bytes, type %x-%x]", header->length, header->command, header->subcommand));
Poco::File folder("incomingPackets/");
folder.createDirectories();
std::time_t theTime = std::time(NULL);;
Poco::FileOutputStream packetFileWriter(Polaris::string_format("incomingPackets/%i.%x-%x.bin", theTime, header->command, header->subcommand));
packetFileWriter.write((char const *) packet, header->length);
packetFileWriter.flush();
packetFileWriter.close();
if (header->command == 0x11 && header->subcommand == 0xB) {
// Key exchange
handleKeyExchange(packet);
return;
}
if (header->command == 0x11 && header->subcommand == 0x00) {
MysteryPacket mystery(5);
PacketData flp = FixedLengthPacket(&mystery).build();
sendPacket(flp);
PacketData welcomeMsg(SystemMessagePacket(u"This has not been implemented yet.\nThank you for connecting to a PolarisServer.", 0x1).build());
sendPacket(welcomeMsg);
}
}
void PolarisConnection::handleKeyExchange(uint8_t *packet) {
PacketHeader *header = (PacketHeader *)packet;
if (header->length < 0x88)
return;
// Cache this key at some point.. maybe?
Cipher *rsa = 0;
CryptoTransform *dec = 0;
try {
RSAKey rsaKey("", "privateKey.pem");
rsa = CipherFactory::defaultFactory().createCipher(rsaKey);
dec = rsa->createDecryptor();
// Reverse the input (encrypted) data
uint8_t input[0x80], output[0x80];
for (int i = 0; i < 0x80; i++)
input[i] = packet[0x87 - i];
int processed = dec->transform(input, sizeof(input), output, sizeof(output));
processed += dec->finalize(output, sizeof(output) - processed);
if (processed >= 0x20) {
// Valid key exchange
// First 16 bytes: Challenge data, encrypted with RC4 key
// Following 16 bytes: RC4 key
std::vector<uint8_t> rc4key(16), rc4iv;
memcpy(rc4key.data(), &output[16], 16);
CipherKey rc4ck("rc4", rc4key, rc4iv);
cipher = CipherFactory::defaultFactory().createCipher(rc4ck);
// First off, generate the response to activate the client
CryptoTransform *dec = cipher->createDecryptor();
uint8_t response[16];
dec->transform(output, 16, response, 16);
delete dec;
// Second, enable RC4 encryption on this connection
if (outputTransform)
delete outputTransform;
if (inputTransform)
delete inputTransform;
outputTransform = cipher->createEncryptor();
inputTransform = cipher->createDecryptor();
// Build the response packet
PacketData responsePacket(PacketHeader(0x18, 0x11, 0xC, 0, 0), response);
sendPacket(responsePacket);
}
} catch (Poco::Exception &e) {
Poco::Util::Application::instance().logger().error(Polaris::string_format("[Key exchange error:]\n%s\n", e.displayText().c_str()));
}
if (rsa)
rsa->release();
delete dec;
}
<commit_msg>Close the socket if key exchange fails<commit_after>#include <packets/Packet.h>
#include "packets/server/BlockHelloPacket.h"
#include "Poco/Crypto/RSAKey.h"
#include "Poco/Crypto/Cipher.h"
#include "Poco/Crypto/CipherKey.h"
#include "Poco/Crypto/CipherFactory.h"
#include <string.h>
#include <packets/server/SystemMessagePacket.h>
#include <packets/FixedLengthPacket.h>
#include <fstream>
#include <ctime>
#include "PolarisConnection.h"
#include "PolarisClient.h"
#include "Poco/Util/Application.h"
#include "Poco/File.h"
#include "Poco/FileStream.h"
#include "RandomHelper.h"
PolarisConnection::PolarisConnection(const StreamSocket& socket, SocketReactor& reactor):
socket(socket),
reactor(reactor),
bufferPtr(new uint8_t[BUFFER_SIZE]),
bufferPosition(0),
outputTransform(0), inputTransform(0)
{
this->client = new PolarisClient(this);
reactor.addEventHandler(socket, NObserver<PolarisConnection, ReadableNotification>(*this, &PolarisConnection::onReadable));
reactor.addEventHandler(socket, NObserver<PolarisConnection, ShutdownNotification>(*this, &PolarisConnection::onShutdown));
Poco::Util::Application::instance().logger().information("New client connected, saying hello!");
BlockHelloPacket hello(201); // TODO Dynamic block pls
PacketData helloData = hello.build();
sendPacket(helloData);
}
PolarisConnection::~PolarisConnection() {
delete this->client;
delete[] this->bufferPtr;
reactor.removeEventHandler(socket, NObserver<PolarisConnection, ReadableNotification>(*this, &PolarisConnection::onReadable));
reactor.removeEventHandler(socket, NObserver<PolarisConnection, ShutdownNotification>(*this, &PolarisConnection::onShutdown));
delete outputTransform;
delete inputTransform;
}
void PolarisConnection::onShutdown(AutoPtr<ShutdownNotification> const ¬ification) {
delete this;
}
void PolarisConnection::onReadable(AutoPtr<ReadableNotification> const ¬ification) {
/*
1. Check if buffer already has data, if so deal with that
2. No data, new packet, read header
3. ...things?
*/
// Fill up the buffer, as much as possible
int readAmount;
if (inputTransform) {
uint8_t encrypted[BUFFER_SIZE];
readAmount = socket.receiveBytes(encrypted, BUFFER_SIZE - bufferPosition);
inputTransform->transform(encrypted, readAmount, &bufferPtr[bufferPosition], readAmount);
} else {
readAmount = socket.receiveBytes(&bufferPtr[bufferPosition], BUFFER_SIZE - bufferPosition);
}
bufferPosition += readAmount;
if (readAmount <= 0) {
// Connection failed
delete this;
return;
}
// Enough to process?
int position = 0;
while ((position + 4) <= bufferPosition) {
uint32_t packetSize = *((uint32_t *)&bufferPtr[position]);
if ((position + packetSize) > bufferPosition) {
// This packet is unfinished, bail out
break;
}
handlePacket(&bufferPtr[position]);
position += packetSize;
}
// If we handled any packets, we must remove their data from the buffer
if (position > 0) {
if (position >= bufferPosition) {
// End was reached, just empty the thing out.
bufferPosition = 0;
} else {
// Some data remains, move it to the beginning
memmove(bufferPtr, &bufferPtr[position], bufferPosition - position);
bufferPosition -= position;
}
}
}
void PolarisConnection::sendPacket(PacketData &data) {
PacketHeader *header = (PacketHeader *)data.getData();
Poco::Util::Application::instance().logger().information(Polaris::string_format("[Sending packet : %d bytes, type %x-%x]\n", header->length, header->command, header->subcommand));
if (outputTransform) {
uint8_t *encoded = new uint8_t[data.getSize()];
this->outputTransform->transform(data.getData(), data.getSize(), encoded, data.getSize());
this->socket.sendBytes(encoded, data.getSize());
delete[] encoded;
} else {
this->socket.sendBytes(data.getData(), data.getSize());
}
}
void PolarisConnection::handlePacket(uint8_t *packet) {
PacketHeader *header = (PacketHeader *)packet;
// Incomplete (corrupted/malicious?) packet
if (header->length < 8)
return;
Poco::Util::Application::instance().logger().information(Polaris::string_format("[Received packet : %d bytes, type %x-%x]", header->length, header->command, header->subcommand));
Poco::File folder("incomingPackets/");
folder.createDirectories();
std::time_t theTime = std::time(NULL);;
Poco::FileOutputStream packetFileWriter(Polaris::string_format("incomingPackets/%i.%x-%x.bin", theTime, header->command, header->subcommand));
packetFileWriter.write((char const *) packet, header->length);
packetFileWriter.flush();
packetFileWriter.close();
if (header->command == 0x11 && header->subcommand == 0xB) {
// Key exchange
handleKeyExchange(packet);
return;
}
if (header->command == 0x11 && header->subcommand == 0x00) {
MysteryPacket mystery(5);
PacketData flp = FixedLengthPacket(&mystery).build();
sendPacket(flp);
PacketData welcomeMsg(SystemMessagePacket(u"This has not been implemented yet.\nThank you for connecting to a PolarisServer.", 0x1).build());
sendPacket(welcomeMsg);
}
}
void PolarisConnection::handleKeyExchange(uint8_t *packet) {
PacketHeader *header = (PacketHeader *)packet;
if (header->length < 0x88)
return;
// Cache this key at some point.. maybe?
Cipher *rsa = 0;
CryptoTransform *dec = 0;
try {
RSAKey rsaKey("", "privateKey.pem");
rsa = CipherFactory::defaultFactory().createCipher(rsaKey);
dec = rsa->createDecryptor();
// Reverse the input (encrypted) data
uint8_t input[0x80], output[0x80];
for (int i = 0; i < 0x80; i++)
input[i] = packet[0x87 - i];
int processed = dec->transform(input, sizeof(input), output, sizeof(output));
processed += dec->finalize(output, sizeof(output) - processed);
if (processed >= 0x20) {
// Valid key exchange
// First 16 bytes: Challenge data, encrypted with RC4 key
// Following 16 bytes: RC4 key
std::vector<uint8_t> rc4key(16), rc4iv;
memcpy(rc4key.data(), &output[16], 16);
CipherKey rc4ck("rc4", rc4key, rc4iv);
cipher = CipherFactory::defaultFactory().createCipher(rc4ck);
// First off, generate the response to activate the client
CryptoTransform *dec = cipher->createDecryptor();
uint8_t response[16];
dec->transform(output, 16, response, 16);
delete dec;
// Second, enable RC4 encryption on this connection
if (outputTransform)
delete outputTransform;
if (inputTransform)
delete inputTransform;
outputTransform = cipher->createEncryptor();
inputTransform = cipher->createDecryptor();
// Build the response packet
PacketData responsePacket(PacketHeader(0x18, 0x11, 0xC, 0, 0), response);
sendPacket(responsePacket);
}
} catch (Poco::Exception &e) {
Poco::Util::Application::instance().logger().error(Polaris::string_format("[Key exchange error: %s]", e.displayText().c_str()));
socket.close();
}
if (rsa)
rsa->release();
delete dec;
}
<|endoftext|>
|
<commit_before>////////////////////////////////////////////////////////////////////////////////
// task - a command line task list manager.
//
// Copyright 2006 - 2009, Paul Beckingham.
// All rights reserved.
//
// This program is free software; you can redistribute it and/or modify it under
// the terms of the GNU General Public License as published by the Free Software
// Foundation; either version 2 of the License, or (at your option) any later
// version.
//
// This program is distributed in the hope that it will be useful, but WITHOUT
// ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
// FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
// details.
//
// You should have received a copy of the GNU General Public License along with
// this program; if not, write to the
//
// Free Software Foundation, Inc.,
// 51 Franklin Street, Fifth Floor,
// Boston, MA
// 02110-1301
// USA
//
////////////////////////////////////////////////////////////////////////////////
#include <iostream>
#include <sstream>
#include <unistd.h>
#include <string.h>
#include <stdio.h>
#include <sys/file.h>
#include "text.h"
#include "util.h"
#include "TDB.h"
#include "main.h"
extern Context context;
////////////////////////////////////////////////////////////////////////////////
// The ctor/dtor do nothing.
// The lock/unlock methods hold the file open.
// There should be only one commit.
//
// +- TDB::TDB
// |
// | +- TDB::lock
// | | open
// | | [lock]
// | |
// | | +- TDB::load (Filter)
// | | | read all
// | | | apply filter
// | | | return subset
// | | |
// | | +- TDB::add (T)
// | | |
// | | +- TDB::update (T)
// | | |
// | | +- TDB::commit
// | | write all
// | |
// | +- TDB::unlock
// | [unlock]
// | close
// |
// +- TDB::~TDB
// [TDB::unlock]
//
TDB::TDB ()
: mLock (true)
, mAllOpenAndLocked (false)
, mId (1)
{
}
////////////////////////////////////////////////////////////////////////////////
TDB::~TDB ()
{
if (mAllOpenAndLocked)
unlock ();
}
////////////////////////////////////////////////////////////////////////////////
void TDB::clear ()
{
mLocations.clear ();
mLock = true;
if (mAllOpenAndLocked)
unlock ();
mAllOpenAndLocked = false;
mId = 1;
mPending.clear ();
mNew.clear ();
mModified.clear ();
}
////////////////////////////////////////////////////////////////////////////////
void TDB::location (const std::string& path)
{
if (access (expandPath (path).c_str (), F_OK))
throw std::string ("Data location '") +
path +
"' does not exist, or is not readable and writable.";
mLocations.push_back (Location (path));
}
////////////////////////////////////////////////////////////////////////////////
void TDB::lock (bool lockFile /* = true */)
{
mLock = lockFile;
mPending.clear ();
mNew.clear ();
mPending.clear ();
foreach (location, mLocations)
{
location->pending = openAndLock (location->path + "/pending.data");
location->completed = openAndLock (location->path + "/completed.data");
}
mAllOpenAndLocked = true;
}
////////////////////////////////////////////////////////////////////////////////
void TDB::unlock ()
{
if (mAllOpenAndLocked)
{
mPending.clear ();
mNew.clear ();
mModified.clear ();
foreach (location, mLocations)
{
fflush (location->pending);
fclose (location->pending);
location->pending = NULL;
fflush (location->completed);
fclose (location->completed);
location->completed = NULL;
}
mAllOpenAndLocked = false;
}
}
////////////////////////////////////////////////////////////////////////////////
// Returns number of filtered tasks.
// Note: tasks.clear () is deliberately not called, to allow the combination of
// multiple files.
int TDB::load (std::vector <Task>& tasks, Filter& filter)
{
#ifdef FEATURE_TDB_OPT
// Special optimization: if the filter contains Att ('status', '', 'pending'),
// and no other 'status' filters, then loadCompleted can be skipped.
int numberStatusClauses = 0;
int numberSimpleStatusClauses = 0;
foreach (att, filter)
{
if (att->name () == "status")
{
++numberStatusClauses;
if (att->mod () == "" &&
(att->value () == "pending" ||
att->value () == "waiting"))
++numberSimpleStatusClauses;
}
}
#endif
loadPending (tasks, filter);
#ifdef FEATURE_TDB_OPT
if (numberStatusClauses == 0 ||
numberStatusClauses != numberSimpleStatusClauses)
loadCompleted (tasks, filter);
else
context.debug ("load optimization short circuit");
#else
loadCompleted (tasks, filter);
#endif
return tasks.size ();
}
////////////////////////////////////////////////////////////////////////////////
// Returns number of filtered tasks.
// Note: tasks.clear () is deliberately not called, to allow the combination of
// multiple files.
int TDB::loadPending (std::vector <Task>& tasks, Filter& filter)
{
std::string file;
int line_number;
try
{
if (mPending.size () == 0)
{
mId = 1;
char line[T_LINE_MAX];
foreach (location, mLocations)
{
line_number = 1;
file = location->path + "/pending.data";
fseek (location->pending, 0, SEEK_SET);
while (fgets (line, T_LINE_MAX, location->pending))
{
int length = ::strlen (line);
if (length > 3) // []\n
{
// TODO Add hidden attribute indicating source?
Task task (line);
task.id = mId++;
mPending.push_back (task);
}
++line_number;
}
}
}
// Now filter and return.
foreach (task, mPending)
if (filter.pass (*task))
tasks.push_back (*task);
// Hand back any accumulated additions, if TDB::loadPending is being called
// repeatedly.
int fakeId = mId;
foreach (task, mNew)
{
task->id = fakeId++;
if (filter.pass (*task))
tasks.push_back (*task);
}
}
catch (std::string& e)
{
std::stringstream s;
s << " in " << file << " at line " << line_number;
throw e + s.str ();
}
return tasks.size ();
}
////////////////////////////////////////////////////////////////////////////////
// Returns number of filtered tasks.
// Note: tasks.clear () is deliberately not called, to allow the combination of
// multiple files.
int TDB::loadCompleted (std::vector <Task>& tasks, Filter& filter)
{
std::string file;
int line_number;
try
{
char line[T_LINE_MAX];
foreach (location, mLocations)
{
// TODO If the filter contains Status:x where x is not deleted or
// completed, then this can be skipped.
line_number = 1;
file = location->path + "/completed.data";
fseek (location->completed, 0, SEEK_SET);
while (fgets (line, T_LINE_MAX, location->completed))
{
int length = ::strlen (line);
if (length > 3) // []\n
{
// TODO Add hidden attribute indicating source?
if (line[length - 1] == '\n')
line[length - 1] = '\0';
Task task (line);
// Note: no id is set for completed tasks.
if (filter.pass (task))
tasks.push_back (task);
}
++line_number;
}
}
}
catch (std::string& e)
{
std::stringstream s;
s << " in " << file << " at line " << line_number;
throw e + s.str ();
}
return tasks.size ();
}
////////////////////////////////////////////////////////////////////////////////
// TODO Write to transaction log.
// Note: mLocations[0] is where all tasks are written.
void TDB::add (const Task& task)
{
mNew.push_back (task);
}
////////////////////////////////////////////////////////////////////////////////
// TODO Write to transaction log.
void TDB::update (const Task& task)
{
mModified.push_back (task);
}
////////////////////////////////////////////////////////////////////////////////
// TODO Writes all, including comments
// Interestingly, only the pending file gets written to. The completed file is
// only modified by TDB::gc.
int TDB::commit ()
{
int quantity = mNew.size () + mModified.size ();
// This is an optimization. If there are only new tasks, and none were
// modified, simply seek to the end of pending and write.
if (mNew.size () && ! mModified.size ())
{
fseek (mLocations[0].pending, 0, SEEK_END);
foreach (task, mNew)
{
mPending.push_back (*task);
fputs (task->composeF4 ().c_str (), mLocations[0].pending);
}
mNew.clear ();
return quantity;
}
// The alternative is to potentially rewrite both files.
else if (mNew.size () || mModified.size ())
{
foreach (task, mPending)
foreach (mtask, mModified)
if (task->id == mtask->id)
*task = *mtask;
mModified.clear ();
foreach (task, mNew)
mPending.push_back (*task);
mNew.clear ();
// Write out all pending.
if (fseek (mLocations[0].pending, 0, SEEK_SET) == 0)
{
ftruncate (fileno (mLocations[0].pending), 0);
foreach (task, mPending)
fputs (task->composeF4 ().c_str (), mLocations[0].pending);
}
}
return quantity;
}
////////////////////////////////////////////////////////////////////////////////
// TODO -> FF4
void TDB::upgrade ()
{
// TODO Read all pending
// TODO Write out all pending
// TODO Read all completed
// TODO Write out all completed
throw std::string ("unimplemented TDB::upgrade");
}
////////////////////////////////////////////////////////////////////////////////
// Scans the pending tasks for any that are completed or deleted, and if so,
// moves them to the completed.data file. Returns a count of tasks moved.
int TDB::gc ()
{
int count = 0;
Date now;
// Set up a second TDB.
Filter filter;
TDB tdb;
tdb.location (mLocations[0].path);
tdb.lock ();
std::vector <Task> pending;
tdb.loadPending (pending, filter);
std::vector <Task> completed;
tdb.loadCompleted (completed, filter);
// Now move completed and deleted tasks from the pending list to the
// completed list. Isn't garbage collection easy?
std::vector <Task> still_pending;
foreach (task, pending)
{
std::string st = task->get ("status");
Task::status s = task->getStatus ();
if (s == Task::completed ||
s == Task::deleted)
{
completed.push_back (*task);
++count;
}
else if (s == Task::waiting)
{
// Wake up tasks that are waiting.
Date wait_date (::atoi (task->get ("wait").c_str ()));
if (now > wait_date)
task->setStatus (Task::pending);
still_pending.push_back (*task);
}
else
still_pending.push_back (*task);
}
pending = still_pending;
// No commit - all updates performed manually.
if (count > 0)
{
if (fseek (tdb.mLocations[0].pending, 0, SEEK_SET) == 0)
{
ftruncate (fileno (tdb.mLocations[0].pending), 0);
foreach (task, pending)
fputs (task->composeF4 ().c_str (), tdb.mLocations[0].pending);
}
if (fseek (tdb.mLocations[0].completed, 0, SEEK_SET) == 0)
{
ftruncate (fileno (tdb.mLocations[0].completed), 0);
foreach (task, completed)
fputs (task->composeF4 ().c_str (), tdb.mLocations[0].completed);
}
}
// Close files.
tdb.unlock ();
std::stringstream s;
s << "gc " << count << " tasks";
context.debug (s.str ());
return count;
}
////////////////////////////////////////////////////////////////////////////////
int TDB::nextId ()
{
return mId++;
}
////////////////////////////////////////////////////////////////////////////////
FILE* TDB::openAndLock (const std::string& file)
{
// TODO Need provision here for read-only locations.
// Check for access.
bool exists = access (file.c_str (), F_OK) ? false : true;
if (exists)
if (access (file.c_str (), R_OK | W_OK))
throw std::string ("Task does not have the correct permissions for '") +
file + "'.";
// Open the file.
FILE* in = fopen (file.c_str (), (exists ? "r+" : "w+"));
if (!in)
throw std::string ("Could not open '") + file + "'.";
// Lock if desired. Try three times before failing.
int retry = 0;
if (mLock)
while (flock (fileno (in), LOCK_EX) && ++retry <= 3)
delay (0.1);
if (retry > 3)
throw std::string ("Could not lock '") + file + "'.";
return in;
}
////////////////////////////////////////////////////////////////////////////////
<commit_msg>Fixed include statement for Linux<commit_after>////////////////////////////////////////////////////////////////////////////////
// task - a command line task list manager.
//
// Copyright 2006 - 2009, Paul Beckingham.
// All rights reserved.
//
// This program is free software; you can redistribute it and/or modify it under
// the terms of the GNU General Public License as published by the Free Software
// Foundation; either version 2 of the License, or (at your option) any later
// version.
//
// This program is distributed in the hope that it will be useful, but WITHOUT
// ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
// FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
// details.
//
// You should have received a copy of the GNU General Public License along with
// this program; if not, write to the
//
// Free Software Foundation, Inc.,
// 51 Franklin Street, Fifth Floor,
// Boston, MA
// 02110-1301
// USA
//
////////////////////////////////////////////////////////////////////////////////
#include <iostream>
#include <sstream>
#include <unistd.h>
#include <string.h>
#include <stdio.h>
#include <sys/file.h>
#include <stdlib.h>
#include "text.h"
#include "util.h"
#include "TDB.h"
#include "main.h"
extern Context context;
////////////////////////////////////////////////////////////////////////////////
// The ctor/dtor do nothing.
// The lock/unlock methods hold the file open.
// There should be only one commit.
//
// +- TDB::TDB
// |
// | +- TDB::lock
// | | open
// | | [lock]
// | |
// | | +- TDB::load (Filter)
// | | | read all
// | | | apply filter
// | | | return subset
// | | |
// | | +- TDB::add (T)
// | | |
// | | +- TDB::update (T)
// | | |
// | | +- TDB::commit
// | | write all
// | |
// | +- TDB::unlock
// | [unlock]
// | close
// |
// +- TDB::~TDB
// [TDB::unlock]
//
TDB::TDB ()
: mLock (true)
, mAllOpenAndLocked (false)
, mId (1)
{
}
////////////////////////////////////////////////////////////////////////////////
TDB::~TDB ()
{
if (mAllOpenAndLocked)
unlock ();
}
////////////////////////////////////////////////////////////////////////////////
void TDB::clear ()
{
mLocations.clear ();
mLock = true;
if (mAllOpenAndLocked)
unlock ();
mAllOpenAndLocked = false;
mId = 1;
mPending.clear ();
mNew.clear ();
mModified.clear ();
}
////////////////////////////////////////////////////////////////////////////////
void TDB::location (const std::string& path)
{
if (access (expandPath (path).c_str (), F_OK))
throw std::string ("Data location '") +
path +
"' does not exist, or is not readable and writable.";
mLocations.push_back (Location (path));
}
////////////////////////////////////////////////////////////////////////////////
void TDB::lock (bool lockFile /* = true */)
{
mLock = lockFile;
mPending.clear ();
mNew.clear ();
mPending.clear ();
foreach (location, mLocations)
{
location->pending = openAndLock (location->path + "/pending.data");
location->completed = openAndLock (location->path + "/completed.data");
}
mAllOpenAndLocked = true;
}
////////////////////////////////////////////////////////////////////////////////
void TDB::unlock ()
{
if (mAllOpenAndLocked)
{
mPending.clear ();
mNew.clear ();
mModified.clear ();
foreach (location, mLocations)
{
fflush (location->pending);
fclose (location->pending);
location->pending = NULL;
fflush (location->completed);
fclose (location->completed);
location->completed = NULL;
}
mAllOpenAndLocked = false;
}
}
////////////////////////////////////////////////////////////////////////////////
// Returns number of filtered tasks.
// Note: tasks.clear () is deliberately not called, to allow the combination of
// multiple files.
int TDB::load (std::vector <Task>& tasks, Filter& filter)
{
#ifdef FEATURE_TDB_OPT
// Special optimization: if the filter contains Att ('status', '', 'pending'),
// and no other 'status' filters, then loadCompleted can be skipped.
int numberStatusClauses = 0;
int numberSimpleStatusClauses = 0;
foreach (att, filter)
{
if (att->name () == "status")
{
++numberStatusClauses;
if (att->mod () == "" &&
(att->value () == "pending" ||
att->value () == "waiting"))
++numberSimpleStatusClauses;
}
}
#endif
loadPending (tasks, filter);
#ifdef FEATURE_TDB_OPT
if (numberStatusClauses == 0 ||
numberStatusClauses != numberSimpleStatusClauses)
loadCompleted (tasks, filter);
else
context.debug ("load optimization short circuit");
#else
loadCompleted (tasks, filter);
#endif
return tasks.size ();
}
////////////////////////////////////////////////////////////////////////////////
// Returns number of filtered tasks.
// Note: tasks.clear () is deliberately not called, to allow the combination of
// multiple files.
int TDB::loadPending (std::vector <Task>& tasks, Filter& filter)
{
std::string file;
int line_number;
try
{
if (mPending.size () == 0)
{
mId = 1;
char line[T_LINE_MAX];
foreach (location, mLocations)
{
line_number = 1;
file = location->path + "/pending.data";
fseek (location->pending, 0, SEEK_SET);
while (fgets (line, T_LINE_MAX, location->pending))
{
int length = ::strlen (line);
if (length > 3) // []\n
{
// TODO Add hidden attribute indicating source?
Task task (line);
task.id = mId++;
mPending.push_back (task);
}
++line_number;
}
}
}
// Now filter and return.
foreach (task, mPending)
if (filter.pass (*task))
tasks.push_back (*task);
// Hand back any accumulated additions, if TDB::loadPending is being called
// repeatedly.
int fakeId = mId;
foreach (task, mNew)
{
task->id = fakeId++;
if (filter.pass (*task))
tasks.push_back (*task);
}
}
catch (std::string& e)
{
std::stringstream s;
s << " in " << file << " at line " << line_number;
throw e + s.str ();
}
return tasks.size ();
}
////////////////////////////////////////////////////////////////////////////////
// Returns number of filtered tasks.
// Note: tasks.clear () is deliberately not called, to allow the combination of
// multiple files.
int TDB::loadCompleted (std::vector <Task>& tasks, Filter& filter)
{
std::string file;
int line_number;
try
{
char line[T_LINE_MAX];
foreach (location, mLocations)
{
// TODO If the filter contains Status:x where x is not deleted or
// completed, then this can be skipped.
line_number = 1;
file = location->path + "/completed.data";
fseek (location->completed, 0, SEEK_SET);
while (fgets (line, T_LINE_MAX, location->completed))
{
int length = ::strlen (line);
if (length > 3) // []\n
{
// TODO Add hidden attribute indicating source?
if (line[length - 1] == '\n')
line[length - 1] = '\0';
Task task (line);
// Note: no id is set for completed tasks.
if (filter.pass (task))
tasks.push_back (task);
}
++line_number;
}
}
}
catch (std::string& e)
{
std::stringstream s;
s << " in " << file << " at line " << line_number;
throw e + s.str ();
}
return tasks.size ();
}
////////////////////////////////////////////////////////////////////////////////
// TODO Write to transaction log.
// Note: mLocations[0] is where all tasks are written.
void TDB::add (const Task& task)
{
mNew.push_back (task);
}
////////////////////////////////////////////////////////////////////////////////
// TODO Write to transaction log.
void TDB::update (const Task& task)
{
mModified.push_back (task);
}
////////////////////////////////////////////////////////////////////////////////
// TODO Writes all, including comments
// Interestingly, only the pending file gets written to. The completed file is
// only modified by TDB::gc.
int TDB::commit ()
{
int quantity = mNew.size () + mModified.size ();
// This is an optimization. If there are only new tasks, and none were
// modified, simply seek to the end of pending and write.
if (mNew.size () && ! mModified.size ())
{
fseek (mLocations[0].pending, 0, SEEK_END);
foreach (task, mNew)
{
mPending.push_back (*task);
fputs (task->composeF4 ().c_str (), mLocations[0].pending);
}
mNew.clear ();
return quantity;
}
// The alternative is to potentially rewrite both files.
else if (mNew.size () || mModified.size ())
{
foreach (task, mPending)
foreach (mtask, mModified)
if (task->id == mtask->id)
*task = *mtask;
mModified.clear ();
foreach (task, mNew)
mPending.push_back (*task);
mNew.clear ();
// Write out all pending.
if (fseek (mLocations[0].pending, 0, SEEK_SET) == 0)
{
ftruncate (fileno (mLocations[0].pending), 0);
foreach (task, mPending)
fputs (task->composeF4 ().c_str (), mLocations[0].pending);
}
}
return quantity;
}
////////////////////////////////////////////////////////////////////////////////
// TODO -> FF4
void TDB::upgrade ()
{
// TODO Read all pending
// TODO Write out all pending
// TODO Read all completed
// TODO Write out all completed
throw std::string ("unimplemented TDB::upgrade");
}
////////////////////////////////////////////////////////////////////////////////
// Scans the pending tasks for any that are completed or deleted, and if so,
// moves them to the completed.data file. Returns a count of tasks moved.
int TDB::gc ()
{
int count = 0;
Date now;
// Set up a second TDB.
Filter filter;
TDB tdb;
tdb.location (mLocations[0].path);
tdb.lock ();
std::vector <Task> pending;
tdb.loadPending (pending, filter);
std::vector <Task> completed;
tdb.loadCompleted (completed, filter);
// Now move completed and deleted tasks from the pending list to the
// completed list. Isn't garbage collection easy?
std::vector <Task> still_pending;
foreach (task, pending)
{
std::string st = task->get ("status");
Task::status s = task->getStatus ();
if (s == Task::completed ||
s == Task::deleted)
{
completed.push_back (*task);
++count;
}
else if (s == Task::waiting)
{
// Wake up tasks that are waiting.
Date wait_date (::atoi (task->get ("wait").c_str ()));
if (now > wait_date)
task->setStatus (Task::pending);
still_pending.push_back (*task);
}
else
still_pending.push_back (*task);
}
pending = still_pending;
// No commit - all updates performed manually.
if (count > 0)
{
if (fseek (tdb.mLocations[0].pending, 0, SEEK_SET) == 0)
{
ftruncate (fileno (tdb.mLocations[0].pending), 0);
foreach (task, pending)
fputs (task->composeF4 ().c_str (), tdb.mLocations[0].pending);
}
if (fseek (tdb.mLocations[0].completed, 0, SEEK_SET) == 0)
{
ftruncate (fileno (tdb.mLocations[0].completed), 0);
foreach (task, completed)
fputs (task->composeF4 ().c_str (), tdb.mLocations[0].completed);
}
}
// Close files.
tdb.unlock ();
std::stringstream s;
s << "gc " << count << " tasks";
context.debug (s.str ());
return count;
}
////////////////////////////////////////////////////////////////////////////////
int TDB::nextId ()
{
return mId++;
}
////////////////////////////////////////////////////////////////////////////////
FILE* TDB::openAndLock (const std::string& file)
{
// TODO Need provision here for read-only locations.
// Check for access.
bool exists = access (file.c_str (), F_OK) ? false : true;
if (exists)
if (access (file.c_str (), R_OK | W_OK))
throw std::string ("Task does not have the correct permissions for '") +
file + "'.";
// Open the file.
FILE* in = fopen (file.c_str (), (exists ? "r+" : "w+"));
if (!in)
throw std::string ("Could not open '") + file + "'.";
// Lock if desired. Try three times before failing.
int retry = 0;
if (mLock)
while (flock (fileno (in), LOCK_EX) && ++retry <= 3)
delay (0.1);
if (retry > 3)
throw std::string ("Could not lock '") + file + "'.";
return in;
}
////////////////////////////////////////////////////////////////////////////////
<|endoftext|>
|
<commit_before>#include "testing/testing.hpp"
#include "routing/road_graph.hpp"
#include "routing/routing_tests/road_graph_builder.hpp"
#include "std/algorithm.hpp"
namespace routing
{
UNIT_TEST(RoadGraph_NearestTurns)
{
// 2nd road
// o
// |
// |
// o
// |
// | 1st road
// o--o--x--o--o
// |
// |
// o
// |
// |
// o
//
// Just two roads intersecting at (0, 0).
routing_test::RoadGraphMockSource graph;
{
IRoadGraph::RoadInfo ri0;
ri0.m_points.emplace_back(2, 0);
ri0.m_points.emplace_back(-1, 0);
ri0.m_points.emplace_back(0, 0);
ri0.m_points.emplace_back(1, 0);
ri0.m_points.emplace_back(2, 0);
ri0.m_speedKMPH = 5;
ri0.m_bidirectional = true;
IRoadGraph::RoadInfo ri1;
ri1.m_points.emplace_back(0, -2);
ri1.m_points.emplace_back(0, -1);
ri1.m_points.emplace_back(0, 0);
ri1.m_points.emplace_back(0, 1);
ri1.m_points.emplace_back(0, 2);
ri1.m_speedKMPH = 5;
ri1.m_bidirectional = true;
graph.AddRoad(move(ri0));
graph.AddRoad(move(ri1));
}
// We're standing at:
// ... x--o ... segment and looking to the right.
RoadPos const crossPos(0 /* featureId */, true /* forward */, 2 /* segId */, m2::PointD(0, 0));
IRoadGraph::RoadPosVectorT expected = {
// It's possible to get to the standing RoadPos from RoadPos'es on
// the first road marked with > and <.
//
// ...
// |
// ...--o>>x<<o--...
// |
// ...
//
RoadPos(0 /* first road */, true /* forward */, 1 /* segId */, m2::PointD(0, 0)),
RoadPos(0 /* first road */, false /* forward */, 2 /* segId */, m2::PointD(0, 0)),
// It's possible to get to the standing RoadPos from RoadPos'es on
// the second road marked with v and ^.
//
// ...
// |
// o
// v
// v
// ...-x-...
// ^
// ^
// o
// |
// ...
//
RoadPos(1 /* first road */, true /* forward */, 1 /* segId */, m2::PointD(0, 0)),
RoadPos(1 /* first road */, false /* forward */, 2 /* segId */, m2::PointD(0, 0)),
};
IRoadGraph::TurnsVectorT turns;
graph.GetNearestTurns(crossPos, turns);
IRoadGraph::RoadPosVectorT actual;
for (PossibleTurn const & turn : turns) {
actual.push_back(turn.m_pos);
TEST_EQUAL(5, turn.m_speedKMPH, ());
TEST_EQUAL(0, turn.m_metersCovered, ());
TEST_EQUAL(0, turn.m_secondsCovered, ());
}
sort(expected.begin(), expected.end());
sort(actual.begin(), actual.end());
TEST_EQUAL(expected, actual, ());
}
} // namespace routing
<commit_msg>Review fixes.<commit_after>#include "testing/testing.hpp"
#include "routing/road_graph.hpp"
#include "routing/routing_tests/road_graph_builder.hpp"
#include "std/algorithm.hpp"
namespace routing
{
UNIT_TEST(RoadGraph_NearestTurns)
{
// 1st road
// o
// |
// |
// o
// |
// | 0th road
// o--o--x--o--o
// |
// |
// o
// |
// |
// o
//
// Two roads intersecting at (0, 0).
routing_test::RoadGraphMockSource graph;
{
IRoadGraph::RoadInfo ri0;
ri0.m_points.emplace_back(-2, 0);
ri0.m_points.emplace_back(-1, 0);
ri0.m_points.emplace_back(0, 0);
ri0.m_points.emplace_back(1, 0);
ri0.m_points.emplace_back(2, 0);
ri0.m_speedKMPH = 5;
ri0.m_bidirectional = true;
IRoadGraph::RoadInfo ri1;
ri1.m_points.emplace_back(0, -2);
ri1.m_points.emplace_back(0, -1);
ri1.m_points.emplace_back(0, 0);
ri1.m_points.emplace_back(0, 1);
ri1.m_points.emplace_back(0, 2);
ri1.m_speedKMPH = 5;
ri1.m_bidirectional = true;
graph.AddRoad(move(ri0));
graph.AddRoad(move(ri1));
}
// We are standing at ... x--o ... segment and are looking to the
// right.
RoadPos const crossPos(0 /* featureId */, true /* forward */, 2 /* segId */, m2::PointD(0, 0));
IRoadGraph::RoadPosVectorT expected = {
// It is possible to get to the RoadPos we are standing at from
// RoadPos'es on the first road marked with >> and <<.
//
// ...
// |
// ...--o>>x<<o--...
// |
// ...
//
RoadPos(0 /* first road */, true /* forward */, 1 /* segId */, m2::PointD(0, 0)),
RoadPos(0 /* first road */, false /* forward */, 2 /* segId */, m2::PointD(0, 0)),
// It is possible to get to the RoadPos we are standing at from
// RoadPos'es on the second road marked with v and ^.
//
// ...
// |
// o
// v
// v
// ...-x-...
// ^
// ^
// o
// |
// ...
//
RoadPos(1 /* first road */, true /* forward */, 1 /* segId */, m2::PointD(0, 0)),
RoadPos(1 /* first road */, false /* forward */, 2 /* segId */, m2::PointD(0, 0)),
};
IRoadGraph::TurnsVectorT turns;
graph.GetNearestTurns(crossPos, turns);
IRoadGraph::RoadPosVectorT actual;
for (PossibleTurn const & turn : turns) {
actual.push_back(turn.m_pos);
TEST_EQUAL(5, turn.m_speedKMPH, ());
TEST_EQUAL(0, turn.m_metersCovered, ());
TEST_EQUAL(0, turn.m_secondsCovered, ());
}
sort(expected.begin(), expected.end());
sort(actual.begin(), actual.end());
TEST_EQUAL(expected, actual, ());
}
} // namespace routing
<|endoftext|>
|
<commit_before>/**
* @file
* @brief Implementation of object with set of particles at pixel
* @copyright Copyright (c) 2017 CERN and the Allpix Squared authors.
* This software is distributed under the terms of the MIT License, copied verbatim in the file "LICENSE.md".
* In applying this license, CERN does not waive the privileges and immunities granted to it by virtue of its status as an
* Intergovernmental Organization or submit itself to any jurisdiction.
*/
#include "PixelCharge.hpp"
#include <set>
#include "exceptions.h"
using namespace allpix;
PixelCharge::PixelCharge(Pixel pixel, unsigned int charge, std::vector<const PropagatedCharge*> propagated_charges)
: pixel_(std::move(pixel)), charge_(charge) {
// Unique set of MC particles
std::set<TRef> unique_particles;
// Store all propagated charges and their MC particles
for(auto& propagated_charge : propagated_charges) {
propagated_charges_.push_back(const_cast<PropagatedCharge*>(propagated_charge)); // NOLINT
unique_particles.insert(propagated_charge->mc_particle_);
}
// Store the MC particle references
for(auto& mc_particle : unique_particles) {
mc_particles_.push_back(mc_particle);
}
}
PixelCharge::PixelCharge(Pixel pixel, Pulse pulse, std::vector<const PropagatedCharge*> propagated_charges)
: PixelCharge(pixel, pulse.getCharge(), propagated_charges) {
pulse_ = std::move(pulse);
}
const Pixel& PixelCharge::getPixel() const {
return pixel_;
}
Pixel::Index PixelCharge::getIndex() const {
return getPixel().getIndex();
}
unsigned int PixelCharge::getCharge() const {
return charge_;
}
/**
* @throws MissingReferenceException If the pointed object is not in scope
*
* Objects are stored as vector of TRef and can only be accessed if pointed objects are in scope
*/
std::vector<const PropagatedCharge*> PixelCharge::getPropagatedCharges() const {
// FIXME: This is not very efficient unfortunately
std::vector<const PropagatedCharge*> propagated_charges;
for(auto& propagated_charge : propagated_charges_) {
if(!propagated_charge.IsValid() || propagated_charge.GetObject() == nullptr) {
throw MissingReferenceException(typeid(*this), typeid(PropagatedCharge));
}
propagated_charges.emplace_back(dynamic_cast<PropagatedCharge*>(propagated_charge.GetObject()));
}
return propagated_charges;
}
/**
* @throws MissingReferenceException If the pointed object is not in scope
*
* MCParticles can only be fetched if the full history of objects are in scope and stored
*/
std::vector<const MCParticle*> PixelCharge::getMCParticles() const {
std::vector<const MCParticle*> mc_particles;
for(auto& mc_particle : mc_particles_) {
if(!mc_particle.IsValid() || mc_particle.GetObject() == nullptr) {
throw MissingReferenceException(typeid(*this), typeid(MCParticle));
}
mc_particles.emplace_back(dynamic_cast<MCParticle*>(mc_particle.GetObject()));
}
// Return as a vector of mc particles
return mc_particles;
}
<commit_msg>Move things in PixelCharge constructor<commit_after>/**
* @file
* @brief Implementation of object with set of particles at pixel
* @copyright Copyright (c) 2017 CERN and the Allpix Squared authors.
* This software is distributed under the terms of the MIT License, copied verbatim in the file "LICENSE.md".
* In applying this license, CERN does not waive the privileges and immunities granted to it by virtue of its status as an
* Intergovernmental Organization or submit itself to any jurisdiction.
*/
#include "PixelCharge.hpp"
#include <set>
#include "exceptions.h"
using namespace allpix;
PixelCharge::PixelCharge(Pixel pixel, unsigned int charge, std::vector<const PropagatedCharge*> propagated_charges)
: pixel_(std::move(pixel)), charge_(charge) {
// Unique set of MC particles
std::set<TRef> unique_particles;
// Store all propagated charges and their MC particles
for(auto& propagated_charge : propagated_charges) {
propagated_charges_.push_back(const_cast<PropagatedCharge*>(propagated_charge)); // NOLINT
unique_particles.insert(propagated_charge->mc_particle_);
}
// Store the MC particle references
for(auto& mc_particle : unique_particles) {
mc_particles_.push_back(mc_particle);
}
}
PixelCharge::PixelCharge(Pixel pixel, Pulse pulse, std::vector<const PropagatedCharge*> propagated_charges)
: PixelCharge(std::move(pixel), pulse.getCharge(), std::move(propagated_charges)) {
pulse_ = std::move(pulse);
}
const Pixel& PixelCharge::getPixel() const {
return pixel_;
}
Pixel::Index PixelCharge::getIndex() const {
return getPixel().getIndex();
}
unsigned int PixelCharge::getCharge() const {
return charge_;
}
/**
* @throws MissingReferenceException If the pointed object is not in scope
*
* Objects are stored as vector of TRef and can only be accessed if pointed objects are in scope
*/
std::vector<const PropagatedCharge*> PixelCharge::getPropagatedCharges() const {
// FIXME: This is not very efficient unfortunately
std::vector<const PropagatedCharge*> propagated_charges;
for(auto& propagated_charge : propagated_charges_) {
if(!propagated_charge.IsValid() || propagated_charge.GetObject() == nullptr) {
throw MissingReferenceException(typeid(*this), typeid(PropagatedCharge));
}
propagated_charges.emplace_back(dynamic_cast<PropagatedCharge*>(propagated_charge.GetObject()));
}
return propagated_charges;
}
/**
* @throws MissingReferenceException If the pointed object is not in scope
*
* MCParticles can only be fetched if the full history of objects are in scope and stored
*/
std::vector<const MCParticle*> PixelCharge::getMCParticles() const {
std::vector<const MCParticle*> mc_particles;
for(auto& mc_particle : mc_particles_) {
if(!mc_particle.IsValid() || mc_particle.GetObject() == nullptr) {
throw MissingReferenceException(typeid(*this), typeid(MCParticle));
}
mc_particles.emplace_back(dynamic_cast<MCParticle*>(mc_particle.GetObject()));
}
// Return as a vector of mc particles
return mc_particles;
}
<|endoftext|>
|
<commit_before><commit_msg>x509_certificate_nss: remove unused ScopedCERTCertificate and ScopedCERTCertList<commit_after><|endoftext|>
|
<commit_before>// //////////////////////////////////////////////////////////////////////
// Import section
// //////////////////////////////////////////////////////////////////////
// STL
#include <cassert>
// Boost
#include <boost/make_shared.hpp>
// StdAir
#include <stdair/stdair_exceptions.hpp>
#include <stdair/basic/BasConst_Event.hpp>
#include <stdair/bom/EventStruct.hpp>
#include <stdair/bom/EventQueue.hpp>
#include <stdair/service/Logger.hpp>
namespace stdair {
// //////////////////////////////////////////////////////////////////////
EventQueue::EventQueue ()
: _key (DEFAULT_EVENT_QUEUE_ID), _parent (NULL),
_progressStatus (stdair::DEFAULT_PROGRESS_STATUS,
stdair::DEFAULT_PROGRESS_STATUS) {
}
// //////////////////////////////////////////////////////////////////////
EventQueue::EventQueue (const Key_T& iKey)
: _key (iKey), _parent (NULL),
_progressStatus (stdair::DEFAULT_PROGRESS_STATUS,
stdair::DEFAULT_PROGRESS_STATUS) {
}
// //////////////////////////////////////////////////////////////////////
EventQueue::EventQueue (const EventQueue& iEventQueue)
: _key (DEFAULT_EVENT_QUEUE_ID), _parent (NULL),
_progressStatus (stdair::DEFAULT_PROGRESS_STATUS,
stdair::DEFAULT_PROGRESS_STATUS) {
assert (false);
}
// //////////////////////////////////////////////////////////////////////
EventQueue::~EventQueue () {
_eventList.clear();
_nbOfEvents.clear();
}
// //////////////////////////////////////////////////////////////////////
std::string EventQueue::toString() const {
std::ostringstream oStr;
oStr << "(" << _eventList.size() << ") "
<< _progressStatus.getCurrentNb() << "/{"
<< _progressStatus.getExpectedNb() << ","
<< _progressStatus.getActualNb() << "}";
return oStr.str();
}
// //////////////////////////////////////////////////////////////////////
std::string EventQueue::display() const {
std::ostringstream oStr;
oStr << toString();
/*
* \note The following can be very consuming (in time, CPU and
* memory) when there are a lot of demand streams (e.g., several
* hundreds of thousands). Uncomment it only for debug purposes.
*/
unsigned int demandStreamIdx = 1;
for (NbOfEventsByDemandStreamMap_T::const_iterator itNbOfEventsMap =
_nbOfEvents.begin(); itNbOfEventsMap != _nbOfEvents.end();
++itNbOfEventsMap, ++demandStreamIdx) {
const DemandStreamKeyStr_T& lDemandStreyKeyStr = itNbOfEventsMap->first;
oStr << ", [" << demandStreamIdx << "][" << lDemandStreyKeyStr << "] ";
const ProgressStatus& lProgressStatus = itNbOfEventsMap->second;
oStr << lProgressStatus;
}
return oStr.str();
}
// //////////////////////////////////////////////////////////////////////
Count_T EventQueue::getQueueSize() const {
return _eventList.size();
}
// //////////////////////////////////////////////////////////////////////
bool EventQueue::isQueueEmpty() const {
return _eventList.empty();
}
// //////////////////////////////////////////////////////////////////////
bool EventQueue::isQueueDone() const {
const bool isQueueEmpty = _eventList.empty();
return isQueueEmpty;
}
// //////////////////////////////////////////////////////////////////////
void EventQueue::reset() {
// Reset only the current number of events, not the expected one
_progressStatus.setCurrentNb (DEFAULT_PROGRESS_STATUS);
//
//_holderMap.clear();
_eventList.clear();
_nbOfEvents.clear();
}
// //////////////////////////////////////////////////////////////////////
void EventQueue::
addStatus (const DemandStreamKeyStr_T& iDemandStreamKeyStr,
const NbOfRequests_T& iExpectedTotalNbOfEvents) {
/**
* \note After the initialisation of the event queue (e.g., by a
* call to the TRADEMGEN_Service::generateFirstRequests() method),
* there are, by construction, exactly as many events as distinct
* demand streams. Indeed, the event queue contains a single event
* structure for every demand stream.
*/
// Initialise the progress status object for the current demand stream
const Count_T lExpectedTotalNbOfEventsInt =
std::floor (iExpectedTotalNbOfEvents);
const ProgressStatus lProgressStatus (1, lExpectedTotalNbOfEventsInt,
lExpectedTotalNbOfEventsInt);
// Insert the (Boost) progress display object into the dedicated map
const bool hasInsertBeenSuccessful =
_nbOfEvents.insert (NbOfEventsByDemandStreamMap_T::
value_type (iDemandStreamKeyStr,
lProgressStatus)).second;
if (hasInsertBeenSuccessful == false) {
STDAIR_LOG_ERROR ("No progress_status can be inserted "
<< "for the following DemandStream: "
<< iDemandStreamKeyStr
<< ". EventQueue: " << toString());
throw EventException ("No progress_status can be inserted for the "
"following DemandStream: " + iDemandStreamKeyStr
+ ". EventQueue: " + toString());
}
// Update the overall progress status
_progressStatus.setExpectedNb (_progressStatus.getExpectedNb()
+ iExpectedTotalNbOfEvents);
_progressStatus.setActualNb (_progressStatus.getActualNb()
+ iExpectedTotalNbOfEvents);
}
// //////////////////////////////////////////////////////////////////////
ProgressStatus EventQueue::
getStatus (const DemandStreamKeyStr_T& iDemandStreamKey) const {
NbOfEventsByDemandStreamMap_T::const_iterator itNbOfEventsMap =
_nbOfEvents.find (iDemandStreamKey);
if (itNbOfEventsMap != _nbOfEvents.end()) {
const ProgressStatus& oProgressStatus = itNbOfEventsMap->second;
return oProgressStatus;
}
return ProgressStatus();
}
// //////////////////////////////////////////////////////////////////////
EventStruct EventQueue::popEvent() {
assert (_eventList.empty() == false);
// Get an iterator on the first event (sorted by date-time stamps)
EventList_T::iterator itEvent = _eventList.begin();
// Extract the corresponding Event structure
EventStruct lEventStruct = itEvent->second;
// Extract the key of the demand stream
const DemandStreamKeyStr_T& lDemandStreamKeyStr =
lEventStruct.getDemandStreamKey();
// Retrieve the progress status specific to that demand stream
const ProgressStatus& lProgressStatus = getStatus (lDemandStreamKeyStr);
// Update the progress status of the event structure, specific to
// the demand stream
lEventStruct.setSpecificStatus (lProgressStatus);
// Update the (current number part of the) overall progress
// status, to account for the event that is being popped out of
// the event queue
++_progressStatus;
// Update the overall progress status of the event structure
lEventStruct.setOverallStatus (_progressStatus);
// Remove the event, which has just been retrieved
_eventList.erase (itEvent);
//
return lEventStruct;
}
// //////////////////////////////////////////////////////////////////////
bool EventQueue::addEvent (EventStruct& ioEventStruct) {
bool insertionSucceeded =
_eventList.insert (EventListElement_T (ioEventStruct._eventTimeStamp,
ioEventStruct)).second;
/**
If the insertion has not been successful, try repeatedly until the
insertion becomes successful.
<br>The date-time is counted in milliseconds (1e-3 second). Hence,
one thousand (1e3) of attempts correspond to 1 second.
*/
const unsigned int idx = 0;
while (insertionSucceeded == false && idx != 1e3) {
// Retrieve the date-time stamp (expressed in milliseconds)
LongDuration_T& lEventTimeStamp (ioEventStruct._eventTimeStamp);
++lEventTimeStamp;
// Retry to insert into the event queue
insertionSucceeded =
_eventList.insert (EventListElement_T (ioEventStruct._eventTimeStamp,
ioEventStruct)).second;
}
// Extract the corresponding demand stream key
const DemandStreamKeyStr_T& lDemandStreamKeyStr =
ioEventStruct.getDemandStreamKey();
// Update the progress status for the corresponding demand stream
NbOfEventsByDemandStreamMap_T::iterator itNbOfEventsMap =
_nbOfEvents.find (lDemandStreamKeyStr);
if (itNbOfEventsMap != _nbOfEvents.end()) {
ProgressStatus& lProgressStatus = itNbOfEventsMap->second;
++lProgressStatus;
}
return insertionSucceeded;
}
}
<commit_msg>[StdAir][Dev] Just use the standard ProgressStatus::reset() method, from within EventQueue::reset().<commit_after>// //////////////////////////////////////////////////////////////////////
// Import section
// //////////////////////////////////////////////////////////////////////
// STL
#include <cassert>
// Boost
#include <boost/make_shared.hpp>
// StdAir
#include <stdair/stdair_exceptions.hpp>
#include <stdair/basic/BasConst_Event.hpp>
#include <stdair/bom/EventStruct.hpp>
#include <stdair/bom/EventQueue.hpp>
#include <stdair/service/Logger.hpp>
namespace stdair {
// //////////////////////////////////////////////////////////////////////
EventQueue::EventQueue()
: _key (DEFAULT_EVENT_QUEUE_ID), _parent (NULL),
_progressStatus (stdair::DEFAULT_PROGRESS_STATUS,
stdair::DEFAULT_PROGRESS_STATUS) {
}
// //////////////////////////////////////////////////////////////////////
EventQueue::EventQueue (const Key_T& iKey)
: _key (iKey), _parent (NULL),
_progressStatus (stdair::DEFAULT_PROGRESS_STATUS,
stdair::DEFAULT_PROGRESS_STATUS) {
}
// //////////////////////////////////////////////////////////////////////
EventQueue::EventQueue (const EventQueue& iEventQueue)
: _key (DEFAULT_EVENT_QUEUE_ID), _parent (NULL),
_progressStatus (stdair::DEFAULT_PROGRESS_STATUS,
stdair::DEFAULT_PROGRESS_STATUS) {
assert (false);
}
// //////////////////////////////////////////////////////////////////////
EventQueue::~EventQueue() {
_eventList.clear();
_nbOfEvents.clear();
}
// //////////////////////////////////////////////////////////////////////
std::string EventQueue::toString() const {
std::ostringstream oStr;
oStr << "(" << _eventList.size() << ") "
<< _progressStatus.getCurrentNb() << "/{"
<< _progressStatus.getExpectedNb() << ","
<< _progressStatus.getActualNb() << "}";
return oStr.str();
}
// //////////////////////////////////////////////////////////////////////
std::string EventQueue::display() const {
std::ostringstream oStr;
oStr << toString();
/*
* \note The following can be very consuming (in time, CPU and
* memory) when there are a lot of demand streams (e.g., several
* hundreds of thousands). Uncomment it only for debug purposes.
*/
unsigned int demandStreamIdx = 1;
for (NbOfEventsByDemandStreamMap_T::const_iterator itNbOfEventsMap =
_nbOfEvents.begin(); itNbOfEventsMap != _nbOfEvents.end();
++itNbOfEventsMap, ++demandStreamIdx) {
const DemandStreamKeyStr_T& lDemandStreyKeyStr = itNbOfEventsMap->first;
oStr << ", [" << demandStreamIdx << "][" << lDemandStreyKeyStr << "] ";
const ProgressStatus& lProgressStatus = itNbOfEventsMap->second;
oStr << lProgressStatus;
}
return oStr.str();
}
// //////////////////////////////////////////////////////////////////////
Count_T EventQueue::getQueueSize() const {
return _eventList.size();
}
// //////////////////////////////////////////////////////////////////////
bool EventQueue::isQueueEmpty() const {
return _eventList.empty();
}
// //////////////////////////////////////////////////////////////////////
bool EventQueue::isQueueDone() const {
const bool isQueueEmpty = _eventList.empty();
return isQueueEmpty;
}
// //////////////////////////////////////////////////////////////////////
void EventQueue::reset() {
// Reset only the current number of events, not the expected one
_progressStatus.reset();
//
_eventList.clear();
_nbOfEvents.clear();
}
// //////////////////////////////////////////////////////////////////////
void EventQueue::
addStatus (const DemandStreamKeyStr_T& iDemandStreamKeyStr,
const NbOfRequests_T& iExpectedTotalNbOfEvents) {
/**
* \note After the initialisation of the event queue (e.g., by a
* call to the TRADEMGEN_Service::generateFirstRequests() method),
* there are, by construction, exactly as many events as distinct
* demand streams. Indeed, the event queue contains a single event
* structure for every demand stream.
*/
// Initialise the progress status object for the current demand stream
const Count_T lExpectedTotalNbOfEventsInt =
std::floor (iExpectedTotalNbOfEvents);
const ProgressStatus lProgressStatus (1, lExpectedTotalNbOfEventsInt,
lExpectedTotalNbOfEventsInt);
// Insert the (Boost) progress display object into the dedicated map
const bool hasInsertBeenSuccessful =
_nbOfEvents.insert (NbOfEventsByDemandStreamMap_T::
value_type (iDemandStreamKeyStr,
lProgressStatus)).second;
if (hasInsertBeenSuccessful == false) {
STDAIR_LOG_ERROR ("No progress_status can be inserted "
<< "for the following DemandStream: "
<< iDemandStreamKeyStr
<< ". EventQueue: " << toString());
throw EventException ("No progress_status can be inserted for the "
"following DemandStream: " + iDemandStreamKeyStr
+ ". EventQueue: " + toString());
}
// Update the overall progress status
_progressStatus.setExpectedNb (_progressStatus.getExpectedNb()
+ iExpectedTotalNbOfEvents);
_progressStatus.setActualNb (_progressStatus.getActualNb()
+ iExpectedTotalNbOfEvents);
}
// //////////////////////////////////////////////////////////////////////
ProgressStatus EventQueue::
getStatus (const DemandStreamKeyStr_T& iDemandStreamKey) const {
NbOfEventsByDemandStreamMap_T::const_iterator itNbOfEventsMap =
_nbOfEvents.find (iDemandStreamKey);
if (itNbOfEventsMap != _nbOfEvents.end()) {
const ProgressStatus& oProgressStatus = itNbOfEventsMap->second;
return oProgressStatus;
}
return ProgressStatus();
}
// //////////////////////////////////////////////////////////////////////
EventStruct EventQueue::popEvent() {
assert (_eventList.empty() == false);
// Get an iterator on the first event (sorted by date-time stamps)
EventList_T::iterator itEvent = _eventList.begin();
// Extract the corresponding Event structure
EventStruct lEventStruct = itEvent->second;
// Extract the key of the demand stream
const DemandStreamKeyStr_T& lDemandStreamKeyStr =
lEventStruct.getDemandStreamKey();
// Retrieve the progress status specific to that demand stream
const ProgressStatus& lProgressStatus = getStatus (lDemandStreamKeyStr);
// Update the progress status of the event structure, specific to
// the demand stream
lEventStruct.setSpecificStatus (lProgressStatus);
// Update the (current number part of the) overall progress
// status, to account for the event that is being popped out of
// the event queue
++_progressStatus;
// Update the overall progress status of the event structure
lEventStruct.setOverallStatus (_progressStatus);
// Remove the event, which has just been retrieved
_eventList.erase (itEvent);
//
return lEventStruct;
}
// //////////////////////////////////////////////////////////////////////
bool EventQueue::addEvent (EventStruct& ioEventStruct) {
bool insertionSucceeded =
_eventList.insert (EventListElement_T (ioEventStruct._eventTimeStamp,
ioEventStruct)).second;
/**
If the insertion has not been successful, try repeatedly until the
insertion becomes successful.
<br>The date-time is counted in milliseconds (1e-3 second). Hence,
one thousand (1e3) of attempts correspond to 1 second.
*/
const unsigned int idx = 0;
while (insertionSucceeded == false && idx != 1e3) {
// Retrieve the date-time stamp (expressed in milliseconds)
LongDuration_T& lEventTimeStamp (ioEventStruct._eventTimeStamp);
++lEventTimeStamp;
// Retry to insert into the event queue
insertionSucceeded =
_eventList.insert (EventListElement_T (ioEventStruct._eventTimeStamp,
ioEventStruct)).second;
}
// Extract the corresponding demand stream key
const DemandStreamKeyStr_T& lDemandStreamKeyStr =
ioEventStruct.getDemandStreamKey();
// Update the progress status for the corresponding demand stream
NbOfEventsByDemandStreamMap_T::iterator itNbOfEventsMap =
_nbOfEvents.find (lDemandStreamKeyStr);
if (itNbOfEventsMap != _nbOfEvents.end()) {
ProgressStatus& lProgressStatus = itNbOfEventsMap->second;
++lProgressStatus;
}
return insertionSucceeded;
}
}
<|endoftext|>
|
<commit_before>// Copyright 2017 The Abseil Authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "absl/base/internal/raw_logging.h"
#include <stddef.h>
#include <cstdarg>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include "absl/base/config.h"
#include "absl/base/internal/atomic_hook.h"
#include "absl/base/log_severity.h"
// We know how to perform low-level writes to stderr in POSIX and Windows. For
// these platforms, we define the token ABSL_LOW_LEVEL_WRITE_SUPPORTED.
// Much of raw_logging.cc becomes a no-op when we can't output messages,
// although a FATAL ABSL_RAW_LOG message will still abort the process.
// ABSL_HAVE_POSIX_WRITE is defined when the platform provides posix write()
// (as from unistd.h)
//
// This preprocessor token is also defined in raw_io.cc. If you need to copy
// this, consider moving both to config.h instead.
#if defined(__linux__) || defined(__APPLE__) || defined(__FreeBSD__) || \
defined(__Fuchsia__)
#include <unistd.h>
#define ABSL_HAVE_POSIX_WRITE 1
#define ABSL_LOW_LEVEL_WRITE_SUPPORTED 1
#else
#undef ABSL_HAVE_POSIX_WRITE
#endif
// ABSL_HAVE_SYSCALL_WRITE is defined when the platform provides the syscall
// syscall(SYS_write, /*int*/ fd, /*char* */ buf, /*size_t*/ len);
// for low level operations that want to avoid libc.
#if (defined(__linux__) || defined(__FreeBSD__)) && !defined(__ANDROID__)
#include <sys/syscall.h>
#define ABSL_HAVE_SYSCALL_WRITE 1
#define ABSL_LOW_LEVEL_WRITE_SUPPORTED 1
#else
#undef ABSL_HAVE_SYSCALL_WRITE
#endif
#ifdef _WIN32
#include <io.h>
#define ABSL_HAVE_RAW_IO 1
#define ABSL_LOW_LEVEL_WRITE_SUPPORTED 1
#else
#undef ABSL_HAVE_RAW_IO
#endif
// TODO(gfalcon): We want raw-logging to work on as many platforms as possible.
// Explicitly #error out when not ABSL_LOW_LEVEL_WRITE_SUPPORTED, except for a
// whitelisted set of platforms for which we expect not to be able to raw log.
ABSL_CONST_INIT static absl::base_internal::AtomicHook<
absl::raw_logging_internal::LogPrefixHook> log_prefix_hook;
ABSL_CONST_INIT static absl::base_internal::AtomicHook<
absl::raw_logging_internal::AbortHook> abort_hook;
#ifdef ABSL_LOW_LEVEL_WRITE_SUPPORTED
static const char kTruncated[] = " ... (message truncated)\n";
// sprintf the format to the buffer, adjusting *buf and *size to reflect the
// consumed bytes, and return whether the message fit without truncation. If
// truncation occurred, if possible leave room in the buffer for the message
// kTruncated[].
inline static bool VADoRawLog(char** buf, int* size, const char* format,
va_list ap) ABSL_PRINTF_ATTRIBUTE(3, 0);
inline static bool VADoRawLog(char** buf, int* size,
const char* format, va_list ap) {
int n = vsnprintf(*buf, *size, format, ap);
bool result = true;
if (n < 0 || n > *size) {
result = false;
if (static_cast<size_t>(*size) > sizeof(kTruncated)) {
n = *size - sizeof(kTruncated); // room for truncation message
} else {
n = 0; // no room for truncation message
}
}
*size -= n;
*buf += n;
return result;
}
#endif // ABSL_LOW_LEVEL_WRITE_SUPPORTED
static constexpr int kLogBufSize = 3000;
namespace absl {
namespace raw_logging_internal {
void SafeWriteToStderr(const char *s, size_t len);
} // namespace raw_logging_internal
} // namespace absl
namespace {
// CAVEAT: vsnprintf called from *DoRawLog below has some (exotic) code paths
// that invoke malloc() and getenv() that might acquire some locks.
// Helper for RawLog below.
// *DoRawLog writes to *buf of *size and move them past the written portion.
// It returns true iff there was no overflow or error.
bool DoRawLog(char** buf, int* size, const char* format, ...)
ABSL_PRINTF_ATTRIBUTE(3, 4);
bool DoRawLog(char** buf, int* size, const char* format, ...) {
va_list ap;
va_start(ap, format);
int n = vsnprintf(*buf, *size, format, ap);
va_end(ap);
if (n < 0 || n > *size) return false;
*size -= n;
*buf += n;
return true;
}
void RawLogVA(absl::LogSeverity severity, const char* file, int line,
const char* format, va_list ap) ABSL_PRINTF_ATTRIBUTE(4, 0);
void RawLogVA(absl::LogSeverity severity, const char* file, int line,
const char* format, va_list ap) {
char buffer[kLogBufSize];
char* buf = buffer;
int size = sizeof(buffer);
#ifdef ABSL_LOW_LEVEL_WRITE_SUPPORTED
bool enabled = true;
#else
bool enabled = false;
#endif
#ifdef ABSL_MIN_LOG_LEVEL
if (static_cast<int>(severity) < ABSL_MIN_LOG_LEVEL &&
severity < absl::LogSeverity::kFatal) {
enabled = false;
}
#endif
auto log_prefix_hook_ptr = log_prefix_hook.Load();
if (log_prefix_hook_ptr) {
enabled = log_prefix_hook_ptr(severity, file, line, &buf, &size);
} else {
if (enabled) {
DoRawLog(&buf, &size, "[%s : %d] RAW: ", file, line);
}
}
const char* const prefix_end = buf;
#ifdef ABSL_LOW_LEVEL_WRITE_SUPPORTED
if (enabled) {
bool no_chop = VADoRawLog(&buf, &size, format, ap);
if (no_chop) {
DoRawLog(&buf, &size, "\n");
} else {
DoRawLog(&buf, &size, "%s", kTruncated);
}
absl::raw_logging_internal::SafeWriteToStderr(buffer, strlen(buffer));
}
#else
static_cast<void>(format);
static_cast<void>(ap);
#endif
// Abort the process after logging a FATAL message, even if the output itself
// was suppressed.
if (severity == absl::LogSeverity::kFatal) {
abort_hook(file, line, buffer, prefix_end, buffer + kLogBufSize);
abort();
}
}
} // namespace
namespace absl {
namespace raw_logging_internal {
// Writes the provided buffer directly to stderr, in a safe, low-level manner.
//
// In POSIX this means calling write(), which is async-signal safe and does
// not malloc. If the platform supports the SYS_write syscall, we invoke that
// directly to side-step any libc interception.
void SafeWriteToStderr(const char *s, size_t len) {
#if defined(ABSL_HAVE_SYSCALL_WRITE)
syscall(SYS_write, STDERR_FILENO, s, len);
#elif defined(ABSL_HAVE_POSIX_WRITE)
write(STDERR_FILENO, s, len);
#elif defined(ABSL_HAVE_RAW_IO)
_write(/* stderr */ 2, s, len);
#else
// stderr logging unsupported on this platform
(void) s;
(void) len;
#endif
}
void RawLog(absl::LogSeverity severity, const char* file, int line,
const char* format, ...) ABSL_PRINTF_ATTRIBUTE(4, 5);
void RawLog(absl::LogSeverity severity, const char* file, int line,
const char* format, ...) {
va_list ap;
va_start(ap, format);
RawLogVA(severity, file, line, format, ap);
va_end(ap);
}
bool RawLoggingFullySupported() {
#ifdef ABSL_LOW_LEVEL_WRITE_SUPPORTED
return true;
#else // !ABSL_LOW_LEVEL_WRITE_SUPPORTED
return false;
#endif // !ABSL_LOW_LEVEL_WRITE_SUPPORTED
}
} // namespace raw_logging_internal
} // namespace absl
<commit_msg>#include "absl/base/attributes.h"<commit_after>// Copyright 2017 The Abseil Authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "absl/base/internal/raw_logging.h"
#include <stddef.h>
#include <cstdarg>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include "absl/base/attributes.h"
#include "absl/base/config.h"
#include "absl/base/internal/atomic_hook.h"
#include "absl/base/log_severity.h"
// We know how to perform low-level writes to stderr in POSIX and Windows. For
// these platforms, we define the token ABSL_LOW_LEVEL_WRITE_SUPPORTED.
// Much of raw_logging.cc becomes a no-op when we can't output messages,
// although a FATAL ABSL_RAW_LOG message will still abort the process.
// ABSL_HAVE_POSIX_WRITE is defined when the platform provides posix write()
// (as from unistd.h)
//
// This preprocessor token is also defined in raw_io.cc. If you need to copy
// this, consider moving both to config.h instead.
#if defined(__linux__) || defined(__APPLE__) || defined(__FreeBSD__) || \
defined(__Fuchsia__)
#include <unistd.h>
#define ABSL_HAVE_POSIX_WRITE 1
#define ABSL_LOW_LEVEL_WRITE_SUPPORTED 1
#else
#undef ABSL_HAVE_POSIX_WRITE
#endif
// ABSL_HAVE_SYSCALL_WRITE is defined when the platform provides the syscall
// syscall(SYS_write, /*int*/ fd, /*char* */ buf, /*size_t*/ len);
// for low level operations that want to avoid libc.
#if (defined(__linux__) || defined(__FreeBSD__)) && !defined(__ANDROID__)
#include <sys/syscall.h>
#define ABSL_HAVE_SYSCALL_WRITE 1
#define ABSL_LOW_LEVEL_WRITE_SUPPORTED 1
#else
#undef ABSL_HAVE_SYSCALL_WRITE
#endif
#ifdef _WIN32
#include <io.h>
#define ABSL_HAVE_RAW_IO 1
#define ABSL_LOW_LEVEL_WRITE_SUPPORTED 1
#else
#undef ABSL_HAVE_RAW_IO
#endif
// TODO(gfalcon): We want raw-logging to work on as many platforms as possible.
// Explicitly #error out when not ABSL_LOW_LEVEL_WRITE_SUPPORTED, except for a
// whitelisted set of platforms for which we expect not to be able to raw log.
ABSL_CONST_INIT static absl::base_internal::AtomicHook<
absl::raw_logging_internal::LogPrefixHook> log_prefix_hook;
ABSL_CONST_INIT static absl::base_internal::AtomicHook<
absl::raw_logging_internal::AbortHook> abort_hook;
#ifdef ABSL_LOW_LEVEL_WRITE_SUPPORTED
static const char kTruncated[] = " ... (message truncated)\n";
// sprintf the format to the buffer, adjusting *buf and *size to reflect the
// consumed bytes, and return whether the message fit without truncation. If
// truncation occurred, if possible leave room in the buffer for the message
// kTruncated[].
inline static bool VADoRawLog(char** buf, int* size, const char* format,
va_list ap) ABSL_PRINTF_ATTRIBUTE(3, 0);
inline static bool VADoRawLog(char** buf, int* size,
const char* format, va_list ap) {
int n = vsnprintf(*buf, *size, format, ap);
bool result = true;
if (n < 0 || n > *size) {
result = false;
if (static_cast<size_t>(*size) > sizeof(kTruncated)) {
n = *size - sizeof(kTruncated); // room for truncation message
} else {
n = 0; // no room for truncation message
}
}
*size -= n;
*buf += n;
return result;
}
#endif // ABSL_LOW_LEVEL_WRITE_SUPPORTED
static constexpr int kLogBufSize = 3000;
namespace absl {
namespace raw_logging_internal {
void SafeWriteToStderr(const char *s, size_t len);
} // namespace raw_logging_internal
} // namespace absl
namespace {
// CAVEAT: vsnprintf called from *DoRawLog below has some (exotic) code paths
// that invoke malloc() and getenv() that might acquire some locks.
// Helper for RawLog below.
// *DoRawLog writes to *buf of *size and move them past the written portion.
// It returns true iff there was no overflow or error.
bool DoRawLog(char** buf, int* size, const char* format, ...)
ABSL_PRINTF_ATTRIBUTE(3, 4);
bool DoRawLog(char** buf, int* size, const char* format, ...) {
va_list ap;
va_start(ap, format);
int n = vsnprintf(*buf, *size, format, ap);
va_end(ap);
if (n < 0 || n > *size) return false;
*size -= n;
*buf += n;
return true;
}
void RawLogVA(absl::LogSeverity severity, const char* file, int line,
const char* format, va_list ap) ABSL_PRINTF_ATTRIBUTE(4, 0);
void RawLogVA(absl::LogSeverity severity, const char* file, int line,
const char* format, va_list ap) {
char buffer[kLogBufSize];
char* buf = buffer;
int size = sizeof(buffer);
#ifdef ABSL_LOW_LEVEL_WRITE_SUPPORTED
bool enabled = true;
#else
bool enabled = false;
#endif
#ifdef ABSL_MIN_LOG_LEVEL
if (static_cast<int>(severity) < ABSL_MIN_LOG_LEVEL &&
severity < absl::LogSeverity::kFatal) {
enabled = false;
}
#endif
auto log_prefix_hook_ptr = log_prefix_hook.Load();
if (log_prefix_hook_ptr) {
enabled = log_prefix_hook_ptr(severity, file, line, &buf, &size);
} else {
if (enabled) {
DoRawLog(&buf, &size, "[%s : %d] RAW: ", file, line);
}
}
const char* const prefix_end = buf;
#ifdef ABSL_LOW_LEVEL_WRITE_SUPPORTED
if (enabled) {
bool no_chop = VADoRawLog(&buf, &size, format, ap);
if (no_chop) {
DoRawLog(&buf, &size, "\n");
} else {
DoRawLog(&buf, &size, "%s", kTruncated);
}
absl::raw_logging_internal::SafeWriteToStderr(buffer, strlen(buffer));
}
#else
static_cast<void>(format);
static_cast<void>(ap);
#endif
// Abort the process after logging a FATAL message, even if the output itself
// was suppressed.
if (severity == absl::LogSeverity::kFatal) {
abort_hook(file, line, buffer, prefix_end, buffer + kLogBufSize);
abort();
}
}
} // namespace
namespace absl {
namespace raw_logging_internal {
// Writes the provided buffer directly to stderr, in a safe, low-level manner.
//
// In POSIX this means calling write(), which is async-signal safe and does
// not malloc. If the platform supports the SYS_write syscall, we invoke that
// directly to side-step any libc interception.
void SafeWriteToStderr(const char *s, size_t len) {
#if defined(ABSL_HAVE_SYSCALL_WRITE)
syscall(SYS_write, STDERR_FILENO, s, len);
#elif defined(ABSL_HAVE_POSIX_WRITE)
write(STDERR_FILENO, s, len);
#elif defined(ABSL_HAVE_RAW_IO)
_write(/* stderr */ 2, s, len);
#else
// stderr logging unsupported on this platform
(void) s;
(void) len;
#endif
}
void RawLog(absl::LogSeverity severity, const char* file, int line,
const char* format, ...) ABSL_PRINTF_ATTRIBUTE(4, 5);
void RawLog(absl::LogSeverity severity, const char* file, int line,
const char* format, ...) {
va_list ap;
va_start(ap, format);
RawLogVA(severity, file, line, format, ap);
va_end(ap);
}
bool RawLoggingFullySupported() {
#ifdef ABSL_LOW_LEVEL_WRITE_SUPPORTED
return true;
#else // !ABSL_LOW_LEVEL_WRITE_SUPPORTED
return false;
#endif // !ABSL_LOW_LEVEL_WRITE_SUPPORTED
}
} // namespace raw_logging_internal
} // namespace absl
<|endoftext|>
|
<commit_before>/*!
\copyright (c) RDO-Team, 2011
\file rdo_resource.cpp
\authors Урусов Андрей ([email protected])
\authors Лущан Дмитрий ([email protected])
\date 16.04.2008
\brief RDOResource implementation
\indent 4T
*/
// ---------------------------------------------------------------------------- PCH
#include "simulator/runtime/pch/stdpch.h"
// ----------------------------------------------------------------------- INCLUDES
#include <boost/foreach.hpp>
// ----------------------------------------------------------------------- SYNOPSIS
#include "simulator/runtime/rdo_resource.h"
#include "simulator/runtime/rdo_runtime.h"
// --------------------------------------------------------------------------------
OPEN_RDO_RUNTIME_NAMESPACE
// --------------------------------------------------------------------------------
// -------------------- RDOResource
// --------------------------------------------------------------------------------
RDOResource::RDOResource(CREF(LPRDORuntime) pRuntime, CREF(ParamList) paramList, LPIResourceType pResType, ruint resID, ruint typeID, rbool trace, rbool temporary)
: RDORuntimeObject ( )
, RDOTraceableObject (trace, resID, rdo::toString(resID + 1))
, m_temporary (temporary )
, m_state (RDOResource::CS_None )
, m_type (typeID )
, m_referenceCount (0 )
, m_resType (pResType )
, m_db (pRuntime->getDB() )
{
appendParams(paramList.begin(), paramList.end());
}
/// @todo копирующий конструктор не используется - нужен ли он?
RDOResource::RDOResource(CREF(LPRDORuntime) pRuntime, CREF(RDOResource) copy)
: RDORuntimeObject ( )
, RDOTraceableObject (copy.traceable(), copy.getTraceID(), copy.traceId())
, m_paramList (copy.m_paramList )
, m_temporary (copy.m_temporary )
, m_state (copy.m_state )
, m_type (copy.m_type )
, m_referenceCount (0 )
, m_resType (copy.m_resType )
, m_typeId (copy.m_typeId )
{
UNUSED(pRuntime);
appendParams(copy.m_paramList.begin(), copy.m_paramList.end());
/// @todo посмотреть history и принять решение о комментарии
// getRuntime()->incrementResourceIdReference( getTraceID() );
}
RDOResource::~RDOResource()
{}
rbool RDOResource::operator!= (RDOResource &other)
{
if (m_type != other.m_type) return true;
if (m_paramList.size() != other.m_paramList.size()) return true;
int size = m_paramList.size();
for (int i = 0; i < size; ++i)
{
if (m_paramList.at(i) != other.m_paramList.at(i)) return true;
}
return false;
}
LPRDOResource RDOResource::clone(CREF(LPRDORuntime) pRuntime) const
{
LPRDOResource pResource = rdo::Factory<RDOResource>::create(pRuntime, m_paramList, m_resType, getTraceID(), m_type, traceable(), m_temporary);
ASSERT(pResource);
pRuntime->insertNewResource(pResource);
return pResource;
}
tstring RDOResource::getTypeId() const
{
rdo::ostringstream str;
str << m_type;
return str.str();
}
tstring RDOResource::traceParametersValue()
{
rdo::ostringstream str;
if(m_paramList.size() > 0)
{
ParamList::iterator end = m_paramList.end();
for (ParamList::iterator it = m_paramList.begin();;)
{
#ifdef RDOSIM_COMPATIBLE
rdo::ostringstream _str;
_str << *it;
tstring::size_type pos = _str.str().find("e");
if (pos != tstring::npos)
{
tstring __str = _str.str();
__str.erase(pos + 2, 1);
str << __str.c_str();
}
else
{
str << _str.str().c_str();
}
#else
str << *it;
#endif
if (++it == end)
break;
str << " ";
}
}
return str.str();
}
tstring RDOResource::traceResourceState(char prefix, CREF(LPRDORuntime) pRuntime)
{
rdo::ostringstream res;
if (traceable() || (prefix != '\0'))
{
if (m_state == RDOResource::CS_NoChange || m_state == RDOResource::CS_NonExist)
return "";
if (prefix != '\0')
res << prefix;
switch (m_state)
{
case RDOResource::CS_Create:
res << "RC ";
break;
case RDOResource::CS_Erase:
res << "RE "
#ifdef RDOSIM_COMPATIBLE
<< pRuntime->getCurrentTime() << " "
<< traceTypeId() << " "
<< traceId() << std::endl;
return res.str();
#else
;
#endif
break;
default:
res << "RK ";
break;
}
res << pRuntime->getCurrentTime() << " "
<< traceTypeId() << " "
<< traceId() << " "
<< traceParametersValue() << std::endl;
}
return res.str();
}
void RDOResource::setParam(ruint index, CREF(RDOValue) value)
{
QSqlQuery query;
query.exec(QString("select rss_param.value, pg_class.relname \
from rss_param, pg_class, rdo_value \
where rss_param.rss_id=%1 \
and rss_param.id=%2 \
and pg_class.relfilenode=rdo_value.table_id \
and rdo_value.value_id=rss_param.value;")
.arg(getTraceID())
.arg(index));
query.next();
int value_id = query.value(query.record().indexOf("value")).toInt();
QString table_name = query.value(query.record().indexOf("relname")).toString();
#define DEFINE_RDO_VALUE(Value) \
m_db->queryExec(QString("update %1 set vv=%2 where id=%3")\
.arg(table_name) \
.arg(Value) \
.arg(value_id));
switch (value.typeID())
{
case RDOType::t_unknow : break;
case RDOType::t_int : DEFINE_RDO_VALUE( value.getInt () ); break;
case RDOType::t_real : DEFINE_RDO_VALUE( value.getDouble () ); break;
case RDOType::t_enum : DEFINE_RDO_VALUE(QString("'%1'").arg(QString::fromStdString(value.getAsString()))); break;
case RDOType::t_bool : DEFINE_RDO_VALUE(QString("'%1'").arg(QString::fromStdString(value.getAsString()))); break;
case RDOType::t_string : DEFINE_RDO_VALUE(QString("'%1'").arg(QString::fromStdString(value.getString ()))); break;
case RDOType::t_identificator : DEFINE_RDO_VALUE(QString("'%1'").arg(QString::fromStdString(value.getAsString()))); break;
default : throw RDOValueException("Данная величина не может быть записана в базу данных");
}
ASSERT(index < m_paramList.size());
setState(CS_Keep);
m_paramList[index] = value;
}
CREF(RDOValue) RDOResource::getParam(ruint index)
{
ASSERT(index < m_paramList.size());
#ifndef DB_CACHE_ENABLE
QSqlQuery query;
int traceID = getTraceID();
query.exec(QString("select value from rss_param where rss_id=%1 and id=%2;")
.arg(traceID)
.arg(index));
query.next();
int value_id = query.value(query.record().indexOf("value")).toInt();
query.exec(QString("select relname from pg_class, rdo_value where pg_class.relfilenode=rdo_value.table_id and rdo_value.value_id=%1;")
.arg(value_id));
query.next();
QString table_name = query.value(query.record().indexOf("relname")).toString();
query.exec(QString("select vv from %1 where id=%2;")
.arg(table_name)
.arg(value_id));
query.next();
QVariant varValue = query.value(query.record().indexOf("vv"));
if (table_name == QString("int_rv"))
{
int varValueInt = varValue.toInt();
if (varValueInt != m_paramList[index].getInt())
{
m_paramList[index] = RDOValue(varValueInt);
}
}
else if (table_name == QString("real_rv"))
{
double varValueDouble = varValue.toDouble();
if (varValueDouble != m_paramList[index].getDouble())
{
m_paramList[index] = RDOValue(varValueDouble);
}
}
else if (table_name == QString("enum_rv"))
{
tstring varValueEnum = varValue.toString().toStdString();
if (varValueEnum != m_paramList[index].getAsString())
{
m_paramList[index] = RDOValue(m_paramList[index].type().object_static_cast<RDOEnumType>(),varValueEnum);
}
}
else if (table_name == QString("bool_rv"))
{
bool varValueBool = varValue.toBool();
if (varValueBool != m_paramList[index].getBool())
{
m_paramList[index] = RDOValue(varValueBool);
}
}
else if (table_name == QString("string_rv"))
{
tstring varValueString = varValue.toString().toStdString();
if (varValueString != m_paramList[index].getString())
{
m_paramList[index] = RDOValue(varValueString);
}
}
else if (table_name == QString("identificator_rv"))
{
tstring varValueIdentificator = varValue.toString().toStdString();
if (varValueIdentificator != m_paramList[index].getIdentificator())
{
m_paramList[index] = RDOValue(varValueIdentificator);
}
}
#endif
return m_paramList[index];
}
void RDOResource::serializeInDB() const
{
int rss_id = m_db->insertRowInd("rss",QString("%1,%2,%3")
.arg(getTraceID())
.arg(boost::lexical_cast<int>(getTypeId()))
.arg(traceable() ? "true" : "false"));
int param_id = -1;
BOOST_FOREACH(const RDOValue& param, m_paramList)
{
param.serializeInDB(*m_db);
m_db->insertRow("rss_param",QString("%1,%2,%3")
.arg(rss_id)
.arg(++param_id)
.arg(m_db->popContext<int>()));
}
}
CLOSE_RDO_RUNTIME_NAMESPACE
<commit_msg> - оптимизация запроса<commit_after>/*!
\copyright (c) RDO-Team, 2011
\file rdo_resource.cpp
\authors Урусов Андрей ([email protected])
\authors Лущан Дмитрий ([email protected])
\date 16.04.2008
\brief RDOResource implementation
\indent 4T
*/
// ---------------------------------------------------------------------------- PCH
#include "simulator/runtime/pch/stdpch.h"
// ----------------------------------------------------------------------- INCLUDES
#include <boost/foreach.hpp>
// ----------------------------------------------------------------------- SYNOPSIS
#include "simulator/runtime/rdo_resource.h"
#include "simulator/runtime/rdo_runtime.h"
// --------------------------------------------------------------------------------
OPEN_RDO_RUNTIME_NAMESPACE
// --------------------------------------------------------------------------------
// -------------------- RDOResource
// --------------------------------------------------------------------------------
RDOResource::RDOResource(CREF(LPRDORuntime) pRuntime, CREF(ParamList) paramList, LPIResourceType pResType, ruint resID, ruint typeID, rbool trace, rbool temporary)
: RDORuntimeObject ( )
, RDOTraceableObject (trace, resID, rdo::toString(resID + 1))
, m_temporary (temporary )
, m_state (RDOResource::CS_None )
, m_type (typeID )
, m_referenceCount (0 )
, m_resType (pResType )
, m_db (pRuntime->getDB() )
{
appendParams(paramList.begin(), paramList.end());
}
/// @todo копирующий конструктор не используется - нужен ли он?
RDOResource::RDOResource(CREF(LPRDORuntime) pRuntime, CREF(RDOResource) copy)
: RDORuntimeObject ( )
, RDOTraceableObject (copy.traceable(), copy.getTraceID(), copy.traceId())
, m_paramList (copy.m_paramList )
, m_temporary (copy.m_temporary )
, m_state (copy.m_state )
, m_type (copy.m_type )
, m_referenceCount (0 )
, m_resType (copy.m_resType )
, m_typeId (copy.m_typeId )
{
UNUSED(pRuntime);
appendParams(copy.m_paramList.begin(), copy.m_paramList.end());
/// @todo посмотреть history и принять решение о комментарии
// getRuntime()->incrementResourceIdReference( getTraceID() );
}
RDOResource::~RDOResource()
{}
rbool RDOResource::operator!= (RDOResource &other)
{
if (m_type != other.m_type) return true;
if (m_paramList.size() != other.m_paramList.size()) return true;
int size = m_paramList.size();
for (int i = 0; i < size; ++i)
{
if (m_paramList.at(i) != other.m_paramList.at(i)) return true;
}
return false;
}
LPRDOResource RDOResource::clone(CREF(LPRDORuntime) pRuntime) const
{
LPRDOResource pResource = rdo::Factory<RDOResource>::create(pRuntime, m_paramList, m_resType, getTraceID(), m_type, traceable(), m_temporary);
ASSERT(pResource);
pRuntime->insertNewResource(pResource);
return pResource;
}
tstring RDOResource::getTypeId() const
{
rdo::ostringstream str;
str << m_type;
return str.str();
}
tstring RDOResource::traceParametersValue()
{
rdo::ostringstream str;
if(m_paramList.size() > 0)
{
ParamList::iterator end = m_paramList.end();
for (ParamList::iterator it = m_paramList.begin();;)
{
#ifdef RDOSIM_COMPATIBLE
rdo::ostringstream _str;
_str << *it;
tstring::size_type pos = _str.str().find("e");
if (pos != tstring::npos)
{
tstring __str = _str.str();
__str.erase(pos + 2, 1);
str << __str.c_str();
}
else
{
str << _str.str().c_str();
}
#else
str << *it;
#endif
if (++it == end)
break;
str << " ";
}
}
return str.str();
}
tstring RDOResource::traceResourceState(char prefix, CREF(LPRDORuntime) pRuntime)
{
rdo::ostringstream res;
if (traceable() || (prefix != '\0'))
{
if (m_state == RDOResource::CS_NoChange || m_state == RDOResource::CS_NonExist)
return "";
if (prefix != '\0')
res << prefix;
switch (m_state)
{
case RDOResource::CS_Create:
res << "RC ";
break;
case RDOResource::CS_Erase:
res << "RE "
#ifdef RDOSIM_COMPATIBLE
<< pRuntime->getCurrentTime() << " "
<< traceTypeId() << " "
<< traceId() << std::endl;
return res.str();
#else
;
#endif
break;
default:
res << "RK ";
break;
}
res << pRuntime->getCurrentTime() << " "
<< traceTypeId() << " "
<< traceId() << " "
<< traceParametersValue() << std::endl;
}
return res.str();
}
void RDOResource::setParam(ruint index, CREF(RDOValue) value)
{
QSqlQuery query;
query.exec(QString("select rss_param.value, pg_class.relname \
from rss_param, pg_class, rdo_value \
where rss_param.rss_id=%1 \
and rss_param.id=%2 \
and pg_class.relfilenode=rdo_value.table_id \
and rdo_value.value_id=rss_param.value;")
.arg(getTraceID())
.arg(index));
query.next();
int value_id = query.value(query.record().indexOf("value")).toInt();
QString table_name = query.value(query.record().indexOf("relname")).toString();
#define DEFINE_RDO_VALUE(Value) \
m_db->queryExec(QString("update %1 set vv=%2 where id=%3")\
.arg(table_name) \
.arg(Value) \
.arg(value_id));
switch (value.typeID())
{
case RDOType::t_unknow : break;
case RDOType::t_int : DEFINE_RDO_VALUE( value.getInt () ); break;
case RDOType::t_real : DEFINE_RDO_VALUE( value.getDouble () ); break;
case RDOType::t_enum : DEFINE_RDO_VALUE(QString("'%1'").arg(QString::fromStdString(value.getAsString()))); break;
case RDOType::t_bool : DEFINE_RDO_VALUE(QString("'%1'").arg(QString::fromStdString(value.getAsString()))); break;
case RDOType::t_string : DEFINE_RDO_VALUE(QString("'%1'").arg(QString::fromStdString(value.getString ()))); break;
case RDOType::t_identificator : DEFINE_RDO_VALUE(QString("'%1'").arg(QString::fromStdString(value.getAsString()))); break;
default : throw RDOValueException("Данная величина не может быть записана в базу данных");
}
ASSERT(index < m_paramList.size());
setState(CS_Keep);
m_paramList[index] = value;
}
CREF(RDOValue) RDOResource::getParam(ruint index)
{
ASSERT(index < m_paramList.size());
#ifndef DB_CACHE_ENABLE
QSqlQuery query;
query.exec(QString("select rss_param.value, pg_class.relname \
from rss_param, pg_class, rdo_value \
where rss_param.rss_id=%1 \
and rss_param.id=%2 \
and pg_class.relfilenode=rdo_value.table_id \
and rdo_value.value_id=rss_param.value;")
.arg(getTraceID())
.arg(index));
query.next();
int value_id = query.value(query.record().indexOf("value")).toInt();
QString table_name = query.value(query.record().indexOf("relname")).toString();
query.exec(QString("select vv from %1 where id=%2;")
.arg(table_name)
.arg(value_id));
query.next();
QVariant varValue = query.value(query.record().indexOf("vv"));
if (table_name == QString("int_rv"))
{
int varValueInt = varValue.toInt();
if (varValueInt != m_paramList[index].getInt())
{
m_paramList[index] = RDOValue(varValueInt);
}
}
else if (table_name == QString("real_rv"))
{
double varValueDouble = varValue.toDouble();
if (varValueDouble != m_paramList[index].getDouble())
{
m_paramList[index] = RDOValue(varValueDouble);
}
}
else if (table_name == QString("enum_rv"))
{
tstring varValueEnum = varValue.toString().toStdString();
if (varValueEnum != m_paramList[index].getAsString())
{
m_paramList[index] = RDOValue(m_paramList[index].type().object_static_cast<RDOEnumType>(),varValueEnum);
}
}
else if (table_name == QString("bool_rv"))
{
bool varValueBool = varValue.toBool();
if (varValueBool != m_paramList[index].getBool())
{
m_paramList[index] = RDOValue(varValueBool);
}
}
else if (table_name == QString("string_rv"))
{
tstring varValueString = varValue.toString().toStdString();
if (varValueString != m_paramList[index].getString())
{
m_paramList[index] = RDOValue(varValueString);
}
}
else if (table_name == QString("identificator_rv"))
{
tstring varValueIdentificator = varValue.toString().toStdString();
if (varValueIdentificator != m_paramList[index].getIdentificator())
{
m_paramList[index] = RDOValue(varValueIdentificator);
}
}
#endif
return m_paramList[index];
}
void RDOResource::serializeInDB() const
{
int rss_id = m_db->insertRowInd("rss",QString("%1,%2,%3")
.arg(getTraceID())
.arg(boost::lexical_cast<int>(getTypeId()))
.arg(traceable() ? "true" : "false"));
int param_id = -1;
BOOST_FOREACH(const RDOValue& param, m_paramList)
{
param.serializeInDB(*m_db);
m_db->insertRow("rss_param",QString("%1,%2,%3")
.arg(rss_id)
.arg(++param_id)
.arg(m_db->popContext<int>()));
}
}
CLOSE_RDO_RUNTIME_NAMESPACE
<|endoftext|>
|
<commit_before>#ifndef NEU_BIAS_LAYER_KERNEL_SOURCE_HPP
#define NEU_BIAS_LAYER_KERNEL_SOURCE_HPP
//20151023
#include <boost/compute/utility/source.hpp>
namespace neu {
constexpr char bias_forward_kernel_source[] = BOOST_COMPUTE_STRINGIZE_SOURCE(
__kernel void forward(
const __global float* input, const int input_offset,
__global float* output, const int output_offset,
const __global float* bias,
const int input_dim)
{
const int b = get_global_id(1);
const int o = get_global_id(0);
const int index = o+input_dim*b;
output[index+output_offset] = input[index+input_offset] + bias[o];
}
);
constexpr char bias_update_kernel_source[] = BOOST_COMPUTE_STRINGIZE_SOURCE(
__kernel void update(
const __global float* delta,
__global float* del_bias,
const int input_dim, const int batch_size)
{
const int o = get_global_id(0);
float bias_sum = 0.0;
for(int b = 0; b < batch_size; ++b) {
bias_sum += delta[o+input_dim*b];
}
del_bias[o] = bias_sum/batch_size;
}
);
}// namespace neu
#endif //NEU_BIAS_LAYER_KERNEL_SOURCE_HPP
<commit_msg>fix bias kernel implicit comversion of float<commit_after>#ifndef NEU_BIAS_LAYER_KERNEL_SOURCE_HPP
#define NEU_BIAS_LAYER_KERNEL_SOURCE_HPP
//20151023
#include <boost/compute/utility/source.hpp>
namespace neu {
constexpr char bias_forward_kernel_source[] = BOOST_COMPUTE_STRINGIZE_SOURCE(
__kernel void forward(
const __global float* input, const int input_offset,
__global float* output, const int output_offset,
const __global float* bias,
const int input_dim)
{
const int b = get_global_id(1);
const int o = get_global_id(0);
const int index = o+input_dim*b;
output[index+output_offset] = input[index+input_offset] + bias[o];
}
);
constexpr char bias_update_kernel_source[] = BOOST_COMPUTE_STRINGIZE_SOURCE(
__kernel void update(
const __global float* delta,
__global float* del_bias,
const int input_dim, const int batch_size)
{
const int o = get_global_id(0);
float bias_sum = 0.f;
for(int b = 0; b < batch_size; ++b) {
bias_sum += delta[o+input_dim*b];
}
del_bias[o] = bias_sum/batch_size;
}
);
}// namespace neu
#endif //NEU_BIAS_LAYER_KERNEL_SOURCE_HPP
<|endoftext|>
|
<commit_before><commit_msg>fdo#43556 round pos&dim of report controls & sections to nearest 10^-4m<commit_after><|endoftext|>
|
<commit_before>#include "app.h"
#include "stdio.h"
#include <stdarg.h> // for va_start, etc
#include <memory> // for std::unique_ptr
#include <GLFW/glfw3.h> // for glVertex3f, etc
#include <Eigen/Geometry> // for cross product
using namespace Eigen;
void App::initialize() {
// set up lights
const GLfloat light_position0[] = { 0.0, 0.0, -10.0, 1.0 };
const GLfloat light_diffuse0[] = { 0.1, 0.1, 0.1, 1.0 };
const GLfloat light_position1[] = { 0.0, 0.0, 10.0, 1.0 };
const GLfloat light_diffuse1[] = { 0.4, 0.4, 1.0, 1.0 };
const GLfloat light_specular1[] = { 0.5, 0.5, 0.5, 1.0 };
glClearColor (0.0, 0.0, 0.0, 0.0);
glShadeModel (GL_FLAT);
glEnable(GL_LIGHTING);
glLightfv(GL_LIGHT0, GL_POSITION, light_position0);
glLightfv(GL_LIGHT0, GL_DIFFUSE, light_diffuse0);
glEnable(GL_LIGHT0);
glLightfv(GL_LIGHT1, GL_POSITION, light_position1);
glLightfv(GL_LIGHT1, GL_DIFFUSE, light_diffuse1);
glLightfv(GL_LIGHT1, GL_SPECULAR, light_specular1);
glEnable(GL_LIGHT1);
glEnable(GL_DEPTH_TEST);
// set up terrain
noise.set_amplitude(3.0f);
log("The amplitude is %g\n", noise.get_amplitude());
for(float i=-width; i<=width+0.005; i+=0.1f) {
std::vector<Eigen::Vector3f> row;
for(float j=-height; j<=height+0.005; j+= 0.1f) {
Vector3f vert(i, j, noise.get_height2D(i, j));
//log("vert: (%f, %f, %f)\n", vert[0], vert[1], vert[2]);
row.push_back(vert);
}
vertices.push_back(row);
}
// set up camera
camera_roll = 30.0f;
camera_pitch = 70.0f;
camera_position = Vector3f(0, 0, 0);
}
void App::update(double delta) {
float mvmt_speed = 30.0f;
float cspeed = 1.0f;
if (keys_pressed.up) {
if (keys_pressed.shift) {
camera_position += Vector3f(0, cspeed, 0)*delta;
} else {
camera_pitch += mvmt_speed*delta;
}
}
if (keys_pressed.down) {
if (keys_pressed.shift) {
camera_position -= Vector3f(0, cspeed, 0)*delta;
} else {
camera_pitch -= mvmt_speed*delta;
}
}
if (keys_pressed.left) {
if (keys_pressed.shift) {
camera_position -= Vector3f(cspeed, 0, 0)*delta;
} else {
camera_roll -= mvmt_speed*delta;
}
}
if (keys_pressed.right) {
if (keys_pressed.shift) {
camera_position += Vector3f(cspeed, 0, 0)*delta;
} else {
camera_roll += mvmt_speed*delta;
}
}
}
void App::draw() {
// draw each quad
for(int i=0; i<vertices.size()-1; i++) {
for(int j=0; j<vertices[i].size()-1; j++) {
Vector3f bl = vertices[i][j];
Vector3f br = vertices[i+1][j];
Vector3f tl = vertices[i][j+1];
Vector3f tr = vertices[i+1][j+1];
Vector3f n0 = (br - bl).cross(tl - bl);
n0.normalize();
glBegin(GL_QUADS);
glNormal3f(n0[0], n0[1], n0[2]);
// counter-clockwise order
glVertex3f(bl[0], bl[1], bl[2]);
glVertex3f(br[0], br[1], br[2]);
glVertex3f(tr[0], tr[1], tr[2]);
glVertex3f(tl[0], tl[1], tl[2]);
glEnd();
}
}
}
void log(const std::string fmt_str, ...) {
int final_n, n = fmt_str.size() * 2; /* reserve 2 times as much as the length of the fmt_str */
std::string str;
std::unique_ptr<char[]> formatted;
va_list ap;
while(1) {
formatted.reset(new char[n]); /* wrap the plain char array into the unique_ptr */
strcpy(&formatted[0], fmt_str.c_str());
va_start(ap, fmt_str);
final_n = vsnprintf(&formatted[0], n, fmt_str.c_str(), ap);
va_end(ap);
if (final_n < 0 || final_n >= n)
n += abs(final_n - n + 1);
else
break;
}
fputs(formatted.get(), stderr);
}
<commit_msg>control tuning<commit_after>#include "app.h"
#include "stdio.h"
#include <stdarg.h> // for va_start, etc
#include <memory> // for std::unique_ptr
#include <GLFW/glfw3.h> // for glVertex3f, etc
#include <Eigen/Geometry> // for cross product
using namespace Eigen;
void App::initialize() {
// set up lights
const GLfloat light_position0[] = { 0.0, 0.0, -10.0, 1.0 };
const GLfloat light_diffuse0[] = { 0.1, 0.1, 0.1, 1.0 };
const GLfloat light_position1[] = { 0.0, 0.0, 10.0, 1.0 };
const GLfloat light_diffuse1[] = { 0.4, 0.4, 1.0, 1.0 };
const GLfloat light_specular1[] = { 0.5, 0.5, 0.5, 1.0 };
glClearColor (0.0, 0.0, 0.0, 0.0);
glShadeModel (GL_FLAT);
glEnable(GL_LIGHTING);
glLightfv(GL_LIGHT0, GL_POSITION, light_position0);
glLightfv(GL_LIGHT0, GL_DIFFUSE, light_diffuse0);
glEnable(GL_LIGHT0);
glLightfv(GL_LIGHT1, GL_POSITION, light_position1);
glLightfv(GL_LIGHT1, GL_DIFFUSE, light_diffuse1);
glLightfv(GL_LIGHT1, GL_SPECULAR, light_specular1);
glEnable(GL_LIGHT1);
glEnable(GL_DEPTH_TEST);
// set up terrain
noise.set_amplitude(3.0f);
log("The amplitude is %g\n", noise.get_amplitude());
for(float i=-width; i<=width+0.005; i+=0.1f) {
std::vector<Eigen::Vector3f> row;
for(float j=-height; j<=height+0.005; j+= 0.1f) {
Vector3f vert(i, j, noise.get_height2D(i, j));
//log("vert: (%f, %f, %f)\n", vert[0], vert[1], vert[2]);
row.push_back(vert);
}
vertices.push_back(row);
}
// set up camera
camera_roll = 30.0f;
camera_pitch = 70.0f;
camera_position = Vector3f(0, 0, 0);
}
void App::update(double delta) {
float mvmt_speed = 20.0f;
float cspeed = 0.7f;
if (keys_pressed.up) {
if (keys_pressed.shift) {
camera_position += Vector3f(0, cspeed, 0)*delta;
} else {
camera_pitch += mvmt_speed*delta;
}
}
if (keys_pressed.down) {
if (keys_pressed.shift) {
camera_position -= Vector3f(0, cspeed, 0)*delta;
} else {
camera_pitch -= mvmt_speed*delta;
}
}
if (keys_pressed.left) {
if (keys_pressed.shift) {
camera_position -= Vector3f(cspeed, 0, 0)*delta;
} else {
camera_roll -= mvmt_speed*delta;
}
}
if (keys_pressed.right) {
if (keys_pressed.shift) {
camera_position += Vector3f(cspeed, 0, 0)*delta;
} else {
camera_roll += mvmt_speed*delta;
}
}
}
void App::draw() {
// draw each quad
for(int i=0; i<vertices.size()-1; i++) {
for(int j=0; j<vertices[i].size()-1; j++) {
Vector3f bl = vertices[i][j];
Vector3f br = vertices[i+1][j];
Vector3f tl = vertices[i][j+1];
Vector3f tr = vertices[i+1][j+1];
Vector3f n0 = (br - bl).cross(tl - bl);
n0.normalize();
glBegin(GL_QUADS);
glNormal3f(n0[0], n0[1], n0[2]);
// counter-clockwise order
glVertex3f(bl[0], bl[1], bl[2]);
glVertex3f(br[0], br[1], br[2]);
glVertex3f(tr[0], tr[1], tr[2]);
glVertex3f(tl[0], tl[1], tl[2]);
glEnd();
}
}
}
void log(const std::string fmt_str, ...) {
int final_n, n = fmt_str.size() * 2; /* reserve 2 times as much as the length of the fmt_str */
std::string str;
std::unique_ptr<char[]> formatted;
va_list ap;
while(1) {
formatted.reset(new char[n]); /* wrap the plain char array into the unique_ptr */
strcpy(&formatted[0], fmt_str.c_str());
va_start(ap, fmt_str);
final_n = vsnprintf(&formatted[0], n, fmt_str.c_str(), ap);
va_end(ap);
if (final_n < 0 || final_n >= n)
n += abs(final_n - n + 1);
else
break;
}
fputs(formatted.get(), stderr);
}
<|endoftext|>
|
<commit_before>#ifndef __SOTA_AST__
#define __SOTA_AST__ = 1
#include <string>
#include <vector>
#include <iostream>
#include "z2h/ast.hpp"
#include "z2h/token.hpp"
namespace sota {
inline void sepby(std::ostream &os, std::string sep, std::vector<z2h::Ast *> items) {
if (items.size()) {
size_t i = 0;
for (; i < items.size() - 1; ++i) {
os << *items[i] << sep;
}
os << *items[i];
}
}
struct NewlineAst : public z2h::Ast {
~NewlineAst() {}
NewlineAst(z2h::Token *token)
: z2h::Ast(token) {}
protected:
void Print(std::ostream &os) const {
os << "(nl " + token->value + ")";
}
};
struct IdentifierAst : public z2h::Ast {
~IdentifierAst() {}
IdentifierAst(z2h::Token *token)
: z2h::Ast(token) {}
protected:
void Print(std::ostream &os) const {
os << "(id " + token->value + ")";
}
};
struct NumberAst : public z2h::Ast {
~NumberAst() {}
NumberAst(z2h::Token *token)
: z2h::Ast(token) {}
protected:
void Print(std::ostream &os) const {
os << "(num " + token->value + ")";
}
};
struct ExpressionsAst : public z2h::Ast {
std::vector<z2h::Ast *> expressions;
~ExpressionsAst() {}
ExpressionsAst(std::vector<z2h::Ast *> expressions) {
for (auto expression : expressions)
this->expressions.push_back(expression);
}
protected:
void Print(std::ostream &os) const {
os << "(exprs ";
sepby(os, ", ", expressions);
os << ")";
}
};
struct InfixAst : public z2h::Ast {
z2h::Ast *left;
z2h::Ast *right;
~InfixAst() {}
InfixAst(z2h::Token *token, z2h::Ast *left, z2h::Ast *right)
: z2h::Ast(token)
, left(left)
, right(right) {}
protected:
void Print(std::ostream &os) const {
os << "(" + token->value + " " << *left << " " << *right << ")";
}
};
struct PrefixAst : public z2h::Ast {
z2h::Ast *right;
~PrefixAst() {}
PrefixAst(z2h::Token *token, z2h::Ast *right)
: z2h::Ast(token)
, right(right) {}
protected:
void Print(std::ostream &os) const {
os << "(" + token->value + " " << *right << ")";
}
};
struct AssignAst : public z2h::Ast {
z2h::Ast *left;
z2h::Ast *right;
~AssignAst() {}
AssignAst(z2h::Token *token, z2h::Ast *left, z2h::Ast *right)
: z2h::Ast(token)
, left(left)
, right(right) {}
protected:
void Print(std::ostream &os) const {
os << "(" + token->value + " " << *left << " " << *right << ")";
}
};
struct FuncAst : public z2h::Ast {
z2h::Ast *args;
z2h::Ast *body;
~FuncAst() {}
FuncAst(z2h::Token *token, z2h::Ast *args, z2h::Ast *body)
: z2h::Ast(token)
, args(args)
, body(body) {}
protected:
void Print(std::ostream &os) const {
os << "(func " << *args << " " << *body << ")";
}
};
struct ConditionalAst : public z2h::Ast {
struct Pair {
z2h::Ast *predicate;
z2h::Ast *action;
Pair(z2h::Ast *predicate, z2h::Ast *action)
: predicate(predicate)
, action(action) {}
protected:
friend std::ostream & operator <<(std::ostream &os, const Pair &pair) {
os << "(pair " << *pair.predicate << " " << *pair.action << ")";
return os;
}
};
std::vector<Pair> pairs;
z2h::Ast *action;
~ConditionalAst() {}
ConditionalAst(z2h::Token *token, std::initializer_list<Pair> pairs)
: z2h::Ast(token)
, pairs(pairs)
, action(nullptr) {}
ConditionalAst(z2h::Token *token, std::initializer_list<Pair> pairs, z2h::Ast *action)
: z2h::Ast(token)
, pairs(pairs)
, action(action) {}
protected:
void Print(std::ostream &os) const {
os << "(cond";
for (auto pair : pairs) {
os << " " << pair;
}
if (nullptr != action)
os << " " << *action;
os << ")";
}
};
}
#endif /*__SOTA_AST__*/
<commit_msg>went with -> over func ... -sai<commit_after>#ifndef __SOTA_AST__
#define __SOTA_AST__ = 1
#include <string>
#include <vector>
#include <iostream>
#include "z2h/ast.hpp"
#include "z2h/token.hpp"
namespace sota {
inline void sepby(std::ostream &os, std::string sep, std::vector<z2h::Ast *> items) {
if (items.size()) {
size_t i = 0;
for (; i < items.size() - 1; ++i) {
os << *items[i] << sep;
}
os << *items[i];
}
}
struct NewlineAst : public z2h::Ast {
~NewlineAst() {}
NewlineAst(z2h::Token *token)
: z2h::Ast(token) {}
protected:
void Print(std::ostream &os) const {
os << "(nl " + token->value + ")";
}
};
struct IdentifierAst : public z2h::Ast {
~IdentifierAst() {}
IdentifierAst(z2h::Token *token)
: z2h::Ast(token) {}
protected:
void Print(std::ostream &os) const {
os << "(id " + token->value + ")";
}
};
struct NumberAst : public z2h::Ast {
~NumberAst() {}
NumberAst(z2h::Token *token)
: z2h::Ast(token) {}
protected:
void Print(std::ostream &os) const {
os << "(num " + token->value + ")";
}
};
struct ExpressionsAst : public z2h::Ast {
std::vector<z2h::Ast *> expressions;
~ExpressionsAst() {}
ExpressionsAst(std::vector<z2h::Ast *> expressions) {
for (auto expression : expressions)
this->expressions.push_back(expression);
}
protected:
void Print(std::ostream &os) const {
os << "(exprs ";
sepby(os, ", ", expressions);
os << ")";
}
};
struct InfixAst : public z2h::Ast {
z2h::Ast *left;
z2h::Ast *right;
~InfixAst() {}
InfixAst(z2h::Token *token, z2h::Ast *left, z2h::Ast *right)
: z2h::Ast(token)
, left(left)
, right(right) {}
protected:
void Print(std::ostream &os) const {
os << "(" + token->value + " " << *left << " " << *right << ")";
}
};
struct PrefixAst : public z2h::Ast {
z2h::Ast *right;
~PrefixAst() {}
PrefixAst(z2h::Token *token, z2h::Ast *right)
: z2h::Ast(token)
, right(right) {}
protected:
void Print(std::ostream &os) const {
os << "(" + token->value + " " << *right << ")";
}
};
struct AssignAst : public z2h::Ast {
z2h::Ast *left;
z2h::Ast *right;
~AssignAst() {}
AssignAst(z2h::Token *token, z2h::Ast *left, z2h::Ast *right)
: z2h::Ast(token)
, left(left)
, right(right) {}
protected:
void Print(std::ostream &os) const {
os << "(" + token->value + " " << *left << " " << *right << ")";
}
};
struct FuncAst : public z2h::Ast {
z2h::Ast *args;
z2h::Ast *body;
~FuncAst() {}
FuncAst(z2h::Token *token, z2h::Ast *args, z2h::Ast *body)
: z2h::Ast(token)
, args(args)
, body(body) {}
protected:
void Print(std::ostream &os) const {
os << "(-> " << *args << " " << *body << ")";
}
};
struct ConditionalAst : public z2h::Ast {
struct Pair {
z2h::Ast *predicate;
z2h::Ast *action;
Pair(z2h::Ast *predicate, z2h::Ast *action)
: predicate(predicate)
, action(action) {}
protected:
friend std::ostream & operator <<(std::ostream &os, const Pair &pair) {
os << "(pair " << *pair.predicate << " " << *pair.action << ")";
return os;
}
};
std::vector<Pair> pairs;
z2h::Ast *action;
~ConditionalAst() {}
ConditionalAst(z2h::Token *token, std::initializer_list<Pair> pairs)
: z2h::Ast(token)
, pairs(pairs)
, action(nullptr) {}
ConditionalAst(z2h::Token *token, std::initializer_list<Pair> pairs, z2h::Ast *action)
: z2h::Ast(token)
, pairs(pairs)
, action(action) {}
protected:
void Print(std::ostream &os) const {
os << "(cond";
for (auto pair : pairs) {
os << " " << pair;
}
if (nullptr != action)
os << " " << *action;
os << ")";
}
};
}
#endif /*__SOTA_AST__*/
<|endoftext|>
|
<commit_before>#include <tgbot/bot.h>
#include <tgbot/logger.h>
#include <tgbot/utils/https.h>
#include <sstream>
#include <thread>
using namespace tgbot;
tgbot::LongPollBot::LongPollBot(
const std::string &token,
const std::vector<types::UpdateType> &filterUpdates, const int &limit,
const int &timeout)
: Bot(token, filterUpdates, limit, timeout) {}
void tgbot::LongPollBot::start() {
getLogger().info("starting HTTP long poll...");
CURL *fetchConnection = utils::http::curlEasyInit();
curl_easy_setopt(fetchConnection, CURLOPT_TCP_KEEPALIVE, 1L);
curl_easy_setopt(fetchConnection, CURLOPT_TCP_KEEPIDLE, 60);
std::vector<types::Update> updates;
while (true) {
if (getUpdates(fetchConnection, updates)) {
makeCallback(updates);
updates.clear();
}
}
}
void tgbot::Bot::makeCallback(const std::vector<types::Update> &updates) const {
std::thread tmpHolder;
for (auto const &update : updates) {
if (__notifyEachUpdate)
getLogger().info("received update - " + std::to_string(update.updateId));
if (update.updateType == types::UpdateType::MESSAGE) {
types::Message messageObject = std::move(*update.message);
bool byCommandStart = false;
if (commandCallback.size() && messageObject.text) {
for (auto const &c : commandCallback) {
if (std::get<1>(c)(*(messageObject.text), std::get<0>(c))) {
std::vector<std::string> args;
std::string arg;
std::istringstream istr(*messageObject.text);
while (getline(istr, arg, ' ')) args.push_back(std::move(arg));
tmpHolder = std::thread(std::get<3>(c), std::move(messageObject),
*this, std::move(args));
byCommandStart = true;
break;
}
}
}
if (messageCallback && !byCommandStart)
tmpHolder =
std::thread(messageCallback, std::move(messageObject), *this);
else if (!messageCallback)
getLogger().error(
"could not make any call to handler... Did you forgot "
"Bot::callback() or something else?");
}
else if (update.updateType == types::UpdateType::EDITED_MESSAGE &&
editedMessageCallback)
tmpHolder = std::thread(editedMessageCallback,
std::move(*update.editedMessage), *this);
else if (update.updateType == types::UpdateType::CALLBACK_QUERY &&
callbackQueryCallback)
tmpHolder = std::thread(callbackQueryCallback,
std::move(*update.callbackQuery), *this);
else if (update.updateType == types::UpdateType::CHOSEN_INLINE_RESULT &&
chosenInlineResultCallback)
tmpHolder = std::thread(chosenInlineResultCallback,
std::move(*update.chosenInlineResult), *this);
else if (update.updateType == types::UpdateType::EDITED_CHANNEL_POST &&
editedChannelPostCallback)
tmpHolder = std::thread(editedChannelPostCallback,
std::move(*update.editedChannelPost), *this);
else if (update.updateType == types::UpdateType::INLINE_QUERY &&
inlineQueryCallback)
tmpHolder = std::thread(inlineQueryCallback,
std::move(*update.inlineQuery), *this);
else if (update.updateType == types::UpdateType::PRE_CHECKOUT_QUERY &&
preCheckoutQueryCallback)
tmpHolder = std::thread(preCheckoutQueryCallback,
std::move(*update.preCheckoutQuery), *this);
else if (update.updateType == types::UpdateType::SHIPPING_QUERY &&
shippingQueryCallback)
tmpHolder = std::thread(shippingQueryCallback,
std::move(*update.shippingQuery), *this);
else if (update.updateType == types::UpdateType::CHANNEL_POST &&
channelPostCallback)
tmpHolder = std::thread(channelPostCallback,
std::move(*update.channelPost), *this);
else
getLogger().error(
"could not make any call to handler... Did you forgot "
"Bot::callback() or something else?");
if (tmpHolder.joinable()) tmpHolder.detach();
}
}
void tgbot::Bot::notifyEachUpdate(bool t) { __notifyEachUpdate = t; }
<commit_msg>Inopportune error un missing callback() when using matchers<commit_after>#include <tgbot/bot.h>
#include <tgbot/logger.h>
#include <tgbot/utils/https.h>
#include <sstream>
#include <thread>
using namespace tgbot;
tgbot::LongPollBot::LongPollBot(
const std::string &token,
const std::vector<types::UpdateType> &filterUpdates, const int &limit,
const int &timeout)
: Bot(token, filterUpdates, limit, timeout) {}
void tgbot::LongPollBot::start() {
getLogger().info("starting HTTP long poll...");
CURL *fetchConnection = utils::http::curlEasyInit();
curl_easy_setopt(fetchConnection, CURLOPT_TCP_KEEPALIVE, 1L);
curl_easy_setopt(fetchConnection, CURLOPT_TCP_KEEPIDLE, 60);
std::vector<types::Update> updates;
while (true) {
if (getUpdates(fetchConnection, updates)) {
makeCallback(updates);
updates.clear();
}
}
}
void tgbot::Bot::makeCallback(const std::vector<types::Update> &updates) const {
std::thread tmpHolder;
for (auto const &update : updates) {
if (__notifyEachUpdate)
getLogger().info("received update - " + std::to_string(update.updateId));
if (update.updateType == types::UpdateType::MESSAGE) {
types::Message messageObject = std::move(*update.message);
bool byCommandStart = false;
if (commandCallback.size() && messageObject.text) {
for (auto const &c : commandCallback) {
if (std::get<1>(c)(*(messageObject.text), std::get<0>(c))) {
std::vector<std::string> args;
std::string arg;
std::istringstream istr(*messageObject.text);
while (getline(istr, arg, ' ')) args.push_back(std::move(arg));
tmpHolder = std::thread(std::get<3>(c), std::move(messageObject),
*this, std::move(args));
byCommandStart = true;
break;
}
}
}
if (messageCallback && !byCommandStart)
tmpHolder =
std::thread(messageCallback, std::move(messageObject), *this);
else if (!messageCallback && !byCommandStart)
getLogger().error(
"could not make any call to handler... Did you forgot "
"Bot::callback() or something else?");
}
else if (update.updateType == types::UpdateType::EDITED_MESSAGE &&
editedMessageCallback)
tmpHolder = std::thread(editedMessageCallback,
std::move(*update.editedMessage), *this);
else if (update.updateType == types::UpdateType::CALLBACK_QUERY &&
callbackQueryCallback)
tmpHolder = std::thread(callbackQueryCallback,
std::move(*update.callbackQuery), *this);
else if (update.updateType == types::UpdateType::CHOSEN_INLINE_RESULT &&
chosenInlineResultCallback)
tmpHolder = std::thread(chosenInlineResultCallback,
std::move(*update.chosenInlineResult), *this);
else if (update.updateType == types::UpdateType::EDITED_CHANNEL_POST &&
editedChannelPostCallback)
tmpHolder = std::thread(editedChannelPostCallback,
std::move(*update.editedChannelPost), *this);
else if (update.updateType == types::UpdateType::INLINE_QUERY &&
inlineQueryCallback)
tmpHolder = std::thread(inlineQueryCallback,
std::move(*update.inlineQuery), *this);
else if (update.updateType == types::UpdateType::PRE_CHECKOUT_QUERY &&
preCheckoutQueryCallback)
tmpHolder = std::thread(preCheckoutQueryCallback,
std::move(*update.preCheckoutQuery), *this);
else if (update.updateType == types::UpdateType::SHIPPING_QUERY &&
shippingQueryCallback)
tmpHolder = std::thread(shippingQueryCallback,
std::move(*update.shippingQuery), *this);
else if (update.updateType == types::UpdateType::CHANNEL_POST &&
channelPostCallback)
tmpHolder = std::thread(channelPostCallback,
std::move(*update.channelPost), *this);
else
getLogger().error(
"could not make any call to handler... Did you forgot "
"Bot::callback() or something else?");
if (tmpHolder.joinable()) tmpHolder.detach();
}
}
void tgbot::Bot::notifyEachUpdate(bool t) { __notifyEachUpdate = t; }
<|endoftext|>
|
<commit_before>#include <iostream>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <sys/utsname.h>
#include <string.h>
#include <linux/limits.h>
#include "btf.h"
#include "types.h"
#include "bpftrace.h"
#ifdef HAVE_LIBBPF_BTF_DUMP
#include <linux/bpf.h>
#include <linux/btf.h>
#include <bpf/btf.h>
#include <bpf/libbpf.h>
namespace bpftrace {
struct btf_location {
const char *path; // path with possible "%s" format to be replaced current release
bool raw; // file is either as ELF (false) or raw BTF data (true)
};
static unsigned char *get_data(const char *file, ssize_t *sizep)
{
struct stat st;
if (stat(file, &st))
return nullptr;
FILE *f;
f = fopen(file, "rb");
if (!f)
return nullptr;
unsigned char *data;
unsigned int size;
size = st.st_size;
data = (unsigned char *) malloc(size);
if (!data)
{
fclose(f);
return nullptr;
}
ssize_t ret = fread(data, 1, st.st_size, f);
if (ret != st.st_size)
{
free(data);
fclose(f);
return nullptr;
}
fclose(f);
*sizep = size;
return data;
}
static struct btf* btf_raw(char *file)
{
unsigned char *data;
ssize_t size;
struct btf *btf;
data = get_data(file, &size);
if (!data)
{
std::cerr << "BTF: failed to read data from: " << file << std::endl;
return nullptr;
}
btf = btf__new(data, (__u32) size);
free(data);
return btf;
}
static int libbpf_print(enum libbpf_print_level level, const char *msg, va_list ap)
{
fprintf(stderr, "BTF: (%d) ", level);
return vfprintf(stderr, msg, ap);
}
static struct btf *btf_open(struct btf_location *locs)
{
struct utsname buf;
uname(&buf);
for (int i = 0; locs[i].path; i++)
{
char path[PATH_MAX + 1];
snprintf(path, PATH_MAX, locs[i].path, buf.release);
if (access(path, R_OK))
continue;
struct btf *btf;
if (locs[i].raw)
btf = btf_raw(path);
else
btf = btf__parse_elf(path, nullptr);
int err = libbpf_get_error(btf);
if (err)
{
if (bt_verbose)
{
char err_buf[256];
libbpf_strerror(libbpf_get_error(btf), err_buf, sizeof(err_buf));
std::cerr << "BTF: failed to read data (" << err_buf << ") from: " << path << std::endl;
}
continue;
}
if (bt_verbose)
{
std::cerr << "BTF: using data from " << path << std::endl;
}
return btf;
}
return nullptr;
}
BTF::BTF(void) : btf(nullptr), state(NODATA)
{
// 'borrowed' from libbpf's bpf_core_find_kernel_btf
// from Andrii Nakryiko
struct btf_location locs_normal[] =
{
{ "/sys/kernel/btf/vmlinux", true },
{ "/boot/vmlinux-%1$s", false },
{ "/lib/modules/%1$s/vmlinux-%1$s", false },
{ "/lib/modules/%1$s/build/vmlinux", false },
{ "/usr/lib/modules/%1$s/kernel/vmlinux", false },
{ "/usr/lib/debug/boot/vmlinux-%1$s", false },
{ "/usr/lib/debug/boot/vmlinux-%1$s.debug", false },
{ "/usr/lib/debug/lib/modules/%1$s/vmlinux", false },
{ nullptr, false },
};
struct btf_location locs_test[] =
{
{ nullptr, true },
{ nullptr, false },
};
struct btf_location *locs = locs_normal;
// Try to get BTF file from BPFTRACE_BTF_TEST env
char *path = std::getenv("BPFTRACE_BTF_TEST");
if (path)
{
locs_test[0].path = path;
locs = locs_test;
}
btf = btf_open(locs);
if (btf)
{
libbpf_set_print(libbpf_print);
state = OK;
}
else
{
std::cerr << "BTF: failed to find BTF data " << std::endl;
}
}
BTF::~BTF()
{
btf__free(btf);
}
static void dump_printf(void *ctx, const char *fmt, va_list args)
{
std::string *ret = static_cast<std::string*>(ctx);
char *str;
if (vasprintf(&str, fmt, args) < 0)
return;
*ret += str;
free(str);
}
static const char *btf_str(const struct btf *btf, __u32 off)
{
if (!off)
return "(anon)";
return btf__name_by_offset(btf, off) ? : "(invalid)";
}
std::string BTF::c_def(std::unordered_set<std::string>& set)
{
std::string ret = std::string("");
struct btf_dump_opts opts = { .ctx = &ret, };
struct btf_dump *dump;
char err_buf[256];
int err;
dump = btf_dump__new(btf, nullptr, &opts, dump_printf);
err = libbpf_get_error(dump);
if (err)
{
libbpf_strerror(err, err_buf, sizeof(err_buf));
std::cerr << "BTF: failed to initialize dump (" << err_buf << ")" << std::endl;
return std::string("");
}
std::unordered_set<std::string> myset(set);
__s32 id, max = (__s32) btf__get_nr_types(btf);
for (id = 1; id <= max && myset.size(); id++)
{
const struct btf_type *t = btf__type_by_id(btf, id);
const char *str = btf_str(btf, t->name_off);
auto it = myset.find(str);
if (it != myset.end())
{
btf_dump__dump_type(dump, id);
myset.erase(it);
}
}
btf_dump__free(dump);
return ret;
}
std::string BTF::type_of(const std::string& name, const std::string& field)
{
__s32 type_id = btf__find_by_name(btf, name.c_str());
if (type_id < 0)
return std::string("");
const struct btf_type *type = btf__type_by_id(btf, type_id);
if (!type ||
(BTF_INFO_KIND(type->info) != BTF_KIND_STRUCT &&
BTF_INFO_KIND(type->info) != BTF_KIND_UNION))
return std::string("");
// We need to walk through oaa the struct/union members
// and try to find the requested field name.
//
// More info on struct/union members:
// https://www.kernel.org/doc/html/latest/bpf/btf.html#btf-kind-union
const struct btf_member *m = reinterpret_cast<const struct btf_member*>(type + 1);
for (unsigned int i = 0; i < BTF_INFO_VLEN(type->info); i++)
{
std::string m_name = btf__name_by_offset(btf, m[i].name_off);
if (m_name != field)
continue;
const struct btf_type *f = btf__type_by_id(btf, m[i].type);
if (!f)
break;
// Get rid of all the pointers on the way to the actual type.
while (BTF_INFO_KIND(f->info) == BTF_KIND_PTR) {
f = btf__type_by_id(btf, f->type);
}
return btf_str(btf, f->name_off);
}
return std::string("");
}
} // namespace bpftrace
#else // HAVE_LIBBPF_BTF_DUMP
namespace bpftrace {
BTF::BTF() { }
BTF::~BTF() { }
std::string BTF::c_def(std::unordered_set<std::string>& set __attribute__((__unused__))) { return std::string(""); }
std::string BTF::type_of(const std::string& name __attribute__((__unused__)),
const std::string& field __attribute__((__unused__))) {
return std::string("");
}
} // namespace bpftrace
#endif // HAVE_LIBBPF_BTF_DUMP
<commit_msg>Only warn about missing BTF info in debug mode<commit_after>#include <iostream>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <sys/utsname.h>
#include <string.h>
#include <linux/limits.h>
#include "btf.h"
#include "types.h"
#include "bpftrace.h"
#ifdef HAVE_LIBBPF_BTF_DUMP
#include <linux/bpf.h>
#include <linux/btf.h>
#include <bpf/btf.h>
#include <bpf/libbpf.h>
namespace bpftrace {
struct btf_location {
const char *path; // path with possible "%s" format to be replaced current release
bool raw; // file is either as ELF (false) or raw BTF data (true)
};
static unsigned char *get_data(const char *file, ssize_t *sizep)
{
struct stat st;
if (stat(file, &st))
return nullptr;
FILE *f;
f = fopen(file, "rb");
if (!f)
return nullptr;
unsigned char *data;
unsigned int size;
size = st.st_size;
data = (unsigned char *) malloc(size);
if (!data)
{
fclose(f);
return nullptr;
}
ssize_t ret = fread(data, 1, st.st_size, f);
if (ret != st.st_size)
{
free(data);
fclose(f);
return nullptr;
}
fclose(f);
*sizep = size;
return data;
}
static struct btf* btf_raw(char *file)
{
unsigned char *data;
ssize_t size;
struct btf *btf;
data = get_data(file, &size);
if (!data)
{
std::cerr << "BTF: failed to read data from: " << file << std::endl;
return nullptr;
}
btf = btf__new(data, (__u32) size);
free(data);
return btf;
}
static int libbpf_print(enum libbpf_print_level level, const char *msg, va_list ap)
{
fprintf(stderr, "BTF: (%d) ", level);
return vfprintf(stderr, msg, ap);
}
static struct btf *btf_open(struct btf_location *locs)
{
struct utsname buf;
uname(&buf);
for (int i = 0; locs[i].path; i++)
{
char path[PATH_MAX + 1];
snprintf(path, PATH_MAX, locs[i].path, buf.release);
if (access(path, R_OK))
continue;
struct btf *btf;
if (locs[i].raw)
btf = btf_raw(path);
else
btf = btf__parse_elf(path, nullptr);
int err = libbpf_get_error(btf);
if (err)
{
if (bt_verbose)
{
char err_buf[256];
libbpf_strerror(libbpf_get_error(btf), err_buf, sizeof(err_buf));
std::cerr << "BTF: failed to read data (" << err_buf << ") from: " << path << std::endl;
}
continue;
}
if (bt_verbose)
{
std::cerr << "BTF: using data from " << path << std::endl;
}
return btf;
}
return nullptr;
}
BTF::BTF(void) : btf(nullptr), state(NODATA)
{
// 'borrowed' from libbpf's bpf_core_find_kernel_btf
// from Andrii Nakryiko
struct btf_location locs_normal[] =
{
{ "/sys/kernel/btf/vmlinux", true },
{ "/boot/vmlinux-%1$s", false },
{ "/lib/modules/%1$s/vmlinux-%1$s", false },
{ "/lib/modules/%1$s/build/vmlinux", false },
{ "/usr/lib/modules/%1$s/kernel/vmlinux", false },
{ "/usr/lib/debug/boot/vmlinux-%1$s", false },
{ "/usr/lib/debug/boot/vmlinux-%1$s.debug", false },
{ "/usr/lib/debug/lib/modules/%1$s/vmlinux", false },
{ nullptr, false },
};
struct btf_location locs_test[] =
{
{ nullptr, true },
{ nullptr, false },
};
struct btf_location *locs = locs_normal;
// Try to get BTF file from BPFTRACE_BTF_TEST env
char *path = std::getenv("BPFTRACE_BTF_TEST");
if (path)
{
locs_test[0].path = path;
locs = locs_test;
}
btf = btf_open(locs);
if (btf)
{
libbpf_set_print(libbpf_print);
state = OK;
}
else if (bt_debug != DebugLevel::kNone)
{
std::cerr << "BTF: failed to find BTF data " << std::endl;
}
}
BTF::~BTF()
{
btf__free(btf);
}
static void dump_printf(void *ctx, const char *fmt, va_list args)
{
std::string *ret = static_cast<std::string*>(ctx);
char *str;
if (vasprintf(&str, fmt, args) < 0)
return;
*ret += str;
free(str);
}
static const char *btf_str(const struct btf *btf, __u32 off)
{
if (!off)
return "(anon)";
return btf__name_by_offset(btf, off) ? : "(invalid)";
}
std::string BTF::c_def(std::unordered_set<std::string>& set)
{
std::string ret = std::string("");
struct btf_dump_opts opts = { .ctx = &ret, };
struct btf_dump *dump;
char err_buf[256];
int err;
dump = btf_dump__new(btf, nullptr, &opts, dump_printf);
err = libbpf_get_error(dump);
if (err)
{
libbpf_strerror(err, err_buf, sizeof(err_buf));
std::cerr << "BTF: failed to initialize dump (" << err_buf << ")" << std::endl;
return std::string("");
}
std::unordered_set<std::string> myset(set);
__s32 id, max = (__s32) btf__get_nr_types(btf);
for (id = 1; id <= max && myset.size(); id++)
{
const struct btf_type *t = btf__type_by_id(btf, id);
const char *str = btf_str(btf, t->name_off);
auto it = myset.find(str);
if (it != myset.end())
{
btf_dump__dump_type(dump, id);
myset.erase(it);
}
}
btf_dump__free(dump);
return ret;
}
std::string BTF::type_of(const std::string& name, const std::string& field)
{
__s32 type_id = btf__find_by_name(btf, name.c_str());
if (type_id < 0)
return std::string("");
const struct btf_type *type = btf__type_by_id(btf, type_id);
if (!type ||
(BTF_INFO_KIND(type->info) != BTF_KIND_STRUCT &&
BTF_INFO_KIND(type->info) != BTF_KIND_UNION))
return std::string("");
// We need to walk through oaa the struct/union members
// and try to find the requested field name.
//
// More info on struct/union members:
// https://www.kernel.org/doc/html/latest/bpf/btf.html#btf-kind-union
const struct btf_member *m = reinterpret_cast<const struct btf_member*>(type + 1);
for (unsigned int i = 0; i < BTF_INFO_VLEN(type->info); i++)
{
std::string m_name = btf__name_by_offset(btf, m[i].name_off);
if (m_name != field)
continue;
const struct btf_type *f = btf__type_by_id(btf, m[i].type);
if (!f)
break;
// Get rid of all the pointers on the way to the actual type.
while (BTF_INFO_KIND(f->info) == BTF_KIND_PTR) {
f = btf__type_by_id(btf, f->type);
}
return btf_str(btf, f->name_off);
}
return std::string("");
}
} // namespace bpftrace
#else // HAVE_LIBBPF_BTF_DUMP
namespace bpftrace {
BTF::BTF() { }
BTF::~BTF() { }
std::string BTF::c_def(std::unordered_set<std::string>& set __attribute__((__unused__))) { return std::string(""); }
std::string BTF::type_of(const std::string& name __attribute__((__unused__)),
const std::string& field __attribute__((__unused__))) {
return std::string("");
}
} // namespace bpftrace
#endif // HAVE_LIBBPF_BTF_DUMP
<|endoftext|>
|
<commit_before>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <assert.h>
#include "LedControllerRequestProxy.h"
#include "GeneratedTypes.h"
int main(int argc, const char **argv)
{
LedControllerRequestProxy *device = new LedControllerRequestProxy(IfcNames_LedControllerRequestPortal);
printf("Starting LED test");
portalExec_start();
#ifdef BSIM
// BSIM does not run very many cycles per second
int blink = 10;
#else
int blink = 100000000;
#endif
int blinkon = 10;
int blinkoff = 5;
for (int i = 0; i < 20; i++) {
printf("blink %d", blinkon);
device->setLeds(blinkon, blink);
sleep(2);
device->setLeds(blinkoff, blink);
sleep(2);
}
printf("Done.\n");
}
<commit_msg>print blinkoff<commit_after>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <assert.h>
#include "LedControllerRequestProxy.h"
#include "GeneratedTypes.h"
int main(int argc, const char **argv)
{
LedControllerRequestProxy *device = new LedControllerRequestProxy(IfcNames_LedControllerRequestPortal);
printf("Starting LED test");
portalExec_start();
#ifdef BSIM
// BSIM does not run very many cycles per second
int blink = 10;
#else
int blink = 100000000;
#endif
int blinkon = 10;
int blinkoff = 5;
for (int i = 0; i < 20; i++) {
printf("blink %d", blinkon);
device->setLeds(blinkon, blink);
sleep(2);
printf("blink off %d", blinkoff);
device->setLeds(blinkoff, blink);
sleep(2);
}
printf("Done.\n");
}
<|endoftext|>
|
<commit_before>// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "ppapi/proxy/ppapi_command_buffer_proxy.h"
#include "ppapi/proxy/ppapi_messages.h"
#include "ppapi/proxy/proxy_channel.h"
#include "ppapi/shared_impl/api_id.h"
#include "ppapi/shared_impl/host_resource.h"
namespace ppapi {
namespace proxy {
PpapiCommandBufferProxy::PpapiCommandBufferProxy(
const ppapi::HostResource& resource,
ProxyChannel* channel)
: resource_(resource),
channel_(channel) {
}
PpapiCommandBufferProxy::~PpapiCommandBufferProxy() {
// Delete all the locally cached shared memory objects, closing the handle
// in this process.
for (TransferBufferMap::iterator it = transfer_buffers_.begin();
it != transfer_buffers_.end(); ++it) {
delete it->second.shared_memory;
it->second.shared_memory = NULL;
}
}
void PpapiCommandBufferProxy::ReportChannelError() {
if (!channel_error_callback_.is_null()) {
channel_error_callback_.Run();
channel_error_callback_.Reset();
}
}
int PpapiCommandBufferProxy::GetRouteID() const {
NOTIMPLEMENTED();
return 0;
}
bool PpapiCommandBufferProxy::Echo(const base::Closure& callback) {
return false;
}
bool PpapiCommandBufferProxy::SetSurfaceVisible(bool visible) {
NOTIMPLEMENTED();
return true;
}
bool PpapiCommandBufferProxy::DiscardBackbuffer() {
NOTIMPLEMENTED();
return true;
}
bool PpapiCommandBufferProxy::EnsureBackbuffer() {
NOTIMPLEMENTED();
return true;
}
uint32 PpapiCommandBufferProxy::InsertSyncPoint() {
NOTIMPLEMENTED();
return 0;
}
void PpapiCommandBufferProxy::WaitSyncPoint(uint32 sync_point) {
NOTIMPLEMENTED();
}
bool PpapiCommandBufferProxy::SignalSyncPoint(uint32 sync_point,
const base::Closure& callback) {
NOTIMPLEMENTED();
return false;
}
void PpapiCommandBufferProxy::SetMemoryAllocationChangedCallback(
const base::Callback<void(
const content::GpuMemoryAllocationForRenderer&)>& callback) {
NOTIMPLEMENTED();
}
bool PpapiCommandBufferProxy::SetParent(
CommandBufferProxy* parent_command_buffer,
uint32 parent_texture_id) {
// TODO(fsamuel): Need a proper implementation of this to support offscreen
// contexts in the guest renderer (WebGL, canvas, etc).
NOTIMPLEMENTED();
return false;
}
void PpapiCommandBufferProxy::SetChannelErrorCallback(
const base::Closure& callback) {
channel_error_callback_ = callback;
}
void PpapiCommandBufferProxy::SetNotifyRepaintTask(
const base::Closure& callback) {
NOTIMPLEMENTED();
}
void PpapiCommandBufferProxy::SetOnConsoleMessageCallback(
const GpuConsoleMessageCallback& callback) {
NOTIMPLEMENTED();
}
bool PpapiCommandBufferProxy::Initialize() {
return Send(new PpapiHostMsg_PPBGraphics3D_InitCommandBuffer(
ppapi::API_ID_PPB_GRAPHICS_3D, resource_));
}
gpu::CommandBuffer::State PpapiCommandBufferProxy::GetState() {
// Send will flag state with lost context if IPC fails.
if (last_state_.error == gpu::error::kNoError) {
gpu::CommandBuffer::State state;
bool success = false;
if (Send(new PpapiHostMsg_PPBGraphics3D_GetState(
ppapi::API_ID_PPB_GRAPHICS_3D, resource_, &state, &success))) {
UpdateState(state, success);
}
}
return last_state_;
}
gpu::CommandBuffer::State PpapiCommandBufferProxy::GetLastState() {
// Note: The locking command buffer wrapper does not take a global lock before
// calling this function.
return last_state_;
}
void PpapiCommandBufferProxy::Flush(int32 put_offset) {
if (last_state_.error != gpu::error::kNoError)
return;
IPC::Message* message = new PpapiHostMsg_PPBGraphics3D_AsyncFlush(
ppapi::API_ID_PPB_GRAPHICS_3D, resource_, put_offset);
// Do not let a synchronous flush hold up this message. If this handler is
// deferred until after the synchronous flush completes, it will overwrite the
// cached last_state_ with out-of-date data.
message->set_unblock(true);
Send(message);
}
gpu::CommandBuffer::State PpapiCommandBufferProxy::FlushSync(int32 put_offset,
int32 last_known_get) {
if (last_known_get == last_state_.get_offset) {
// Send will flag state with lost context if IPC fails.
if (last_state_.error == gpu::error::kNoError) {
gpu::CommandBuffer::State state;
bool success = false;
if (Send(new PpapiHostMsg_PPBGraphics3D_Flush(
ppapi::API_ID_PPB_GRAPHICS_3D, resource_, put_offset,
last_known_get, &state, &success))) {
UpdateState(state, success);
}
}
} else {
Flush(put_offset);
}
return last_state_;
}
void PpapiCommandBufferProxy::SetGetBuffer(int32 transfer_buffer_id) {
if (last_state_.error == gpu::error::kNoError) {
Send(new PpapiHostMsg_PPBGraphics3D_SetGetBuffer(
ppapi::API_ID_PPB_GRAPHICS_3D, resource_, transfer_buffer_id));
}
}
void PpapiCommandBufferProxy::SetGetOffset(int32 get_offset) {
// Not implemented in proxy.
NOTREACHED();
}
int32 PpapiCommandBufferProxy::CreateTransferBuffer(
size_t size,
int32 id_request) {
if (last_state_.error == gpu::error::kNoError) {
int32 id;
if (Send(new PpapiHostMsg_PPBGraphics3D_CreateTransferBuffer(
ppapi::API_ID_PPB_GRAPHICS_3D, resource_, size, &id))) {
return id;
}
}
return -1;
}
int32 PpapiCommandBufferProxy::RegisterTransferBuffer(
base::SharedMemory* shared_memory,
size_t size,
int32 id_request) {
// Not implemented in proxy.
NOTREACHED();
return -1;
}
void PpapiCommandBufferProxy::DestroyTransferBuffer(int32 id) {
if (last_state_.error != gpu::error::kNoError)
return;
// Remove the transfer buffer from the client side4 cache.
TransferBufferMap::iterator it = transfer_buffers_.find(id);
DCHECK(it != transfer_buffers_.end());
// Delete the shared memory object, closing the handle in this process.
delete it->second.shared_memory;
transfer_buffers_.erase(it);
Send(new PpapiHostMsg_PPBGraphics3D_DestroyTransferBuffer(
ppapi::API_ID_PPB_GRAPHICS_3D, resource_, id));
}
gpu::Buffer PpapiCommandBufferProxy::GetTransferBuffer(int32 id) {
if (last_state_.error != gpu::error::kNoError)
return gpu::Buffer();
// Check local cache to see if there is already a client side shared memory
// object for this id.
TransferBufferMap::iterator it = transfer_buffers_.find(id);
if (it != transfer_buffers_.end()) {
return it->second;
}
// Assuming we are in the renderer process, the service is responsible for
// duplicating the handle. This might not be true for NaCl.
ppapi::proxy::SerializedHandle handle(
ppapi::proxy::SerializedHandle::SHARED_MEMORY);
if (!Send(new PpapiHostMsg_PPBGraphics3D_GetTransferBuffer(
ppapi::API_ID_PPB_GRAPHICS_3D, resource_, id, &handle))) {
return gpu::Buffer();
}
if (!handle.is_shmem())
return gpu::Buffer();
// Cache the transfer buffer shared memory object client side.
scoped_ptr<base::SharedMemory> shared_memory(
new base::SharedMemory(handle.shmem(), false));
// Map the shared memory on demand.
if (!shared_memory->memory()) {
if (!shared_memory->Map(handle.size())) {
return gpu::Buffer();
}
}
gpu::Buffer buffer;
buffer.ptr = shared_memory->memory();
buffer.size = handle.size();
buffer.shared_memory = shared_memory.release();
transfer_buffers_[id] = buffer;
return buffer;
}
void PpapiCommandBufferProxy::SetToken(int32 token) {
NOTREACHED();
}
void PpapiCommandBufferProxy::SetParseError(gpu::error::Error error) {
NOTREACHED();
}
void PpapiCommandBufferProxy::SetContextLostReason(
gpu::error::ContextLostReason reason) {
NOTREACHED();
}
bool PpapiCommandBufferProxy::Send(IPC::Message* msg) {
DCHECK(last_state_.error == gpu::error::kNoError);
if (channel_->Send(msg))
return true;
last_state_.error = gpu::error::kLostContext;
return false;
}
void PpapiCommandBufferProxy::UpdateState(
const gpu::CommandBuffer::State& state,
bool success) {
// Handle wraparound. It works as long as we don't have more than 2B state
// updates in flight across which reordering occurs.
if (success) {
if (state.generation - last_state_.generation < 0x80000000U) {
last_state_ = state;
}
} else {
last_state_.error = gpu::error::kLostContext;
++last_state_.generation;
}
}
} // namespace proxy
} // namespace ppapi
<commit_msg>Don't crash when destoying transfer buffer that isn't mapped.<commit_after>// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "ppapi/proxy/ppapi_command_buffer_proxy.h"
#include "ppapi/proxy/ppapi_messages.h"
#include "ppapi/proxy/proxy_channel.h"
#include "ppapi/shared_impl/api_id.h"
#include "ppapi/shared_impl/host_resource.h"
namespace ppapi {
namespace proxy {
PpapiCommandBufferProxy::PpapiCommandBufferProxy(
const ppapi::HostResource& resource,
ProxyChannel* channel)
: resource_(resource),
channel_(channel) {
}
PpapiCommandBufferProxy::~PpapiCommandBufferProxy() {
// Delete all the locally cached shared memory objects, closing the handle
// in this process.
for (TransferBufferMap::iterator it = transfer_buffers_.begin();
it != transfer_buffers_.end(); ++it) {
delete it->second.shared_memory;
it->second.shared_memory = NULL;
}
}
void PpapiCommandBufferProxy::ReportChannelError() {
if (!channel_error_callback_.is_null()) {
channel_error_callback_.Run();
channel_error_callback_.Reset();
}
}
int PpapiCommandBufferProxy::GetRouteID() const {
NOTIMPLEMENTED();
return 0;
}
bool PpapiCommandBufferProxy::Echo(const base::Closure& callback) {
return false;
}
bool PpapiCommandBufferProxy::SetSurfaceVisible(bool visible) {
NOTIMPLEMENTED();
return true;
}
bool PpapiCommandBufferProxy::DiscardBackbuffer() {
NOTIMPLEMENTED();
return true;
}
bool PpapiCommandBufferProxy::EnsureBackbuffer() {
NOTIMPLEMENTED();
return true;
}
uint32 PpapiCommandBufferProxy::InsertSyncPoint() {
NOTIMPLEMENTED();
return 0;
}
void PpapiCommandBufferProxy::WaitSyncPoint(uint32 sync_point) {
NOTIMPLEMENTED();
}
bool PpapiCommandBufferProxy::SignalSyncPoint(uint32 sync_point,
const base::Closure& callback) {
NOTIMPLEMENTED();
return false;
}
void PpapiCommandBufferProxy::SetMemoryAllocationChangedCallback(
const base::Callback<void(
const content::GpuMemoryAllocationForRenderer&)>& callback) {
NOTIMPLEMENTED();
}
bool PpapiCommandBufferProxy::SetParent(
CommandBufferProxy* parent_command_buffer,
uint32 parent_texture_id) {
// TODO(fsamuel): Need a proper implementation of this to support offscreen
// contexts in the guest renderer (WebGL, canvas, etc).
NOTIMPLEMENTED();
return false;
}
void PpapiCommandBufferProxy::SetChannelErrorCallback(
const base::Closure& callback) {
channel_error_callback_ = callback;
}
void PpapiCommandBufferProxy::SetNotifyRepaintTask(
const base::Closure& callback) {
NOTIMPLEMENTED();
}
void PpapiCommandBufferProxy::SetOnConsoleMessageCallback(
const GpuConsoleMessageCallback& callback) {
NOTIMPLEMENTED();
}
bool PpapiCommandBufferProxy::Initialize() {
return Send(new PpapiHostMsg_PPBGraphics3D_InitCommandBuffer(
ppapi::API_ID_PPB_GRAPHICS_3D, resource_));
}
gpu::CommandBuffer::State PpapiCommandBufferProxy::GetState() {
// Send will flag state with lost context if IPC fails.
if (last_state_.error == gpu::error::kNoError) {
gpu::CommandBuffer::State state;
bool success = false;
if (Send(new PpapiHostMsg_PPBGraphics3D_GetState(
ppapi::API_ID_PPB_GRAPHICS_3D, resource_, &state, &success))) {
UpdateState(state, success);
}
}
return last_state_;
}
gpu::CommandBuffer::State PpapiCommandBufferProxy::GetLastState() {
// Note: The locking command buffer wrapper does not take a global lock before
// calling this function.
return last_state_;
}
void PpapiCommandBufferProxy::Flush(int32 put_offset) {
if (last_state_.error != gpu::error::kNoError)
return;
IPC::Message* message = new PpapiHostMsg_PPBGraphics3D_AsyncFlush(
ppapi::API_ID_PPB_GRAPHICS_3D, resource_, put_offset);
// Do not let a synchronous flush hold up this message. If this handler is
// deferred until after the synchronous flush completes, it will overwrite the
// cached last_state_ with out-of-date data.
message->set_unblock(true);
Send(message);
}
gpu::CommandBuffer::State PpapiCommandBufferProxy::FlushSync(int32 put_offset,
int32 last_known_get) {
if (last_known_get == last_state_.get_offset) {
// Send will flag state with lost context if IPC fails.
if (last_state_.error == gpu::error::kNoError) {
gpu::CommandBuffer::State state;
bool success = false;
if (Send(new PpapiHostMsg_PPBGraphics3D_Flush(
ppapi::API_ID_PPB_GRAPHICS_3D, resource_, put_offset,
last_known_get, &state, &success))) {
UpdateState(state, success);
}
}
} else {
Flush(put_offset);
}
return last_state_;
}
void PpapiCommandBufferProxy::SetGetBuffer(int32 transfer_buffer_id) {
if (last_state_.error == gpu::error::kNoError) {
Send(new PpapiHostMsg_PPBGraphics3D_SetGetBuffer(
ppapi::API_ID_PPB_GRAPHICS_3D, resource_, transfer_buffer_id));
}
}
void PpapiCommandBufferProxy::SetGetOffset(int32 get_offset) {
// Not implemented in proxy.
NOTREACHED();
}
int32 PpapiCommandBufferProxy::CreateTransferBuffer(
size_t size,
int32 id_request) {
if (last_state_.error == gpu::error::kNoError) {
int32 id;
if (Send(new PpapiHostMsg_PPBGraphics3D_CreateTransferBuffer(
ppapi::API_ID_PPB_GRAPHICS_3D, resource_, size, &id))) {
return id;
}
}
return -1;
}
int32 PpapiCommandBufferProxy::RegisterTransferBuffer(
base::SharedMemory* shared_memory,
size_t size,
int32 id_request) {
// Not implemented in proxy.
NOTREACHED();
return -1;
}
void PpapiCommandBufferProxy::DestroyTransferBuffer(int32 id) {
if (last_state_.error != gpu::error::kNoError)
return;
// Remove the transfer buffer from the client side4 cache.
TransferBufferMap::iterator it = transfer_buffers_.find(id);
if (it != transfer_buffers_.end()) {
// Delete the shared memory object, closing the handle in this process.
delete it->second.shared_memory;
transfer_buffers_.erase(it);
}
Send(new PpapiHostMsg_PPBGraphics3D_DestroyTransferBuffer(
ppapi::API_ID_PPB_GRAPHICS_3D, resource_, id));
}
gpu::Buffer PpapiCommandBufferProxy::GetTransferBuffer(int32 id) {
if (last_state_.error != gpu::error::kNoError)
return gpu::Buffer();
// Check local cache to see if there is already a client side shared memory
// object for this id.
TransferBufferMap::iterator it = transfer_buffers_.find(id);
if (it != transfer_buffers_.end()) {
return it->second;
}
// Assuming we are in the renderer process, the service is responsible for
// duplicating the handle. This might not be true for NaCl.
ppapi::proxy::SerializedHandle handle(
ppapi::proxy::SerializedHandle::SHARED_MEMORY);
if (!Send(new PpapiHostMsg_PPBGraphics3D_GetTransferBuffer(
ppapi::API_ID_PPB_GRAPHICS_3D, resource_, id, &handle))) {
return gpu::Buffer();
}
if (!handle.is_shmem())
return gpu::Buffer();
// Cache the transfer buffer shared memory object client side.
scoped_ptr<base::SharedMemory> shared_memory(
new base::SharedMemory(handle.shmem(), false));
// Map the shared memory on demand.
if (!shared_memory->memory()) {
if (!shared_memory->Map(handle.size())) {
return gpu::Buffer();
}
}
gpu::Buffer buffer;
buffer.ptr = shared_memory->memory();
buffer.size = handle.size();
buffer.shared_memory = shared_memory.release();
transfer_buffers_[id] = buffer;
return buffer;
}
void PpapiCommandBufferProxy::SetToken(int32 token) {
NOTREACHED();
}
void PpapiCommandBufferProxy::SetParseError(gpu::error::Error error) {
NOTREACHED();
}
void PpapiCommandBufferProxy::SetContextLostReason(
gpu::error::ContextLostReason reason) {
NOTREACHED();
}
bool PpapiCommandBufferProxy::Send(IPC::Message* msg) {
DCHECK(last_state_.error == gpu::error::kNoError);
if (channel_->Send(msg))
return true;
last_state_.error = gpu::error::kLostContext;
return false;
}
void PpapiCommandBufferProxy::UpdateState(
const gpu::CommandBuffer::State& state,
bool success) {
// Handle wraparound. It works as long as we don't have more than 2B state
// updates in flight across which reordering occurs.
if (success) {
if (state.generation - last_state_.generation < 0x80000000U) {
last_state_ = state;
}
} else {
last_state_.error = gpu::error::kLostContext;
++last_state_.generation;
}
}
} // namespace proxy
} // namespace ppapi
<|endoftext|>
|
<commit_before>/*****************************************************************************
* Licensed to Qualys, Inc. (QUALYS) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* QUALYS licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
****************************************************************************/
/**
* @file
* @brief Predicate --- Standard IronBee Tests
*
* @author Christopher Alfeld <[email protected]>
**/
#include "standard_test.hpp"
#include <predicate/reporter.hpp>
#include <ironbee/rule_engine.h>
using namespace IronBee::Predicate;
using namespace std;
class TestStandardIronBee :
public StandardTest
{
};
TEST_F(TestStandardIronBee, field)
{
uint8_t data[4] = {'t', 'e', 's', 't'};
ib_status_t rc = ib_data_add_bytestr(
m_transaction.ib()->data,
"TestStandard.Field",
data, 4,
NULL
);
EXPECT_EQ(IB_OK, rc);
EXPECT_EQ("test", eval_s("(field 'TestStandard.Field')"));
}
TEST_F(TestStandardIronBee, Operator)
{
EXPECT_TRUE(eval_bool("(operator 'istreq' 'fOo' 'foo')"));
EXPECT_FALSE(eval_bool("(operator 'istreq' 'fOo' 'bar')"));
EXPECT_THROW(eval_bool("(operator 'dne' 'a' 'b')"), IronBee::einval);
EXPECT_THROW(eval_bool("(operator)"), IronBee::einval);
EXPECT_THROW(eval_bool("(operator 'a')"), IronBee::einval);
EXPECT_THROW(eval_bool("(operator 'a' 'b')"), IronBee::einval);
EXPECT_THROW(eval_bool("(operator 'a' 'b' 'c' 'd')"), IronBee::einval);
EXPECT_THROW(eval_bool("(operator 'a' null 'c')"), IronBee::einval);
EXPECT_THROW(eval_bool("(operator null 'b' 'c')"), IronBee::einval);
}
TEST_F(TestStandardIronBee, transformation)
{
EXPECT_EQ("foo", eval_s("(transformation 'lowercase' 'fOO')"));
EXPECT_THROW(eval_s("(transformation)"), IronBee::einval);
EXPECT_THROW(eval_s("(transformation 'a')"), IronBee::einval);
EXPECT_THROW(eval_s("(transformation 'a' 'b' 'c')"), IronBee::einval);
EXPECT_THROW(eval_s("(transformation null 'b')"), IronBee::einval);
}
TEST_F(TestStandardIronBee, phase)
{
// Track old rule_exec so we can restore it.
ib_rule_exec_t* old_rule_exec = m_transaction.ib()->rule_exec;
// Test data rule exec.
ib_rule_exec_t rule_exec;
m_transaction.ib()->rule_exec = &rule_exec;
rule_exec.phase = IB_PHASE_REQUEST_HEADER;
EXPECT_FALSE(eval_bool("(isFinished (waitPhase 'response_header' 'foo'))"));
rule_exec.phase = IB_PHASE_RESPONSE_HEADER;
EXPECT_TRUE(eval_bool("(isFinished (waitPhase 'response_header' 'foo'))"));
rule_exec.phase = IB_PHASE_REQUEST_HEADER;
EXPECT_TRUE(eval_bool("(isFinished (finishPhase 'request_header' (sequence 0)))"));
rule_exec.phase = IB_PHASE_RESPONSE_HEADER;
EXPECT_FALSE(eval_bool("(isFinished (finishPhase 'request_header' (sequence 0)))"));
EXPECT_THROW(eval_s("(waitPhase)"), IronBee::einval);
EXPECT_THROW(eval_s("(waitPhase 'request_header')"), IronBee::einval);
EXPECT_THROW(eval_s("(waitPhase 'request_header' 'b' 'c')"), IronBee::einval);
EXPECT_THROW(eval_s("(waitPhase null 'b')"), IronBee::einval);
EXPECT_THROW(eval_s("(waitPhase 'foo' 'b')"), IronBee::einval);
EXPECT_THROW(eval_s("(finishPhase)"), IronBee::einval);
EXPECT_THROW(eval_s("(finishPhase 'request_header')"), IronBee::einval);
EXPECT_THROW(eval_s("(finishPhase 'request_header' 'b' 'c')"), IronBee::einval);
EXPECT_THROW(eval_s("(finishPhase null 'b')"), IronBee::einval);
EXPECT_THROW(eval_s("(finishPhase 'foo' 'b')"), IronBee::einval);
m_transaction.ib()->rule_exec = old_rule_exec;
}
class TestAsk :
public Call
{
public:
virtual std::string name() const
{
return "test_ask";
}
virtual void pre_eval(Environment environment, NodeReporter reporter)
{
m_value =
IronBee::Field::create_dynamic_list<Value>(
environment.main_memory_pool(),
"", 0,
getter,
boost::function<
void(
IronBee::Field,
const char*, size_t,
IronBee::ConstList<Value>
)
>()
);
}
protected:
virtual void calculate(EvalContext context)
{
add_value(m_value);
finish();
}
private:
static
IronBee::ConstList<Value> getter(
IronBee::ConstField f,
const char* param,
size_t n
)
{
cout << "getter called with param = " << string(param, n) << endl;
using namespace IronBee;
typedef List<Value> result_t;
result_t result = result_t::create(f.memory_pool());
result.push_back(
IronBee::Field::create_byte_string(
f.memory_pool(),
param, n,
IronBee::ByteString::create(
f.memory_pool(),
param, n
)
)
);
return result;
}
Value m_value;
};
TEST_F(TestStandardIronBee, Ask)
{
m_factory.add<TestAsk>();
/* Test dynamic behavior. */
EXPECT_EQ("foo", eval_s("(ask 'foo' (test_ask))"));
/* Test sublike behavior. */
EXPECT_EQ("1", eval_s("(ask 'a' (gather (cat (setName 'a' '1') (setName 'b' 2) (setName 'c' 3))))"));
EXPECT_TRUE(eval_bool("(isLonger 1 (ask 'a' (gather (cat (setName 'a' '1') (setName 'b' 2) (setName 'a' 3)))))"));
EXPECT_THROW(eval_bool("(ask)"), IronBee::einval);
EXPECT_THROW(eval_bool("(ask 1 'b')"), IronBee::einval);
EXPECT_THROW(eval_bool("(ask 'a')"), IronBee::einval);
EXPECT_THROW(eval_bool("(ask 'a' 'b' 'c')"), IronBee::einval);
}
<commit_msg>predicate/tests: Remove debugging output.<commit_after>/*****************************************************************************
* Licensed to Qualys, Inc. (QUALYS) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* QUALYS licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
****************************************************************************/
/**
* @file
* @brief Predicate --- Standard IronBee Tests
*
* @author Christopher Alfeld <[email protected]>
**/
#include "standard_test.hpp"
#include <predicate/reporter.hpp>
#include <ironbee/rule_engine.h>
using namespace IronBee::Predicate;
using namespace std;
class TestStandardIronBee :
public StandardTest
{
};
TEST_F(TestStandardIronBee, field)
{
uint8_t data[4] = {'t', 'e', 's', 't'};
ib_status_t rc = ib_data_add_bytestr(
m_transaction.ib()->data,
"TestStandard.Field",
data, 4,
NULL
);
EXPECT_EQ(IB_OK, rc);
EXPECT_EQ("test", eval_s("(field 'TestStandard.Field')"));
}
TEST_F(TestStandardIronBee, Operator)
{
EXPECT_TRUE(eval_bool("(operator 'istreq' 'fOo' 'foo')"));
EXPECT_FALSE(eval_bool("(operator 'istreq' 'fOo' 'bar')"));
EXPECT_THROW(eval_bool("(operator 'dne' 'a' 'b')"), IronBee::einval);
EXPECT_THROW(eval_bool("(operator)"), IronBee::einval);
EXPECT_THROW(eval_bool("(operator 'a')"), IronBee::einval);
EXPECT_THROW(eval_bool("(operator 'a' 'b')"), IronBee::einval);
EXPECT_THROW(eval_bool("(operator 'a' 'b' 'c' 'd')"), IronBee::einval);
EXPECT_THROW(eval_bool("(operator 'a' null 'c')"), IronBee::einval);
EXPECT_THROW(eval_bool("(operator null 'b' 'c')"), IronBee::einval);
}
TEST_F(TestStandardIronBee, transformation)
{
EXPECT_EQ("foo", eval_s("(transformation 'lowercase' 'fOO')"));
EXPECT_THROW(eval_s("(transformation)"), IronBee::einval);
EXPECT_THROW(eval_s("(transformation 'a')"), IronBee::einval);
EXPECT_THROW(eval_s("(transformation 'a' 'b' 'c')"), IronBee::einval);
EXPECT_THROW(eval_s("(transformation null 'b')"), IronBee::einval);
}
TEST_F(TestStandardIronBee, phase)
{
// Track old rule_exec so we can restore it.
ib_rule_exec_t* old_rule_exec = m_transaction.ib()->rule_exec;
// Test data rule exec.
ib_rule_exec_t rule_exec;
m_transaction.ib()->rule_exec = &rule_exec;
rule_exec.phase = IB_PHASE_REQUEST_HEADER;
EXPECT_FALSE(eval_bool("(isFinished (waitPhase 'response_header' 'foo'))"));
rule_exec.phase = IB_PHASE_RESPONSE_HEADER;
EXPECT_TRUE(eval_bool("(isFinished (waitPhase 'response_header' 'foo'))"));
rule_exec.phase = IB_PHASE_REQUEST_HEADER;
EXPECT_TRUE(eval_bool("(isFinished (finishPhase 'request_header' (sequence 0)))"));
rule_exec.phase = IB_PHASE_RESPONSE_HEADER;
EXPECT_FALSE(eval_bool("(isFinished (finishPhase 'request_header' (sequence 0)))"));
EXPECT_THROW(eval_s("(waitPhase)"), IronBee::einval);
EXPECT_THROW(eval_s("(waitPhase 'request_header')"), IronBee::einval);
EXPECT_THROW(eval_s("(waitPhase 'request_header' 'b' 'c')"), IronBee::einval);
EXPECT_THROW(eval_s("(waitPhase null 'b')"), IronBee::einval);
EXPECT_THROW(eval_s("(waitPhase 'foo' 'b')"), IronBee::einval);
EXPECT_THROW(eval_s("(finishPhase)"), IronBee::einval);
EXPECT_THROW(eval_s("(finishPhase 'request_header')"), IronBee::einval);
EXPECT_THROW(eval_s("(finishPhase 'request_header' 'b' 'c')"), IronBee::einval);
EXPECT_THROW(eval_s("(finishPhase null 'b')"), IronBee::einval);
EXPECT_THROW(eval_s("(finishPhase 'foo' 'b')"), IronBee::einval);
m_transaction.ib()->rule_exec = old_rule_exec;
}
class TestAsk :
public Call
{
public:
virtual std::string name() const
{
return "test_ask";
}
virtual void pre_eval(Environment environment, NodeReporter reporter)
{
m_value =
IronBee::Field::create_dynamic_list<Value>(
environment.main_memory_pool(),
"", 0,
getter,
boost::function<
void(
IronBee::Field,
const char*, size_t,
IronBee::ConstList<Value>
)
>()
);
}
protected:
virtual void calculate(EvalContext context)
{
add_value(m_value);
finish();
}
private:
static
IronBee::ConstList<Value> getter(
IronBee::ConstField f,
const char* param,
size_t n
)
{
using namespace IronBee;
typedef List<Value> result_t;
result_t result = result_t::create(f.memory_pool());
result.push_back(
IronBee::Field::create_byte_string(
f.memory_pool(),
param, n,
IronBee::ByteString::create(
f.memory_pool(),
param, n
)
)
);
return result;
}
Value m_value;
};
TEST_F(TestStandardIronBee, Ask)
{
m_factory.add<TestAsk>();
/* Test dynamic behavior. */
EXPECT_EQ("foo", eval_s("(ask 'foo' (test_ask))"));
/* Test sublike behavior. */
EXPECT_EQ("1", eval_s("(ask 'a' (gather (cat (setName 'a' '1') (setName 'b' 2) (setName 'c' 3))))"));
EXPECT_TRUE(eval_bool("(isLonger 1 (ask 'a' (gather (cat (setName 'a' '1') (setName 'b' 2) (setName 'a' 3)))))"));
EXPECT_THROW(eval_bool("(ask)"), IronBee::einval);
EXPECT_THROW(eval_bool("(ask 1 'b')"), IronBee::einval);
EXPECT_THROW(eval_bool("(ask 'a')"), IronBee::einval);
EXPECT_THROW(eval_bool("(ask 'a' 'b' 'c')"), IronBee::einval);
}
<|endoftext|>
|
<commit_before>/******************************************************
* disk.cpp - Disk module implementation
* created 140204 jonathan howard ([email protected])
******************************************************/
#include "hdd.h"
#include <cstring>
#include <cstdlib>
#include <stdexcept>
#define BUFFER_SIZE (2048 * sizeof(WORD))
#define FILE_SIZE(x) (x.programSize + x.inputBufferSize + x.outputBufferSize + x.tempBufferSize)
HDD::HDD()
{
/* use c-style array memory allocation */
buffer = new WORD[2048]();
}
HDD::~HDD()
{
delete[] buffer;
}
void * HDD::newFile(size_t size)
{
// DLOG("[HDD] creating file with size %lu", size);
// File * fs;
// for (fs = (File *)buffer; fs->id == 0; fs += sizeof(File) + (FILE_SIZE((*fs)) * sizeof(WORD)));
// return fs;
return std::malloc(size);
}
void * HDD::newFile(size_t id, void * data, size_t size)
{
#if DEBUG
if (id == 0)
throw std::invalid_argument("id must not equal 0");
#endif
File * fs;
for (fs = (File *)buffer; fs->id == 0; fs += sizeof(File) + (FILE_SIZE((*fs)) * sizeof(WORD)));
fs->id = id;
fs->programSize = size;
std::memcpy(fs + sizeof(File), data, size);
return fs;
}
File * HDD::findFile(unsigned int id)
{
for (File * fs = (File *)buffer; fs->id == 0; fs += sizeof(File) + (FILE_SIZE((*fs)) * sizeof(WORD)))
{
if (fs->id == id)
{
return fs;
}
}
return nullptr;
}
<commit_msg>uncommented newFile logging<commit_after>/******************************************************
* disk.cpp - Disk module implementation
* created 140204 jonathan howard ([email protected])
******************************************************/
#include "hdd.h"
#include <cstring>
#include <cstdlib>
#include <stdexcept>
#define BUFFER_SIZE (2048 * sizeof(WORD))
#define FILE_SIZE(x) (x.programSize + x.inputBufferSize + x.outputBufferSize + x.tempBufferSize)
HDD::HDD()
{
/* use c-style array memory allocation */
buffer = new WORD[2048]();
}
HDD::~HDD()
{
delete[] buffer;
}
void * HDD::newFile(size_t size)
{
DLOG("[HDD] creating file with size %lu", size);
// File * fs;
// for (fs = (File *)buffer; fs->id == 0; fs += sizeof(File) + (FILE_SIZE((*fs)) * sizeof(WORD)));
// return fs;
return std::malloc(size);
}
void * HDD::newFile(size_t id, void * data, size_t size)
{
#if DEBUG
if (id == 0)
throw std::invalid_argument("id must not equal 0");
#endif
File * fs;
for (fs = (File *)buffer; fs->id == 0; fs += sizeof(File) + (FILE_SIZE((*fs)) * sizeof(WORD)));
fs->id = id;
fs->programSize = size;
std::memcpy(fs + sizeof(File), data, size);
return fs;
}
File * HDD::findFile(unsigned int id)
{
for (File * fs = (File *)buffer; fs->id == 0; fs += sizeof(File) + (FILE_SIZE((*fs)) * sizeof(WORD)))
{
if (fs->id == id)
{
return fs;
}
}
return nullptr;
}
<|endoftext|>
|
<commit_before>#include <ros/ros.h>
#include <geometry_msgs/Twist.h>
#include <tf/transform_broadcaster.h>
#include <boost/bind.hpp>
#include <boost/lambda/lambda.hpp>
#include <sys/time.h>
#include "imu/bool_msg.h"
#include "Comm.h"
#include <sensor_msgs/Imu.h>
#include <stdexcept>
class CheckSumError : public std::logic_error {
public:
CheckSumError(const std::string &data) :
std::logic_error("Received the Invalid IMU Data: " + data)
{
}
};
float deg_to_rad(float deg) {
return deg / 180.0f * M_PI;
}
template<class T>
bool isInRange(T value, T max, T min){
return (value >= min) && (value <= max);
}
struct ImuData {
double angular_deg[3];
bool flag;
ImuData(){
for(int i=0; i < 2; i++){
angular_deg[i] = 0;
}
}
};
// 角度ごとにURGのデータを送信するためのサービス
// 要求があったときに,URGのデータを別のトピックに送信するだけ
class IMU {
private:
ros::Publisher imu_pub_;
ros::ServiceServer reset_service_;
ros::ServiceServer carivrate_service_;
float geta;
CComm* usb;
double gyro_unit;
double acc_unit;
double init_angle;
std::string port_name;
int baudrate;
ros::Rate loop_rate;
int z_axis_dir_;
ImuData getImuData(){
ImuData data;
char command[2] = {0};
char command2[50] = {0};
char temp[6];
unsigned long int sum = 0;
const float temp_unit = 0.00565;
sprintf(command, "o");
usb->Send(command, strlen(command));
ros::Duration(0.03).sleep();
usb->Recv(command2, 50);
ROS_INFO_STREAM("recv = " << command2);
if (command2[0] == '\0') {
data.flag = false;
return data;
}
data.flag = true;
memmove(temp,command2,4);
sum = sum ^ ((short)strtol(temp, NULL, 16));
data.angular_deg[0] = ((short)strtol(temp, NULL, 16)) * gyro_unit;
memmove(temp,command2+4,4);
sum = sum ^ ((short)strtol(temp, NULL, 16));
data.angular_deg[1] = ((short)strtol(temp, NULL, 16)) * gyro_unit;
memmove(temp,command2+8,4);
sum = sum ^ ((short)strtol(temp, NULL, 16));
data.angular_deg[2] = ((short)strtol(temp, NULL, 16)) * gyro_unit * z_axis_dir_;
memmove(temp,command2+12,4);
if(sum != ((short)strtol(temp, NULL, 16))){
ROS_ERROR_STREAM("Recv Checksum: " << ((short)strtol(temp, NULL, 16)));
ROS_ERROR_STREAM("Calculate Checksum: " << sum);
throw CheckSumError(command2);
}
//while(data.angular_deg[2] < -180) data.angular_deg[2] += 180;
//while(data.angular_deg[2] > 180) data.angular_deg[2] -= 180;
return data;
}
public:
bool resetCallback(imu::bool_msg::Request &req,
imu::bool_msg::Response &res)
{
char command[2] = {0};
sprintf(command, "0");
usb->Send(command, strlen(command));
sleep(1);
std::cout << "Gyro 0 Reset" << std::endl;
return true;
}
bool caribrateCallback(imu::bool_msg::Request &req,
imu::bool_msg::Response &res)
{
char command[2] = {0};
std::cout << "Calibration" << std::endl;
sprintf(command, "a");
usb->Send(command, strlen(command));
std::cout << "Caribrate start ";
for(int i=0; i<8; ++i) {
std::cout << ". ";
sleep(1);
}
std::cout << "finish." << std::endl;
return true;
}
IMU(ros::NodeHandle node) :
imu_pub_(node.advertise<sensor_msgs::Imu>("imu", 10)),
reset_service_(node.advertiseService("imu_reset", &IMU::resetCallback, this)),
carivrate_service_(node.advertiseService("imu_caribrate", &IMU::caribrateCallback, this)),
geta(0), gyro_unit(0.00836181640625), acc_unit(0.8), init_angle(0.0),
port_name("/dev/ttyUSB0"), baudrate(115200), loop_rate(50), z_axis_dir_(-1)
{
ros::NodeHandle private_nh("~");
private_nh.getParam("port_name", port_name);
private_nh.param<double>("gyro_unit", gyro_unit, gyro_unit);
private_nh.param<double>("acc_unit", acc_unit, acc_unit);
private_nh.param<int>("baud_rate", baudrate, baudrate);
private_nh.param<double>("init_angle", init_angle, init_angle);
private_nh.param<int>("z_axis_dir", z_axis_dir_, z_axis_dir_);
usb = new CComm(port_name, baudrate);
}
bool init() {
char command[2] = {0};
char command2[101] = {0};
//シリアルポートオープン
if (!usb->Open()) {
std::cerr << "open error" << std::endl;
return false;
}
std::cout << "device open success" << std::endl;
sleep(1);
//コンフィギュレーション キャリブレーション
// if(m_calibration == true){
std::cout << "Calibration" << std::endl;
sprintf(command, "a");
usb->Send(command, strlen(command));
std::cout << "send = " << command << std::endl;
for(int i=0; i<8; ++i) {
printf(". ");
sleep(1);
}
// }
//コンフィギュレーション リセット
// if(m_reset == true){
sprintf(command, "0");
usb->Send(command, strlen(command)); //送信
std::cout << "send = " << command << std::endl;
sleep(1);
std::cout << "Gyro 0 Reset" << std::endl;
// }
geta = 0;
usb->Recv(command2, 100); //空読み バッファクリアが効かない?
usb->ClearRecvBuf(); //バッファクリア
return true;
}
void run() {
double old_angular_z_deg = getImuData().angular_deg[2];
double angular_z_deg = 0;
unsigned short abnormal_count = 0;
while (ros::ok()) {
tf::Quaternion q;
sensor_msgs::Imu output_msg;
try{
ImuData data = getImuData();
if (data.flag == false){
usb->Close();
if(!usb->Open()) {
std::cerr << "reconnecting" << std::endl;
}
}else{
output_msg.header.stamp = ros::Time::now();
ROS_INFO_STREAM("x_deg = " << data.angular_deg[0]);
ROS_INFO_STREAM("y_deg = " << data.angular_deg[1]);
ROS_INFO_STREAM("z_deg = " << data.angular_deg[2]);
if(!isInRange(std::abs(old_angular_z_deg), 180.0, 165.0) && !isInRange(std::abs(data.angular_deg[2]), 180.0, 165.0) &&
std::abs(old_angular_z_deg - data.angular_deg[2]) > 40 && abnormal_count < 4){
ROS_WARN_STREAM("Angle change too large: z = " << data.angular_deg[2]);
ROS_WARN_STREAM("old_z = " << old_angular_z_deg);
abnormal_count++;
continue;
}else{
abnormal_count = 0;
angular_z_deg = data.angular_deg[2];
}
//output_msg.orientation = tf::createQuaternionMsgFromYaw(deg_to_rad(angular_z_deg));
q = tf::createQuaternionFromRPY(deg_to_rad(data.angular_deg[0]),deg_to_rad(data.angular_deg[1]),deg_to_rad(angular_z_deg));
tf::quaternionTFToMsg(q, output_msg.orientation);
imu_pub_.publish(output_msg);
old_angular_z_deg = angular_z_deg;
}
}catch(const CheckSumError &e){
output_msg.header.stamp = ros::Time::now();
ROS_ERROR_STREAM(e.what());
continue;
}
ros::spinOnce();
//loop_rate.sleep();
}
}
};
int main(int argc, char * argv[])
{
ros::init(argc, argv, "imu");
ros::NodeHandle node;
IMU imu(node);
if(!imu.init()) return 1;
imu.run();
return 0;
}
<commit_msg>Fix pitch unit<commit_after>#include <ros/ros.h>
#include <geometry_msgs/Twist.h>
#include <tf/transform_broadcaster.h>
#include <boost/bind.hpp>
#include <boost/lambda/lambda.hpp>
#include <sys/time.h>
#include "imu/bool_msg.h"
#include "Comm.h"
#include <sensor_msgs/Imu.h>
#include <stdexcept>
class CheckSumError : public std::logic_error {
public:
CheckSumError(const std::string &data) :
std::logic_error("Received the Invalid IMU Data: " + data)
{
}
};
float deg_to_rad(float deg) {
return deg / 180.0f * M_PI;
}
template<class T>
bool isInRange(T value, T max, T min){
return (value >= min) && (value <= max);
}
struct ImuData {
double angular_deg[3];
bool flag;
ImuData(){
for(int i=0; i < 2; i++){
angular_deg[i] = 0;
}
}
};
// 角度ごとにURGのデータを送信するためのサービス
// 要求があったときに,URGのデータを別のトピックに送信するだけ
class IMU {
private:
ros::Publisher imu_pub_;
ros::ServiceServer reset_service_;
ros::ServiceServer carivrate_service_;
float geta;
CComm* usb;
double gyro_unit;
double acc_unit;
double init_angle;
std::string port_name;
int baudrate;
ros::Rate loop_rate;
int z_axis_dir_;
ImuData getImuData(){
ImuData data;
char command[2] = {0};
char command2[50] = {0};
char temp[6];
unsigned long int sum = 0;
const float temp_unit = 0.00565;
sprintf(command, "o");
usb->Send(command, strlen(command));
ros::Duration(0.03).sleep();
usb->Recv(command2, 50);
ROS_INFO_STREAM("recv = " << command2);
if (command2[0] == '\0') {
data.flag = false;
return data;
}
data.flag = true;
memmove(temp,command2,4);
sum = sum ^ ((short)strtol(temp, NULL, 16));
data.angular_deg[0] = ((short)strtol(temp, NULL, 16)) * gyro_unit;
memmove(temp,command2+4,4);
sum = sum ^ ((short)strtol(temp, NULL, 16));
data.angular_deg[1] = ((short)strtol(temp, NULL, 16)) * gyro_unit;
memmove(temp,command2+8,4);
sum = sum ^ ((short)strtol(temp, NULL, 16));
data.angular_deg[2] = ((short)strtol(temp, NULL, 16)) * gyro_unit * z_axis_dir_;
memmove(temp,command2+12,4);
if(sum != ((short)strtol(temp, NULL, 16))){
ROS_ERROR_STREAM("Recv Checksum: " << ((short)strtol(temp, NULL, 16)));
ROS_ERROR_STREAM("Calculate Checksum: " << sum);
throw CheckSumError(command2);
}
//while(data.angular_deg[2] < -180) data.angular_deg[2] += 180;
//while(data.angular_deg[2] > 180) data.angular_deg[2] -= 180;
return data;
}
public:
bool resetCallback(imu::bool_msg::Request &req,
imu::bool_msg::Response &res)
{
char command[2] = {0};
sprintf(command, "0");
usb->Send(command, strlen(command));
sleep(1);
std::cout << "Gyro 0 Reset" << std::endl;
return true;
}
bool caribrateCallback(imu::bool_msg::Request &req,
imu::bool_msg::Response &res)
{
char command[2] = {0};
std::cout << "Calibration" << std::endl;
sprintf(command, "a");
usb->Send(command, strlen(command));
std::cout << "Caribrate start ";
for(int i=0; i<8; ++i) {
std::cout << ". ";
sleep(1);
}
std::cout << "finish." << std::endl;
return true;
}
IMU(ros::NodeHandle node) :
imu_pub_(node.advertise<sensor_msgs::Imu>("imu", 10)),
reset_service_(node.advertiseService("imu_reset", &IMU::resetCallback, this)),
carivrate_service_(node.advertiseService("imu_caribrate", &IMU::caribrateCallback, this)),
geta(0), gyro_unit(0.00836181640625), acc_unit(0.8), init_angle(0.0),
port_name("/dev/ttyUSB0"), baudrate(115200), loop_rate(50), z_axis_dir_(-1)
{
ros::NodeHandle private_nh("~");
private_nh.getParam("port_name", port_name);
private_nh.param<double>("gyro_unit", gyro_unit, gyro_unit);
private_nh.param<double>("acc_unit", acc_unit, acc_unit);
private_nh.param<int>("baud_rate", baudrate, baudrate);
private_nh.param<double>("init_angle", init_angle, init_angle);
private_nh.param<int>("z_axis_dir", z_axis_dir_, z_axis_dir_);
usb = new CComm(port_name, baudrate);
}
bool init() {
char command[2] = {0};
char command2[101] = {0};
//シリアルポートオープン
if (!usb->Open()) {
std::cerr << "open error" << std::endl;
return false;
}
std::cout << "device open success" << std::endl;
sleep(1);
//コンフィギュレーション キャリブレーション
// if(m_calibration == true){
std::cout << "Calibration" << std::endl;
sprintf(command, "a");
usb->Send(command, strlen(command));
std::cout << "send = " << command << std::endl;
for(int i=0; i<8; ++i) {
printf(". ");
sleep(1);
}
// }
//コンフィギュレーション リセット
// if(m_reset == true){
sprintf(command, "0");
usb->Send(command, strlen(command)); //送信
std::cout << "send = " << command << std::endl;
sleep(1);
std::cout << "Gyro 0 Reset" << std::endl;
// }
geta = 0;
usb->Recv(command2, 100); //空読み バッファクリアが効かない?
usb->ClearRecvBuf(); //バッファクリア
return true;
}
void run() {
double old_angular_z_deg = getImuData().angular_deg[2];
double angular_z_deg = 0;
unsigned short abnormal_count = 0;
while (ros::ok()) {
tf::Quaternion q;
sensor_msgs::Imu output_msg;
try{
ImuData data = getImuData();
if (data.flag == false){
usb->Close();
if(!usb->Open()) {
std::cerr << "reconnecting" << std::endl;
}
}else{
output_msg.header.stamp = ros::Time::now();
ROS_INFO_STREAM("x_deg = " << data.angular_deg[0]);
ROS_INFO_STREAM("y_deg = " << data.angular_deg[1]);
ROS_INFO_STREAM("z_deg = " << data.angular_deg[2]);
if(!isInRange(std::abs(old_angular_z_deg), 180.0, 165.0) && !isInRange(std::abs(data.angular_deg[2]), 180.0, 165.0) &&
std::abs(old_angular_z_deg - data.angular_deg[2]) > 40 && abnormal_count < 4){
ROS_WARN_STREAM("Angle change too large: z = " << data.angular_deg[2]);
ROS_WARN_STREAM("old_z = " << old_angular_z_deg);
abnormal_count++;
continue;
}else{
abnormal_count = 0;
angular_z_deg = data.angular_deg[2];
}
//output_msg.orientation = tf::createQuaternionMsgFromYaw(deg_to_rad(angular_z_deg));
q = tf::createQuaternionFromRPY(deg_to_rad(data.angular_deg[0]),deg_to_rad(-data.angular_deg[1]),deg_to_rad(angular_z_deg));
tf::quaternionTFToMsg(q, output_msg.orientation);
imu_pub_.publish(output_msg);
old_angular_z_deg = angular_z_deg;
}
}catch(const CheckSumError &e){
output_msg.header.stamp = ros::Time::now();
ROS_ERROR_STREAM(e.what());
continue;
}
ros::spinOnce();
//loop_rate.sleep();
}
}
};
int main(int argc, char * argv[])
{
ros::init(argc, argv, "imu");
ros::NodeHandle node;
IMU imu(node);
if(!imu.init()) return 1;
imu.run();
return 0;
}
<|endoftext|>
|
<commit_before>// MIT License
// Copyright (c) 2017 Zhuhao Wang
// 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 "nekit/init.h"
#include <boost/log/utility/setup/common_attributes.hpp>
namespace nekit {
void Initailize() { boost::log::add_common_attributes(); }
} // namespace nekit
<commit_msg>FEAT: Initialize OpenSSL crypto when initialize libnekit<commit_after>// MIT License
// Copyright (c) 2017 Zhuhao Wang
// 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 "nekit/init.h"
#include <boost/log/utility/setup/common_attributes.hpp>
#include <openssl/evp.h>
namespace nekit {
void Initailize() {
boost::log::add_common_attributes();
OpenSSL_add_all_algorithms();
}
} // namespace nekit
<|endoftext|>
|
<commit_before>// Copyright (c) 2009-2012 The Bitcoin developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include <map>
#include <openssl/ecdsa.h>
#include <openssl/obj_mac.h>
#include "key.h"
// Generate a private key from just the secret parameter
int EC_KEY_regenerate_key(EC_KEY *eckey, BIGNUM *priv_key)
{
int ok = 0;
BN_CTX *ctx = NULL;
EC_POINT *pub_key = NULL;
if (!eckey) return 0;
const EC_GROUP *group = EC_KEY_get0_group(eckey);
if ((ctx = BN_CTX_new()) == NULL)
goto err;
pub_key = EC_POINT_new(group);
if (pub_key == NULL)
goto err;
if (!EC_POINT_mul(group, pub_key, priv_key, NULL, NULL, ctx))
goto err;
EC_KEY_set_private_key(eckey,priv_key);
EC_KEY_set_public_key(eckey,pub_key);
ok = 1;
err:
if (pub_key)
EC_POINT_free(pub_key);
if (ctx != NULL)
BN_CTX_free(ctx);
return(ok);
}
// Perform ECDSA key recovery (see SEC1 4.1.6) for curves over (mod p)-fields
// recid selects which key is recovered
// if check is nonzero, additional checks are performed
int ECDSA_SIG_recover_key_GFp(EC_KEY *eckey, ECDSA_SIG *ecsig, const unsigned char *msg, int msglen, int recid, int check)
{
if (!eckey) return 0;
int ret = 0;
BN_CTX *ctx = NULL;
BIGNUM *x = NULL;
BIGNUM *e = NULL;
BIGNUM *order = NULL;
BIGNUM *sor = NULL;
BIGNUM *eor = NULL;
BIGNUM *field = NULL;
EC_POINT *R = NULL;
EC_POINT *O = NULL;
EC_POINT *Q = NULL;
BIGNUM *rr = NULL;
BIGNUM *zero = NULL;
int n = 0;
int i = recid / 2;
const EC_GROUP *group = EC_KEY_get0_group(eckey);
if ((ctx = BN_CTX_new()) == NULL) { ret = -1; goto err; }
BN_CTX_start(ctx);
order = BN_CTX_get(ctx);
if (!EC_GROUP_get_order(group, order, ctx)) { ret = -2; goto err; }
x = BN_CTX_get(ctx);
if (!BN_copy(x, order)) { ret=-1; goto err; }
if (!BN_mul_word(x, i)) { ret=-1; goto err; }
if (!BN_add(x, x, ecsig->r)) { ret=-1; goto err; }
field = BN_CTX_get(ctx);
if (!EC_GROUP_get_curve_GFp(group, field, NULL, NULL, ctx)) { ret=-2; goto err; }
if (BN_cmp(x, field) >= 0) { ret=0; goto err; }
if ((R = EC_POINT_new(group)) == NULL) { ret = -2; goto err; }
if (!EC_POINT_set_compressed_coordinates_GFp(group, R, x, recid % 2, ctx)) { ret=0; goto err; }
if (check)
{
if ((O = EC_POINT_new(group)) == NULL) { ret = -2; goto err; }
if (!EC_POINT_mul(group, O, NULL, R, order, ctx)) { ret=-2; goto err; }
if (!EC_POINT_is_at_infinity(group, O)) { ret = 0; goto err; }
}
if ((Q = EC_POINT_new(group)) == NULL) { ret = -2; goto err; }
n = EC_GROUP_get_degree(group);
e = BN_CTX_get(ctx);
if (!BN_bin2bn(msg, msglen, e)) { ret=-1; goto err; }
if (8*msglen > n) BN_rshift(e, e, 8-(n & 7));
zero = BN_CTX_get(ctx);
if (!BN_zero(zero)) { ret=-1; goto err; }
if (!BN_mod_sub(e, zero, e, order, ctx)) { ret=-1; goto err; }
rr = BN_CTX_get(ctx);
if (!BN_mod_inverse(rr, ecsig->r, order, ctx)) { ret=-1; goto err; }
sor = BN_CTX_get(ctx);
if (!BN_mod_mul(sor, ecsig->s, rr, order, ctx)) { ret=-1; goto err; }
eor = BN_CTX_get(ctx);
if (!BN_mod_mul(eor, e, rr, order, ctx)) { ret=-1; goto err; }
if (!EC_POINT_mul(group, Q, eor, R, sor, ctx)) { ret=-2; goto err; }
if (!EC_KEY_set_public_key(eckey, Q)) { ret=-2; goto err; }
ret = 1;
err:
if (ctx) {
BN_CTX_end(ctx);
BN_CTX_free(ctx);
}
if (R != NULL) EC_POINT_free(R);
if (O != NULL) EC_POINT_free(O);
if (Q != NULL) EC_POINT_free(Q);
return ret;
}
void CKey::SetCompressedPubKey()
{
EC_KEY_set_conv_form(pkey, POINT_CONVERSION_COMPRESSED);
fCompressedPubKey = true;
}
void CKey::Reset()
{
fCompressedPubKey = false;
pkey = EC_KEY_new_by_curve_name(NID_secp256k1);
if (pkey == NULL)
throw key_error("CKey::CKey() : EC_KEY_new_by_curve_name failed");
fSet = false;
}
CKey::CKey()
{
Reset();
}
CKey::CKey(const CKey& b)
{
pkey = EC_KEY_dup(b.pkey);
if (pkey == NULL)
throw key_error("CKey::CKey(const CKey&) : EC_KEY_dup failed");
fSet = b.fSet;
}
CKey& CKey::operator=(const CKey& b)
{
if (!EC_KEY_copy(pkey, b.pkey))
throw key_error("CKey::operator=(const CKey&) : EC_KEY_copy failed");
fSet = b.fSet;
return (*this);
}
CKey::~CKey()
{
EC_KEY_free(pkey);
}
bool CKey::IsNull() const
{
return !fSet;
}
bool CKey::IsCompressed() const
{
return fCompressedPubKey;
}
void CKey::MakeNewKey(bool fCompressed)
{
if (!EC_KEY_generate_key(pkey))
throw key_error("CKey::MakeNewKey() : EC_KEY_generate_key failed");
if (fCompressed)
SetCompressedPubKey();
fSet = true;
}
bool CKey::SetPrivKey(const CPrivKey& vchPrivKey)
{
const unsigned char* pbegin = &vchPrivKey[0];
if (!d2i_ECPrivateKey(&pkey, &pbegin, vchPrivKey.size()))
return false;
fSet = true;
return true;
}
bool CKey::SetSecret(const CSecret& vchSecret, bool fCompressed)
{
EC_KEY_free(pkey);
pkey = EC_KEY_new_by_curve_name(NID_secp256k1);
if (pkey == NULL)
throw key_error("CKey::SetSecret() : EC_KEY_new_by_curve_name failed");
if (vchSecret.size() != 32)
throw key_error("CKey::SetSecret() : secret must be 32 bytes");
BIGNUM *bn = BN_bin2bn(&vchSecret[0],32,BN_new());
if (bn == NULL)
throw key_error("CKey::SetSecret() : BN_bin2bn failed");
if (!EC_KEY_regenerate_key(pkey,bn))
{
BN_clear_free(bn);
throw key_error("CKey::SetSecret() : EC_KEY_regenerate_key failed");
}
BN_clear_free(bn);
fSet = true;
if (fCompressed || fCompressedPubKey)
SetCompressedPubKey();
return true;
}
CSecret CKey::GetSecret(bool &fCompressed) const
{
CSecret vchRet;
vchRet.resize(32);
const BIGNUM *bn = EC_KEY_get0_private_key(pkey);
int nBytes = BN_num_bytes(bn);
if (bn == NULL)
throw key_error("CKey::GetSecret() : EC_KEY_get0_private_key failed");
int n=BN_bn2bin(bn,&vchRet[32 - nBytes]);
if (n != nBytes)
throw key_error("CKey::GetSecret(): BN_bn2bin failed");
fCompressed = fCompressedPubKey;
return vchRet;
}
CPrivKey CKey::GetPrivKey() const
{
int nSize = i2d_ECPrivateKey(pkey, NULL);
if (!nSize)
throw key_error("CKey::GetPrivKey() : i2d_ECPrivateKey failed");
CPrivKey vchPrivKey(nSize, 0);
unsigned char* pbegin = &vchPrivKey[0];
if (i2d_ECPrivateKey(pkey, &pbegin) != nSize)
throw key_error("CKey::GetPrivKey() : i2d_ECPrivateKey returned unexpected size");
return vchPrivKey;
}
bool CKey::SetPubKey(const CPubKey& vchPubKey)
{
const unsigned char* pbegin = &vchPubKey.vchPubKey[0];
if (!o2i_ECPublicKey(&pkey, &pbegin, vchPubKey.vchPubKey.size()))
return false;
fSet = true;
if (vchPubKey.vchPubKey.size() == 33)
SetCompressedPubKey();
return true;
}
CPubKey CKey::GetPubKey() const
{
int nSize = i2o_ECPublicKey(pkey, NULL);
if (!nSize)
throw key_error("CKey::GetPubKey() : i2o_ECPublicKey failed");
std::vector<unsigned char> vchPubKey(nSize, 0);
unsigned char* pbegin = &vchPubKey[0];
if (i2o_ECPublicKey(pkey, &pbegin) != nSize)
throw key_error("CKey::GetPubKey() : i2o_ECPublicKey returned unexpected size");
return CPubKey(vchPubKey);
}
bool CKey::Sign(uint256 hash, std::vector<unsigned char>& vchSig)
{
unsigned int nSize = ECDSA_size(pkey);
vchSig.resize(nSize); // Make sure it is big enough
if (!ECDSA_sign(0, (unsigned char*)&hash, sizeof(hash), &vchSig[0], &nSize, pkey))
{
vchSig.clear();
return false;
}
vchSig.resize(nSize); // Shrink to fit actual size
return true;
}
// create a compact signature (65 bytes), which allows reconstructing the used public key
// The format is one header byte, followed by two times 32 bytes for the serialized r and s values.
// The header byte: 0x1B = first key with even y, 0x1C = first key with odd y,
// 0x1D = second key with even y, 0x1E = second key with odd y
bool CKey::SignCompact(uint256 hash, std::vector<unsigned char>& vchSig)
{
bool fOk = false;
ECDSA_SIG *sig = ECDSA_do_sign((unsigned char*)&hash, sizeof(hash), pkey);
if (sig==NULL)
return false;
vchSig.clear();
vchSig.resize(65,0);
int nBitsR = BN_num_bits(sig->r);
int nBitsS = BN_num_bits(sig->s);
if (nBitsR <= 256 && nBitsS <= 256)
{
int nRecId = -1;
for (int i=0; i<4; i++)
{
CKey keyRec;
keyRec.fSet = true;
if (fCompressedPubKey)
keyRec.SetCompressedPubKey();
if (ECDSA_SIG_recover_key_GFp(keyRec.pkey, sig, (unsigned char*)&hash, sizeof(hash), i, 1) == 1)
if (keyRec.GetPubKey() == this->GetPubKey())
{
nRecId = i;
break;
}
}
if (nRecId == -1)
throw key_error("CKey::SignCompact() : unable to construct recoverable key");
vchSig[0] = nRecId+27+(fCompressedPubKey ? 4 : 0);
BN_bn2bin(sig->r,&vchSig[33-(nBitsR+7)/8]);
BN_bn2bin(sig->s,&vchSig[65-(nBitsS+7)/8]);
fOk = true;
}
ECDSA_SIG_free(sig);
return fOk;
}
// reconstruct public key from a compact signature
// This is only slightly more CPU intensive than just verifying it.
// If this function succeeds, the recovered public key is guaranteed to be valid
// (the signature is a valid signature of the given data for that key)
bool CKey::SetCompactSignature(uint256 hash, const std::vector<unsigned char>& vchSig)
{
if (vchSig.size() != 65)
return false;
int nV = vchSig[0];
if (nV<27 || nV>=35)
return false;
ECDSA_SIG *sig = ECDSA_SIG_new();
BN_bin2bn(&vchSig[1],32,sig->r);
BN_bin2bn(&vchSig[33],32,sig->s);
EC_KEY_free(pkey);
pkey = EC_KEY_new_by_curve_name(NID_secp256k1);
if (nV >= 31)
{
SetCompressedPubKey();
nV -= 4;
}
if (ECDSA_SIG_recover_key_GFp(pkey, sig, (unsigned char*)&hash, sizeof(hash), nV - 27, 0) == 1)
{
fSet = true;
ECDSA_SIG_free(sig);
return true;
}
return false;
}
bool CKey::Verify(uint256 hash, const std::vector<unsigned char>& vchSig)
{
// -1 = error, 0 = bad sig, 1 = good
if (ECDSA_verify(0, (unsigned char*)&hash, sizeof(hash), &vchSig[0], vchSig.size(), pkey) != 1)
return false;
return true;
}
bool CKey::VerifyCompact(uint256 hash, const std::vector<unsigned char>& vchSig)
{
CKey key;
if (!key.SetCompactSignature(hash, vchSig))
return false;
if (GetPubKey() != key.GetPubKey())
return false;
return true;
}
bool CKey::IsValid()
{
if (!fSet)
return false;
bool fCompr;
CSecret secret = GetSecret(fCompr);
CKey key2;
key2.SetSecret(secret, fCompr);
return GetPubKey() == key2.GetPubKey();
}
<commit_msg>fix a memory leak in key.cpp<commit_after>// Copyright (c) 2009-2012 The Bitcoin developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include <map>
#include <openssl/ecdsa.h>
#include <openssl/obj_mac.h>
#include "key.h"
// Generate a private key from just the secret parameter
int EC_KEY_regenerate_key(EC_KEY *eckey, BIGNUM *priv_key)
{
int ok = 0;
BN_CTX *ctx = NULL;
EC_POINT *pub_key = NULL;
if (!eckey) return 0;
const EC_GROUP *group = EC_KEY_get0_group(eckey);
if ((ctx = BN_CTX_new()) == NULL)
goto err;
pub_key = EC_POINT_new(group);
if (pub_key == NULL)
goto err;
if (!EC_POINT_mul(group, pub_key, priv_key, NULL, NULL, ctx))
goto err;
EC_KEY_set_private_key(eckey,priv_key);
EC_KEY_set_public_key(eckey,pub_key);
ok = 1;
err:
if (pub_key)
EC_POINT_free(pub_key);
if (ctx != NULL)
BN_CTX_free(ctx);
return(ok);
}
// Perform ECDSA key recovery (see SEC1 4.1.6) for curves over (mod p)-fields
// recid selects which key is recovered
// if check is nonzero, additional checks are performed
int ECDSA_SIG_recover_key_GFp(EC_KEY *eckey, ECDSA_SIG *ecsig, const unsigned char *msg, int msglen, int recid, int check)
{
if (!eckey) return 0;
int ret = 0;
BN_CTX *ctx = NULL;
BIGNUM *x = NULL;
BIGNUM *e = NULL;
BIGNUM *order = NULL;
BIGNUM *sor = NULL;
BIGNUM *eor = NULL;
BIGNUM *field = NULL;
EC_POINT *R = NULL;
EC_POINT *O = NULL;
EC_POINT *Q = NULL;
BIGNUM *rr = NULL;
BIGNUM *zero = NULL;
int n = 0;
int i = recid / 2;
const EC_GROUP *group = EC_KEY_get0_group(eckey);
if ((ctx = BN_CTX_new()) == NULL) { ret = -1; goto err; }
BN_CTX_start(ctx);
order = BN_CTX_get(ctx);
if (!EC_GROUP_get_order(group, order, ctx)) { ret = -2; goto err; }
x = BN_CTX_get(ctx);
if (!BN_copy(x, order)) { ret=-1; goto err; }
if (!BN_mul_word(x, i)) { ret=-1; goto err; }
if (!BN_add(x, x, ecsig->r)) { ret=-1; goto err; }
field = BN_CTX_get(ctx);
if (!EC_GROUP_get_curve_GFp(group, field, NULL, NULL, ctx)) { ret=-2; goto err; }
if (BN_cmp(x, field) >= 0) { ret=0; goto err; }
if ((R = EC_POINT_new(group)) == NULL) { ret = -2; goto err; }
if (!EC_POINT_set_compressed_coordinates_GFp(group, R, x, recid % 2, ctx)) { ret=0; goto err; }
if (check)
{
if ((O = EC_POINT_new(group)) == NULL) { ret = -2; goto err; }
if (!EC_POINT_mul(group, O, NULL, R, order, ctx)) { ret=-2; goto err; }
if (!EC_POINT_is_at_infinity(group, O)) { ret = 0; goto err; }
}
if ((Q = EC_POINT_new(group)) == NULL) { ret = -2; goto err; }
n = EC_GROUP_get_degree(group);
e = BN_CTX_get(ctx);
if (!BN_bin2bn(msg, msglen, e)) { ret=-1; goto err; }
if (8*msglen > n) BN_rshift(e, e, 8-(n & 7));
zero = BN_CTX_get(ctx);
if (!BN_zero(zero)) { ret=-1; goto err; }
if (!BN_mod_sub(e, zero, e, order, ctx)) { ret=-1; goto err; }
rr = BN_CTX_get(ctx);
if (!BN_mod_inverse(rr, ecsig->r, order, ctx)) { ret=-1; goto err; }
sor = BN_CTX_get(ctx);
if (!BN_mod_mul(sor, ecsig->s, rr, order, ctx)) { ret=-1; goto err; }
eor = BN_CTX_get(ctx);
if (!BN_mod_mul(eor, e, rr, order, ctx)) { ret=-1; goto err; }
if (!EC_POINT_mul(group, Q, eor, R, sor, ctx)) { ret=-2; goto err; }
if (!EC_KEY_set_public_key(eckey, Q)) { ret=-2; goto err; }
ret = 1;
err:
if (ctx) {
BN_CTX_end(ctx);
BN_CTX_free(ctx);
}
if (R != NULL) EC_POINT_free(R);
if (O != NULL) EC_POINT_free(O);
if (Q != NULL) EC_POINT_free(Q);
return ret;
}
void CKey::SetCompressedPubKey()
{
EC_KEY_set_conv_form(pkey, POINT_CONVERSION_COMPRESSED);
fCompressedPubKey = true;
}
void CKey::Reset()
{
fCompressedPubKey = false;
if (pkey != NULL)
EC_KEY_free(pkey);
pkey = EC_KEY_new_by_curve_name(NID_secp256k1);
if (pkey == NULL)
throw key_error("CKey::CKey() : EC_KEY_new_by_curve_name failed");
fSet = false;
}
CKey::CKey()
{
pkey = NULL;
Reset();
}
CKey::CKey(const CKey& b)
{
pkey = EC_KEY_dup(b.pkey);
if (pkey == NULL)
throw key_error("CKey::CKey(const CKey&) : EC_KEY_dup failed");
fSet = b.fSet;
}
CKey& CKey::operator=(const CKey& b)
{
if (!EC_KEY_copy(pkey, b.pkey))
throw key_error("CKey::operator=(const CKey&) : EC_KEY_copy failed");
fSet = b.fSet;
return (*this);
}
CKey::~CKey()
{
EC_KEY_free(pkey);
}
bool CKey::IsNull() const
{
return !fSet;
}
bool CKey::IsCompressed() const
{
return fCompressedPubKey;
}
void CKey::MakeNewKey(bool fCompressed)
{
if (!EC_KEY_generate_key(pkey))
throw key_error("CKey::MakeNewKey() : EC_KEY_generate_key failed");
if (fCompressed)
SetCompressedPubKey();
fSet = true;
}
bool CKey::SetPrivKey(const CPrivKey& vchPrivKey)
{
const unsigned char* pbegin = &vchPrivKey[0];
if (!d2i_ECPrivateKey(&pkey, &pbegin, vchPrivKey.size()))
return false;
fSet = true;
return true;
}
bool CKey::SetSecret(const CSecret& vchSecret, bool fCompressed)
{
EC_KEY_free(pkey);
pkey = EC_KEY_new_by_curve_name(NID_secp256k1);
if (pkey == NULL)
throw key_error("CKey::SetSecret() : EC_KEY_new_by_curve_name failed");
if (vchSecret.size() != 32)
throw key_error("CKey::SetSecret() : secret must be 32 bytes");
BIGNUM *bn = BN_bin2bn(&vchSecret[0],32,BN_new());
if (bn == NULL)
throw key_error("CKey::SetSecret() : BN_bin2bn failed");
if (!EC_KEY_regenerate_key(pkey,bn))
{
BN_clear_free(bn);
throw key_error("CKey::SetSecret() : EC_KEY_regenerate_key failed");
}
BN_clear_free(bn);
fSet = true;
if (fCompressed || fCompressedPubKey)
SetCompressedPubKey();
return true;
}
CSecret CKey::GetSecret(bool &fCompressed) const
{
CSecret vchRet;
vchRet.resize(32);
const BIGNUM *bn = EC_KEY_get0_private_key(pkey);
int nBytes = BN_num_bytes(bn);
if (bn == NULL)
throw key_error("CKey::GetSecret() : EC_KEY_get0_private_key failed");
int n=BN_bn2bin(bn,&vchRet[32 - nBytes]);
if (n != nBytes)
throw key_error("CKey::GetSecret(): BN_bn2bin failed");
fCompressed = fCompressedPubKey;
return vchRet;
}
CPrivKey CKey::GetPrivKey() const
{
int nSize = i2d_ECPrivateKey(pkey, NULL);
if (!nSize)
throw key_error("CKey::GetPrivKey() : i2d_ECPrivateKey failed");
CPrivKey vchPrivKey(nSize, 0);
unsigned char* pbegin = &vchPrivKey[0];
if (i2d_ECPrivateKey(pkey, &pbegin) != nSize)
throw key_error("CKey::GetPrivKey() : i2d_ECPrivateKey returned unexpected size");
return vchPrivKey;
}
bool CKey::SetPubKey(const CPubKey& vchPubKey)
{
const unsigned char* pbegin = &vchPubKey.vchPubKey[0];
if (!o2i_ECPublicKey(&pkey, &pbegin, vchPubKey.vchPubKey.size()))
return false;
fSet = true;
if (vchPubKey.vchPubKey.size() == 33)
SetCompressedPubKey();
return true;
}
CPubKey CKey::GetPubKey() const
{
int nSize = i2o_ECPublicKey(pkey, NULL);
if (!nSize)
throw key_error("CKey::GetPubKey() : i2o_ECPublicKey failed");
std::vector<unsigned char> vchPubKey(nSize, 0);
unsigned char* pbegin = &vchPubKey[0];
if (i2o_ECPublicKey(pkey, &pbegin) != nSize)
throw key_error("CKey::GetPubKey() : i2o_ECPublicKey returned unexpected size");
return CPubKey(vchPubKey);
}
bool CKey::Sign(uint256 hash, std::vector<unsigned char>& vchSig)
{
unsigned int nSize = ECDSA_size(pkey);
vchSig.resize(nSize); // Make sure it is big enough
if (!ECDSA_sign(0, (unsigned char*)&hash, sizeof(hash), &vchSig[0], &nSize, pkey))
{
vchSig.clear();
return false;
}
vchSig.resize(nSize); // Shrink to fit actual size
return true;
}
// create a compact signature (65 bytes), which allows reconstructing the used public key
// The format is one header byte, followed by two times 32 bytes for the serialized r and s values.
// The header byte: 0x1B = first key with even y, 0x1C = first key with odd y,
// 0x1D = second key with even y, 0x1E = second key with odd y
bool CKey::SignCompact(uint256 hash, std::vector<unsigned char>& vchSig)
{
bool fOk = false;
ECDSA_SIG *sig = ECDSA_do_sign((unsigned char*)&hash, sizeof(hash), pkey);
if (sig==NULL)
return false;
vchSig.clear();
vchSig.resize(65,0);
int nBitsR = BN_num_bits(sig->r);
int nBitsS = BN_num_bits(sig->s);
if (nBitsR <= 256 && nBitsS <= 256)
{
int nRecId = -1;
for (int i=0; i<4; i++)
{
CKey keyRec;
keyRec.fSet = true;
if (fCompressedPubKey)
keyRec.SetCompressedPubKey();
if (ECDSA_SIG_recover_key_GFp(keyRec.pkey, sig, (unsigned char*)&hash, sizeof(hash), i, 1) == 1)
if (keyRec.GetPubKey() == this->GetPubKey())
{
nRecId = i;
break;
}
}
if (nRecId == -1)
throw key_error("CKey::SignCompact() : unable to construct recoverable key");
vchSig[0] = nRecId+27+(fCompressedPubKey ? 4 : 0);
BN_bn2bin(sig->r,&vchSig[33-(nBitsR+7)/8]);
BN_bn2bin(sig->s,&vchSig[65-(nBitsS+7)/8]);
fOk = true;
}
ECDSA_SIG_free(sig);
return fOk;
}
// reconstruct public key from a compact signature
// This is only slightly more CPU intensive than just verifying it.
// If this function succeeds, the recovered public key is guaranteed to be valid
// (the signature is a valid signature of the given data for that key)
bool CKey::SetCompactSignature(uint256 hash, const std::vector<unsigned char>& vchSig)
{
if (vchSig.size() != 65)
return false;
int nV = vchSig[0];
if (nV<27 || nV>=35)
return false;
ECDSA_SIG *sig = ECDSA_SIG_new();
BN_bin2bn(&vchSig[1],32,sig->r);
BN_bin2bn(&vchSig[33],32,sig->s);
EC_KEY_free(pkey);
pkey = EC_KEY_new_by_curve_name(NID_secp256k1);
if (nV >= 31)
{
SetCompressedPubKey();
nV -= 4;
}
if (ECDSA_SIG_recover_key_GFp(pkey, sig, (unsigned char*)&hash, sizeof(hash), nV - 27, 0) == 1)
{
fSet = true;
ECDSA_SIG_free(sig);
return true;
}
return false;
}
bool CKey::Verify(uint256 hash, const std::vector<unsigned char>& vchSig)
{
// -1 = error, 0 = bad sig, 1 = good
if (ECDSA_verify(0, (unsigned char*)&hash, sizeof(hash), &vchSig[0], vchSig.size(), pkey) != 1)
return false;
return true;
}
bool CKey::VerifyCompact(uint256 hash, const std::vector<unsigned char>& vchSig)
{
CKey key;
if (!key.SetCompactSignature(hash, vchSig))
return false;
if (GetPubKey() != key.GetPubKey())
return false;
return true;
}
bool CKey::IsValid()
{
if (!fSet)
return false;
bool fCompr;
CSecret secret = GetSecret(fCompr);
CKey key2;
key2.SetSecret(secret, fCompr);
return GetPubKey() == key2.GetPubKey();
}
<|endoftext|>
|
<commit_before>#include <cerrno>
#include <chrono>
#include <cstring>
#include <fstream>
#include <iomanip>
#include <iostream>
#include <sstream>
#include <string>
#include <uv.h>
#include "log.h"
using std::cerr;
using std::chrono::steady_clock;
using std::cout;
using std::dec;
using std::endl;
using std::ofstream;
using std::ostream;
using std::ostringstream;
using std::setw;
using std::strerror;
using std::string;
using std::to_string;
class NullLogger : public Logger
{
public:
NullLogger() = default;
Logger *prefix(const char * /*file*/, int /*line*/) override { return this; }
ostream &stream() override { return unopened; }
private:
ofstream unopened;
};
class FileLogger : public Logger
{
public:
FileLogger(const char *filename) : log_stream{filename, std::ios::out | std::ios::app}
{
if (!log_stream) {
int stream_errno = errno;
ostringstream msg;
msg << "Unable to log to " << filename << ": " << strerror(stream_errno);
err = msg.str();
}
FileLogger::prefix(__FILE__, __LINE__);
log_stream << "FileLogger opened." << endl;
}
Logger *prefix(const char *file, int line) override
{
log_stream << "[" << setw(15) << file << ":" << setw(3) << dec << line << "] ";
return this;
}
ostream &stream() override { return log_stream; }
string get_error() const override { return err; }
private:
ofstream log_stream;
string err;
};
class StderrLogger : public Logger
{
public:
StderrLogger()
{
StderrLogger::prefix(__FILE__, __LINE__);
cerr << "StderrLogger opened." << endl;
}
Logger *prefix(const char *file, int line) override
{
cerr << "[" << setw(15) << file << ":" << setw(3) << dec << line << "] ";
return this;
}
ostream &stream() override { return cerr; }
string get_error() const override
{
if (!cerr) {
return "Unable to log to stderr";
}
return "";
}
};
class StdoutLogger : public Logger
{
public:
StdoutLogger()
{
StdoutLogger::prefix(__FILE__, __LINE__);
cout << "StdoutLogger opened." << endl;
}
Logger *prefix(const char *file, int line) override
{
cout << "[" << setw(15) << file << ":" << setw(3) << dec << line << "] ";
return this;
}
ostream &stream() override { return cout; }
string get_error() const override
{
if (!cout) {
return "Unable to log to stdout";
}
return "";
}
};
static uv_key_t current_logger_key;
static NullLogger the_null_logger;
static uv_once_t make_key_once = UV_ONCE_INIT;
static void make_key()
{
uv_key_create(¤t_logger_key);
}
Logger *Logger::current()
{
uv_once(&make_key_once, &make_key);
auto *logger = static_cast<Logger *>(uv_key_get(¤t_logger_key));
if (logger == nullptr) {
uv_key_set(¤t_logger_key, static_cast<void *>(&the_null_logger));
logger = &the_null_logger;
}
return logger;
}
string replace_logger(const Logger *new_logger)
{
string r = new_logger->get_error();
if (!r.empty()) {
if (new_logger != &the_null_logger) {
delete new_logger;
}
return r;
}
Logger *prior = Logger::current();
if (prior != &the_null_logger) {
delete prior;
}
uv_key_set(¤t_logger_key, (void *) new_logger);
return "";
}
string Logger::to_file(const char *filename)
{
return replace_logger(new FileLogger(filename));
}
string Logger::to_stderr()
{
return replace_logger(new StderrLogger());
}
string Logger::to_stdout()
{
return replace_logger(new StdoutLogger());
}
string Logger::disable()
{
return replace_logger(&the_null_logger);
}
string plural(long quantity, const string &singular_form, const string &plural_form)
{
string result;
result += to_string(quantity);
result += " ";
if (quantity == 1) {
result += singular_form;
} else {
result += plural_form;
}
return result;
}
string plural(long quantity, const string &singular_form)
{
string plural_form(singular_form + "s");
return plural(quantity, singular_form, plural_form);
}
Timer::Timer()
{
start = steady_clock::now();
}
void Timer::stop()
{
duration = measure_duration();
}
string Timer::format_duration() const
{
size_t total = duration;
if (total == 0) {
total = measure_duration();
}
size_t milliseconds = total;
size_t seconds = milliseconds / 1000;
milliseconds -= (seconds * 1000);
size_t minutes = seconds / 60;
seconds -= (minutes * 60);
size_t hours = minutes / 60;
minutes -= (hours * 60);
ostringstream out;
if (hours > 0) out << plural(hours, "hour") << ' ';
if (minutes > 0) out << plural(minutes, "minute") << ' ';
if (seconds > 0) out << plural(seconds, "second") << ' ';
out << plural(milliseconds, "millisecond") << " (" << total << "ms)";
return out.str();
}
<commit_msg>Initialize duration<commit_after>#include <cerrno>
#include <chrono>
#include <cstring>
#include <fstream>
#include <iomanip>
#include <iostream>
#include <sstream>
#include <string>
#include <uv.h>
#include "log.h"
using std::cerr;
using std::chrono::steady_clock;
using std::cout;
using std::dec;
using std::endl;
using std::ofstream;
using std::ostream;
using std::ostringstream;
using std::setw;
using std::strerror;
using std::string;
using std::to_string;
class NullLogger : public Logger
{
public:
NullLogger() = default;
Logger *prefix(const char * /*file*/, int /*line*/) override { return this; }
ostream &stream() override { return unopened; }
private:
ofstream unopened;
};
class FileLogger : public Logger
{
public:
FileLogger(const char *filename) : log_stream{filename, std::ios::out | std::ios::app}
{
if (!log_stream) {
int stream_errno = errno;
ostringstream msg;
msg << "Unable to log to " << filename << ": " << strerror(stream_errno);
err = msg.str();
}
FileLogger::prefix(__FILE__, __LINE__);
log_stream << "FileLogger opened." << endl;
}
Logger *prefix(const char *file, int line) override
{
log_stream << "[" << setw(15) << file << ":" << setw(3) << dec << line << "] ";
return this;
}
ostream &stream() override { return log_stream; }
string get_error() const override { return err; }
private:
ofstream log_stream;
string err;
};
class StderrLogger : public Logger
{
public:
StderrLogger()
{
StderrLogger::prefix(__FILE__, __LINE__);
cerr << "StderrLogger opened." << endl;
}
Logger *prefix(const char *file, int line) override
{
cerr << "[" << setw(15) << file << ":" << setw(3) << dec << line << "] ";
return this;
}
ostream &stream() override { return cerr; }
string get_error() const override
{
if (!cerr) {
return "Unable to log to stderr";
}
return "";
}
};
class StdoutLogger : public Logger
{
public:
StdoutLogger()
{
StdoutLogger::prefix(__FILE__, __LINE__);
cout << "StdoutLogger opened." << endl;
}
Logger *prefix(const char *file, int line) override
{
cout << "[" << setw(15) << file << ":" << setw(3) << dec << line << "] ";
return this;
}
ostream &stream() override { return cout; }
string get_error() const override
{
if (!cout) {
return "Unable to log to stdout";
}
return "";
}
};
static uv_key_t current_logger_key;
static NullLogger the_null_logger;
static uv_once_t make_key_once = UV_ONCE_INIT;
static void make_key()
{
uv_key_create(¤t_logger_key);
}
Logger *Logger::current()
{
uv_once(&make_key_once, &make_key);
auto *logger = static_cast<Logger *>(uv_key_get(¤t_logger_key));
if (logger == nullptr) {
uv_key_set(¤t_logger_key, static_cast<void *>(&the_null_logger));
logger = &the_null_logger;
}
return logger;
}
string replace_logger(const Logger *new_logger)
{
string r = new_logger->get_error();
if (!r.empty()) {
if (new_logger != &the_null_logger) {
delete new_logger;
}
return r;
}
Logger *prior = Logger::current();
if (prior != &the_null_logger) {
delete prior;
}
uv_key_set(¤t_logger_key, (void *) new_logger);
return "";
}
string Logger::to_file(const char *filename)
{
return replace_logger(new FileLogger(filename));
}
string Logger::to_stderr()
{
return replace_logger(new StderrLogger());
}
string Logger::to_stdout()
{
return replace_logger(new StdoutLogger());
}
string Logger::disable()
{
return replace_logger(&the_null_logger);
}
string plural(long quantity, const string &singular_form, const string &plural_form)
{
string result;
result += to_string(quantity);
result += " ";
if (quantity == 1) {
result += singular_form;
} else {
result += plural_form;
}
return result;
}
string plural(long quantity, const string &singular_form)
{
string plural_form(singular_form + "s");
return plural(quantity, singular_form, plural_form);
}
Timer::Timer() : start{steady_clock::now()}, duration{0}
{
//
}
void Timer::stop()
{
duration = measure_duration();
}
string Timer::format_duration() const
{
size_t total = duration;
if (total == 0) {
total = measure_duration();
}
size_t milliseconds = total;
size_t seconds = milliseconds / 1000;
milliseconds -= (seconds * 1000);
size_t minutes = seconds / 60;
seconds -= (minutes * 60);
size_t hours = minutes / 60;
minutes -= (hours * 60);
ostringstream out;
if (hours > 0) out << plural(hours, "hour") << ' ';
if (minutes > 0) out << plural(minutes, "minute") << ' ';
if (seconds > 0) out << plural(seconds, "second") << ' ';
out << plural(milliseconds, "millisecond") << " (" << total << "ms)";
return out.str();
}
<|endoftext|>
|
<commit_before>
/**
* \file main.cc
* \Author Andrea Barberio <[email protected]>
* \date October 2015
* \brief entry point for dublin-traceroute
*
* This file contains the main routine for calling the standalone dublin-traceroute
* executable.
*/
#include <iostream>
#include <fstream>
#include <dublintraceroute/dublin_traceroute.h>
// TODO argument parsing
#define TARGET "8.8.8.8"
#define PATHS 10
void
usage(const char *name) {
std::cout << "Usage: " << name << " target" << std::endl;
exit(EXIT_FAILURE);
}
int
main(int argc, char **argv) {
if (argc != 2)
usage(argv[0]);
const std::string target = std::string(argv[1]);
std::cout << "Starting dublin-traceroute" << std::endl;
DublinTraceroute Dublin(
target,
12345,
(1<<15) + 666, // traceroute's port
PATHS
);
std::cout
<< "Traceroute from 0.0.0.0:" << Dublin.srcport()
<< " to " << Dublin.dst()
<< ":" << Dublin.dstport() << "~" << (Dublin.dstport() + PATHS - 1)
<< std::endl;
std::shared_ptr<TracerouteResults> results;
try {
results = std::make_shared<TracerouteResults>(Dublin.traceroute());
} catch (DublinTracerouteException &e) {
std::cout << "Failed: " << e.what() << std::endl;
exit(EXIT_FAILURE);
} catch (std::runtime_error &e) {
std::cout << "Failed: " << e.what() << std::endl;
exit(EXIT_FAILURE);
}
results->show();
// Save as JSON
std::ofstream jsonfile;
jsonfile.open("trace.json");
jsonfile << results->to_json();
jsonfile.close();
std::cout << "Saved JSON file to trace.json ." << std::endl;
std::cout << "You can convert it to DOT by running scripts/to_graphviz.py trace.json" << std::endl;
}
<commit_msg>Update main.cc<commit_after>/**
* \file main.cc
* \Author Andrea Barberio <[email protected]>
* \date October 2015
* \brief entry point for dublin-traceroute
*
* This file contains the main routine for calling the standalone dublin-traceroute
* executable.
*/
#include <iostream>
#include <fstream>
#include <dublintraceroute/dublin_traceroute.h>
// TODO argument parsing
#define TARGET "8.8.8.8"
#define PATHS 10
void
usage(const char *name) {
std::cout << "Usage: " << name << " target" << std::endl;
exit(EXIT_FAILURE);
}
int
main(int argc, char **argv) {
if (argc != 2)
usage(argv[0]);
const std::string target = std::string(argv[1]);
std::cout << "Starting dublin-traceroute" << std::endl;
DublinTraceroute Dublin(
target,
12345,
(1<<15) + 666, // traceroute's port
PATHS
);
std::cout
<< "Traceroute from 0.0.0.0:" << Dublin.srcport()
<< " to " << Dublin.dst()
<< ":" << Dublin.dstport() << "~" << (Dublin.dstport() + PATHS - 1)
<< std::endl;
std::shared_ptr<TracerouteResults> results;
try {
results = std::make_shared<TracerouteResults>(Dublin.traceroute());
} catch (DublinTracerouteException &e) {
std::cout << "Failed: " << e.what() << std::endl;
exit(EXIT_FAILURE);
} catch (std::runtime_error &e) {
std::cout << "Failed: " << e.what() << std::endl;
exit(EXIT_FAILURE);
}
results->show();
// Save as JSON
std::ofstream jsonfile;
jsonfile.open("trace.json");
jsonfile << results->to_json();
jsonfile.close();
std::cout << "Saved JSON file to trace.json ." << std::endl;
std::cout << "You can convert it to DOT by running scripts/to_graphviz.py trace.json" << std::endl;
}
<|endoftext|>
|
<commit_before>// Copyright (c) 2012, Rasmus Andersson. All rights reserved.
// Use of this source code is governed by a MIT-style license that can be
// found in the LICENSE file.
#include <string.h>
#include <stdlib.h>
#include <iostream>
#include <fstream>
#include "codegen/Visitor.h"
#include "parse/FileInput.h"
#include "parse/Tokenizer.h"
#include "parse/TokenBuffer.h"
#include "parse/Parser.h"
#include "Text.h"
#include <llvm/Support/raw_ostream.h>
#include <llvm/ExecutionEngine/ExecutionEngine.h>
#include <fcntl.h>
// from lli.cpp
#include <llvm/LLVMContext.h>
#include <llvm/Module.h>
#include <llvm/Type.h>
#include <llvm/ADT/Triple.h>
#include <llvm/Bitcode/ReaderWriter.h>
#include <llvm/CodeGen/LinkAllCodegenComponents.h>
#include <llvm/ExecutionEngine/GenericValue.h>
#include <llvm/ExecutionEngine/Interpreter.h>
#include <llvm/ExecutionEngine/JIT.h>
#include <llvm/ExecutionEngine/JITEventListener.h>
#include <llvm/ExecutionEngine/MCJIT.h>
#include <llvm/Support/CommandLine.h>
#include <llvm/Support/IRReader.h>
#include <llvm/Support/ManagedStatic.h>
#include <llvm/Support/PluginLoader.h>
#include <llvm/Support/PrettyStackTrace.h>
#include <llvm/Support/raw_ostream.h>
#include <llvm/Support/Process.h>
#include <llvm/Support/Signals.h>
#include <llvm/Support/TargetSelect.h>
#include <cerrno>
using namespace llvm;
using namespace hue;
namespace {
cl::opt<std::string>
InputFile(cl::desc("<input source>"), cl::Positional, cl::init("-"));
cl::list<std::string>
InputArgv(cl::ConsumeAfter, cl::desc("<program arguments>..."));
cl::opt<bool> ForceInterpreter("force-interpreter",
cl::desc("Force interpretation: disable JIT"),
cl::init(false));
cl::opt<bool> UseMCJIT(
"use-mcjit", cl::desc("Enable use of the MC-based JIT (if available)"),
cl::init(false));
cl::opt<std::string> OutputIR(
"output-ir", cl::desc("Generate and write IR to file at <path>."),
cl::value_desc("path"),
cl::init(" "));
cl::opt<bool> NoExecution("no-exec",
cl::desc("Do not execute program (useful for linting or generating IR code)"),
cl::init(false));
// Determine optimization level.
cl::opt<char>
OptLevel("O",
cl::desc("Optimization level. [-O0, -O1, -O2, or -O3] "
"(default = '-O2')"),
cl::Prefix,
cl::ZeroOrMore,
cl::init(' '));
cl::opt<std::string>
TargetTriple("mtriple", cl::desc("Override target triple for module"));
cl::opt<std::string>
MArch("march",
cl::desc("Architecture to generate assembly for (see --version)"));
cl::opt<std::string>
MCPU("mcpu",
cl::desc("Target a specific cpu type (-mcpu=help for details)"),
cl::value_desc("cpu-name"),
cl::init(""));
cl::list<std::string>
MAttrs("mattr",
cl::CommaSeparated,
cl::desc("Target specific attributes (-mattr=help for details)"),
cl::value_desc("a1,+a2,-a3,..."));
cl::opt<std::string>
EntryFunc("entry-function",
cl::desc("Specify the entry function (default = 'main') "
"of the executable"),
cl::value_desc("function"),
cl::init("main"));
cl::opt<std::string>
FakeArgv0("fake-argv0",
cl::desc("Override the 'argv[0]' value passed into the executing"
" program"), cl::value_desc("executable"));
cl::opt<bool>
DisableCoreFiles("disable-core-files", cl::Hidden,
cl::desc("Disable emission of core files if possible"));
cl::opt<bool>
NoLazyCompilation("disable-lazy-compilation",
cl::desc("Disable JIT lazy compilation"),
cl::init(false));
cl::opt<Reloc::Model>
RelocModel("relocation-model",
cl::desc("Choose relocation model"),
cl::init(Reloc::Default),
cl::values(
clEnumValN(Reloc::Default, "default",
"Target default relocation model"),
clEnumValN(Reloc::Static, "static",
"Non-relocatable code"),
clEnumValN(Reloc::PIC_, "pic",
"Fully relocatable, position independent code"),
clEnumValN(Reloc::DynamicNoPIC, "dynamic-no-pic",
"Relocatable external references, non-relocatable code"),
clEnumValEnd));
cl::opt<llvm::CodeModel::Model>
CMModel("code-model",
cl::desc("Choose code model"),
cl::init(CodeModel::JITDefault),
cl::values(clEnumValN(CodeModel::JITDefault, "default",
"Target default JIT code model"),
clEnumValN(CodeModel::Small, "small",
"Small code model"),
clEnumValN(CodeModel::Kernel, "kernel",
"Kernel code model"),
clEnumValN(CodeModel::Medium, "medium",
"Medium code model"),
clEnumValN(CodeModel::Large, "large",
"Large code model"),
clEnumValEnd));
}
static ExecutionEngine *EE = 0;
static void do_shutdown() {
// Cygwin-1.5 invokes DLL's dtors before atexit handler.
#ifndef DO_NOTHING_ATEXIT
delete EE;
llvm_shutdown();
#endif
}
int main(int argc, char **argv, char * const *envp) {
sys::PrintStackTraceOnErrorSignal();
PrettyStackTraceProgram X(argc, argv);
LLVMContext &Context = getGlobalContext();
atexit(do_shutdown); // Call llvm_shutdown() on exit.
// If we have a native target, initialize it to ensure it is linked in and
// usable by the JIT.
InitializeNativeTarget();
InitializeNativeTargetAsmPrinter();
cl::ParseCommandLineOptions(argc, argv,
"hue/llvm interpreter & dynamic compiler\n");
// If the user doesn't want core files, disable them.
if (DisableCoreFiles)
sys::Process::PreventCoreFiles();
std::string ErrorMsg;
// Read input file
Text textSource;
if (!textSource.setFromUTF8FileOrSTDIN(InputFile.c_str(), ErrorMsg)) {
std::cerr << "Failed to open input file: " << ErrorMsg << std::endl;
return 1;
}
// A tokenizer produce tokens parsed from a ByteInput
Tokenizer tokenizer(textSource);
// A TokenBuffer reads tokens from a Tokenizer and maintains limited history
TokenBuffer tokens(tokenizer);
// A parser reads the token buffer and produce an AST
Parser parser(tokens);
// Parse the input into an AST
ast::Function *moduleFunc = parser.parseModule();
if (!moduleFunc) return 1;
if (parser.errors().size() != 0) {
std::cerr << parser.errors().size() << " parse error(s)." << std::endl;
return 1;
}
std::cerr << "Parsed module: " << moduleFunc->body()->toString() << std::endl;
//return 0; // xxx only parser
// Generate code
codegen::Visitor codegenVisitor;
llvm::Module *Mod = codegenVisitor.genModule(llvm::getGlobalContext(), "hello", moduleFunc);
//std::cout << "moduleIR: " << Mod << std::endl;
if (!Mod) {
std::cerr << codegenVisitor.errors().size() << " error(s) during code generation." << std::endl;
return 1;
}
// Output IR
if (OutputIR != " ") {
if (OutputIR.empty() || OutputIR == "-") {
Mod->print(outs(), 0);
} else {
llvm::raw_fd_ostream os(OutputIR.c_str(), ErrorMsg);
if (os.has_error()) {
std::cerr << "Failed to open file for output: " << ErrorMsg << std::endl;
return 1;
}
Mod->print(os, 0);
}
}
// Do not execute program?
if (NoExecution)
return 0;
// Okay. Let's run this code.
// If not jitting lazily, load the whole bitcode file eagerly too.
if (NoLazyCompilation) {
if (Mod->MaterializeAllPermanently(&ErrorMsg)) {
errs() << argv[0] << ": bitcode didn't read correctly.\n";
errs() << "Reason: " << ErrorMsg << "\n";
exit(1);
}
}
EngineBuilder builder(Mod);
builder.setMArch(MArch);
builder.setMCPU(MCPU);
builder.setMAttrs(MAttrs);
builder.setRelocationModel(RelocModel);
builder.setCodeModel(CMModel);
builder.setErrorStr(&ErrorMsg);
builder.setEngineKind(ForceInterpreter
? EngineKind::Interpreter
: EngineKind::JIT);
// If we are supposed to override the target triple, do so now.
if (!TargetTriple.empty())
Mod->setTargetTriple(Triple::normalize(TargetTriple));
// Enable MCJIT, if desired.
if (UseMCJIT)
builder.setUseMCJIT(true);
CodeGenOpt::Level OLvl = CodeGenOpt::Default;
switch (OptLevel) {
default:
errs() << argv[0] << ": invalid optimization level.\n";
return 1;
case ' ': break;
case '0': OLvl = CodeGenOpt::None; break;
case '1': OLvl = CodeGenOpt::Less; break;
case '2': OLvl = CodeGenOpt::Default; break;
case '3': OLvl = CodeGenOpt::Aggressive; break;
}
builder.setOptLevel(OLvl);
EE = builder.create();
if (!EE) {
if (!ErrorMsg.empty())
errs() << argv[0] << ": error creating EE: " << ErrorMsg << "\n";
else
errs() << argv[0] << ": unknown error creating EE!\n";
exit(1);
}
EE->RegisterJITEventListener(createOProfileJITEventListener());
EE->DisableLazyCompilation(NoLazyCompilation);
// If the user specifically requested an argv[0] to pass into the program,
// do it now.
if (!FakeArgv0.empty()) {
InputFile = FakeArgv0;
} else {
// Otherwise, if there is a .hue suffix on the executable strip it off
if (StringRef(InputFile).endswith(".hue"))
InputFile.erase(InputFile.length() - 4);
}
// Add the module's name to the start of the vector of arguments to main().
InputArgv.insert(InputArgv.begin(), InputFile);
// Call the main function from M as if its signature were:
// int main (int argc, char **argv, const char **envp)
// using the contents of Args to determine argc & argv, and the contents of
// EnvVars to determine envp.
//
llvm::Function *EntryFn = Mod->getFunction(EntryFunc);
if (!EntryFn) {
errs() << '\'' << EntryFunc << "\' function not found in module.\n";
return -1;
}
// If the program doesn't explicitly call exit, we will need the Exit
// function later on to make an explicit call, so get the function now.
Constant *Exit = Mod->getOrInsertFunction("exit", llvm::Type::getVoidTy(Context),
llvm::Type::getInt32Ty(Context),
NULL);
// Reset errno to zero on entry to main.
errno = 0;
// Run static constructors.
EE->runStaticConstructorsDestructors(false);
if (NoLazyCompilation) {
for (Module::iterator I = Mod->begin(), E = Mod->end(); I != E; ++I) {
llvm::Function *Fn = &*I;
if (Fn != EntryFn && !Fn->isDeclaration())
EE->getPointerToFunction(Fn);
}
}
// Run main.
int Result = EE->runFunctionAsMain(EntryFn, InputArgv, envp);
// Run static destructors.
EE->runStaticConstructorsDestructors(true);
// If the program didn't call exit explicitly, we should call it now.
// This ensures that any atexit handlers get called correctly.
if (llvm::Function *ExitF = dyn_cast<llvm::Function>(Exit)) {
std::vector<GenericValue> Args;
GenericValue ResultGV;
ResultGV.IntVal = APInt(32, Result);
Args.push_back(ResultGV);
EE->runFunction(ExitF, Args);
errs() << "ERROR: exit(" << Result << ") returned!\n";
abort();
} else {
errs() << "ERROR: exit defined with wrong prototype!\n";
abort();
}
//
// From here:
//
// PATH=$PATH:$(pwd)/deps/llvm/bin/bin
//
// Run the generated program:
// lli out.ll
//
// Generate target assembler:
// llc -asm-verbose -o=- out.ll
//
// Generate target image:
// llvm-as -o=- out.ll | llvm-ld -native -o=out.a -
//
// See http://llvm.org/docs/CommandGuide/ for details on these tools.
//
return 0;
}<commit_msg>bin/hue: removed the no-exec argument and added arguments parse-only and compile-only<commit_after>// Copyright (c) 2012, Rasmus Andersson. All rights reserved.
// Use of this source code is governed by a MIT-style license that can be
// found in the LICENSE file.
#include <string.h>
#include <stdlib.h>
#include <iostream>
#include <fstream>
#include "codegen/Visitor.h"
#include "parse/FileInput.h"
#include "parse/Tokenizer.h"
#include "parse/TokenBuffer.h"
#include "parse/Parser.h"
#include "Text.h"
#include <llvm/Support/raw_ostream.h>
#include <llvm/ExecutionEngine/ExecutionEngine.h>
#include <fcntl.h>
// from lli.cpp
#include <llvm/LLVMContext.h>
#include <llvm/Module.h>
#include <llvm/Type.h>
#include <llvm/ADT/Triple.h>
#include <llvm/Bitcode/ReaderWriter.h>
#include <llvm/CodeGen/LinkAllCodegenComponents.h>
#include <llvm/ExecutionEngine/GenericValue.h>
#include <llvm/ExecutionEngine/Interpreter.h>
#include <llvm/ExecutionEngine/JIT.h>
#include <llvm/ExecutionEngine/JITEventListener.h>
#include <llvm/ExecutionEngine/MCJIT.h>
#include <llvm/Support/CommandLine.h>
#include <llvm/Support/IRReader.h>
#include <llvm/Support/ManagedStatic.h>
#include <llvm/Support/PluginLoader.h>
#include <llvm/Support/PrettyStackTrace.h>
#include <llvm/Support/raw_ostream.h>
#include <llvm/Support/Process.h>
#include <llvm/Support/Signals.h>
#include <llvm/Support/TargetSelect.h>
#include <cerrno>
using namespace llvm;
using namespace hue;
namespace {
cl::opt<std::string>
InputFile(cl::desc("<input source>"), cl::Positional, cl::init("-"));
cl::list<std::string>
InputArgv(cl::ConsumeAfter, cl::desc("<program arguments>..."));
cl::opt<bool> ForceInterpreter("force-interpreter",
cl::desc("Force interpretation: disable JIT"),
cl::init(false));
cl::opt<bool> UseMCJIT(
"use-mcjit", cl::desc("Enable use of the MC-based JIT (if available)"),
cl::init(false));
cl::opt<std::string> OutputIR(
"output-ir", cl::desc("Generate and write IR to file at <path>."),
cl::value_desc("path"),
cl::init(" "));
cl::opt<bool> OnlyParse("parse-only",
cl::desc("Only parse the source, but do not compile or execute."),
cl::init(false));
cl::opt<bool> OnlyCompile("compile-only",
cl::desc("Only compile the source, but do not execute."),
cl::init(false));
// Determine optimization level.
cl::opt<char>
OptLevel("O",
cl::desc("Optimization level. [-O0, -O1, -O2, or -O3] "
"(default = '-O2')"),
cl::Prefix,
cl::ZeroOrMore,
cl::init(' '));
cl::opt<std::string>
TargetTriple("mtriple", cl::desc("Override target triple for module"));
cl::opt<std::string>
MArch("march",
cl::desc("Architecture to generate assembly for (see --version)"));
cl::opt<std::string>
MCPU("mcpu",
cl::desc("Target a specific cpu type (-mcpu=help for details)"),
cl::value_desc("cpu-name"),
cl::init(""));
cl::list<std::string>
MAttrs("mattr",
cl::CommaSeparated,
cl::desc("Target specific attributes (-mattr=help for details)"),
cl::value_desc("a1,+a2,-a3,..."));
cl::opt<std::string>
EntryFunc("entry-function",
cl::desc("Specify the entry function (default = 'main') "
"of the executable"),
cl::value_desc("function"),
cl::init("main"));
cl::opt<std::string>
FakeArgv0("fake-argv0",
cl::desc("Override the 'argv[0]' value passed into the executing"
" program"), cl::value_desc("executable"));
cl::opt<bool>
DisableCoreFiles("disable-core-files", cl::Hidden,
cl::desc("Disable emission of core files if possible"));
cl::opt<bool>
NoLazyCompilation("disable-lazy-compilation",
cl::desc("Disable JIT lazy compilation"),
cl::init(false));
cl::opt<Reloc::Model>
RelocModel("relocation-model",
cl::desc("Choose relocation model"),
cl::init(Reloc::Default),
cl::values(
clEnumValN(Reloc::Default, "default",
"Target default relocation model"),
clEnumValN(Reloc::Static, "static",
"Non-relocatable code"),
clEnumValN(Reloc::PIC_, "pic",
"Fully relocatable, position independent code"),
clEnumValN(Reloc::DynamicNoPIC, "dynamic-no-pic",
"Relocatable external references, non-relocatable code"),
clEnumValEnd));
cl::opt<llvm::CodeModel::Model>
CMModel("code-model",
cl::desc("Choose code model"),
cl::init(CodeModel::JITDefault),
cl::values(clEnumValN(CodeModel::JITDefault, "default",
"Target default JIT code model"),
clEnumValN(CodeModel::Small, "small",
"Small code model"),
clEnumValN(CodeModel::Kernel, "kernel",
"Kernel code model"),
clEnumValN(CodeModel::Medium, "medium",
"Medium code model"),
clEnumValN(CodeModel::Large, "large",
"Large code model"),
clEnumValEnd));
}
static ExecutionEngine *EE = 0;
static void do_shutdown() {
// Cygwin-1.5 invokes DLL's dtors before atexit handler.
#ifndef DO_NOTHING_ATEXIT
delete EE;
llvm_shutdown();
#endif
}
int main(int argc, char **argv, char * const *envp) {
sys::PrintStackTraceOnErrorSignal();
PrettyStackTraceProgram X(argc, argv);
LLVMContext &Context = getGlobalContext();
atexit(do_shutdown); // Call llvm_shutdown() on exit.
// If we have a native target, initialize it to ensure it is linked in and
// usable by the JIT.
InitializeNativeTarget();
InitializeNativeTargetAsmPrinter();
cl::ParseCommandLineOptions(argc, argv, "hue interpreter & dynamic compiler\n");
// If the user doesn't want core files, disable them.
if (DisableCoreFiles)
sys::Process::PreventCoreFiles();
std::string ErrorMsg;
// Read input file
Text textSource;
if (!textSource.setFromUTF8FileOrSTDIN(InputFile.c_str(), ErrorMsg)) {
std::cerr << "Failed to open input file: " << ErrorMsg << std::endl;
return 1;
}
// A tokenizer produce tokens parsed from a ByteInput
Tokenizer tokenizer(textSource);
// A TokenBuffer reads tokens from a Tokenizer and maintains limited history
TokenBuffer tokens(tokenizer);
// A parser reads the token buffer and produce an AST
Parser parser(tokens);
// Parse the input into an AST
ast::Function *moduleFunc = parser.parseModule();
if (!moduleFunc) return 1;
if (parser.errors().size() != 0) {
std::cerr << parser.errors().size() << " parse error(s)." << std::endl;
return 1;
}
// Only parse? Then we are done.
if (OnlyParse) {
std::cout << moduleFunc->body()->toString() << std::endl;
return 0;
}
// Generate code
codegen::Visitor codegenVisitor;
llvm::Module *Mod = codegenVisitor.genModule(llvm::getGlobalContext(), "hello", moduleFunc);
//std::cout << "moduleIR: " << Mod << std::endl;
if (!Mod) {
std::cerr << codegenVisitor.errors().size() << " error(s) during code generation." << std::endl;
return 1;
}
// Output IR
if (OutputIR != " ") {
if (OutputIR.empty() || OutputIR == "-") {
Mod->print(outs(), 0);
} else {
llvm::raw_fd_ostream os(OutputIR.c_str(), ErrorMsg);
if (os.has_error()) {
std::cerr << "Failed to open file for output: " << ErrorMsg << std::endl;
return 1;
}
Mod->print(os, 0);
}
}
// Only compile? Then we are done.
if (OnlyCompile)
return 0;
// Okay. Let's run this code.
// If not jitting lazily, load the whole bitcode file eagerly too.
if (NoLazyCompilation) {
if (Mod->MaterializeAllPermanently(&ErrorMsg)) {
errs() << argv[0] << ": bitcode didn't read correctly.\n";
errs() << "Reason: " << ErrorMsg << "\n";
exit(1);
}
}
EngineBuilder builder(Mod);
builder.setMArch(MArch);
builder.setMCPU(MCPU);
builder.setMAttrs(MAttrs);
builder.setRelocationModel(RelocModel);
builder.setCodeModel(CMModel);
builder.setErrorStr(&ErrorMsg);
builder.setEngineKind(ForceInterpreter
? EngineKind::Interpreter
: EngineKind::JIT);
// If we are supposed to override the target triple, do so now.
if (!TargetTriple.empty())
Mod->setTargetTriple(Triple::normalize(TargetTriple));
// Enable MCJIT, if desired.
if (UseMCJIT)
builder.setUseMCJIT(true);
CodeGenOpt::Level OLvl = CodeGenOpt::Default;
switch (OptLevel) {
default:
errs() << argv[0] << ": invalid optimization level.\n";
return 1;
case ' ': break;
case '0': OLvl = CodeGenOpt::None; break;
case '1': OLvl = CodeGenOpt::Less; break;
case '2': OLvl = CodeGenOpt::Default; break;
case '3': OLvl = CodeGenOpt::Aggressive; break;
}
builder.setOptLevel(OLvl);
EE = builder.create();
if (!EE) {
if (!ErrorMsg.empty())
errs() << argv[0] << ": error creating EE: " << ErrorMsg << "\n";
else
errs() << argv[0] << ": unknown error creating EE!\n";
exit(1);
}
EE->RegisterJITEventListener(createOProfileJITEventListener());
EE->DisableLazyCompilation(NoLazyCompilation);
// If the user specifically requested an argv[0] to pass into the program,
// do it now.
if (!FakeArgv0.empty()) {
InputFile = FakeArgv0;
} else {
// Otherwise, if there is a .hue suffix on the executable strip it off
if (StringRef(InputFile).endswith(".hue"))
InputFile.erase(InputFile.length() - 4);
}
// Add the module's name to the start of the vector of arguments to main().
InputArgv.insert(InputArgv.begin(), InputFile);
// Call the main function from M as if its signature were:
// int main (int argc, char **argv, const char **envp)
// using the contents of Args to determine argc & argv, and the contents of
// EnvVars to determine envp.
//
llvm::Function *EntryFn = Mod->getFunction(EntryFunc);
if (!EntryFn) {
errs() << '\'' << EntryFunc << "\' function not found in module.\n";
return -1;
}
// If the program doesn't explicitly call exit, we will need the Exit
// function later on to make an explicit call, so get the function now.
Constant *Exit = Mod->getOrInsertFunction("exit", llvm::Type::getVoidTy(Context),
llvm::Type::getInt32Ty(Context),
NULL);
// Reset errno to zero on entry to main.
errno = 0;
// Run static constructors.
EE->runStaticConstructorsDestructors(false);
if (NoLazyCompilation) {
for (Module::iterator I = Mod->begin(), E = Mod->end(); I != E; ++I) {
llvm::Function *Fn = &*I;
if (Fn != EntryFn && !Fn->isDeclaration())
EE->getPointerToFunction(Fn);
}
}
// Run main.
int Result = EE->runFunctionAsMain(EntryFn, InputArgv, envp);
// Run static destructors.
EE->runStaticConstructorsDestructors(true);
// If the program didn't call exit explicitly, we should call it now.
// This ensures that any atexit handlers get called correctly.
if (llvm::Function *ExitF = dyn_cast<llvm::Function>(Exit)) {
std::vector<GenericValue> Args;
GenericValue ResultGV;
ResultGV.IntVal = APInt(32, Result);
Args.push_back(ResultGV);
EE->runFunction(ExitF, Args);
errs() << "ERROR: exit(" << Result << ") returned!\n";
abort();
} else {
errs() << "ERROR: exit defined with wrong prototype!\n";
abort();
}
//
// From here:
//
// PATH=$PATH:$(pwd)/deps/llvm/bin/bin
//
// Run the generated program:
// lli out.ll
//
// Generate target assembler:
// llc -asm-verbose -o=- out.ll
//
// Generate target image:
// llvm-as -o=- out.ll | llvm-ld -native -o=out.a -
//
// See http://llvm.org/docs/CommandGuide/ for details on these tools.
//
return 0;
}<|endoftext|>
|
<commit_before>#include <iostream>
#include "NTClient.h"
int main(int argc, char** argv) {
NTClient nclient = NTClient("asd4wderg", "123asd123"); // Throw-away account
cout << "Logging account in...\n";
nclient.login();
return 0;
}<commit_msg>NitroType is banning my throw away accounts<commit_after>#include <iostream>
#include "NTClient.h"
int main(int argc, char** argv) {
NTClient nclient = NTClient("gfsiosd", "123asd123"); // Throw-away account
cout << "Logging account in...\n";
nclient.login();
return 0;
}<|endoftext|>
|
<commit_before>// Copyright (c) 2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "base/sys_info.h"
#include "base/basictypes.h"
#include "base/file_path.h"
#include "base/file_util.h"
#include "base/string_tokenizer.h"
#include "base/string_util.h"
namespace base {
#if defined(OFFICIAL_BUILD)
static const char kLinuxStandardBaseVersionKey[] = "GOOGLE_RELEASE";
#else
static const char kLinuxStandardBaseVersionKey[] = "DISTRIB_RELEASE";
#endif
const char kLinuxStandardBaseReleaseFile[] = "/etc/lsb-release";
// static
void SysInfo::OperatingSystemVersionNumbers(int32 *major_version,
int32 *minor_version,
int32 *bugfix_version) {
// TODO(cmasone): If this gets called a lot, it may kill performance.
// consider using static variables to cache these values?
FilePath path(kLinuxStandardBaseReleaseFile);
std::string contents;
if (file_util::ReadFileToString(path, &contents)) {
ParseLsbRelease(contents, major_version, minor_version, bugfix_version);
}
}
// static
std::string SysInfo::GetLinuxStandardBaseVersionKey() {
return std::string(kLinuxStandardBaseVersionKey);
}
// static
void SysInfo::ParseLsbRelease(const std::string& lsb_release,
int32 *major_version,
int32 *minor_version,
int32 *bugfix_version) {
size_t version_key_index =
lsb_release.find(kLinuxStandardBaseVersionKey,
arraysize(kLinuxStandardBaseVersionKey) - 1);
if (std::string::npos == version_key_index) {
return;
}
size_t start_index = lsb_release.find_first_of('=', version_key_index);
start_index++; // Move past '='.
size_t length = lsb_release.find_first_of('\n', start_index) - start_index;
std::string version = lsb_release.substr(start_index, length);
StringTokenizer tokenizer(version, ".");
for (int i = 0; i < 3 && tokenizer.GetNext(); i++) {
if (0 == i) {
*major_version = StringToInt(tokenizer.token());
*minor_version = *bugfix_version = 0;
} else if (1 == i) {
*minor_version = StringToInt(tokenizer.token());
} else { // 2 == i
*bugfix_version = StringToInt(tokenizer.token());
}
}
}
} // namespace base
<commit_msg>We want GOOGLE_CHROME_BUILDs on Chrome OS to get the appropriate OS version info. Review URL: http://codereview.chromium.org/294003<commit_after>// Copyright (c) 2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "base/sys_info.h"
#include "base/basictypes.h"
#include "base/file_path.h"
#include "base/file_util.h"
#include "base/string_tokenizer.h"
#include "base/string_util.h"
namespace base {
#if defined(GOOGLE_CHROME_BUILD)
static const char kLinuxStandardBaseVersionKey[] = "GOOGLE_RELEASE";
#else
static const char kLinuxStandardBaseVersionKey[] = "DISTRIB_RELEASE";
#endif
const char kLinuxStandardBaseReleaseFile[] = "/etc/lsb-release";
// static
void SysInfo::OperatingSystemVersionNumbers(int32 *major_version,
int32 *minor_version,
int32 *bugfix_version) {
// TODO(cmasone): If this gets called a lot, it may kill performance.
// consider using static variables to cache these values?
FilePath path(kLinuxStandardBaseReleaseFile);
std::string contents;
if (file_util::ReadFileToString(path, &contents)) {
ParseLsbRelease(contents, major_version, minor_version, bugfix_version);
}
}
// static
std::string SysInfo::GetLinuxStandardBaseVersionKey() {
return std::string(kLinuxStandardBaseVersionKey);
}
// static
void SysInfo::ParseLsbRelease(const std::string& lsb_release,
int32 *major_version,
int32 *minor_version,
int32 *bugfix_version) {
size_t version_key_index =
lsb_release.find(kLinuxStandardBaseVersionKey,
arraysize(kLinuxStandardBaseVersionKey) - 1);
if (std::string::npos == version_key_index) {
return;
}
size_t start_index = lsb_release.find_first_of('=', version_key_index);
start_index++; // Move past '='.
size_t length = lsb_release.find_first_of('\n', start_index) - start_index;
std::string version = lsb_release.substr(start_index, length);
StringTokenizer tokenizer(version, ".");
for (int i = 0; i < 3 && tokenizer.GetNext(); i++) {
if (0 == i) {
*major_version = StringToInt(tokenizer.token());
*minor_version = *bugfix_version = 0;
} else if (1 == i) {
*minor_version = StringToInt(tokenizer.token());
} else { // 2 == i
*bugfix_version = StringToInt(tokenizer.token());
}
}
}
} // namespace base
<|endoftext|>
|
<commit_before>// -----------------------------------------------------------------------------
//
// Copyright (C) The BioDynaMo Project.
// 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.
//
// See the LICENSE file distributed with this work for details.
// See the NOTICE file distributed with this work for additional information
// regarding copyright ownership.
//
// -----------------------------------------------------------------------------
#include <array>
#include "core/biology_module/grow_divide.h"
#include "core/container/sim_object_vector.h"
#include "core/environment/environment.h"
#include "core/functor.h"
#include "core/gpu/gpu_helper.h"
#include "core/operation/displacement_op.h"
#include "core/sim_object/cell.h"
#include "gtest/gtest.h"
#include "unit/test_util/test_util.h"
namespace bdm {
namespace displacement_op_gpu_test_internal {
// NB: The GPU execution 'context' for the displacement operation differes,
// from the CPU version. Once the CPU version supports the same execution
// context, we can include it for direct comparison of results.
static constexpr double kEps = 10 * abs_error<double>::value;
class DisplacementOpCpuVerify {
public:
struct CalculateDisplacement;
struct UpdateCells;
void operator()() {
auto* sim = Simulation::GetActive();
auto* rm = sim->GetResourceManager();
SimObjectVector<Double3> displacements;
CalculateDisplacement cd(&displacements);
rm->ApplyOnAllElementsParallelDynamic(1000, cd);
UpdateCells uc(&displacements);
rm->ApplyOnAllElementsParallelDynamic(1000, uc);
}
struct CalculateDisplacement : public Functor<void, SimObject*, SoHandle> {
SimObjectVector<Double3>* displacements_;
CalculateDisplacement(SimObjectVector<Double3>* displacements) {
displacements_ = displacements;
}
void operator()(SimObject* so, SoHandle soh) override {
auto* sim = Simulation::GetActive();
auto* env = sim->GetEnvironment();
auto* param = sim->GetParam();
auto search_radius = env->GetLargestObjectSize();
auto squared_radius_ = search_radius * search_radius;
const auto& displacement = so->CalculateDisplacement(
squared_radius_, param->simulation_time_step_);
(*displacements_)[soh] = displacement;
}
};
struct UpdateCells : public Functor<void, SimObject*, SoHandle> {
SimObjectVector<Double3>* displacements_;
UpdateCells(SimObjectVector<Double3>* displacements) {
displacements_ = displacements;
}
void operator()(SimObject* so, SoHandle soh) override {
auto* sim = Simulation::GetActive();
auto* param = sim->GetParam();
so->ApplyDisplacement((*displacements_)[soh]);
if (param->bound_space_) {
ApplyBoundingBox(so, param->min_bound_, param->max_bound_);
}
}
};
};
void RunTest(OpComputeTarget mode) {
auto set_param = [&](Param* param) {
switch (mode) {
case kOpenCl:
param->compute_target_ = "opencl";
case kCuda:
param->compute_target_ = "cuda";
default:
return;
}
};
enum Case { kCompute, kVerify };
std::vector<Simulation*> sims;
sims.push_back(new Simulation("GPU", set_param));
sims.push_back(new Simulation("CPU_Verify", set_param));
std::array<SoUid, 2> uid_ref;
for (size_t i = 0; i < sims.size(); i++) {
auto& sim = sims[i];
sim->Activate();
auto* rm = sim->GetResourceManager();
auto* env = sim->GetEnvironment();
uid_ref[i] = SoUid(sim->GetSoUidGenerator()->GetHighestIndex());
// Cell 0
Cell* cell = new Cell();
cell->SetAdherence(0.3);
cell->SetDiameter(10);
cell->SetMass(1.4);
cell->SetPosition({0, 0, 0});
rm->push_back(cell);
// Cell 1
Cell* cell_1 = new Cell();
cell_1->SetAdherence(0.4);
cell_1->SetDiameter(10);
cell_1->SetMass(1.1);
cell_1->SetPosition({0, 8, 0});
rm->push_back(cell_1);
env->Update();
if (i == Case::kCompute) {
// Execute operation
(*NewOperation("displacement"))();
} else {
// Run verification on CPU
DisplacementOpCpuVerify cpu_op;
cpu_op();
}
}
// check results
auto rm0 = sims[Case::kCompute]->GetResourceManager();
auto rm1 = sims[Case::kVerify]->GetResourceManager();
auto cell0 = static_cast<Cell*>(rm0->GetSimObject(uid_ref[0] + 0));
auto cell1 = static_cast<Cell*>(rm0->GetSimObject(uid_ref[0] + 1));
auto vcell0 = static_cast<Cell*>(rm1->GetSimObject(uid_ref[1] + 0));
auto vcell1 = static_cast<Cell*>(rm1->GetSimObject(uid_ref[1] + 1));
EXPECT_ARR_NEAR_GPU(vcell0->GetPosition(), cell0->GetPosition());
EXPECT_ARR_NEAR_GPU(vcell1->GetPosition(), cell1->GetPosition());
// check if tractor_force has been reset to zero
EXPECT_ARR_NEAR_GPU(cell0->GetTractorForce(), {0, 0, 0});
EXPECT_ARR_NEAR_GPU(cell1->GetTractorForce(), {0, 0, 0});
// remaining fields should remain unchanged
// cell 0
EXPECT_NEAR(0.3, cell0->GetAdherence(), kEps);
EXPECT_NEAR(10, cell0->GetDiameter(), kEps);
EXPECT_NEAR(1.4, cell0->GetMass(), kEps);
// cell 1
EXPECT_NEAR(0.4, cell1->GetAdherence(), kEps);
EXPECT_NEAR(10, cell1->GetDiameter(), kEps);
EXPECT_NEAR(1.1, cell1->GetMass(), kEps);
}
#ifdef USE_CUDA
TEST(DisplacementOpGpuTest, ComputeSoaCuda) { RunTest(kCuda); }
#endif
#ifdef USE_OPENCL
TEST(DisplacementOpGpuTest, ComputeSoaOpenCL) { RunTest(kOpenCl); }
#endif
void RunTest2(OpComputeTarget mode) {
auto set_param = [&](auto* param) {
switch (mode) {
case kOpenCl:
param->compute_target_ = "opencl";
case kCuda:
param->compute_target_ = "cuda";
default:
return;
}
};
enum Case { kCompute, kVerify };
std::vector<Simulation*> sims;
sims.push_back(new Simulation("GPU", set_param));
sims.push_back(new Simulation("CPU_Verify", set_param));
std::array<SoUid, 2> uid_ref;
for (size_t i = 0; i < sims.size(); i++) {
auto& sim = sims[i];
sim->Activate();
auto* rm = sim->GetResourceManager();
auto* env = sim->GetEnvironment();
uid_ref[i] = SoUid(sim->GetSoUidGenerator()->GetHighestIndex());
double space = 20;
for (size_t i = 0; i < 3; i++) {
for (size_t j = 0; j < 3; j++) {
for (size_t k = 0; k < 3; k++) {
Cell* cell = new Cell({k * space, j * space, i * space});
cell->SetDiameter(30);
cell->SetAdherence(0.4);
cell->SetMass(1.0);
rm->push_back(cell);
}
}
}
env->Update();
if (i == Case::kCompute) {
// Execute operation
(*NewOperation("displacement"))();
} else {
// Run verification on CPU
DisplacementOpCpuVerify cpu_op;
cpu_op();
}
}
// check results
auto rm0 = sims[Case::kCompute]->GetResourceManager();
auto rm1 = sims[Case::kVerify]->GetResourceManager();
// clang-format off
EXPECT_ARR_NEAR_GPU(rm1->GetSimObject(uid_ref[1] + 0)->GetPosition(), rm0->GetSimObject(uid_ref[0] + 0)->GetPosition());
EXPECT_ARR_NEAR_GPU(rm1->GetSimObject(uid_ref[1] + 1)->GetPosition(), rm0->GetSimObject(uid_ref[0] + 1)->GetPosition());
EXPECT_ARR_NEAR_GPU(rm1->GetSimObject(uid_ref[1] + 2)->GetPosition(), rm0->GetSimObject(uid_ref[0] + 2)->GetPosition());
EXPECT_ARR_NEAR_GPU(rm1->GetSimObject(uid_ref[1] + 3)->GetPosition(), rm0->GetSimObject(uid_ref[0] + 3)->GetPosition());
EXPECT_ARR_NEAR_GPU(rm1->GetSimObject(uid_ref[1] + 4)->GetPosition(), rm0->GetSimObject(uid_ref[0] + 4)->GetPosition());
EXPECT_ARR_NEAR_GPU(rm1->GetSimObject(uid_ref[1] + 5)->GetPosition(), rm0->GetSimObject(uid_ref[0] + 5)->GetPosition());
EXPECT_ARR_NEAR_GPU(rm1->GetSimObject(uid_ref[1] + 6)->GetPosition(), rm0->GetSimObject(uid_ref[0] + 6)->GetPosition());
EXPECT_ARR_NEAR_GPU(rm1->GetSimObject(uid_ref[1] + 7)->GetPosition(), rm0->GetSimObject(uid_ref[0] + 7)->GetPosition());
EXPECT_ARR_NEAR_GPU(rm1->GetSimObject(uid_ref[1] + 8)->GetPosition(), rm0->GetSimObject(uid_ref[0] + 8)->GetPosition());
EXPECT_ARR_NEAR_GPU(rm1->GetSimObject(uid_ref[1] + 9)->GetPosition(), rm0->GetSimObject(uid_ref[0] + 9)->GetPosition());
EXPECT_ARR_NEAR_GPU(rm1->GetSimObject(uid_ref[1] + 10)->GetPosition(), rm0->GetSimObject(uid_ref[0] + 10)->GetPosition());
EXPECT_ARR_NEAR_GPU(rm1->GetSimObject(uid_ref[1] + 11)->GetPosition(), rm0->GetSimObject(uid_ref[0] + 11)->GetPosition());
EXPECT_ARR_NEAR_GPU(rm1->GetSimObject(uid_ref[1] + 12)->GetPosition(), rm0->GetSimObject(uid_ref[0] + 12)->GetPosition());
EXPECT_ARR_NEAR_GPU(rm1->GetSimObject(uid_ref[1] + 13)->GetPosition(), rm0->GetSimObject(uid_ref[0] + 13)->GetPosition());
EXPECT_ARR_NEAR_GPU(rm1->GetSimObject(uid_ref[1] + 14)->GetPosition(), rm0->GetSimObject(uid_ref[0] + 14)->GetPosition());
EXPECT_ARR_NEAR_GPU(rm1->GetSimObject(uid_ref[1] + 15)->GetPosition(), rm0->GetSimObject(uid_ref[0] + 15)->GetPosition());
EXPECT_ARR_NEAR_GPU(rm1->GetSimObject(uid_ref[1] + 16)->GetPosition(), rm0->GetSimObject(uid_ref[0] + 16)->GetPosition());
EXPECT_ARR_NEAR_GPU(rm1->GetSimObject(uid_ref[1] + 17)->GetPosition(), rm0->GetSimObject(uid_ref[0] + 17)->GetPosition());
EXPECT_ARR_NEAR_GPU(rm1->GetSimObject(uid_ref[1] + 18)->GetPosition(), rm0->GetSimObject(uid_ref[0] + 18)->GetPosition());
EXPECT_ARR_NEAR_GPU(rm1->GetSimObject(uid_ref[1] + 19)->GetPosition(), rm0->GetSimObject(uid_ref[0] + 19)->GetPosition());
EXPECT_ARR_NEAR_GPU(rm1->GetSimObject(uid_ref[1] + 20)->GetPosition(), rm0->GetSimObject(uid_ref[0] + 20)->GetPosition());
EXPECT_ARR_NEAR_GPU(rm1->GetSimObject(uid_ref[1] + 21)->GetPosition(), rm0->GetSimObject(uid_ref[0] + 21)->GetPosition());
EXPECT_ARR_NEAR_GPU(rm1->GetSimObject(uid_ref[1] + 22)->GetPosition(), rm0->GetSimObject(uid_ref[0] + 22)->GetPosition());
EXPECT_ARR_NEAR_GPU(rm1->GetSimObject(uid_ref[1] + 23)->GetPosition(), rm0->GetSimObject(uid_ref[0] + 23)->GetPosition());
EXPECT_ARR_NEAR_GPU(rm1->GetSimObject(uid_ref[1] + 24)->GetPosition(), rm0->GetSimObject(uid_ref[0] + 24)->GetPosition());
EXPECT_ARR_NEAR_GPU(rm1->GetSimObject(uid_ref[1] + 25)->GetPosition(), rm0->GetSimObject(uid_ref[0] + 25)->GetPosition());
EXPECT_ARR_NEAR_GPU(rm1->GetSimObject(uid_ref[1] + 26)->GetPosition(), rm0->GetSimObject(uid_ref[0] + 26)->GetPosition());
// clang-format on
}
#ifdef USE_CUDA
TEST(DisplacementOpGpuTest, ComputeSoaNewCuda) { RunTest2(kCuda); }
#endif
#ifdef USE_OPENCL
TEST(DisplacementOpGpuTest, ComputeSoaNewOpenCL) { RunTest2(kOpenCl); }
#endif
} // namespace displacement_op_gpu_test_internal
} // namespace bdm
<commit_msg>Set correct backend for GPU tests<commit_after>// -----------------------------------------------------------------------------
//
// Copyright (C) The BioDynaMo Project.
// 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.
//
// See the LICENSE file distributed with this work for details.
// See the NOTICE file distributed with this work for additional information
// regarding copyright ownership.
//
// -----------------------------------------------------------------------------
#include <array>
#include "core/biology_module/grow_divide.h"
#include "core/container/sim_object_vector.h"
#include "core/environment/environment.h"
#include "core/functor.h"
#include "core/gpu/gpu_helper.h"
#include "core/operation/displacement_op.h"
#include "core/sim_object/cell.h"
#include "gtest/gtest.h"
#include "unit/test_util/test_util.h"
namespace bdm {
namespace displacement_op_gpu_test_internal {
// NB: The GPU execution 'context' for the displacement operation differes,
// from the CPU version. Once the CPU version supports the same execution
// context, we can include it for direct comparison of results.
static constexpr double kEps = 10 * abs_error<double>::value;
class DisplacementOpCpuVerify {
public:
struct CalculateDisplacement;
struct UpdateCells;
void operator()() {
auto* sim = Simulation::GetActive();
auto* rm = sim->GetResourceManager();
SimObjectVector<Double3> displacements;
CalculateDisplacement cd(&displacements);
rm->ApplyOnAllElementsParallelDynamic(1000, cd);
UpdateCells uc(&displacements);
rm->ApplyOnAllElementsParallelDynamic(1000, uc);
}
struct CalculateDisplacement : public Functor<void, SimObject*, SoHandle> {
SimObjectVector<Double3>* displacements_;
CalculateDisplacement(SimObjectVector<Double3>* displacements) {
displacements_ = displacements;
}
void operator()(SimObject* so, SoHandle soh) override {
auto* sim = Simulation::GetActive();
auto* env = sim->GetEnvironment();
auto* param = sim->GetParam();
auto search_radius = env->GetLargestObjectSize();
auto squared_radius_ = search_radius * search_radius;
const auto& displacement = so->CalculateDisplacement(
squared_radius_, param->simulation_time_step_);
(*displacements_)[soh] = displacement;
}
};
struct UpdateCells : public Functor<void, SimObject*, SoHandle> {
SimObjectVector<Double3>* displacements_;
UpdateCells(SimObjectVector<Double3>* displacements) {
displacements_ = displacements;
}
void operator()(SimObject* so, SoHandle soh) override {
auto* sim = Simulation::GetActive();
auto* param = sim->GetParam();
so->ApplyDisplacement((*displacements_)[soh]);
if (param->bound_space_) {
ApplyBoundingBox(so, param->min_bound_, param->max_bound_);
}
}
};
};
void RunTest(OpComputeTarget mode) {
auto set_param = [&](Param* param) {
switch (mode) {
case kOpenCl:
param->compute_target_ = "opencl";
case kCuda:
param->compute_target_ = "cuda";
default:
return;
}
};
enum Case { kCompute, kVerify };
std::vector<Simulation*> sims;
sims.push_back(new Simulation("GPU", set_param));
sims.push_back(new Simulation("CPU_Verify", set_param));
std::array<SoUid, 2> uid_ref;
for (size_t i = 0; i < sims.size(); i++) {
auto& sim = sims[i];
sim->Activate();
auto* rm = sim->GetResourceManager();
auto* env = sim->GetEnvironment();
uid_ref[i] = SoUid(sim->GetSoUidGenerator()->GetHighestIndex());
// Cell 0
Cell* cell = new Cell();
cell->SetAdherence(0.3);
cell->SetDiameter(10);
cell->SetMass(1.4);
cell->SetPosition({0, 0, 0});
rm->push_back(cell);
// Cell 1
Cell* cell_1 = new Cell();
cell_1->SetAdherence(0.4);
cell_1->SetDiameter(10);
cell_1->SetMass(1.1);
cell_1->SetPosition({0, 8, 0});
rm->push_back(cell_1);
env->Update();
if (i == Case::kCompute) {
auto *op = NewOperation("displacement");
op->SelectComputeTarget(mode);
op->SetUp();
(*op)();
op->TearDown();
} else {
// Run verification on CPU
DisplacementOpCpuVerify cpu_op;
cpu_op();
}
}
// check results
auto rm0 = sims[Case::kCompute]->GetResourceManager();
auto rm1 = sims[Case::kVerify]->GetResourceManager();
auto cell0 = static_cast<Cell*>(rm0->GetSimObject(uid_ref[0] + 0));
auto cell1 = static_cast<Cell*>(rm0->GetSimObject(uid_ref[0] + 1));
auto vcell0 = static_cast<Cell*>(rm1->GetSimObject(uid_ref[1] + 0));
auto vcell1 = static_cast<Cell*>(rm1->GetSimObject(uid_ref[1] + 1));
EXPECT_ARR_NEAR_GPU(vcell0->GetPosition(), cell0->GetPosition());
EXPECT_ARR_NEAR_GPU(vcell1->GetPosition(), cell1->GetPosition());
// check if tractor_force has been reset to zero
EXPECT_ARR_NEAR_GPU(cell0->GetTractorForce(), {0, 0, 0});
EXPECT_ARR_NEAR_GPU(cell1->GetTractorForce(), {0, 0, 0});
// remaining fields should remain unchanged
// cell 0
EXPECT_NEAR(0.3, cell0->GetAdherence(), kEps);
EXPECT_NEAR(10, cell0->GetDiameter(), kEps);
EXPECT_NEAR(1.4, cell0->GetMass(), kEps);
// cell 1
EXPECT_NEAR(0.4, cell1->GetAdherence(), kEps);
EXPECT_NEAR(10, cell1->GetDiameter(), kEps);
EXPECT_NEAR(1.1, cell1->GetMass(), kEps);
}
#ifdef USE_CUDA
TEST(DisplacementOpGpuTest, ComputeSoaCuda) { RunTest(kCuda); }
#endif
#ifdef USE_OPENCL
TEST(DisplacementOpGpuTest, ComputeSoaOpenCL) { RunTest(kOpenCl); }
#endif
void RunTest2(OpComputeTarget mode) {
auto set_param = [&](auto* param) {
switch (mode) {
case kOpenCl:
param->compute_target_ = "opencl";
case kCuda:
param->compute_target_ = "cuda";
default:
return;
}
};
enum Case { kCompute, kVerify };
std::vector<Simulation*> sims;
sims.push_back(new Simulation("GPU", set_param));
sims.push_back(new Simulation("CPU_Verify", set_param));
std::array<SoUid, 2> uid_ref;
for (size_t i = 0; i < sims.size(); i++) {
auto& sim = sims[i];
sim->Activate();
auto* rm = sim->GetResourceManager();
auto* env = sim->GetEnvironment();
uid_ref[i] = SoUid(sim->GetSoUidGenerator()->GetHighestIndex());
double space = 20;
for (size_t i = 0; i < 3; i++) {
for (size_t j = 0; j < 3; j++) {
for (size_t k = 0; k < 3; k++) {
Cell* cell = new Cell({k * space, j * space, i * space});
cell->SetDiameter(30);
cell->SetAdherence(0.4);
cell->SetMass(1.0);
rm->push_back(cell);
}
}
}
env->Update();
if (i == Case::kCompute) {
auto *op = NewOperation("displacement");
op->SelectComputeTarget(mode);
op->SetUp();
(*op)();
op->TearDown();
} else {
// Run verification on CPU
DisplacementOpCpuVerify cpu_op;
cpu_op();
}
}
// check results
auto rm0 = sims[Case::kCompute]->GetResourceManager();
auto rm1 = sims[Case::kVerify]->GetResourceManager();
// clang-format off
EXPECT_ARR_NEAR_GPU(rm1->GetSimObject(uid_ref[1] + 0)->GetPosition(), rm0->GetSimObject(uid_ref[0] + 0)->GetPosition());
EXPECT_ARR_NEAR_GPU(rm1->GetSimObject(uid_ref[1] + 1)->GetPosition(), rm0->GetSimObject(uid_ref[0] + 1)->GetPosition());
EXPECT_ARR_NEAR_GPU(rm1->GetSimObject(uid_ref[1] + 2)->GetPosition(), rm0->GetSimObject(uid_ref[0] + 2)->GetPosition());
EXPECT_ARR_NEAR_GPU(rm1->GetSimObject(uid_ref[1] + 3)->GetPosition(), rm0->GetSimObject(uid_ref[0] + 3)->GetPosition());
EXPECT_ARR_NEAR_GPU(rm1->GetSimObject(uid_ref[1] + 4)->GetPosition(), rm0->GetSimObject(uid_ref[0] + 4)->GetPosition());
EXPECT_ARR_NEAR_GPU(rm1->GetSimObject(uid_ref[1] + 5)->GetPosition(), rm0->GetSimObject(uid_ref[0] + 5)->GetPosition());
EXPECT_ARR_NEAR_GPU(rm1->GetSimObject(uid_ref[1] + 6)->GetPosition(), rm0->GetSimObject(uid_ref[0] + 6)->GetPosition());
EXPECT_ARR_NEAR_GPU(rm1->GetSimObject(uid_ref[1] + 7)->GetPosition(), rm0->GetSimObject(uid_ref[0] + 7)->GetPosition());
EXPECT_ARR_NEAR_GPU(rm1->GetSimObject(uid_ref[1] + 8)->GetPosition(), rm0->GetSimObject(uid_ref[0] + 8)->GetPosition());
EXPECT_ARR_NEAR_GPU(rm1->GetSimObject(uid_ref[1] + 9)->GetPosition(), rm0->GetSimObject(uid_ref[0] + 9)->GetPosition());
EXPECT_ARR_NEAR_GPU(rm1->GetSimObject(uid_ref[1] + 10)->GetPosition(), rm0->GetSimObject(uid_ref[0] + 10)->GetPosition());
EXPECT_ARR_NEAR_GPU(rm1->GetSimObject(uid_ref[1] + 11)->GetPosition(), rm0->GetSimObject(uid_ref[0] + 11)->GetPosition());
EXPECT_ARR_NEAR_GPU(rm1->GetSimObject(uid_ref[1] + 12)->GetPosition(), rm0->GetSimObject(uid_ref[0] + 12)->GetPosition());
EXPECT_ARR_NEAR_GPU(rm1->GetSimObject(uid_ref[1] + 13)->GetPosition(), rm0->GetSimObject(uid_ref[0] + 13)->GetPosition());
EXPECT_ARR_NEAR_GPU(rm1->GetSimObject(uid_ref[1] + 14)->GetPosition(), rm0->GetSimObject(uid_ref[0] + 14)->GetPosition());
EXPECT_ARR_NEAR_GPU(rm1->GetSimObject(uid_ref[1] + 15)->GetPosition(), rm0->GetSimObject(uid_ref[0] + 15)->GetPosition());
EXPECT_ARR_NEAR_GPU(rm1->GetSimObject(uid_ref[1] + 16)->GetPosition(), rm0->GetSimObject(uid_ref[0] + 16)->GetPosition());
EXPECT_ARR_NEAR_GPU(rm1->GetSimObject(uid_ref[1] + 17)->GetPosition(), rm0->GetSimObject(uid_ref[0] + 17)->GetPosition());
EXPECT_ARR_NEAR_GPU(rm1->GetSimObject(uid_ref[1] + 18)->GetPosition(), rm0->GetSimObject(uid_ref[0] + 18)->GetPosition());
EXPECT_ARR_NEAR_GPU(rm1->GetSimObject(uid_ref[1] + 19)->GetPosition(), rm0->GetSimObject(uid_ref[0] + 19)->GetPosition());
EXPECT_ARR_NEAR_GPU(rm1->GetSimObject(uid_ref[1] + 20)->GetPosition(), rm0->GetSimObject(uid_ref[0] + 20)->GetPosition());
EXPECT_ARR_NEAR_GPU(rm1->GetSimObject(uid_ref[1] + 21)->GetPosition(), rm0->GetSimObject(uid_ref[0] + 21)->GetPosition());
EXPECT_ARR_NEAR_GPU(rm1->GetSimObject(uid_ref[1] + 22)->GetPosition(), rm0->GetSimObject(uid_ref[0] + 22)->GetPosition());
EXPECT_ARR_NEAR_GPU(rm1->GetSimObject(uid_ref[1] + 23)->GetPosition(), rm0->GetSimObject(uid_ref[0] + 23)->GetPosition());
EXPECT_ARR_NEAR_GPU(rm1->GetSimObject(uid_ref[1] + 24)->GetPosition(), rm0->GetSimObject(uid_ref[0] + 24)->GetPosition());
EXPECT_ARR_NEAR_GPU(rm1->GetSimObject(uid_ref[1] + 25)->GetPosition(), rm0->GetSimObject(uid_ref[0] + 25)->GetPosition());
EXPECT_ARR_NEAR_GPU(rm1->GetSimObject(uid_ref[1] + 26)->GetPosition(), rm0->GetSimObject(uid_ref[0] + 26)->GetPosition());
// clang-format on
}
#ifdef USE_CUDA
TEST(DisplacementOpGpuTest, ComputeSoaNewCuda) { RunTest2(kCuda); }
#endif
#ifdef USE_OPENCL
TEST(DisplacementOpGpuTest, ComputeSoaNewOpenCL) { RunTest2(kOpenCl); }
#endif
} // namespace displacement_op_gpu_test_internal
} // namespace bdm
<|endoftext|>
|
<commit_before>#include "ChSolverParallel.h"
using namespace chrono;
real Func1(const int &SIZE, real* __restrict__ x, real* __restrict__ mb_tmp) {
real mb_tmp_norm = 0;
real _mb_tmp_;
real *x_ = (real*) __builtin_assume_aligned(x, 16);
real *mb_tmp_ = (real*) __builtin_assume_aligned(mb_tmp, 16);
//#pragma omp parallel for reduction(+:mb_tmp_norm)
for (int i = 0; i < SIZE; i++) {
_mb_tmp_ = x_[i] - 1.0f;
mb_tmp_norm += _mb_tmp_ * _mb_tmp_;
mb_tmp_[i] = _mb_tmp_;
}
mb_tmp_norm = sqrt(mb_tmp_norm);
return mb_tmp_norm;
}
void Func2(const size_t &SIZE, const real t_k, real* __restrict__ x, real* __restrict__ mg_tmp1, real* __restrict__ b, real* __restrict__ mg, real* __restrict__ mx,
real* __restrict__ my) {
//#pragma omp parallel for
for (int i = 0; i < SIZE; i++) {
real _mg_ = mg_tmp1[i] - b[i];
mg[i] = _mg_;
mx[i] = -t_k * _mg_ + my[i];
}
}
void Func3(const size_t &SIZE, real* __restrict__ mg_tmp, real* __restrict__ mg_tmp1, real* __restrict__ b, real* __restrict__ mg, real* __restrict__ mx, real* __restrict__ my,
real & obj1, real & obj2, real & dot_mg_ms, real & norm_ms) {
obj1 = 0.0;
obj2 = 0.0;
dot_mg_ms = 0;
norm_ms = 0;
real _mg_tmp_, _b_, _ms_, _mx_, _my_;
//#pragma omp parallel for reduction(+:obj1,obj2,dot_mg_ms,norm_ms)
for (int i = 0; i < SIZE; i++) {
_mg_tmp_ = mg_tmp[i];
_b_ = b[i];
_ms_ = .5 * _mg_tmp_ - _b_;
_mx_ = mx[i];
_my_ = my[i];
obj1 += _mx_ * _ms_;
_ms_ = .5 * mg_tmp1[i] - _b_;
obj2 += _my_ * _ms_;
_ms_ = _mx_ - _my_;
dot_mg_ms += mg[i] * _ms_;
norm_ms += _ms_ * _ms_;
}
norm_ms = sqrt(norm_ms);
}
uint ChSolverParallel::SolveAPGDRS(custom_vector<real> &x, custom_vector<real> &b, const uint max_iter,const int SIZE) {
real gdiff = 1e-6;
real lastgoodres=10e30;
real theta_k=init_theta_k;
real theta_k1=theta_k;
real beta_k1=0.0;
real L_k;
Project(x.data());
ShurProduct(x,mg);
real mb_tmp_norm = Func1(SIZE,x.data(),mb_tmp.data());
ShurProduct(mb_tmp,mg_tmp);
if (mb_tmp_norm == 0) {
L_k = 1;
} else {
L_k =Norm(mg_tmp) / mb_tmp_norm;
}
real t_k = 1.0 / L_k;
my = x;
mx = x;
real obj1=0.0;
real obj2=0.0;
for (current_iteration = 0; current_iteration < max_iter; current_iteration++) {
ShurProduct(my,mg_tmp1);
Func2(SIZE, t_k, x.data(), mg_tmp1.data(), b.data(), mg.data(), mx.data(),
my.data());
Project(mx.data());
ShurProduct(mx,mg_tmp);
obj1=0.0;
obj2=0.0;
real dot_mg_ms = 0;
real norm_ms = 0;
Func3(SIZE, mg_tmp.data(), mg_tmp1.data(), b.data(), mg.data(), mx.data(), my.data(),
obj1, obj2, dot_mg_ms, norm_ms);
while (obj1 > obj2 + dot_mg_ms + 0.5 * L_k * powf(norm_ms, 2.0)) {
L_k = step_grow * L_k;
t_k = 1.0 / L_k;
SEAXPY(-t_k, mg, my, mx); // mx = my + mg*(t_k);
Project(mx.data());
ShurProduct(mx,mg_tmp);
obj1 = dot_mg_ms = norm_ms =0;
#pragma omp parallel for reduction(+:obj1,dot_mg_ms,norm_ms)
for(int i=0; i<SIZE; i++) {
real _mg_tmp_ = mg_tmp[i];
real _b_ = b[i];
real _ms_ = .5*_mg_tmp_-_b_;
real _mx_ = mx[i];
obj1+=_mx_*_ms_;
_ms_ = _mx_-my[i];
dot_mg_ms+=mg[i]*_ms_;
norm_ms+=_ms_*_ms_;
}
norm_ms = sqrt(norm_ms);
}
theta_k1 = (-pow(theta_k, 2) + theta_k * sqrt(pow(theta_k, 2) + 4)) / 2.0;
beta_k1 = theta_k * (1.0 - theta_k) / (pow(theta_k, 2) + theta_k1);
real temp_sum=0;
#pragma omp parallel for reduction(+:temp_sum)
for(int i=0; i<SIZE; i++) {
real _mx_ = mx[i];
real _ms_ = _mx_-x[i];
my[i] = beta_k1*_ms_+_mx_;
temp_sum+=mg[i]*_ms_;
}
if (temp_sum > 0) {
my = mx;
theta_k1 = 1.0;
}
L_k = step_shrink * L_k;
t_k = 1.0 / L_k;
theta_k = theta_k1;
if(current_iteration%5==0) {
real g_proj_norm = Res4(mg_tmp, b, mx, mb_tmp);
if(g_proj_norm < lastgoodres) {
lastgoodres = g_proj_norm;
ml_candidate = mx;
}
residual=lastgoodres;
real maxdeltalambda = CompRes(b,number_of_rigid_rigid); //NormInf(ms);
AtIterationEnd(residual, maxdeltalambda, current_iteration);
if(collision_inside) {
UpdatePosition(ml_candidate);
UpdateContacts();
}
}
if (residual < tolerance) {
break;
}
}
x=ml_candidate;
return current_iteration;
}
<commit_msg>Enable omp for vectorized code<commit_after>#include "ChSolverParallel.h"
using namespace chrono;
real Func1(const int &SIZE, real* __restrict__ x, real* __restrict__ mb_tmp) {
real mb_tmp_norm = 0;
real _mb_tmp_;
real *x_ = (real*) __builtin_assume_aligned(x, 16);
real *mb_tmp_ = (real*) __builtin_assume_aligned(mb_tmp, 16);
#pragma omp parallel for reduction(+:mb_tmp_norm)
for (int i = 0; i < SIZE; i++) {
_mb_tmp_ = x_[i] - 1.0f;
mb_tmp_norm += _mb_tmp_ * _mb_tmp_;
mb_tmp_[i] = _mb_tmp_;
}
mb_tmp_norm = sqrt(mb_tmp_norm);
return mb_tmp_norm;
}
void Func2(const size_t &SIZE, const real t_k, real* __restrict__ x, real* __restrict__ mg_tmp1, real* __restrict__ b, real* __restrict__ mg, real* __restrict__ mx,
real* __restrict__ my) {
#pragma omp parallel for
for (int i = 0; i < SIZE; i++) {
real _mg_ = mg_tmp1[i] - b[i];
mg[i] = _mg_;
mx[i] = -t_k * _mg_ + my[i];
}
}
void Func3(const size_t &SIZE, real* __restrict__ mg_tmp, real* __restrict__ mg_tmp1, real* __restrict__ b, real* __restrict__ mg, real* __restrict__ mx, real* __restrict__ my,
real & _obj1, real & _obj2, real & _dot_mg_ms, real & _norm_ms) {
real obj1 = 0.0;
real obj2 = 0.0;
real dot_mg_ms = 0;
real norm_ms = 0;
real _mg_tmp_, _b_, _ms_, _mx_, _my_;
#pragma omp parallel for reduction(+:obj1,obj2,dot_mg_ms,norm_ms)
for (int i = 0; i < SIZE; i++) {
_mg_tmp_ = mg_tmp[i];
_b_ = b[i];
_ms_ = .5 * _mg_tmp_ - _b_;
_mx_ = mx[i];
_my_ = my[i];
obj1 += _mx_ * _ms_;
_ms_ = .5 * mg_tmp1[i] - _b_;
obj2 += _my_ * _ms_;
_ms_ = _mx_ - _my_;
dot_mg_ms += mg[i] * _ms_;
norm_ms += _ms_ * _ms_;
}
norm_ms = sqrt(norm_ms);
_obj1 = obj1;
_obj2 = obj2;
_dot_mg_ms = dot_mg_ms;
_norm_ms = norm_ms;
}
uint ChSolverParallel::SolveAPGDRS(custom_vector<real> &x, custom_vector<real> &b, const uint max_iter,const int SIZE) {
real gdiff = 1e-6;
real lastgoodres=10e30;
real theta_k=init_theta_k;
real theta_k1=theta_k;
real beta_k1=0.0;
real L_k;
Project(x.data());
ShurProduct(x,mg);
real mb_tmp_norm = Func1(SIZE,x.data(),mb_tmp.data());
ShurProduct(mb_tmp,mg_tmp);
if (mb_tmp_norm == 0) {
L_k = 1;
} else {
L_k =Norm(mg_tmp) / mb_tmp_norm;
}
real t_k = 1.0 / L_k;
my = x;
mx = x;
real obj1=0.0;
real obj2=0.0;
for (current_iteration = 0; current_iteration < max_iter; current_iteration++) {
ShurProduct(my,mg_tmp1);
Func2(SIZE, t_k, x.data(), mg_tmp1.data(), b.data(), mg.data(), mx.data(),
my.data());
Project(mx.data());
ShurProduct(mx,mg_tmp);
obj1=0.0;
obj2=0.0;
real dot_mg_ms = 0;
real norm_ms = 0;
Func3(SIZE, mg_tmp.data(), mg_tmp1.data(), b.data(), mg.data(), mx.data(), my.data(),
obj1, obj2, dot_mg_ms, norm_ms);
while (obj1 > obj2 + dot_mg_ms + 0.5 * L_k * powf(norm_ms, 2.0)) {
L_k = step_grow * L_k;
t_k = 1.0 / L_k;
SEAXPY(-t_k, mg, my, mx); // mx = my + mg*(t_k);
Project(mx.data());
ShurProduct(mx,mg_tmp);
obj1 = dot_mg_ms = norm_ms =0;
#pragma omp parallel for reduction(+:obj1,dot_mg_ms,norm_ms)
for(int i=0; i<SIZE; i++) {
real _mg_tmp_ = mg_tmp[i];
real _b_ = b[i];
real _ms_ = .5*_mg_tmp_-_b_;
real _mx_ = mx[i];
obj1+=_mx_*_ms_;
_ms_ = _mx_-my[i];
dot_mg_ms+=mg[i]*_ms_;
norm_ms+=_ms_*_ms_;
}
norm_ms = sqrt(norm_ms);
}
theta_k1 = (-pow(theta_k, 2) + theta_k * sqrt(pow(theta_k, 2) + 4)) / 2.0;
beta_k1 = theta_k * (1.0 - theta_k) / (pow(theta_k, 2) + theta_k1);
real temp_sum=0;
#pragma omp parallel for reduction(+:temp_sum)
for(int i=0; i<SIZE; i++) {
real _mx_ = mx[i];
real _ms_ = _mx_-x[i];
my[i] = beta_k1*_ms_+_mx_;
temp_sum+=mg[i]*_ms_;
}
if (temp_sum > 0) {
my = mx;
theta_k1 = 1.0;
}
L_k = step_shrink * L_k;
t_k = 1.0 / L_k;
theta_k = theta_k1;
if(current_iteration%5==0) {
real g_proj_norm = Res4(mg_tmp, b, mx, mb_tmp);
if(g_proj_norm < lastgoodres) {
lastgoodres = g_proj_norm;
ml_candidate = mx;
}
residual=lastgoodres;
real maxdeltalambda = CompRes(b,number_of_rigid_rigid); //NormInf(ms);
AtIterationEnd(residual, maxdeltalambda, current_iteration);
if(collision_inside) {
UpdatePosition(ml_candidate);
UpdateContacts();
}
}
if (residual < tolerance) {
break;
}
}
x=ml_candidate;
return current_iteration;
}
<|endoftext|>
|
<commit_before>// $Id$
/***********************************************************************
Moses - factored phrase-based language decoder
Copyright (c) 2006 University of Edinburgh
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 University of Edinburgh 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.
***********************************************************************/
// example file on how to use moses library
#ifdef WIN32
// Include Visual Leak Detector
#include <vld.h>
#endif
#include <fstream>
#include "Main.h"
#include "LatticePath.h"
#include "FactorCollection.h"
#include "Manager.h"
#include "Phrase.h"
#include "Util.h"
#include "LatticePathList.h"
#include "Timer.h"
#include "IOCommandLine.h"
#include "IOFile.h"
#include "Sentence.h"
#include "ConfusionNet.h"
#include "TranslationAnalysis.h"
#if HAVE_CONFIG_H
#include "config.h"
#else
// those not using autoconf have to build MySQL support for now
# define USE_MYSQL 1
#endif
using namespace std;
Timer timer;
bool readInput(InputOutput *inputOutput, int inputType, InputType*& source)
{
delete source;
source=inputOutput->GetInput((inputType ?
static_cast<InputType*>(new ConfusionNet) :
static_cast<InputType*>(new Sentence(Input))));
return (source ? true : false);
}
int main(int argc, char* argv[])
{
timer.start("Starting...");
std::cerr
<<"============================================================================\n"
<<"starting "<<argv[0]<<" (build on "<<__DATE__<<")\n"
<<"============================================================================\n"
<<"\n"
<<"the command line was: \n";
for(int i=0;i<argc;++i) std::cerr<<argv[i]<<" ";
std::cerr
<<"\n"
<<"============================================================================\n";
StaticData staticData;
if (!staticData.LoadParameters(argc, argv))
return EXIT_FAILURE;
/*
* boost::shared_ptr<UnknownWordHandler> unknownWordHandler(new UnknownWordHandler);
staticData.SetUnknownWordHandler(unknownWordHandler);
*/
if (staticData.GetVerboseLevel() > 0)
{
#if N_BEST
std::cerr << "N_BEST=enabled\n";
#else
std::cerr << "N_BEST=disabled\n";
#endif
}
// set up read/writing class
InputOutput *inputOutput = GetInputOutput(staticData);
std::cerr << "The score component vector looks like this:\n" << staticData.GetScoreIndexManager();
std::cerr << "The global weight vector looks like this:\n";
vector<float> weights = staticData.GetAllWeights();
std::cerr << weights[0];
for (size_t j=1; j<weights.size(); j++) { std::cerr << ", " << weights[j]; }
std::cerr << "\n";
// every score must have a weight! check that here:
assert(weights.size() == staticData.GetScoreIndexManager().GetTotalNumberOfScores());
if (inputOutput == NULL)
return EXIT_FAILURE;
// read each sentence & decode
InputType *source=0;
while(readInput(inputOutput,staticData.GetInputType(),source))
{
// note: source is only valid within this while loop!
TRACE_ERR("TRANSLATING: " << *source <<"\n");
staticData.InitializeBeforeSentenceProcessing(*source);
Manager manager(*source, staticData);
manager.ProcessSentence();
inputOutput->SetOutput(manager.GetBestHypothesis(), source->GetTranslationId(),
staticData.GetReportSourceSpan(),
staticData.GetReportAllFactors()
);
// n-best
size_t nBestSize = staticData.GetNBestSize();
if (nBestSize > 0)
{
TRACE_ERR(nBestSize << " " << staticData.GetNBestFilePath() << endl);
LatticePathList nBestList;
manager.CalcNBest(nBestSize, nBestList);
inputOutput->SetNBest(nBestList, source->GetTranslationId());
RemoveAllInColl< LatticePathList::iterator > (nBestList);
}
if (staticData.IsDetailedTranslationReportingEnabled()) {
TranslationAnalysis::PrintTranslationAnalysis(std::cout, manager.GetBestHypothesis());
}
staticData.CleanUpAfterSentenceProcessing();
}
delete inputOutput;
timer.check("End.");
return EXIT_SUCCESS;
}
InputOutput *GetInputOutput(StaticData &staticData)
{
InputOutput *inputOutput;
const std::vector<FactorType> &inputFactorOrder = staticData.GetInputFactorOrder()
,&outputFactorOrder = staticData.GetOutputFactorOrder();
FactorTypeSet inputFactorUsed(inputFactorOrder);
// io
if (staticData.GetIOMethod() == IOMethodFile)
{
TRACE_ERR("IO from File" << endl);
string inputFileHash;
list< Phrase > inputPhraseList;
string filePath = staticData.GetParam("input-file")[0];
TRACE_ERR("About to create ioFile" << endl);
IOFile *ioFile = new IOFile(inputFactorOrder, outputFactorOrder, inputFactorUsed
, staticData.GetFactorCollection()
, staticData.GetNBestSize()
, staticData.GetNBestFilePath()
, filePath);
if(staticData.GetInputType())
{
TRACE_ERR("Do not read input phrases for confusion net translation\n");
}
else
{
TRACE_ERR("About to GetInputPhrase\n");
ioFile->GetInputPhrase(inputPhraseList);
}
TRACE_ERR("After GetInputPhrase" << endl);
inputOutput = ioFile;
inputFileHash = GetMD5Hash(filePath);
TRACE_ERR("About to LoadPhraseTables" << endl);
staticData.LoadPhraseTables(true, inputFileHash, inputPhraseList);
ioFile->ResetSentenceId();
}
else
{
TRACE_ERR("IO from STDOUT/STDIN" << endl);
inputOutput = new IOCommandLine(inputFactorOrder, outputFactorOrder, inputFactorUsed
, staticData.GetFactorCollection()
, staticData.GetNBestSize()
, staticData.GetNBestFilePath());
staticData.LoadPhraseTables();
}
staticData.LoadMapping();
timer.check("Created input-output object");
return inputOutput;
}
<commit_msg>get rid of last vestiges of conditional compilation for N_BEST support. there is virtually no overhead associated with this change and it makes the code/testing cleaner<commit_after>// $Id$
/***********************************************************************
Moses - factored phrase-based language decoder
Copyright (c) 2006 University of Edinburgh
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 University of Edinburgh 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.
***********************************************************************/
// example file on how to use moses library
#ifdef WIN32
// Include Visual Leak Detector
#include <vld.h>
#endif
#include <fstream>
#include "Main.h"
#include "LatticePath.h"
#include "FactorCollection.h"
#include "Manager.h"
#include "Phrase.h"
#include "Util.h"
#include "LatticePathList.h"
#include "Timer.h"
#include "IOCommandLine.h"
#include "IOFile.h"
#include "Sentence.h"
#include "ConfusionNet.h"
#include "TranslationAnalysis.h"
#if HAVE_CONFIG_H
#include "config.h"
#else
// those not using autoconf have to build MySQL support for now
# define USE_MYSQL 1
#endif
using namespace std;
Timer timer;
bool readInput(InputOutput *inputOutput, int inputType, InputType*& source)
{
delete source;
source=inputOutput->GetInput((inputType ?
static_cast<InputType*>(new ConfusionNet) :
static_cast<InputType*>(new Sentence(Input))));
return (source ? true : false);
}
int main(int argc, char* argv[])
{
timer.start("Starting...");
std::cerr
<<"============================================================================\n"
<<"starting "<<argv[0]<<" (build on "<<__DATE__<<")\n"
<<"============================================================================\n"
<<"\n"
<<"the command line was: \n";
for(int i=0;i<argc;++i) std::cerr<<argv[i]<<" ";
std::cerr
<<"\n"
<<"============================================================================\n";
StaticData staticData;
if (!staticData.LoadParameters(argc, argv))
return EXIT_FAILURE;
// set up read/writing class
InputOutput *inputOutput = GetInputOutput(staticData);
std::cerr << "The score component vector looks like this:\n" << staticData.GetScoreIndexManager();
std::cerr << "The global weight vector looks like this:\n";
vector<float> weights = staticData.GetAllWeights();
std::cerr << weights[0];
for (size_t j=1; j<weights.size(); j++) { std::cerr << ", " << weights[j]; }
std::cerr << "\n";
// every score must have a weight! check that here:
assert(weights.size() == staticData.GetScoreIndexManager().GetTotalNumberOfScores());
if (inputOutput == NULL)
return EXIT_FAILURE;
// read each sentence & decode
InputType *source=0;
while(readInput(inputOutput,staticData.GetInputType(),source))
{
// note: source is only valid within this while loop!
TRACE_ERR("TRANSLATING: " << *source <<"\n");
staticData.InitializeBeforeSentenceProcessing(*source);
Manager manager(*source, staticData);
manager.ProcessSentence();
inputOutput->SetOutput(manager.GetBestHypothesis(), source->GetTranslationId(),
staticData.GetReportSourceSpan(),
staticData.GetReportAllFactors()
);
// n-best
size_t nBestSize = staticData.GetNBestSize();
if (nBestSize > 0)
{
TRACE_ERR(nBestSize << " " << staticData.GetNBestFilePath() << endl);
LatticePathList nBestList;
manager.CalcNBest(nBestSize, nBestList);
inputOutput->SetNBest(nBestList, source->GetTranslationId());
RemoveAllInColl< LatticePathList::iterator > (nBestList);
}
if (staticData.IsDetailedTranslationReportingEnabled()) {
TranslationAnalysis::PrintTranslationAnalysis(std::cout, manager.GetBestHypothesis());
}
staticData.CleanUpAfterSentenceProcessing();
}
delete inputOutput;
timer.check("End.");
return EXIT_SUCCESS;
}
InputOutput *GetInputOutput(StaticData &staticData)
{
InputOutput *inputOutput;
const std::vector<FactorType> &inputFactorOrder = staticData.GetInputFactorOrder()
,&outputFactorOrder = staticData.GetOutputFactorOrder();
FactorTypeSet inputFactorUsed(inputFactorOrder);
// io
if (staticData.GetIOMethod() == IOMethodFile)
{
TRACE_ERR("IO from File" << endl);
string inputFileHash;
list< Phrase > inputPhraseList;
string filePath = staticData.GetParam("input-file")[0];
TRACE_ERR("About to create ioFile" << endl);
IOFile *ioFile = new IOFile(inputFactorOrder, outputFactorOrder, inputFactorUsed
, staticData.GetFactorCollection()
, staticData.GetNBestSize()
, staticData.GetNBestFilePath()
, filePath);
if(staticData.GetInputType())
{
TRACE_ERR("Do not read input phrases for confusion net translation\n");
}
else
{
TRACE_ERR("About to GetInputPhrase\n");
ioFile->GetInputPhrase(inputPhraseList);
}
TRACE_ERR("After GetInputPhrase" << endl);
inputOutput = ioFile;
inputFileHash = GetMD5Hash(filePath);
TRACE_ERR("About to LoadPhraseTables" << endl);
staticData.LoadPhraseTables(true, inputFileHash, inputPhraseList);
ioFile->ResetSentenceId();
}
else
{
TRACE_ERR("IO from STDOUT/STDIN" << endl);
inputOutput = new IOCommandLine(inputFactorOrder, outputFactorOrder, inputFactorUsed
, staticData.GetFactorCollection()
, staticData.GetNBestSize()
, staticData.GetNBestFilePath());
staticData.LoadPhraseTables();
}
staticData.LoadMapping();
timer.check("Created input-output object");
return inputOutput;
}
<|endoftext|>
|
<commit_before>/*
===========================================================================
Daemon GPL Source Code
Copyright (C) 2012 Unvanquished Developers
This file is part of the Daemon GPL Source Code (Daemon Source Code).
Daemon Source Code is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
Daemon Source Code 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 Daemon Source Code. If not, see <http://www.gnu.org/licenses/>.
In addition, the Daemon Source Code is also subject to certain additional terms.
You should have received a copy of these additional terms immediately following the
terms and conditions of the GNU General Public License which accompanied the Daemon
Source Code. If not, please request a copy in writing from id Software at the address
below.
If you have questions concerning this license or the applicable additional terms, you
may contact in writing id Software LLC, c/o ZeniMax Media Inc., Suite 120, Rockville,
Maryland 20850 USA.
===========================================================================
*/
#include "q_shared.h"
#include "qcommon.h"
extern "C" {
#include "findlocale/findlocale.h"
}
#include "tinygettext/log.hpp"
#include "tinygettext/tinygettext.hpp"
#include "tinygettext/file_system.hpp"
static Log::Logger LOG(VM_STRING_PREFIX "translation");
using namespace tinygettext;
// Ugly char buffer
static std::string gettextbuffer[ 4 ];
static int num = -1;
DictionaryManager trans_manager;
DictionaryManager trans_managergame;
cvar_t *language;
cvar_t *trans_debug;
cvar_t *trans_encodings;
cvar_t *trans_languages;
/*
====================
DaemonInputbuf
Streambuf based class that uses the engine's File I/O functions for input
====================
*/
class DaemonInputbuf : public std::streambuf
{
private:
static const size_t BUFFER_SIZE = 8192;
fileHandle_t fileHandle;
char buffer[ BUFFER_SIZE ];
size_t putBack;
public:
DaemonInputbuf( const std::string& filename ) : putBack( 1 )
{
char *end;
end = buffer + BUFFER_SIZE - putBack;
setg( end, end, end );
FS_FOpenFileRead( filename.c_str(), &fileHandle );
}
~DaemonInputbuf()
{
if( fileHandle )
{
FS_FCloseFile( fileHandle );
}
}
};
/*
====================
DaemonIstream
Simple istream based class that takes ownership of the streambuf
====================
*/
class DaemonIstream : public std::istream
{
public:
DaemonIstream( const std::string& filename ) : std::istream( new DaemonInputbuf( filename ) ) {}
~DaemonIstream()
{
delete rdbuf();
}
};
/*
====================
DaemonFileSystem
Class used by tinygettext to read files and directories
Uses the engine's File I/O functions for this purpose
====================
*/
class DaemonFileSystem : public FileSystem
{
public:
DaemonFileSystem() = default;
std::vector<std::string> open_directory( const std::string& pathname )
{
int numFiles;
char **files;
std::vector<std::string> ret;
files = FS_ListFiles( pathname.c_str(), nullptr, &numFiles );
for( int i = 0; i < numFiles; i++ )
{
ret.emplace_back( files[ i ] );
}
FS_FreeFileList( files );
return ret;
}
std::unique_ptr<std::istream> open_file( const std::string& filename )
{
return std::unique_ptr<std::istream>( new DaemonIstream( filename ) );
}
};
/*
====================
Logging functions used by tinygettext
====================
*/
void Trans_Error( const std::string& str )
{
LOG.Notice( "^1%s", str.c_str() );
}
void Trans_Warning( const std::string& str )
{
if( trans_debug->integer != 0 )
{
LOG.Notice( "^3%s", str.c_str() );
}
}
void Trans_Info( const std::string& str )
{
if( trans_debug->integer != 0 )
{
LOG.Notice( str.c_str() );
}
}
/*
====================
Trans_SetLanguage
Sets a loaded language. If desired language is not found, set closest match.
If no languages are close, force English.
====================
*/
void Trans_SetLanguage( const char* lang )
{
Language requestLang = Language::from_env( std::string( lang ) );
// default to english
Language bestLang = Language::from_env( "en" );
int bestScore = Language::match( requestLang, bestLang );
std::set<Language> langs = trans_manager.get_languages();
for( std::set<Language>::iterator i = langs.begin(); i != langs.end(); i++ )
{
int score = Language::match( requestLang, *i );
if( score > bestScore )
{
bestScore = score;
bestLang = *i;
}
}
// language not found, display warning
if( bestScore == 0 )
{
LOG.Warn( "Language \"%s\" (%s) not found. Default to \"English\" (en)",
requestLang.get_name().empty() ? "Unknown Language" : requestLang.get_name().c_str(),
lang );
}
trans_manager.set_language( bestLang );
trans_managergame.set_language( bestLang );
Cvar_Set( "language", bestLang.str().c_str() );
LOG.Notice( "Set language to %s" , bestLang.get_name().c_str() );
}
void Trans_UpdateLanguage_f()
{
Trans_SetLanguage( language->string );
}
/*
============
Trans_Init
============
*/
void Trans_Init()
{
char langList[ MAX_TOKEN_CHARS ] = "";
char encList[ MAX_TOKEN_CHARS ] = "";
std::set<Language> langs;
Language lang;
Cmd_AddCommand( "updatelanguage", Trans_UpdateLanguage_f );
language = Cvar_Get( "language", "", CVAR_ARCHIVE );
trans_debug = Cvar_Get( "trans_debug", "0", 0 );
trans_languages = Cvar_Get( "trans_languages", "", CVAR_ROM );
trans_encodings = Cvar_Get( "trans_encodings", "", CVAR_ROM );
// set tinygettext log callbacks
tinygettext::Log::set_log_error_callback( &Trans_Error );
tinygettext::Log::set_log_warning_callback( &Trans_Warning );
tinygettext::Log::set_log_info_callback( &Trans_Info );
trans_manager.set_filesystem( std::unique_ptr<FileSystem>( new DaemonFileSystem ) );
trans_managergame.set_filesystem( std::unique_ptr<FileSystem>( new DaemonFileSystem ) );
trans_manager.add_directory( "translation/client" );
trans_managergame.add_directory( "translation/game" );
langs = trans_manager.get_languages();
for( std::set<Language>::iterator p = langs.begin(); p != langs.end(); p++ )
{
Q_strcat( langList, sizeof( langList ), va( "\"%s\" ", p->get_name().c_str() ) );
Q_strcat( encList, sizeof( encList ), va( "\"%s\" ", p->str().c_str() ) );
}
Cvar_Set( "trans_languages", langList );
Cvar_Set( "trans_encodings", encList );
LOG.Notice( "Loaded %u language%s", langs.size(), ( langs.size() == 1 ? "" : "s" ) );
}
void Trans_LoadDefaultLanguage()
{
FL_Locale *locale;
// Only detect locale if no previous language set.
if( !language->string[0] )
{
FL_FindLocale( &locale, FL_MESSAGES );
// Invalid or not found. Just use builtin language.
if( !locale->lang || !locale->lang[0] || !locale->country || !locale->country[0] )
{
Cvar_Set( "language", "en" );
}
else
{
Cvar_Set( "language", va( "%s%s%s", locale->lang,
locale->country[0] ? "_" : "",
locale->country ) );
}
FL_FreeLocale( &locale );
}
Trans_SetLanguage( language->string );
}
const char* Trans_Gettext_Internal( const char *msgid, DictionaryManager& manager )
{
if ( !msgid )
{
return msgid;
}
num = ( num + 1 ) & 3;
gettextbuffer[ num ] = manager.get_dictionary().translate( msgid );
return gettextbuffer[ num ].c_str();
}
const char* Trans_Pgettext_Internal( const char *ctxt, const char *msgid, DictionaryManager& manager )
{
if ( !ctxt || !msgid )
{
return msgid;
}
num = ( num + 1 ) & 3;
gettextbuffer[ num ] = manager.get_dictionary().translate_ctxt( ctxt, msgid );
return gettextbuffer[ num ].c_str();
}
const char* Trans_GettextPlural_Internal( const char *msgid, const char *msgid_plural, int number, DictionaryManager& manager )
{
if ( !msgid || !msgid_plural )
{
if ( msgid )
{
return msgid;
}
if ( msgid_plural )
{
return msgid_plural;
}
return nullptr;
}
num = ( num + 1 ) & 3;
gettextbuffer[ num ] = manager.get_dictionary().translate_plural( msgid, msgid_plural, number );
return gettextbuffer[ num ].c_str();
}
const char* Trans_Gettext( const char *msgid )
{
return Trans_Gettext_Internal( msgid, trans_manager );
}
const char* Trans_Pgettext( const char *ctxt, const char *msgid )
{
return Trans_Pgettext_Internal( ctxt, msgid, trans_manager );
}
const char* Trans_GettextPlural( const char *msgid, const char *msgid_plural, int num )
{
return Trans_GettextPlural_Internal( msgid, msgid_plural, num, trans_manager );
}
const char* Trans_GettextGame( const char *msgid )
{
return Trans_Gettext_Internal( msgid, trans_managergame );
}
const char* Trans_PgettextGame( const char *ctxt, const char *msgid )
{
return Trans_Pgettext_Internal( ctxt, msgid, trans_managergame );
}
const char* Trans_GettextGamePlural( const char *msgid, const char *msgid_plural, int num )
{
return Trans_GettextPlural_Internal( msgid, msgid_plural, num, trans_managergame );
}
<commit_msg>[flow] Allow to use language even if no country provided<commit_after>/*
===========================================================================
Daemon GPL Source Code
Copyright (C) 2012 Unvanquished Developers
This file is part of the Daemon GPL Source Code (Daemon Source Code).
Daemon Source Code is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
Daemon Source Code 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 Daemon Source Code. If not, see <http://www.gnu.org/licenses/>.
In addition, the Daemon Source Code is also subject to certain additional terms.
You should have received a copy of these additional terms immediately following the
terms and conditions of the GNU General Public License which accompanied the Daemon
Source Code. If not, please request a copy in writing from id Software at the address
below.
If you have questions concerning this license or the applicable additional terms, you
may contact in writing id Software LLC, c/o ZeniMax Media Inc., Suite 120, Rockville,
Maryland 20850 USA.
===========================================================================
*/
#include "q_shared.h"
#include "qcommon.h"
extern "C" {
#include "findlocale/findlocale.h"
}
#include "tinygettext/log.hpp"
#include "tinygettext/tinygettext.hpp"
#include "tinygettext/file_system.hpp"
static Log::Logger LOG(VM_STRING_PREFIX "translation");
using namespace tinygettext;
// Ugly char buffer
static std::string gettextbuffer[ 4 ];
static int num = -1;
DictionaryManager trans_manager;
DictionaryManager trans_managergame;
cvar_t *language;
cvar_t *trans_debug;
cvar_t *trans_encodings;
cvar_t *trans_languages;
/*
====================
DaemonInputbuf
Streambuf based class that uses the engine's File I/O functions for input
====================
*/
class DaemonInputbuf : public std::streambuf
{
private:
static const size_t BUFFER_SIZE = 8192;
fileHandle_t fileHandle;
char buffer[ BUFFER_SIZE ];
size_t putBack;
public:
DaemonInputbuf( const std::string& filename ) : putBack( 1 )
{
char *end;
end = buffer + BUFFER_SIZE - putBack;
setg( end, end, end );
FS_FOpenFileRead( filename.c_str(), &fileHandle );
}
~DaemonInputbuf()
{
if( fileHandle )
{
FS_FCloseFile( fileHandle );
}
}
};
/*
====================
DaemonIstream
Simple istream based class that takes ownership of the streambuf
====================
*/
class DaemonIstream : public std::istream
{
public:
DaemonIstream( const std::string& filename ) : std::istream( new DaemonInputbuf( filename ) ) {}
~DaemonIstream()
{
delete rdbuf();
}
};
/*
====================
DaemonFileSystem
Class used by tinygettext to read files and directories
Uses the engine's File I/O functions for this purpose
====================
*/
class DaemonFileSystem : public FileSystem
{
public:
DaemonFileSystem() = default;
std::vector<std::string> open_directory( const std::string& pathname )
{
int numFiles;
char **files;
std::vector<std::string> ret;
files = FS_ListFiles( pathname.c_str(), nullptr, &numFiles );
for( int i = 0; i < numFiles; i++ )
{
ret.emplace_back( files[ i ] );
}
FS_FreeFileList( files );
return ret;
}
std::unique_ptr<std::istream> open_file( const std::string& filename )
{
return std::unique_ptr<std::istream>( new DaemonIstream( filename ) );
}
};
/*
====================
Logging functions used by tinygettext
====================
*/
void Trans_Error( const std::string& str )
{
LOG.Notice( "^1%s", str.c_str() );
}
void Trans_Warning( const std::string& str )
{
if( trans_debug->integer != 0 )
{
LOG.Notice( "^3%s", str.c_str() );
}
}
void Trans_Info( const std::string& str )
{
if( trans_debug->integer != 0 )
{
LOG.Notice( str.c_str() );
}
}
/*
====================
Trans_SetLanguage
Sets a loaded language. If desired language is not found, set closest match.
If no languages are close, force English.
====================
*/
void Trans_SetLanguage( const char* lang )
{
Language requestLang = Language::from_env( std::string( lang ) );
// default to english
Language bestLang = Language::from_env( "en" );
int bestScore = Language::match( requestLang, bestLang );
std::set<Language> langs = trans_manager.get_languages();
for( std::set<Language>::iterator i = langs.begin(); i != langs.end(); i++ )
{
int score = Language::match( requestLang, *i );
if( score > bestScore )
{
bestScore = score;
bestLang = *i;
}
}
// language not found, display warning
if( bestScore == 0 )
{
LOG.Warn( "Language \"%s\" (%s) not found. Default to \"English\" (en)",
requestLang.get_name().empty() ? "Unknown Language" : requestLang.get_name().c_str(),
lang );
}
trans_manager.set_language( bestLang );
trans_managergame.set_language( bestLang );
Cvar_Set( "language", bestLang.str().c_str() );
LOG.Notice( "Set language to %s" , bestLang.get_name().c_str() );
}
void Trans_UpdateLanguage_f()
{
Trans_SetLanguage( language->string );
}
/*
============
Trans_Init
============
*/
void Trans_Init()
{
char langList[ MAX_TOKEN_CHARS ] = "";
char encList[ MAX_TOKEN_CHARS ] = "";
std::set<Language> langs;
Language lang;
Cmd_AddCommand( "updatelanguage", Trans_UpdateLanguage_f );
language = Cvar_Get( "language", "", CVAR_ARCHIVE );
trans_debug = Cvar_Get( "trans_debug", "0", 0 );
trans_languages = Cvar_Get( "trans_languages", "", CVAR_ROM );
trans_encodings = Cvar_Get( "trans_encodings", "", CVAR_ROM );
// set tinygettext log callbacks
tinygettext::Log::set_log_error_callback( &Trans_Error );
tinygettext::Log::set_log_warning_callback( &Trans_Warning );
tinygettext::Log::set_log_info_callback( &Trans_Info );
trans_manager.set_filesystem( std::unique_ptr<FileSystem>( new DaemonFileSystem ) );
trans_managergame.set_filesystem( std::unique_ptr<FileSystem>( new DaemonFileSystem ) );
trans_manager.add_directory( "translation/client" );
trans_managergame.add_directory( "translation/game" );
langs = trans_manager.get_languages();
for( std::set<Language>::iterator p = langs.begin(); p != langs.end(); p++ )
{
Q_strcat( langList, sizeof( langList ), va( "\"%s\" ", p->get_name().c_str() ) );
Q_strcat( encList, sizeof( encList ), va( "\"%s\" ", p->str().c_str() ) );
}
Cvar_Set( "trans_languages", langList );
Cvar_Set( "trans_encodings", encList );
LOG.Notice( "Loaded %u language%s", langs.size(), ( langs.size() == 1 ? "" : "s" ) );
}
void Trans_LoadDefaultLanguage()
{
FL_Locale *locale;
// Only detect locale if no previous language set.
if( !language->string[0] )
{
FL_FindLocale( &locale, FL_MESSAGES );
// Invalid or not found. Just use builtin language.
if( !locale->lang || !locale->lang[0] )
{
Cvar_Set( "language", "en" );
}
else
{
Cvar_Set( "language", va( "%s%s%s", locale->lang,
locale->country[0] ? "_" : "",
locale->country ) );
}
FL_FreeLocale( &locale );
}
Trans_SetLanguage( language->string );
}
const char* Trans_Gettext_Internal( const char *msgid, DictionaryManager& manager )
{
if ( !msgid )
{
return msgid;
}
num = ( num + 1 ) & 3;
gettextbuffer[ num ] = manager.get_dictionary().translate( msgid );
return gettextbuffer[ num ].c_str();
}
const char* Trans_Pgettext_Internal( const char *ctxt, const char *msgid, DictionaryManager& manager )
{
if ( !ctxt || !msgid )
{
return msgid;
}
num = ( num + 1 ) & 3;
gettextbuffer[ num ] = manager.get_dictionary().translate_ctxt( ctxt, msgid );
return gettextbuffer[ num ].c_str();
}
const char* Trans_GettextPlural_Internal( const char *msgid, const char *msgid_plural, int number, DictionaryManager& manager )
{
if ( !msgid || !msgid_plural )
{
if ( msgid )
{
return msgid;
}
if ( msgid_plural )
{
return msgid_plural;
}
return nullptr;
}
num = ( num + 1 ) & 3;
gettextbuffer[ num ] = manager.get_dictionary().translate_plural( msgid, msgid_plural, number );
return gettextbuffer[ num ].c_str();
}
const char* Trans_Gettext( const char *msgid )
{
return Trans_Gettext_Internal( msgid, trans_manager );
}
const char* Trans_Pgettext( const char *ctxt, const char *msgid )
{
return Trans_Pgettext_Internal( ctxt, msgid, trans_manager );
}
const char* Trans_GettextPlural( const char *msgid, const char *msgid_plural, int num )
{
return Trans_GettextPlural_Internal( msgid, msgid_plural, num, trans_manager );
}
const char* Trans_GettextGame( const char *msgid )
{
return Trans_Gettext_Internal( msgid, trans_managergame );
}
const char* Trans_PgettextGame( const char *ctxt, const char *msgid )
{
return Trans_Pgettext_Internal( ctxt, msgid, trans_managergame );
}
const char* Trans_GettextGamePlural( const char *msgid, const char *msgid_plural, int num )
{
return Trans_GettextPlural_Internal( msgid, msgid_plural, num, trans_managergame );
}
<|endoftext|>
|
<commit_before>/*
* StatZone 1.1.1
* Copyright (c) 2012-2022, Frederic Cambus
* https://www.statdns.com
*
* Created: 2012-02-13
* Last Updated: 2021-11-16
*
* StatZone is released under the BSD 2-Clause license.
* See LICENSE file for details.
*
* SPDX-License-Identifier: BSD-2-Clause
*/
#include <err.h>
#include <getopt.h>
#include <string.h>
#include <chrono>
#include <csignal>
#include <iostream>
#include <string>
#include <unordered_set>
#ifdef HAVE_SECCOMP
#include <sys/prctl.h>
#include <linux/seccomp.h>
#include "seccomp.h"
#endif
#include "config.hpp"
#include "strtolower.hpp"
std::chrono::steady_clock::time_point begin, current, elapsed;
struct results results;
static void
usage()
{
printf("statzone [-hv] zonefile\n\n" \
"The options are as follows:\n\n" \
" -h Display usage.\n" \
" -v Display version.\n");
}
static void
summary()
{
/* Get current timer value */
current = std::chrono::steady_clock::now();
/* Print summary */
std::cerr << "Processed " << results.processedLines << " lines in ";
std::cerr << std::chrono::duration_cast<std::chrono::microseconds>(current - begin).count() / 1E6;
std::cerr << " seconds." << std::endl;
}
#ifdef SIGINFO
void
siginfo_handler(int signum)
{
summary();
}
#endif
int
main(int argc, char *argv[])
{
std::unordered_set<std::string> signed_domains;
std::unordered_set<std::string> unique_ns;
int opt, token_count;
char *linebuffer = NULL;
size_t linesize = 0;
char *input;
std::string domain, previous_domain;
char *rdata, *token = nullptr, *token_lc = nullptr;
FILE *zonefile;
#ifdef HAVE_SECCOMP
if (prctl(PR_SET_NO_NEW_PRIVS, 1, 0, 0, 0)) {
perror("Can't initialize seccomp");
return EXIT_FAILURE;
}
if (prctl(PR_SET_SECCOMP, SECCOMP_MODE_FILTER, &statzone)) {
perror("Can't load seccomp filter");
return EXIT_FAILURE;
}
#endif
#ifdef SIGINFO
signal(SIGINFO, siginfo_handler);
#endif
while ((opt = getopt(argc, argv, "hv")) != -1) {
switch (opt) {
case 'h':
usage();
return EXIT_SUCCESS;
case 'v':
printf("%s\n", VERSION);
return EXIT_SUCCESS;
}
}
if (optind < argc) {
input = argv[optind];
} else {
usage();
return EXIT_SUCCESS;
}
/* Starting timer */
begin = std::chrono::steady_clock::now();
/* Open zone file */
if (!strcmp(input, "-")) {
/* Read from standard input */
zonefile = stdin;
} else {
/* Attempt to read from file */
if (!(zonefile = fopen(input, "r"))) {
perror("Can't open zone file");
return EXIT_FAILURE;
}
}
while (getline(&linebuffer, &linesize, zonefile) != -1) {
if (!*linebuffer)
continue;
if (*linebuffer == ';') /* Comments */
continue;
if (*linebuffer == '$') /* Directives */
continue;
token_count = 0;
token = strtok(linebuffer, " \t");
if (token)
domain = strtolower(token);
while (token) {
if (*token == ';') { /* Comments */
token = nullptr;
continue;
}
token_lc = strtolower(token);
if (token_count && !strcmp(token_lc, "nsec")) {
token = nullptr;
continue;
}
if (token_count && !strcmp(token_lc, "nsec3")) {
token = nullptr;
continue;
}
if (token_count && !strcmp(token_lc, "rrsig")) {
token = nullptr;
continue;
}
if (token_count && !strcmp(token_lc, "a"))
results.a++;
if (token_count && !strcmp(token_lc, "aaaa"))
results.aaaa++;
if (token_count && !strcmp(token_lc, "ds")) {
results.ds++;
signed_domains.insert(domain);
}
if (!strcmp(token_lc, "ns")) {
results.ns++;
if (domain.compare(previous_domain)) {
results.domains++;
previous_domain = domain;
if (!domain.compare(0, 4, "xn--"))
results.idn++;
}
rdata = strtok(nullptr, "\n");
if (rdata && strchr(rdata, ' '))
rdata = strtok(nullptr, "\n");
if (rdata)
unique_ns.insert(rdata);
}
token = strtok(nullptr, " \t");
token_count++;
}
results.processedLines++;
}
/* Don't count origin */
if (results.domains)
results.domains--;
/* Printing CVS values */
std::cout << "---[ CSV values ]--------------------------------------------------------------" << std::endl;
std::cout << "IPv4 Glue,IPv6 Glue,NS,Unique NS,DS,Signed,IDNs,Domains" << std::endl;
std::cout << results.a << ",";
std::cout << results.aaaa << ",";
std::cout << results.ns << ",";
std::cout << unique_ns.size() << ",";
std::cout << results.ds << ",";
std::cout << signed_domains.size() << ",";
std::cout << results.idn << ",";
std::cout << results.domains << std::endl;
/* Printing results */
summary();
/* Clean up */
free(linebuffer);
fclose(zonefile);
return EXIT_SUCCESS;
}
<commit_msg>Remove unneeded <err.h> include.<commit_after>/*
* StatZone 1.1.1
* Copyright (c) 2012-2022, Frederic Cambus
* https://www.statdns.com
*
* Created: 2012-02-13
* Last Updated: 2022-02-10
*
* StatZone is released under the BSD 2-Clause license.
* See LICENSE file for details.
*
* SPDX-License-Identifier: BSD-2-Clause
*/
#include <getopt.h>
#include <string.h>
#include <chrono>
#include <csignal>
#include <iostream>
#include <string>
#include <unordered_set>
#ifdef HAVE_SECCOMP
#include <sys/prctl.h>
#include <linux/seccomp.h>
#include "seccomp.h"
#endif
#include "config.hpp"
#include "strtolower.hpp"
std::chrono::steady_clock::time_point begin, current, elapsed;
struct results results;
static void
usage()
{
printf("statzone [-hv] zonefile\n\n" \
"The options are as follows:\n\n" \
" -h Display usage.\n" \
" -v Display version.\n");
}
static void
summary()
{
/* Get current timer value */
current = std::chrono::steady_clock::now();
/* Print summary */
std::cerr << "Processed " << results.processedLines << " lines in ";
std::cerr << std::chrono::duration_cast<std::chrono::microseconds>(current - begin).count() / 1E6;
std::cerr << " seconds." << std::endl;
}
#ifdef SIGINFO
void
siginfo_handler(int signum)
{
summary();
}
#endif
int
main(int argc, char *argv[])
{
std::unordered_set<std::string> signed_domains;
std::unordered_set<std::string> unique_ns;
int opt, token_count;
char *linebuffer = NULL;
size_t linesize = 0;
char *input;
std::string domain, previous_domain;
char *rdata, *token = nullptr, *token_lc = nullptr;
FILE *zonefile;
#ifdef HAVE_SECCOMP
if (prctl(PR_SET_NO_NEW_PRIVS, 1, 0, 0, 0)) {
perror("Can't initialize seccomp");
return EXIT_FAILURE;
}
if (prctl(PR_SET_SECCOMP, SECCOMP_MODE_FILTER, &statzone)) {
perror("Can't load seccomp filter");
return EXIT_FAILURE;
}
#endif
#ifdef SIGINFO
signal(SIGINFO, siginfo_handler);
#endif
while ((opt = getopt(argc, argv, "hv")) != -1) {
switch (opt) {
case 'h':
usage();
return EXIT_SUCCESS;
case 'v':
printf("%s\n", VERSION);
return EXIT_SUCCESS;
}
}
if (optind < argc) {
input = argv[optind];
} else {
usage();
return EXIT_SUCCESS;
}
/* Starting timer */
begin = std::chrono::steady_clock::now();
/* Open zone file */
if (!strcmp(input, "-")) {
/* Read from standard input */
zonefile = stdin;
} else {
/* Attempt to read from file */
if (!(zonefile = fopen(input, "r"))) {
perror("Can't open zone file");
return EXIT_FAILURE;
}
}
while (getline(&linebuffer, &linesize, zonefile) != -1) {
if (!*linebuffer)
continue;
if (*linebuffer == ';') /* Comments */
continue;
if (*linebuffer == '$') /* Directives */
continue;
token_count = 0;
token = strtok(linebuffer, " \t");
if (token)
domain = strtolower(token);
while (token) {
if (*token == ';') { /* Comments */
token = nullptr;
continue;
}
token_lc = strtolower(token);
if (token_count && !strcmp(token_lc, "nsec")) {
token = nullptr;
continue;
}
if (token_count && !strcmp(token_lc, "nsec3")) {
token = nullptr;
continue;
}
if (token_count && !strcmp(token_lc, "rrsig")) {
token = nullptr;
continue;
}
if (token_count && !strcmp(token_lc, "a"))
results.a++;
if (token_count && !strcmp(token_lc, "aaaa"))
results.aaaa++;
if (token_count && !strcmp(token_lc, "ds")) {
results.ds++;
signed_domains.insert(domain);
}
if (!strcmp(token_lc, "ns")) {
results.ns++;
if (domain.compare(previous_domain)) {
results.domains++;
previous_domain = domain;
if (!domain.compare(0, 4, "xn--"))
results.idn++;
}
rdata = strtok(nullptr, "\n");
if (rdata && strchr(rdata, ' '))
rdata = strtok(nullptr, "\n");
if (rdata)
unique_ns.insert(rdata);
}
token = strtok(nullptr, " \t");
token_count++;
}
results.processedLines++;
}
/* Don't count origin */
if (results.domains)
results.domains--;
/* Printing CVS values */
std::cout << "---[ CSV values ]--------------------------------------------------------------" << std::endl;
std::cout << "IPv4 Glue,IPv6 Glue,NS,Unique NS,DS,Signed,IDNs,Domains" << std::endl;
std::cout << results.a << ",";
std::cout << results.aaaa << ",";
std::cout << results.ns << ",";
std::cout << unique_ns.size() << ",";
std::cout << results.ds << ",";
std::cout << signed_domains.size() << ",";
std::cout << results.idn << ",";
std::cout << results.domains << std::endl;
/* Printing results */
summary();
/* Clean up */
free(linebuffer);
fclose(zonefile);
return EXIT_SUCCESS;
}
<|endoftext|>
|
<commit_before>#include "replication/delete_queue.hpp"
#include "btree/node.hpp"
#include "buffer_cache/buf_lock.hpp"
#include "buffer_cache/co_functions.hpp"
#include "containers/scoped_malloc.hpp"
#include "logger.hpp"
#include "store.hpp"
namespace replication {
namespace delete_queue {
// The offset of the primal offset.
const int PRIMAL_OFFSET_OFFSET = sizeof(block_magic_t);
const int TIMESTAMPS_AND_OFFSETS_OFFSET = PRIMAL_OFFSET_OFFSET + sizeof(off64_t);
const int TIMESTAMPS_AND_OFFSETS_SIZE = sizeof(large_buf_ref) + 3 * sizeof(block_id_t);
const int64_t MAX_DELETE_QUEUE_KEYS_SIZE = 234 * MEGABYTE;
off64_t *primal_offset(void *root_buffer) {
return reinterpret_cast<off64_t *>(reinterpret_cast<char *>(root_buffer) + PRIMAL_OFFSET_OFFSET);
}
large_buf_ref *timestamps_and_offsets_largebuf(void *root_buffer) {
char *p = reinterpret_cast<char *>(root_buffer);
return reinterpret_cast<large_buf_ref *>(p + TIMESTAMPS_AND_OFFSETS_OFFSET);
}
large_buf_ref *keys_largebuf(void *root_buffer) {
char *p = reinterpret_cast<char *>(root_buffer);
return reinterpret_cast<large_buf_ref *>(p + (TIMESTAMPS_AND_OFFSETS_OFFSET + TIMESTAMPS_AND_OFFSETS_SIZE));
}
int keys_largebuf_ref_size(block_size_t block_size) {
return block_size.value() - (TIMESTAMPS_AND_OFFSETS_OFFSET + TIMESTAMPS_AND_OFFSETS_SIZE);
}
} // namespace delete_queue
void add_key_to_delete_queue(boost::shared_ptr<transactor_t>& txor, block_id_t queue_root_id, repli_timestamp timestamp, const store_key_t *key) {
thread_saver_t saver;
// Beware: Right now, some aspects of correctness depend on the
// fact that we hold the queue_root lock for the entire operation.
buf_lock_t queue_root(saver, *txor, queue_root_id, rwi_write);
// TODO this could be a non-major write?
void *queue_root_buf = queue_root->get_data_major_write();
off64_t *primal_offset = delete_queue::primal_offset(queue_root_buf);
large_buf_ref *t_o_ref = delete_queue::timestamps_and_offsets_largebuf(queue_root_buf);
large_buf_ref *keys_ref = delete_queue::keys_largebuf(queue_root_buf);
rassert(t_o_ref->size % sizeof(delete_queue::t_and_o) == 0);
// Figure out what we need to do.
bool will_want_to_dequeue = (keys_ref->size + 1 + int64_t(key->size) > delete_queue::MAX_DELETE_QUEUE_KEYS_SIZE);
bool will_actually_dequeue = false;
delete_queue::t_and_o second_tao = { repli_timestamp::invalid, -1 };
// Possibly update the (timestamp, offset) queue. (This happens at most once per second.)
{
if (t_o_ref->size == 0) {
// HEY: Why must we allocate large_buf_t's with new?
boost::scoped_ptr<large_buf_t> t_o_largebuf(new large_buf_t(txor, t_o_ref, lbref_limit_t(delete_queue::TIMESTAMPS_AND_OFFSETS_SIZE), rwi_write));
// The size is only zero in the unallocated state. (Large
// bufs can't actually handle size zero, so we can't let
// the large buf shrink to that size.)
delete_queue::t_and_o tao;
tao.timestamp = timestamp;
tao.offset = *primal_offset + keys_ref->size;
t_o_largebuf->allocate(sizeof(tao));
t_o_largebuf->fill_at(0, &tao, sizeof(tao));
rassert(keys_ref->size == 0);
rassert(!will_want_to_dequeue);
} else {
delete_queue::t_and_o last_tao;
{
boost::scoped_ptr<large_buf_t> t_o_largebuf(new large_buf_t(txor, t_o_ref, lbref_limit_t(delete_queue::TIMESTAMPS_AND_OFFSETS_SIZE), rwi_write));
co_acquire_large_buf_slice(saver, t_o_largebuf.get(), t_o_ref->size - sizeof(last_tao), sizeof(last_tao));
t_o_largebuf->read_at(t_o_ref->size - sizeof(last_tao), &last_tao, sizeof(last_tao));
if (last_tao.timestamp.time > timestamp.time) {
logWRN("The delete queue is receiving updates out of order (t1 = %d, t2 = %d), or the system clock has been set back! Bringing up a replica may be excessively inefficient.\n", last_tao.timestamp.time, timestamp.time);
// Timestamps must be monotonically increasing, so sorry.
timestamp = last_tao.timestamp;
}
if (last_tao.timestamp.time != timestamp.time) {
delete_queue::t_and_o tao;
tao.timestamp = timestamp;
tao.offset = *primal_offset + keys_ref->size;
int refsize_adjustment_dontcare;
// It's okay to append because we acquired the rhs
// of the large buf.
t_o_largebuf->append(sizeof(tao), &refsize_adjustment_dontcare);
t_o_largebuf->fill_at(t_o_ref->size - sizeof(tao), &tao, sizeof(tao));
}
}
if (will_want_to_dequeue && t_o_ref->size >= int64_t(2 * sizeof(second_tao))) {
boost::scoped_ptr<large_buf_t> t_o_largebuf(new large_buf_t(txor, t_o_ref, lbref_limit_t(delete_queue::TIMESTAMPS_AND_OFFSETS_SIZE), rwi_write));
co_acquire_large_buf_slice(saver, t_o_largebuf.get(), 0, 2 * sizeof(second_tao));
t_o_largebuf->read_at(sizeof(second_tao), &second_tao, sizeof(second_tao));
will_actually_dequeue = true;
// It's okay to unprepend because we acquired the lhs of the large buf.
int refsize_adjustment_dontcare;
t_o_largebuf->unprepend(sizeof(second_tao), &refsize_adjustment_dontcare);
}
}
}
// Update the keys list.
{
lbref_limit_t reflimit = lbref_limit_t(delete_queue::keys_largebuf_ref_size((*txor)->cache->get_block_size()));
int64_t amount_to_unprepend = will_actually_dequeue ? second_tao.offset - *primal_offset : 0;
large_buf_t::co_enqueue(txor, keys_ref, reflimit, amount_to_unprepend, key, 1 + key->size);
*primal_offset += amount_to_unprepend;
}
}
void dump_keys_from_delete_queue(boost::shared_ptr<transactor_t>& txor, block_id_t queue_root_id, repli_timestamp begin_timestamp, deletion_key_stream_receiver_t *recipient) {
thread_saver_t saver;
// Beware: Right now, some aspects of correctness depend on the
// fact that we hold the queue_root lock for the entire operation.
buf_lock_t queue_root(saver, *txor, queue_root_id, rwi_read);
void *queue_root_buf = const_cast<void *>(queue_root->get_data_read());
off64_t *primal_offset = delete_queue::primal_offset(queue_root_buf);
large_buf_ref *t_o_ref = delete_queue::timestamps_and_offsets_largebuf(queue_root_buf);
large_buf_ref *keys_ref = delete_queue::keys_largebuf(queue_root_buf);
if (t_o_ref->size != 0 && keys_ref->size != 0) {
rassert(t_o_ref->size % sizeof(delete_queue::t_and_o) == 0);
// TODO: DON'T hold the queue_root lock for the entire operation. Sheesh.
int64_t begin_offset = 0;
int64_t end_offset = keys_ref->size;
{
boost::scoped_ptr<large_buf_t> t_o_largebuf(new large_buf_t(txor, t_o_ref, lbref_limit_t(delete_queue::TIMESTAMPS_AND_OFFSETS_SIZE), rwi_read));
co_acquire_large_buf(saver, t_o_largebuf.get());
delete_queue::t_and_o tao;
int64_t i = 0, ie = t_o_ref->size;
bool begin_found = false;
while (i < ie) {
t_o_largebuf->read_at(i, &tao, sizeof(tao));
if (!begin_found && begin_timestamp.time <= tao.timestamp.time) {
begin_offset = tao.offset - *primal_offset;
begin_found = true;
break;
}
i += sizeof(tao);
}
if (!begin_found) {
// TODO: Uh, we need to send some kind of "delete
// everything, we are backfilling from the beginning"
// command.
goto done;
}
// So we have a begin_offset and an end_offset.
}
rassert(begin_offset <= end_offset);
if (begin_offset < end_offset) {
boost::scoped_ptr<large_buf_t> keys_largebuf(new large_buf_t(txor, keys_ref, lbref_limit_t(delete_queue::keys_largebuf_ref_size((*txor)->cache->get_block_size())), rwi_read_outdated_ok));
// TODO: acquire subinterval.
co_acquire_large_buf_slice(saver, keys_largebuf.get(), begin_offset, end_offset - begin_offset);
int64_t n = end_offset - begin_offset;
// TODO: don't copy needlessly... sheesh. This is a fake
// implementation, make something that actually streams later.
scoped_malloc<char> buf(n);
keys_largebuf->read_at(begin_offset, buf.get(), n);
char *p = buf.get();
char *e = p + n;
while (p < e) {
btree_key_t *k = reinterpret_cast<btree_key_t *>(p);
rassert(k->size + 1 <= e - p);
recipient->deletion_key(k);
p += k->size + 1;
}
}
}
done:
recipient->done_deletion_keys();
}
// TODO: maybe this function should be somewhere else. Well,
// certainly. Right now we don't have a notion of an "empty"
// largebuf, so we'll know that we have to ->allocate the largebuf
// when we see a size of 0 in the large_buf_ref.
void initialize_large_buf_ref(large_buf_ref *ref, int size_in_bytes) {
int ids_bytes = size_in_bytes - offsetof(large_buf_ref, block_ids);
rassert(ids_bytes > 0);
ref->offset = 0;
ref->size = 0;
for (int i = 0, e = ids_bytes / sizeof(block_id_t); i < e; ++i) {
ref->block_ids[i] = NULL_BLOCK_ID;
}
}
void initialize_empty_delete_queue(delete_queue_block_t *dqb, block_size_t block_size) {
dqb->magic = delete_queue_block_t::expected_magic;
*delete_queue::primal_offset(dqb) = 0;
large_buf_ref *t_and_o = delete_queue::timestamps_and_offsets_largebuf(dqb);
initialize_large_buf_ref(t_and_o, delete_queue::TIMESTAMPS_AND_OFFSETS_SIZE);
large_buf_ref *k = delete_queue::keys_largebuf(dqb);
initialize_large_buf_ref(k, delete_queue::keys_largebuf_ref_size(block_size));
}
const block_magic_t delete_queue_block_t::expected_magic = { { 'D', 'e', 'l', 'Q' } };
} // namespace replication
<commit_msg>Made MAX_DELETE_QUEUE_KEYS_SIZE be 16 * MEGABYTE.<commit_after>#include "replication/delete_queue.hpp"
#include "btree/node.hpp"
#include "buffer_cache/buf_lock.hpp"
#include "buffer_cache/co_functions.hpp"
#include "containers/scoped_malloc.hpp"
#include "logger.hpp"
#include "store.hpp"
namespace replication {
namespace delete_queue {
// The offset of the primal offset.
const int PRIMAL_OFFSET_OFFSET = sizeof(block_magic_t);
const int TIMESTAMPS_AND_OFFSETS_OFFSET = PRIMAL_OFFSET_OFFSET + sizeof(off64_t);
const int TIMESTAMPS_AND_OFFSETS_SIZE = sizeof(large_buf_ref) + 3 * sizeof(block_id_t);
const int64_t MAX_DELETE_QUEUE_KEYS_SIZE = 16 * MEGABYTE;
off64_t *primal_offset(void *root_buffer) {
return reinterpret_cast<off64_t *>(reinterpret_cast<char *>(root_buffer) + PRIMAL_OFFSET_OFFSET);
}
large_buf_ref *timestamps_and_offsets_largebuf(void *root_buffer) {
char *p = reinterpret_cast<char *>(root_buffer);
return reinterpret_cast<large_buf_ref *>(p + TIMESTAMPS_AND_OFFSETS_OFFSET);
}
large_buf_ref *keys_largebuf(void *root_buffer) {
char *p = reinterpret_cast<char *>(root_buffer);
return reinterpret_cast<large_buf_ref *>(p + (TIMESTAMPS_AND_OFFSETS_OFFSET + TIMESTAMPS_AND_OFFSETS_SIZE));
}
int keys_largebuf_ref_size(block_size_t block_size) {
return block_size.value() - (TIMESTAMPS_AND_OFFSETS_OFFSET + TIMESTAMPS_AND_OFFSETS_SIZE);
}
} // namespace delete_queue
void add_key_to_delete_queue(boost::shared_ptr<transactor_t>& txor, block_id_t queue_root_id, repli_timestamp timestamp, const store_key_t *key) {
thread_saver_t saver;
// Beware: Right now, some aspects of correctness depend on the
// fact that we hold the queue_root lock for the entire operation.
buf_lock_t queue_root(saver, *txor, queue_root_id, rwi_write);
// TODO this could be a non-major write?
void *queue_root_buf = queue_root->get_data_major_write();
off64_t *primal_offset = delete_queue::primal_offset(queue_root_buf);
large_buf_ref *t_o_ref = delete_queue::timestamps_and_offsets_largebuf(queue_root_buf);
large_buf_ref *keys_ref = delete_queue::keys_largebuf(queue_root_buf);
rassert(t_o_ref->size % sizeof(delete_queue::t_and_o) == 0);
// Figure out what we need to do.
bool will_want_to_dequeue = (keys_ref->size + 1 + int64_t(key->size) > delete_queue::MAX_DELETE_QUEUE_KEYS_SIZE);
bool will_actually_dequeue = false;
delete_queue::t_and_o second_tao = { repli_timestamp::invalid, -1 };
// Possibly update the (timestamp, offset) queue. (This happens at most once per second.)
{
if (t_o_ref->size == 0) {
// HEY: Why must we allocate large_buf_t's with new?
boost::scoped_ptr<large_buf_t> t_o_largebuf(new large_buf_t(txor, t_o_ref, lbref_limit_t(delete_queue::TIMESTAMPS_AND_OFFSETS_SIZE), rwi_write));
// The size is only zero in the unallocated state. (Large
// bufs can't actually handle size zero, so we can't let
// the large buf shrink to that size.)
delete_queue::t_and_o tao;
tao.timestamp = timestamp;
tao.offset = *primal_offset + keys_ref->size;
t_o_largebuf->allocate(sizeof(tao));
t_o_largebuf->fill_at(0, &tao, sizeof(tao));
rassert(keys_ref->size == 0);
rassert(!will_want_to_dequeue);
} else {
delete_queue::t_and_o last_tao;
{
boost::scoped_ptr<large_buf_t> t_o_largebuf(new large_buf_t(txor, t_o_ref, lbref_limit_t(delete_queue::TIMESTAMPS_AND_OFFSETS_SIZE), rwi_write));
co_acquire_large_buf_slice(saver, t_o_largebuf.get(), t_o_ref->size - sizeof(last_tao), sizeof(last_tao));
t_o_largebuf->read_at(t_o_ref->size - sizeof(last_tao), &last_tao, sizeof(last_tao));
if (last_tao.timestamp.time > timestamp.time) {
logWRN("The delete queue is receiving updates out of order (t1 = %d, t2 = %d), or the system clock has been set back! Bringing up a replica may be excessively inefficient.\n", last_tao.timestamp.time, timestamp.time);
// Timestamps must be monotonically increasing, so sorry.
timestamp = last_tao.timestamp;
}
if (last_tao.timestamp.time != timestamp.time) {
delete_queue::t_and_o tao;
tao.timestamp = timestamp;
tao.offset = *primal_offset + keys_ref->size;
int refsize_adjustment_dontcare;
// It's okay to append because we acquired the rhs
// of the large buf.
t_o_largebuf->append(sizeof(tao), &refsize_adjustment_dontcare);
t_o_largebuf->fill_at(t_o_ref->size - sizeof(tao), &tao, sizeof(tao));
}
}
if (will_want_to_dequeue && t_o_ref->size >= int64_t(2 * sizeof(second_tao))) {
boost::scoped_ptr<large_buf_t> t_o_largebuf(new large_buf_t(txor, t_o_ref, lbref_limit_t(delete_queue::TIMESTAMPS_AND_OFFSETS_SIZE), rwi_write));
co_acquire_large_buf_slice(saver, t_o_largebuf.get(), 0, 2 * sizeof(second_tao));
t_o_largebuf->read_at(sizeof(second_tao), &second_tao, sizeof(second_tao));
will_actually_dequeue = true;
// It's okay to unprepend because we acquired the lhs of the large buf.
int refsize_adjustment_dontcare;
t_o_largebuf->unprepend(sizeof(second_tao), &refsize_adjustment_dontcare);
}
}
}
// Update the keys list.
{
lbref_limit_t reflimit = lbref_limit_t(delete_queue::keys_largebuf_ref_size((*txor)->cache->get_block_size()));
int64_t amount_to_unprepend = will_actually_dequeue ? second_tao.offset - *primal_offset : 0;
large_buf_t::co_enqueue(txor, keys_ref, reflimit, amount_to_unprepend, key, 1 + key->size);
*primal_offset += amount_to_unprepend;
}
}
void dump_keys_from_delete_queue(boost::shared_ptr<transactor_t>& txor, block_id_t queue_root_id, repli_timestamp begin_timestamp, deletion_key_stream_receiver_t *recipient) {
thread_saver_t saver;
// Beware: Right now, some aspects of correctness depend on the
// fact that we hold the queue_root lock for the entire operation.
buf_lock_t queue_root(saver, *txor, queue_root_id, rwi_read);
void *queue_root_buf = const_cast<void *>(queue_root->get_data_read());
off64_t *primal_offset = delete_queue::primal_offset(queue_root_buf);
large_buf_ref *t_o_ref = delete_queue::timestamps_and_offsets_largebuf(queue_root_buf);
large_buf_ref *keys_ref = delete_queue::keys_largebuf(queue_root_buf);
if (t_o_ref->size != 0 && keys_ref->size != 0) {
rassert(t_o_ref->size % sizeof(delete_queue::t_and_o) == 0);
// TODO: DON'T hold the queue_root lock for the entire operation. Sheesh.
int64_t begin_offset = 0;
int64_t end_offset = keys_ref->size;
{
boost::scoped_ptr<large_buf_t> t_o_largebuf(new large_buf_t(txor, t_o_ref, lbref_limit_t(delete_queue::TIMESTAMPS_AND_OFFSETS_SIZE), rwi_read));
co_acquire_large_buf(saver, t_o_largebuf.get());
delete_queue::t_and_o tao;
int64_t i = 0, ie = t_o_ref->size;
bool begin_found = false;
while (i < ie) {
t_o_largebuf->read_at(i, &tao, sizeof(tao));
if (!begin_found && begin_timestamp.time <= tao.timestamp.time) {
begin_offset = tao.offset - *primal_offset;
begin_found = true;
break;
}
i += sizeof(tao);
}
if (!begin_found) {
// TODO: Uh, we need to send some kind of "delete
// everything, we are backfilling from the beginning"
// command.
goto done;
}
// So we have a begin_offset and an end_offset.
}
rassert(begin_offset <= end_offset);
if (begin_offset < end_offset) {
boost::scoped_ptr<large_buf_t> keys_largebuf(new large_buf_t(txor, keys_ref, lbref_limit_t(delete_queue::keys_largebuf_ref_size((*txor)->cache->get_block_size())), rwi_read_outdated_ok));
// TODO: acquire subinterval.
co_acquire_large_buf_slice(saver, keys_largebuf.get(), begin_offset, end_offset - begin_offset);
int64_t n = end_offset - begin_offset;
// TODO: don't copy needlessly... sheesh. This is a fake
// implementation, make something that actually streams later.
scoped_malloc<char> buf(n);
keys_largebuf->read_at(begin_offset, buf.get(), n);
char *p = buf.get();
char *e = p + n;
while (p < e) {
btree_key_t *k = reinterpret_cast<btree_key_t *>(p);
rassert(k->size + 1 <= e - p);
recipient->deletion_key(k);
p += k->size + 1;
}
}
}
done:
recipient->done_deletion_keys();
}
// TODO: maybe this function should be somewhere else. Well,
// certainly. Right now we don't have a notion of an "empty"
// largebuf, so we'll know that we have to ->allocate the largebuf
// when we see a size of 0 in the large_buf_ref.
void initialize_large_buf_ref(large_buf_ref *ref, int size_in_bytes) {
int ids_bytes = size_in_bytes - offsetof(large_buf_ref, block_ids);
rassert(ids_bytes > 0);
ref->offset = 0;
ref->size = 0;
for (int i = 0, e = ids_bytes / sizeof(block_id_t); i < e; ++i) {
ref->block_ids[i] = NULL_BLOCK_ID;
}
}
void initialize_empty_delete_queue(delete_queue_block_t *dqb, block_size_t block_size) {
dqb->magic = delete_queue_block_t::expected_magic;
*delete_queue::primal_offset(dqb) = 0;
large_buf_ref *t_and_o = delete_queue::timestamps_and_offsets_largebuf(dqb);
initialize_large_buf_ref(t_and_o, delete_queue::TIMESTAMPS_AND_OFFSETS_SIZE);
large_buf_ref *k = delete_queue::keys_largebuf(dqb);
initialize_large_buf_ref(k, delete_queue::keys_largebuf_ref_size(block_size));
}
const block_magic_t delete_queue_block_t::expected_magic = { { 'D', 'e', 'l', 'Q' } };
} // namespace replication
<|endoftext|>
|
<commit_before>#include <sys/types.h>
#include <sys/socket.h>
#include <sys/un.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <stdio.h>
#include <errno.h>
#include <string.h>
#include <fcntl.h>
bool socketError = false;
bool socketBlocking = false;
int DDV_OpenUnix(const char adres[], bool nonblock = false){
int s = socket(AF_UNIX, SOCK_STREAM, 0);
int on = 1;
setsockopt(s, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on));
sockaddr_un addr;
addr.sun_family = AF_UNIX;
strcpy(addr.sun_path, adres);
int r = connect(s, (sockaddr*)&addr, sizeof(addr));
if (r == 0){
if (nonblock){
int flags = fcntl(s, F_GETFL, 0);
flags |= O_NONBLOCK;
fcntl(s, F_SETFL, flags);
}
return s;
}else{
close(s);
return 0;
}
}
int DDV_Listen(int port){
int s = socket(AF_INET, SOCK_STREAM, 0);
struct sockaddr_in addr;
addr.sin_family = AF_INET;
addr.sin_port = htons(port);//port 8888
inet_pton(AF_INET, "0.0.0.0", &addr.sin_addr);//listen on all interfaces
int ret = bind(s, (sockaddr*)&addr, sizeof(addr));//bind to all interfaces, chosen port
if (ret == 0){
ret = listen(s, 100);//start listening, backlog of 100 allowed
if (ret == 0){
return s;
}else{
printf("Listen failed! Error: %s\n", strerror(errno));
close(s);
return 0;
}
}else{
printf("Binding failed! Error: %s\n", strerror(errno));
close(s);
return 0;
}
}
int DDV_Accept(int sock, bool nonblock = false){
int r = accept(sock, 0, 0);
if ((r > 0) && nonblock){
int flags = fcntl(r, F_GETFL, 0);
flags |= O_NONBLOCK;
fcntl(r, F_SETFL, flags);
}
return r;
}
bool DDV_write(void * buffer, int todo, int sock){
int sofar = 0;
socketBlocking = false;
while (sofar != todo){
int r = send(sock, (char*)buffer + sofar, todo-sofar, 0);
if (r <= 0){
switch (errno){
case EWOULDBLOCK: printf("Would block\n"); socketBlocking = true; break;
default:
socketError = true;
printf("Could not write! %s\n", strerror(errno));
return false;
break;
}
}
sofar += r;
}
return true;
}
bool DDV_read(void * buffer, int todo, int sock){
int sofar = 0;
socketBlocking = false;
while (sofar != todo){
int r = recv(sock, (char*)buffer + sofar, todo-sofar, 0);
if (r <= 0){
switch (errno){
case EWOULDBLOCK: printf("Read: Would block\n"); socketBlocking = true; break;
default:
socketError = true;
printf("Could not read! %s\n", strerror(errno));
return false;
break;
}
}
sofar += r;
}
return true;
}
bool DDV_read(void * buffer, int width, int count, int sock){return DDV_read(buffer, width*count, sock);}
bool DDV_write(void * buffer, int width, int count, int sock){return DDV_write(buffer, width*count, sock);}
int DDV_iwrite(void * buffer, int todo, int sock){
int r = send(sock, buffer, todo, 0);
if (r < 0){
switch (errno){
case EWOULDBLOCK: printf("Write: Would block\n"); break;
default:
socketError = true;
printf("Could not write! %s\n", strerror(errno));
return false;
break;
}
}
return r;
}
int DDV_iread(void * buffer, int todo, int sock){
int r = recv(sock, buffer, todo, 0);
if (r < 0){
switch (errno){
case EWOULDBLOCK: printf("Read: Would block\n"); break;
default:
socketError = true;
printf("Could not read! %s\n", strerror(errno));
return false;
break;
}
}
return r;
}
<commit_msg>DDVSocket edits<commit_after>#include <sys/types.h>
#include <sys/socket.h>
#include <sys/un.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <stdio.h>
#include <errno.h>
#include <string.h>
#include <fcntl.h>
bool socketError = false;
bool socketBlocking = false;
int DDV_OpenUnix(const char adres[], bool nonblock = false){
int s = socket(AF_UNIX, SOCK_STREAM, 0);
int on = 1;
setsockopt(s, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on));
sockaddr_un addr;
addr.sun_family = AF_UNIX;
strcpy(addr.sun_path, adres);
int r = connect(s, (sockaddr*)&addr, sizeof(addr));
if (r == 0){
if (nonblock){
int flags = fcntl(s, F_GETFL, 0);
flags |= O_NONBLOCK;
fcntl(s, F_SETFL, flags);
}
return s;
}else{
close(s);
return 0;
}
}
int DDV_Listen(int port){
int s = socket(AF_INET, SOCK_STREAM, 0);
struct sockaddr_in addr;
addr.sin_family = AF_INET;
addr.sin_port = htons(port);//port 8888
inet_pton(AF_INET, "0.0.0.0", &addr.sin_addr);//listen on all interfaces
int ret = bind(s, (sockaddr*)&addr, sizeof(addr));//bind to all interfaces, chosen port
if (ret == 0){
ret = listen(s, 100);//start listening, backlog of 100 allowed
if (ret == 0){
return s;
}else{
printf("Listen failed! Error: %s\n", strerror(errno));
close(s);
return 0;
}
}else{
printf("Binding failed! Error: %s\n", strerror(errno));
close(s);
return 0;
}
}
int DDV_Accept(int sock, bool nonblock = false){
int r = accept(sock, 0, 0);
if ((r > 0) && nonblock){
int flags = fcntl(r, F_GETFL, 0);
flags |= O_NONBLOCK;
fcntl(r, F_SETFL, flags);
}
return r;
}
bool DDV_write(void * buffer, int todo, int sock){
int sofar = 0;
socketBlocking = false;
while (sofar != todo){
int r = send(sock, (char*)buffer + sofar, todo-sofar, 0);
if (r <= 0){
switch (errno){
case EWOULDBLOCK: socketBlocking = true; return false; break;
default:
socketError = true;
printf("Could not write! %s\n", strerror(errno));
return false;
break;
}
}
sofar += r;
}
return true;
}
bool DDV_read(void * buffer, int todo, int sock){
int sofar = 0;
socketBlocking = false;
while (sofar != todo){
int r = recv(sock, (char*)buffer + sofar, todo-sofar, 0);
if (r <= 0){
switch (errno){
case EWOULDBLOCK: socketBlocking = true; return false; break;
default:
socketError = true;
printf("Could not read! %s\n", strerror(errno));
return false;
break;
}
}
sofar += r;
}
return true;
}
bool DDV_read(void * buffer, int width, int count, int sock){return DDV_read(buffer, width*count, sock);}
bool DDV_write(void * buffer, int width, int count, int sock){return DDV_write(buffer, width*count, sock);}
int DDV_iwrite(void * buffer, int todo, int sock){
int r = send(sock, buffer, todo, 0);
if (r < 0){
switch (errno){
case EWOULDBLOCK: break;
default:
socketError = true;
printf("Could not write! %s\n", strerror(errno));
return false;
break;
}
}
return r;
}
int DDV_iread(void * buffer, int todo, int sock){
int r = recv(sock, buffer, todo, 0);
if (r < 0){
switch (errno){
case EWOULDBLOCK: break;
default:
socketError = true;
printf("Could not read! %s\n", strerror(errno));
return false;
break;
}
}
return r;
}
<|endoftext|>
|
<commit_before>// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include <glog/logging.h>
#include <iostream>
#include <string>
#include <vector>
#include <mesos/resources.hpp>
#include <mesos/scheduler.hpp>
#include <process/clock.hpp>
#include <process/defer.hpp>
#include <process/dispatch.hpp>
#include <process/http.hpp>
#include <process/process.hpp>
#include <process/protobuf.hpp>
#include <process/time.hpp>
#include <process/metrics/counter.hpp>
#include <process/metrics/gauge.hpp>
#include <process/metrics/metrics.hpp>
#include <stout/bytes.hpp>
#include <stout/flags.hpp>
#include <stout/option.hpp>
#include <stout/os.hpp>
#include <stout/path.hpp>
#include <stout/stringify.hpp>
using namespace mesos;
using namespace mesos::internal;
using std::string;
using process::Clock;
using process::defer;
using process::metrics::Gauge;
using process::metrics::Counter;
const double CPUS_PER_TASK = 0.1;
const double CPUS_PER_EXECUTOR = 0.1;
const int32_t MEM_PER_EXECUTOR = 64;
class Flags : public virtual flags::FlagsBase
{
public:
Flags()
{
add(&Flags::master,
"master",
"Master to connect to.");
add(&Flags::task_memory_usage_limit,
"task_memory_usage_limit",
None(),
"Maximum size, in bytes, of the task's memory usage.\n"
"The task will attempt to occupy memory up until this limit.",
static_cast<const Bytes*>(nullptr),
[](const Bytes& value) -> Option<Error> {
if (value.megabytes() < MEM_PER_EXECUTOR) {
return Error(
"Please use a --task_memory_usage_limit greater than " +
stringify(MEM_PER_EXECUTOR) + " MB");
}
return None();
});
add(&Flags::task_memory,
"task_memory",
"How much memory the framework will require per task.\n"
"If not specified, the task(s) will use all available memory in\n"
"applicable offers.");
add(&Flags::build_dir,
"build_dir",
"The build directory of Mesos. If set, the framework will assume\n"
"that the executor, framework, and agent(s) all live on the same\n"
"machine.");
add(&Flags::executor_uri,
"executor_uri",
"URI the fetcher should use to get the executor.");
add(&Flags::executor_command,
"executor_command",
"The command that should be used to start the executor.\n"
"This will override the value set by `--build_dir`.");
add(&Flags::checkpoint,
"checkpoint",
"Whether this framework should be checkpointed.\n",
false);
add(&Flags::long_running,
"long_running",
"Whether this framework should launch tasks repeatedly\n"
"or exit after finishing a single task.",
false);
}
string master;
Bytes task_memory_usage_limit;
Bytes task_memory;
// Flags for specifying the executor binary.
Option<string> build_dir;
Option<string> executor_uri;
Option<string> executor_command;
bool checkpoint;
bool long_running;
};
// Actor holding the business logic and metrics for the `BalloonScheduler`.
// See `BalloonScheduler` below for the intended behavior.
class BalloonSchedulerProcess : public process::Process<BalloonSchedulerProcess>
{
public:
BalloonSchedulerProcess(
const FrameworkInfo& _frameworkInfo,
const ExecutorInfo& _executor,
const Flags& _flags)
: frameworkInfo(_frameworkInfo),
executor(_executor),
flags(_flags),
taskActive(false),
tasksLaunched(0),
isRegistered(false),
metrics(*this)
{
start_time = Clock::now();
}
void registered()
{
isRegistered = true;
}
void disconnected()
{
isRegistered = false;
}
void resourceOffers(
SchedulerDriver* driver,
const std::vector<Offer>& offers)
{
Resources taskResources = Resources::parse(
"cpus:" + stringify(CPUS_PER_TASK) +
";mem:" + stringify(flags.task_memory.megabytes())).get();
taskResources.allocate(frameworkInfo.role());
Resources executorResources = Resources(executor.resources());
executorResources.allocate(frameworkInfo.role());
foreach (const Offer& offer, offers) {
Resources resources(offer.resources());
// If there is an active task, or if the offer is not
// big enough, reject the offer.
if (taskActive ||
!resources.toUnreserved().contains(
taskResources + executorResources)) {
Filters filters;
filters.set_refuse_seconds(600);
driver->declineOffer(offer.id(), filters);
continue;
}
int taskId = tasksLaunched++;
LOG(INFO) << "Starting task " << taskId;
TaskInfo task;
task.set_name("Balloon Task");
task.mutable_task_id()->set_value(stringify(taskId));
task.mutable_slave_id()->MergeFrom(offer.slave_id());
task.mutable_resources()->CopyFrom(taskResources);
task.set_data(stringify(flags.task_memory_usage_limit));
task.mutable_executor()->CopyFrom(executor);
task.mutable_executor()->mutable_executor_id()
->set_value(stringify(taskId));
driver->launchTasks(offer.id(), {task});
taskActive = true;
}
}
void statusUpdate(SchedulerDriver* driver, const TaskStatus& status)
{
if (!flags.long_running) {
if (status.state() == TASK_FAILED &&
status.reason() == TaskStatus::REASON_CONTAINER_LIMITATION_MEMORY) {
// NOTE: We expect TASK_FAILED when this scheduler is launched by the
// balloon_framework_test.sh shell script. The abort here ensures the
// script considers the test result as "PASS".
driver->abort();
} else if (status.state() == TASK_FAILED ||
status.state() == TASK_FINISHED ||
status.state() == TASK_KILLED ||
status.state() == TASK_LOST ||
status.state() == TASK_ERROR) {
driver->stop();
}
}
if (stringify(tasksLaunched - 1) != status.task_id().value()) {
// We might receive messages from older tasks. Ignore them.
LOG(INFO) << "Ignoring status update from older task "
<< status.task_id();
return;
}
switch (status.state()) {
case TASK_FINISHED:
taskActive = false;
++metrics.tasks_finished;
break;
case TASK_FAILED:
taskActive = false;
if (status.reason() == TaskStatus::REASON_CONTAINER_LIMITATION_MEMORY) {
++metrics.tasks_oomed;
break;
}
// NOTE: Fetching the executor (e.g. `--executor_uri`) may fail
// occasionally if the URI is rate limited. This case is common
// enough that it makes sense to track this failure metric separately.
if (status.reason() == TaskStatus::REASON_CONTAINER_LAUNCH_FAILED) {
++metrics.launch_failures;
break;
}
case TASK_KILLED:
case TASK_LOST:
case TASK_ERROR:
taskActive = false;
++metrics.abnormal_terminations;
break;
default:
break;
}
}
private:
const FrameworkInfo frameworkInfo;
const ExecutorInfo executor;
const Flags flags;
bool taskActive;
int tasksLaunched;
process::Time start_time;
double _uptime_secs()
{
return (Clock::now() - start_time).secs();
}
bool isRegistered;
double _registered()
{
return isRegistered ? 1 : 0;
}
struct Metrics
{
Metrics(const BalloonSchedulerProcess& _scheduler)
: uptime_secs(
"balloon_framework/uptime_secs",
defer(_scheduler, &BalloonSchedulerProcess::_uptime_secs)),
registered(
"balloon_framework/registered",
defer(_scheduler, &BalloonSchedulerProcess::_registered)),
tasks_finished("balloon_framework/tasks_finished"),
tasks_oomed("balloon_framework/tasks_oomed"),
launch_failures("balloon_framework/launch_failures"),
abnormal_terminations("balloon_framework/abnormal_terminations")
{
process::metrics::add(uptime_secs);
process::metrics::add(registered);
process::metrics::add(tasks_finished);
process::metrics::add(tasks_oomed);
process::metrics::add(launch_failures);
process::metrics::add(abnormal_terminations);
}
~Metrics()
{
process::metrics::remove(uptime_secs);
process::metrics::remove(registered);
process::metrics::remove(tasks_finished);
process::metrics::remove(tasks_oomed);
process::metrics::remove(launch_failures);
process::metrics::remove(abnormal_terminations);
}
process::metrics::Gauge uptime_secs;
process::metrics::Gauge registered;
process::metrics::Counter tasks_finished;
process::metrics::Counter tasks_oomed;
process::metrics::Counter launch_failures;
process::metrics::Counter abnormal_terminations;
} metrics;
};
// This scheduler starts a single executor and task which gradually
// increases its memory footprint up to a limit. Depending on the
// resource limits set for the container, the framework expects the
// executor to either finish successfully or be OOM-killed.
class BalloonScheduler : public Scheduler
{
public:
BalloonScheduler(
const FrameworkInfo& _frameworkInfo,
const ExecutorInfo& _executor,
const Flags& _flags)
: process(_frameworkInfo, _executor, _flags)
{
process::spawn(process);
}
virtual ~BalloonScheduler()
{
process::terminate(process);
process::wait(process);
}
virtual void registered(
SchedulerDriver*,
const FrameworkID& frameworkId,
const MasterInfo&)
{
LOG(INFO) << "Registered with framework ID: " << frameworkId;
process::dispatch(
&process,
&BalloonSchedulerProcess::registered);
}
virtual void reregistered(SchedulerDriver*, const MasterInfo& masterInfo)
{
LOG(INFO) << "Reregistered";
process::dispatch(
&process,
&BalloonSchedulerProcess::registered);
}
virtual void disconnected(SchedulerDriver* driver)
{
LOG(INFO) << "Disconnected";
process::dispatch(
&process,
&BalloonSchedulerProcess::disconnected);
}
virtual void resourceOffers(
SchedulerDriver* driver,
const std::vector<Offer>& offers)
{
LOG(INFO) << "Resource offers received";
process::dispatch(
&process,
&BalloonSchedulerProcess::resourceOffers,
driver,
offers);
}
virtual void offerRescinded(
SchedulerDriver* driver,
const OfferID& offerId)
{
LOG(INFO) << "Offer rescinded";
}
virtual void statusUpdate(SchedulerDriver* driver, const TaskStatus& status)
{
LOG(INFO)
<< "Task " << status.task_id() << " in state "
<< TaskState_Name(status.state())
<< ", Source: " << status.source()
<< ", Reason: " << status.reason()
<< (status.has_message() ? ", Message: " + status.message() : "");
process::dispatch(
&process,
&BalloonSchedulerProcess::statusUpdate,
driver,
status);
}
virtual void frameworkMessage(
SchedulerDriver* driver,
const ExecutorID& executorId,
const SlaveID& slaveId,
const string& data)
{
LOG(INFO) << "Framework message: " << data;
}
virtual void slaveLost(SchedulerDriver* driver, const SlaveID& slaveId)
{
LOG(INFO) << "Agent lost: " << slaveId;
}
virtual void executorLost(
SchedulerDriver* driver,
const ExecutorID& executorId,
const SlaveID& slaveId,
int status)
{
LOG(INFO) << "Executor '" << executorId << "' lost on agent: " << slaveId;
}
virtual void error(SchedulerDriver* driver, const string& message)
{
LOG(INFO) << "Error message: " << message;
}
private:
BalloonSchedulerProcess process;
};
int main(int argc, char** argv)
{
Flags flags;
Try<flags::Warnings> load = flags.load("MESOS_", argc, argv);
if (load.isError()) {
EXIT(EXIT_FAILURE) << flags.usage(load.error());
}
const Resources resources = Resources::parse(
"cpus:" + stringify(CPUS_PER_EXECUTOR) +
";mem:" + stringify(MEM_PER_EXECUTOR)).get();
ExecutorInfo executor;
executor.mutable_resources()->CopyFrom(resources);
executor.set_name("Balloon Executor");
executor.set_source("balloon_test");
// Determine the command to run the executor based on three possibilities:
// 1) `--executor_command` was set, which overrides the below cases.
// 2) We are in the Mesos build directory, so the targeted executable
// is actually a libtool wrapper script.
// 3) We have not detected the Mesos build directory, so assume the
// executor is in the same directory as the framework.
string command;
// Find this executable's directory to locate executor.
if (flags.executor_command.isSome()) {
command = flags.executor_command.get();
} else if (flags.build_dir.isSome()) {
command = path::join(
flags.build_dir.get(), "src", "balloon-executor");
} else {
command = path::join(
os::realpath(Path(argv[0]).dirname()).get(),
"balloon-executor");
}
executor.mutable_command()->set_value(command);
// Copy `--executor_uri` into the command.
if (flags.executor_uri.isSome()) {
mesos::CommandInfo::URI* uri = executor.mutable_command()->add_uris();
uri->set_value(flags.executor_uri.get());
uri->set_executable(true);
}
FrameworkInfo framework;
framework.set_user(os::user().get());
framework.set_name("Balloon Framework (C++)");
framework.set_checkpoint(flags.checkpoint);
framework.set_role("*");
framework.add_capabilities()->set_type(
FrameworkInfo::Capability::RESERVATION_REFINEMENT);
BalloonScheduler scheduler(framework, executor, flags);
// Log any flag warnings (after logging is initialized by the scheduler).
foreach (const flags::Warning& warning, load->warnings) {
LOG(WARNING) << warning.message;
}
MesosSchedulerDriver* driver;
// TODO(josephw): Refactor these into a common set of flags.
Option<string> value = os::getenv("MESOS_AUTHENTICATE_FRAMEWORKS");
if (value.isSome()) {
LOG(INFO) << "Enabling authentication for the framework";
value = os::getenv("DEFAULT_PRINCIPAL");
if (value.isNone()) {
EXIT(EXIT_FAILURE)
<< "Expecting authentication principal in the environment";
}
Credential credential;
credential.set_principal(value.get());
framework.set_principal(value.get());
value = os::getenv("DEFAULT_SECRET");
if (value.isNone()) {
EXIT(EXIT_FAILURE)
<< "Expecting authentication secret in the environment";
}
credential.set_secret(value.get());
driver = new MesosSchedulerDriver(
&scheduler, framework, flags.master, credential);
} else {
framework.set_principal("balloon-framework-cpp");
driver = new MesosSchedulerDriver(
&scheduler, framework, flags.master);
}
int status = driver->run() == DRIVER_STOPPED ? 0 : 1;
// Ensure that the driver process terminates.
driver->stop();
delete driver;
return status;
}
<commit_msg>Minor clean up of the balloon framework.<commit_after>// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include <glog/logging.h>
#include <iostream>
#include <string>
#include <vector>
#include <mesos/resources.hpp>
#include <mesos/scheduler.hpp>
#include <process/clock.hpp>
#include <process/defer.hpp>
#include <process/dispatch.hpp>
#include <process/http.hpp>
#include <process/process.hpp>
#include <process/protobuf.hpp>
#include <process/time.hpp>
#include <process/metrics/counter.hpp>
#include <process/metrics/gauge.hpp>
#include <process/metrics/metrics.hpp>
#include <stout/bytes.hpp>
#include <stout/flags.hpp>
#include <stout/option.hpp>
#include <stout/os.hpp>
#include <stout/path.hpp>
#include <stout/stringify.hpp>
using namespace mesos;
using namespace mesos::internal;
using std::string;
using process::Clock;
using process::defer;
using process::metrics::Gauge;
using process::metrics::Counter;
const double CPUS_PER_TASK = 0.1;
const double CPUS_PER_EXECUTOR = 0.1;
const int32_t MEM_PER_EXECUTOR = 64;
class Flags : public virtual flags::FlagsBase
{
public:
Flags()
{
add(&Flags::master,
"master",
"Master to connect to.");
add(&Flags::task_memory_usage_limit,
"task_memory_usage_limit",
None(),
"Maximum size, in bytes, of the task's memory usage.\n"
"The task will attempt to occupy memory up until this limit.",
static_cast<const Bytes*>(nullptr),
[](const Bytes& value) -> Option<Error> {
if (value.megabytes() < MEM_PER_EXECUTOR) {
return Error(
"Please use a --task_memory_usage_limit greater than " +
stringify(MEM_PER_EXECUTOR) + " MB");
}
return None();
});
add(&Flags::task_memory,
"task_memory",
"How much memory the framework will require per task.\n"
"If not specified, the task(s) will use all available memory in\n"
"applicable offers.");
add(&Flags::build_dir,
"build_dir",
"The build directory of Mesos. If set, the framework will assume\n"
"that the executor, framework, and agent(s) all live on the same\n"
"machine.");
add(&Flags::executor_uri,
"executor_uri",
"URI the fetcher should use to get the executor.");
add(&Flags::executor_command,
"executor_command",
"The command that should be used to start the executor.\n"
"This will override the value set by `--build_dir`.");
add(&Flags::checkpoint,
"checkpoint",
"Whether this framework should be checkpointed.\n",
false);
add(&Flags::long_running,
"long_running",
"Whether this framework should launch tasks repeatedly\n"
"or exit after finishing a single task.",
false);
}
string master;
Bytes task_memory_usage_limit;
Bytes task_memory;
// Flags for specifying the executor binary.
Option<string> build_dir;
Option<string> executor_uri;
Option<string> executor_command;
bool checkpoint;
bool long_running;
};
// Actor holding the business logic and metrics for the `BalloonScheduler`.
// See `BalloonScheduler` below for the intended behavior.
class BalloonSchedulerProcess : public process::Process<BalloonSchedulerProcess>
{
public:
BalloonSchedulerProcess(
const FrameworkInfo& _frameworkInfo,
const ExecutorInfo& _executor,
const Flags& _flags)
: frameworkInfo(_frameworkInfo),
executor(_executor),
flags(_flags),
taskActive(false),
tasksLaunched(0),
isRegistered(false),
metrics(*this)
{
start_time = Clock::now();
}
void registered()
{
isRegistered = true;
}
void disconnected()
{
isRegistered = false;
}
void resourceOffers(
SchedulerDriver* driver,
const std::vector<Offer>& offers)
{
Resources taskResources = Resources::parse(
"cpus:" + stringify(CPUS_PER_TASK) +
";mem:" + stringify(flags.task_memory.megabytes())).get();
taskResources.allocate(frameworkInfo.role());
Resources executorResources = Resources(executor.resources());
executorResources.allocate(frameworkInfo.role());
foreach (const Offer& offer, offers) {
Resources resources(offer.resources());
// If there is an active task, or if the offer is not
// big enough, reject the offer.
if (taskActive ||
!resources.toUnreserved().contains(
taskResources + executorResources)) {
Filters filters;
filters.set_refuse_seconds(600);
driver->declineOffer(offer.id(), filters);
continue;
}
int taskId = tasksLaunched++;
LOG(INFO) << "Launching task " << taskId;
TaskInfo task;
task.set_name("Balloon Task");
task.mutable_task_id()->set_value(stringify(taskId));
task.mutable_slave_id()->MergeFrom(offer.slave_id());
task.mutable_resources()->CopyFrom(taskResources);
task.set_data(stringify(flags.task_memory_usage_limit));
task.mutable_executor()->CopyFrom(executor);
task.mutable_executor()->mutable_executor_id()
->set_value(stringify(taskId));
driver->launchTasks(offer.id(), {task});
taskActive = true;
}
}
void statusUpdate(SchedulerDriver* driver, const TaskStatus& status)
{
if (!flags.long_running) {
if (status.state() == TASK_FAILED &&
status.reason() == TaskStatus::REASON_CONTAINER_LIMITATION_MEMORY) {
// NOTE: We expect TASK_FAILED when this scheduler is launched by the
// balloon_framework_test.sh shell script. The abort here ensures the
// script considers the test result as "PASS".
driver->abort();
} else if (status.state() == TASK_FAILED ||
status.state() == TASK_FINISHED ||
status.state() == TASK_KILLED ||
status.state() == TASK_LOST ||
status.state() == TASK_ERROR) {
driver->stop();
}
}
if (stringify(tasksLaunched - 1) != status.task_id().value()) {
// We might receive messages from older tasks. Ignore them.
LOG(INFO) << "Ignoring status update from older task "
<< status.task_id();
return;
}
switch (status.state()) {
case TASK_FINISHED:
taskActive = false;
++metrics.tasks_finished;
break;
case TASK_FAILED:
taskActive = false;
if (status.reason() == TaskStatus::REASON_CONTAINER_LIMITATION_MEMORY) {
++metrics.tasks_oomed;
break;
}
// NOTE: Fetching the executor (e.g. `--executor_uri`) may fail
// occasionally if the URI is rate limited. This case is common
// enough that it makes sense to track this failure metric separately.
if (status.reason() == TaskStatus::REASON_CONTAINER_LAUNCH_FAILED) {
++metrics.launch_failures;
break;
}
case TASK_KILLED:
case TASK_LOST:
case TASK_ERROR:
taskActive = false;
++metrics.abnormal_terminations;
break;
default:
break;
}
}
private:
const FrameworkInfo frameworkInfo;
const ExecutorInfo executor;
const Flags flags;
bool taskActive;
int tasksLaunched;
process::Time start_time;
double _uptime_secs()
{
return (Clock::now() - start_time).secs();
}
bool isRegistered;
double _registered()
{
return isRegistered ? 1 : 0;
}
struct Metrics
{
Metrics(const BalloonSchedulerProcess& _scheduler)
: uptime_secs(
"balloon_framework/uptime_secs",
defer(_scheduler, &BalloonSchedulerProcess::_uptime_secs)),
registered(
"balloon_framework/registered",
defer(_scheduler, &BalloonSchedulerProcess::_registered)),
tasks_finished("balloon_framework/tasks_finished"),
tasks_oomed("balloon_framework/tasks_oomed"),
launch_failures("balloon_framework/launch_failures"),
abnormal_terminations("balloon_framework/abnormal_terminations")
{
process::metrics::add(uptime_secs);
process::metrics::add(registered);
process::metrics::add(tasks_finished);
process::metrics::add(tasks_oomed);
process::metrics::add(launch_failures);
process::metrics::add(abnormal_terminations);
}
~Metrics()
{
process::metrics::remove(uptime_secs);
process::metrics::remove(registered);
process::metrics::remove(tasks_finished);
process::metrics::remove(tasks_oomed);
process::metrics::remove(launch_failures);
process::metrics::remove(abnormal_terminations);
}
process::metrics::Gauge uptime_secs;
process::metrics::Gauge registered;
process::metrics::Counter tasks_finished;
process::metrics::Counter tasks_oomed;
process::metrics::Counter launch_failures;
process::metrics::Counter abnormal_terminations;
} metrics;
};
// This scheduler starts a single executor and task which gradually
// increases its memory footprint up to a limit. Depending on the
// resource limits set for the container, the framework expects the
// executor to either finish successfully or be OOM-killed.
class BalloonScheduler : public Scheduler
{
public:
BalloonScheduler(
const FrameworkInfo& _frameworkInfo,
const ExecutorInfo& _executor,
const Flags& _flags)
: process(_frameworkInfo, _executor, _flags)
{
process::spawn(process);
}
virtual ~BalloonScheduler()
{
process::terminate(process);
process::wait(process);
}
virtual void registered(
SchedulerDriver*,
const FrameworkID& frameworkId,
const MasterInfo&)
{
LOG(INFO) << "Registered with framework ID: " << frameworkId;
process::dispatch(
&process,
&BalloonSchedulerProcess::registered);
}
virtual void reregistered(SchedulerDriver*, const MasterInfo& masterInfo)
{
LOG(INFO) << "Reregistered";
process::dispatch(
&process,
&BalloonSchedulerProcess::registered);
}
virtual void disconnected(SchedulerDriver* driver)
{
LOG(INFO) << "Disconnected";
process::dispatch(
&process,
&BalloonSchedulerProcess::disconnected);
}
virtual void resourceOffers(
SchedulerDriver* driver,
const std::vector<Offer>& offers)
{
LOG(INFO) << "Resource offers received";
process::dispatch(
&process,
&BalloonSchedulerProcess::resourceOffers,
driver,
offers);
}
virtual void offerRescinded(
SchedulerDriver* driver,
const OfferID& offerId)
{
LOG(INFO) << "Offer rescinded";
}
virtual void statusUpdate(SchedulerDriver* driver, const TaskStatus& status)
{
LOG(INFO)
<< "Task " << status.task_id() << " in state "
<< TaskState_Name(status.state())
<< ", Source: " << status.source()
<< ", Reason: " << status.reason()
<< (status.has_message() ? ", Message: " + status.message() : "");
process::dispatch(
&process,
&BalloonSchedulerProcess::statusUpdate,
driver,
status);
}
virtual void frameworkMessage(
SchedulerDriver* driver,
const ExecutorID& executorId,
const SlaveID& slaveId,
const string& data)
{
LOG(INFO) << "Framework message: " << data;
}
virtual void slaveLost(SchedulerDriver* driver, const SlaveID& slaveId)
{
LOG(INFO) << "Agent lost: " << slaveId;
}
virtual void executorLost(
SchedulerDriver* driver,
const ExecutorID& executorId,
const SlaveID& slaveId,
int status)
{
LOG(INFO) << "Executor '" << executorId << "' lost on agent: " << slaveId;
}
virtual void error(SchedulerDriver* driver, const string& message)
{
LOG(INFO) << "Error message: " << message;
}
private:
BalloonSchedulerProcess process;
};
int main(int argc, char** argv)
{
Flags flags;
Try<flags::Warnings> load = flags.load("MESOS_", argc, argv);
if (load.isError()) {
EXIT(EXIT_FAILURE) << flags.usage(load.error());
}
const Resources resources = Resources::parse(
"cpus:" + stringify(CPUS_PER_EXECUTOR) +
";mem:" + stringify(MEM_PER_EXECUTOR)).get();
ExecutorInfo executor;
executor.mutable_resources()->CopyFrom(resources);
executor.set_name("Balloon Executor");
// Determine the command to run the executor based on three possibilities:
// 1) `--executor_command` was set, which overrides the below cases.
// 2) We are in the Mesos build directory, so the targeted executable
// is actually a libtool wrapper script.
// 3) We have not detected the Mesos build directory, so assume the
// executor is in the same directory as the framework.
string command;
// Find this executable's directory to locate executor.
if (flags.executor_command.isSome()) {
command = flags.executor_command.get();
} else if (flags.build_dir.isSome()) {
command = path::join(
flags.build_dir.get(), "src", "balloon-executor");
} else {
command = path::join(
os::realpath(Path(argv[0]).dirname()).get(),
"balloon-executor");
}
executor.mutable_command()->set_value(command);
// Copy `--executor_uri` into the command.
if (flags.executor_uri.isSome()) {
mesos::CommandInfo::URI* uri = executor.mutable_command()->add_uris();
uri->set_value(flags.executor_uri.get());
uri->set_executable(true);
}
FrameworkInfo framework;
framework.set_user(os::user().get());
framework.set_name("Balloon Framework (C++)");
framework.set_checkpoint(flags.checkpoint);
framework.set_role("*");
framework.add_capabilities()->set_type(
FrameworkInfo::Capability::RESERVATION_REFINEMENT);
BalloonScheduler scheduler(framework, executor, flags);
// Log any flag warnings (after logging is initialized by the scheduler).
foreach (const flags::Warning& warning, load->warnings) {
LOG(WARNING) << warning.message;
}
MesosSchedulerDriver* driver;
// TODO(josephw): Refactor these into a common set of flags.
Option<string> value = os::getenv("MESOS_AUTHENTICATE_FRAMEWORKS");
if (value.isSome()) {
LOG(INFO) << "Enabling authentication for the framework";
value = os::getenv("DEFAULT_PRINCIPAL");
if (value.isNone()) {
EXIT(EXIT_FAILURE)
<< "Expecting authentication principal in the environment";
}
Credential credential;
credential.set_principal(value.get());
framework.set_principal(value.get());
value = os::getenv("DEFAULT_SECRET");
if (value.isNone()) {
EXIT(EXIT_FAILURE)
<< "Expecting authentication secret in the environment";
}
credential.set_secret(value.get());
driver = new MesosSchedulerDriver(
&scheduler, framework, flags.master, credential);
} else {
framework.set_principal("balloon-framework-cpp");
driver = new MesosSchedulerDriver(
&scheduler, framework, flags.master);
}
int status = driver->run() == DRIVER_STOPPED ? 0 : 1;
// Ensure that the driver process terminates.
driver->stop();
delete driver;
return status;
}
<|endoftext|>
|
<commit_before>#include <sys/types.h>
#include <sys/socket.h>
#include <sys/un.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <stdio.h>
#include <errno.h>
#include <string.h>
#include <fcntl.h>
bool socketError = false;
bool socketBlocking = false;
int DDV_OpenUnix(const char adres[], bool nonblock = false){
int s = socket(AF_UNIX, SOCK_STREAM, 0);
int on = 1;
setsockopt(s, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on));
sockaddr_un addr;
addr.sun_family = AF_UNIX;
strcpy(addr.sun_path, adres);
int r = connect(s, (sockaddr*)&addr, sizeof(addr));
if (r == 0){
if (nonblock){
int flags = fcntl(s, F_GETFL, 0);
flags |= O_NONBLOCK;
fcntl(s, F_SETFL, flags);
}
return s;
}else{
close(s);
return 0;
}
}
int DDV_Listen(int port){
int s = socket(AF_INET, SOCK_STREAM, 0);
struct sockaddr_in addr;
addr.sin_family = AF_INET;
addr.sin_port = htons(port);//port 8888
inet_pton(AF_INET, "0.0.0.0", &addr.sin_addr);//listen on all interfaces
int ret = bind(s, (sockaddr*)&addr, sizeof(addr));//bind to all interfaces, chosen port
if (ret == 0){
ret = listen(s, 100);//start listening, backlog of 100 allowed
if (ret == 0){
return s;
}else{
printf("Listen failed! Error: %s\n", strerror(errno));
close(s);
return 0;
}
}else{
printf("Binding failed! Error: %s\n", strerror(errno));
close(s);
return 0;
}
}
int DDV_Accept(int sock, bool nonblock = false){
int r = accept(sock, 0, 0);
if ((r > 0) && nonblock){
int flags = fcntl(r, F_GETFL, 0);
flags |= O_NONBLOCK;
fcntl(r, F_SETFL, flags);
}
return r;
}
bool DDV_write(void * buffer, int todo, int sock){
int sofar = 0;
socketBlocking = false;
while (sofar != todo){
int r = send(sock, (char*)buffer + sofar, todo-sofar, 0);
if (r <= 0){
switch (errno){
case EWOULDBLOCK: socketBlocking = true; break;
default:
socketError = true;
printf("Could not write! %s\n", strerror(errno));
return false;
break;
}
}
sofar += r;
}
return true;
}
bool DDV_ready(int sock){
char tmp;
int preflags = fcntl(sock, F_GETFL, 0);
int postflags = preflags | O_NONBLOCK;
fcntl(sock, F_SETFL, postflags);
int r = recv(sock, &tmp, 1, MSG_PEEK);
fcntl(sock, F_SETFL, preflags);
return (r == 1);
}
bool DDV_read(void * buffer, int todo, int sock){
int sofar = 0;
socketBlocking = false;
while (sofar != todo){
int r = recv(sock, (char*)buffer + sofar, todo-sofar, 0);
if (r <= 0){
switch (errno){
case EWOULDBLOCK: socketBlocking = true; break;
default:
socketError = true;
printf("Could not read! %s\n", strerror(errno));
return false;
break;
}
}
sofar += r;
}
return true;
}
bool DDV_read(void * buffer, int width, int count, int sock){return DDV_read(buffer, width*count, sock);}
bool DDV_write(void * buffer, int width, int count, int sock){return DDV_write(buffer, width*count, sock);}
int DDV_iwrite(void * buffer, int todo, int sock){
int r = send(sock, buffer, todo, 0);
if (r < 0){
switch (errno){
case EWOULDBLOCK: break;
default:
socketError = true;
printf("Could not write! %s\n", strerror(errno));
return false;
break;
}
}
return r;
}
int DDV_iread(void * buffer, int todo, int sock){
int r = recv(sock, buffer, todo, 0);
if (r < 0){
switch (errno){
case EWOULDBLOCK: break;
default:
socketError = true;
printf("Could not read! %s\n", strerror(errno));
return false;
break;
}
}
return r;
}
<commit_msg>DDVSocket edits<commit_after>#include <sys/types.h>
#include <sys/socket.h>
#include <sys/un.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <stdio.h>
#include <errno.h>
#include <string.h>
#include <fcntl.h>
bool socketError = false;
bool socketBlocking = false;
int DDV_OpenUnix(const char adres[], bool nonblock = false){
int s = socket(AF_UNIX, SOCK_STREAM, 0);
sockaddr_un addr;
addr.sun_family = AF_UNIX;
strcpy(addr.sun_path, adres);
int r = connect(s, (sockaddr*)&addr, sizeof(addr));
if (r == 0){
if (nonblock){
int flags = fcntl(s, F_GETFL, 0);
flags |= O_NONBLOCK;
fcntl(s, F_SETFL, flags);
}
return s;
}else{
close(s);
return 0;
}
}
int DDV_Listen(int port){
int s = socket(AF_INET, SOCK_STREAM, 0);
int on = 1;
setsockopt(s, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on));
struct sockaddr_in addr;
addr.sin_family = AF_INET;
addr.sin_port = htons(port);//port 8888
inet_pton(AF_INET, "0.0.0.0", &addr.sin_addr);//listen on all interfaces
int ret = bind(s, (sockaddr*)&addr, sizeof(addr));//bind to all interfaces, chosen port
if (ret == 0){
ret = listen(s, 100);//start listening, backlog of 100 allowed
if (ret == 0){
return s;
}else{
printf("Listen failed! Error: %s\n", strerror(errno));
close(s);
return 0;
}
}else{
printf("Binding failed! Error: %s\n", strerror(errno));
close(s);
return 0;
}
}
int DDV_Accept(int sock, bool nonblock = false){
int r = accept(sock, 0, 0);
if ((r > 0) && nonblock){
int flags = fcntl(r, F_GETFL, 0);
flags |= O_NONBLOCK;
fcntl(r, F_SETFL, flags);
}
return r;
}
bool DDV_write(void * buffer, int todo, int sock){
int sofar = 0;
socketBlocking = false;
while (sofar != todo){
int r = send(sock, (char*)buffer + sofar, todo-sofar, 0);
if (r <= 0){
switch (errno){
case EWOULDBLOCK: socketBlocking = true; break;
default:
socketError = true;
printf("Could not write! %s\n", strerror(errno));
return false;
break;
}
}
sofar += r;
}
return true;
}
bool DDV_ready(int sock){
char tmp;
int preflags = fcntl(sock, F_GETFL, 0);
int postflags = preflags | O_NONBLOCK;
fcntl(sock, F_SETFL, postflags);
int r = recv(sock, &tmp, 1, MSG_PEEK);
fcntl(sock, F_SETFL, preflags);
return (r == 1);
}
bool DDV_read(void * buffer, int todo, int sock){
int sofar = 0;
socketBlocking = false;
while (sofar != todo){
int r = recv(sock, (char*)buffer + sofar, todo-sofar, 0);
if (r <= 0){
switch (errno){
case EWOULDBLOCK: socketBlocking = true; break;
default:
socketError = true;
printf("Could not read! %s\n", strerror(errno));
return false;
break;
}
}
sofar += r;
}
return true;
}
bool DDV_read(void * buffer, int width, int count, int sock){return DDV_read(buffer, width*count, sock);}
bool DDV_write(void * buffer, int width, int count, int sock){return DDV_write(buffer, width*count, sock);}
int DDV_iwrite(void * buffer, int todo, int sock){
int r = send(sock, buffer, todo, 0);
if (r < 0){
switch (errno){
case EWOULDBLOCK: break;
default:
socketError = true;
printf("Could not write! %s\n", strerror(errno));
return false;
break;
}
}
return r;
}
int DDV_iread(void * buffer, int todo, int sock){
int r = recv(sock, buffer, todo, 0);
if (r < 0){
switch (errno){
case EWOULDBLOCK: break;
default:
socketError = true;
printf("Could not read! %s\n", strerror(errno));
return false;
break;
}
}
return r;
}
<|endoftext|>
|
<commit_before>/*
* mkContext.cpp
* MonkVG-XCode
*
* Created by Micah Pearlman on 2/22/09.
* Copyright 2009 Monk Games. All rights reserved.
*
*/
#include "mkContext.h"
#include "glPath.h"
using namespace MonkVG;
//static VGContext *g_context = NULL;
VG_API_CALL VGboolean vgCreateContextSH(VGint width, VGint height)
{
IContext::instance().Initialize();
IContext::instance().setWidth( width );
IContext::instance().setHeight( height );
IContext::instance().resize();
return VG_TRUE;
}
VG_API_CALL void vgResizeSurfaceSH(VGint width, VGint height)
{
IContext::instance().setWidth( width );
IContext::instance().setHeight( height );
IContext::instance().resize();
}
VG_API_CALL void vgDestroyContextSH()
{
}
VG_API_CALL void VG_API_ENTRY vgSetf (VGuint type, VGfloat value) VG_API_EXIT {
IContext::instance().set( type, value );
}
VG_API_CALL void VG_API_ENTRY vgSeti (VGuint type, VGint value) VG_API_EXIT {
IContext::instance().set( type, value );
}
VG_API_CALL void VG_API_ENTRY vgSetfv(VGuint type, VGint count,
const VGfloat * values) VG_API_EXIT {
IContext::instance().set( type, values );
}
VG_API_CALL void VG_API_ENTRY vgSetiv(VGuint type, VGint count,
const VGint * values) VG_API_EXIT {
}
VG_API_CALL VGfloat VG_API_ENTRY vgGetf(VGuint type) VG_API_EXIT {
return -1.0f;
}
VG_API_CALL VGint VG_API_ENTRY vgGeti(VGuint type) VG_API_EXIT {
return -1;
}
VG_API_CALL VGint VG_API_ENTRY vgGetVectorSize(VGuint type) VG_API_EXIT {
return -1;
}
VG_API_CALL void VG_API_ENTRY vgGetfv(VGuint type, VGint count, VGfloat * values) VG_API_EXIT {
}
VG_API_CALL void VG_API_ENTRY vgGetiv(VGuint type, VGint count, VGint * values) VG_API_EXIT {
}
/* Masking and Clearing */
VG_API_CALL void VG_API_ENTRY vgClear(VGint x, VGint y, VGint width, VGint height) VG_API_EXIT {
IContext::instance().clear( x, y, width, height );
}
/* Finish and Flush */
VG_API_CALL void VG_API_ENTRY vgFinish(void) VG_API_EXIT {
glFinish();
}
VG_API_CALL void VG_API_ENTRY vgFlush(void) VG_API_EXIT {
glFlush();
}
/*--------------------------------------------------
* Returns the oldest error pending on the current
* context and clears its error code
*--------------------------------------------------*/
VG_API_CALL VGErrorCode vgGetError(void)
{
return IContext::instance().getError();
}
namespace MonkVG {
IContext::IContext()
: _error( VG_NO_ERROR )
, _width( 0 )
, _height( 0 )
, _stroke_line_width( 1.0f )
, _stroke_paint( 0 )
, _fill_paint( 0 )
, _active_matrix( &_path_user_to_surface )
, _fill_rule( VG_EVEN_ODD )
, _renderingQuality( VG_RENDERING_QUALITY_BETTER )
, _tessellationIterations( 16 )
, _matrixMode( VG_MATRIX_PATH_USER_TO_SURFACE )
, _currentBatch( 0 )
, _imageMode( VG_DRAW_IMAGE_NORMAL )
{
_path_user_to_surface.setIdentity();
_glyph_user_to_surface.setIdentity();
_image_user_to_surface.setIdentity();
_active_matrix->setIdentity();
_glyph_origin[0] = _glyph_origin[1] = 0;
setImageMode( _imageMode );
}
//// parameters ////
void IContext::set( VGuint type, VGfloat f ) {
switch ( type ) {
case VG_STROKE_LINE_WIDTH:
setStrokeLineWidth( f );
break;
default:
setError( VG_ILLEGAL_ARGUMENT_ERROR );
break;
}
}
void IContext::set( VGuint type, const VGfloat * fv ) {
switch ( type ) {
case VG_CLEAR_COLOR:
setClearColor( fv );
break;
case VG_GLYPH_ORIGIN:
setGlyphOrigin( fv );
break;
default:
setError( VG_ILLEGAL_ARGUMENT_ERROR );
break;
}
}
void IContext::set( VGuint type, VGint i ) {
switch ( type ) {
case VG_MATRIX_MODE:
setMatrixMode( (VGMatrixMode)i );
break;
case VG_FILL_RULE:
setFillRule( (VGFillRule)i );
break;
case VG_TESSELLATION_ITERATIONS_MNK:
setTessellationIterations( i );
break;
case VG_IMAGE_MODE:
setImageMode( (VGImageMode)i );
break;
default:
break;
}
}
void IContext::get( VGuint type, VGfloat &f ) const {
switch ( type ) {
case VG_STROKE_LINE_WIDTH:
f = getStrokeLineWidth();
break;
default:
IContext::instance().setError( VG_ILLEGAL_ARGUMENT_ERROR );
break;
}
}
void IContext::get( VGuint type, VGfloat *fv ) const {
switch ( type ) {
case VG_CLEAR_COLOR:
getClearColor( fv );
break;
case VG_GLYPH_ORIGIN:
getGlyphOrigin( fv );
break;
default:
IContext::instance().setError( VG_ILLEGAL_ARGUMENT_ERROR );
break;
}
}
void IContext::get( VGuint type, VGint& i ) const {
i = -1;
switch ( type ) {
case VG_MATRIX_MODE:
i = getMatrixMode( );
break;
case VG_FILL_RULE:
i = getFillRule( );
break;
case VG_TESSELLATION_ITERATIONS_MNK:
i = getTessellationIterations( );
break;
case VG_IMAGE_MODE:
i = getImageMode( );
break;
default:
break;
}
}
}
<commit_msg>add stub for vgMask<commit_after>/*
* mkContext.cpp
* MonkVG-XCode
*
* Created by Micah Pearlman on 2/22/09.
* Copyright 2009 Monk Games. All rights reserved.
*
*/
#include "mkContext.h"
#include "glPath.h"
using namespace MonkVG;
//static VGContext *g_context = NULL;
VG_API_CALL VGboolean vgCreateContextSH(VGint width, VGint height)
{
IContext::instance().Initialize();
IContext::instance().setWidth( width );
IContext::instance().setHeight( height );
IContext::instance().resize();
return VG_TRUE;
}
VG_API_CALL void vgResizeSurfaceSH(VGint width, VGint height)
{
IContext::instance().setWidth( width );
IContext::instance().setHeight( height );
IContext::instance().resize();
}
VG_API_CALL void vgDestroyContextSH()
{
}
VG_API_CALL void VG_API_ENTRY vgSetf (VGuint type, VGfloat value) VG_API_EXIT {
IContext::instance().set( type, value );
}
VG_API_CALL void VG_API_ENTRY vgSeti (VGuint type, VGint value) VG_API_EXIT {
IContext::instance().set( type, value );
}
VG_API_CALL void VG_API_ENTRY vgSetfv(VGuint type, VGint count,
const VGfloat * values) VG_API_EXIT {
IContext::instance().set( type, values );
}
VG_API_CALL void VG_API_ENTRY vgSetiv(VGuint type, VGint count,
const VGint * values) VG_API_EXIT {
}
VG_API_CALL VGfloat VG_API_ENTRY vgGetf(VGuint type) VG_API_EXIT {
return -1.0f;
}
VG_API_CALL VGint VG_API_ENTRY vgGeti(VGuint type) VG_API_EXIT {
return -1;
}
VG_API_CALL VGint VG_API_ENTRY vgGetVectorSize(VGuint type) VG_API_EXIT {
return -1;
}
VG_API_CALL void VG_API_ENTRY vgGetfv(VGuint type, VGint count, VGfloat * values) VG_API_EXIT {
}
VG_API_CALL void VG_API_ENTRY vgGetiv(VGuint type, VGint count, VGint * values) VG_API_EXIT {
}
/* Masking and Clearing */
VG_API_CALL void VG_API_ENTRY vgClear(VGint x, VGint y, VGint width, VGint height) VG_API_EXIT {
IContext::instance().clear( x, y, width, height );
}
VG_API_CALL void VG_API_ENTRY vgMask(VGHandle mask, VGMaskOperation operation,VGint x, VGint y,
VGint width, VGint height) VG_API_EXIT {
}
/* Finish and Flush */
VG_API_CALL void VG_API_ENTRY vgFinish(void) VG_API_EXIT {
glFinish();
}
VG_API_CALL void VG_API_ENTRY vgFlush(void) VG_API_EXIT {
glFlush();
}
/*--------------------------------------------------
* Returns the oldest error pending on the current
* context and clears its error code
*--------------------------------------------------*/
VG_API_CALL VGErrorCode vgGetError(void)
{
return IContext::instance().getError();
}
namespace MonkVG {
IContext::IContext()
: _error( VG_NO_ERROR )
, _width( 0 )
, _height( 0 )
, _stroke_line_width( 1.0f )
, _stroke_paint( 0 )
, _fill_paint( 0 )
, _active_matrix( &_path_user_to_surface )
, _fill_rule( VG_EVEN_ODD )
, _renderingQuality( VG_RENDERING_QUALITY_BETTER )
, _tessellationIterations( 16 )
, _matrixMode( VG_MATRIX_PATH_USER_TO_SURFACE )
, _currentBatch( 0 )
, _imageMode( VG_DRAW_IMAGE_NORMAL )
{
_path_user_to_surface.setIdentity();
_glyph_user_to_surface.setIdentity();
_image_user_to_surface.setIdentity();
_active_matrix->setIdentity();
_glyph_origin[0] = _glyph_origin[1] = 0;
setImageMode( _imageMode );
}
//// parameters ////
void IContext::set( VGuint type, VGfloat f ) {
switch ( type ) {
case VG_STROKE_LINE_WIDTH:
setStrokeLineWidth( f );
break;
default:
setError( VG_ILLEGAL_ARGUMENT_ERROR );
break;
}
}
void IContext::set( VGuint type, const VGfloat * fv ) {
switch ( type ) {
case VG_CLEAR_COLOR:
setClearColor( fv );
break;
case VG_GLYPH_ORIGIN:
setGlyphOrigin( fv );
break;
default:
setError( VG_ILLEGAL_ARGUMENT_ERROR );
break;
}
}
void IContext::set( VGuint type, VGint i ) {
switch ( type ) {
case VG_MATRIX_MODE:
setMatrixMode( (VGMatrixMode)i );
break;
case VG_FILL_RULE:
setFillRule( (VGFillRule)i );
break;
case VG_TESSELLATION_ITERATIONS_MNK:
setTessellationIterations( i );
break;
case VG_IMAGE_MODE:
setImageMode( (VGImageMode)i );
break;
default:
break;
}
}
void IContext::get( VGuint type, VGfloat &f ) const {
switch ( type ) {
case VG_STROKE_LINE_WIDTH:
f = getStrokeLineWidth();
break;
default:
IContext::instance().setError( VG_ILLEGAL_ARGUMENT_ERROR );
break;
}
}
void IContext::get( VGuint type, VGfloat *fv ) const {
switch ( type ) {
case VG_CLEAR_COLOR:
getClearColor( fv );
break;
case VG_GLYPH_ORIGIN:
getGlyphOrigin( fv );
break;
default:
IContext::instance().setError( VG_ILLEGAL_ARGUMENT_ERROR );
break;
}
}
void IContext::get( VGuint type, VGint& i ) const {
i = -1;
switch ( type ) {
case VG_MATRIX_MODE:
i = getMatrixMode( );
break;
case VG_FILL_RULE:
i = getFillRule( );
break;
case VG_TESSELLATION_ITERATIONS_MNK:
i = getTessellationIterations( );
break;
case VG_IMAGE_MODE:
i = getImageMode( );
break;
default:
break;
}
}
}
<|endoftext|>
|
<commit_before>/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "ICUFormatNumberFunctor.hpp"
#include <algorithm>
#include <xalanc/ICUBridge/ICUBridge.hpp>
#include <xalanc/Include/XalanAutoPtr.hpp>
#include <xalanc/PlatformSupport/DOMStringHelper.hpp>
#include <xalanc/PlatformSupport/XalanDecimalFormatSymbols.hpp>
#include <xalanc/PlatformSupport/XalanMessageLoader.hpp>
#include <xalanc/XPath/XPathExecutionContext.hpp>
XALAN_CPP_NAMESPACE_BEGIN
ICUFormatNumberFunctor::ICUFormatNumberFunctor(MemoryManagerType& theManager) :
m_decimalFormatCache(theManager),
m_defaultDecimalFormat(theManager, createDecimalFormat(theManager)),
m_memoryManager(theManager)
{
}
ICUFormatNumberFunctor*
ICUFormatNumberFunctor::create(MemoryManagerType& theManager)
{
typedef ICUFormatNumberFunctor ThisType;
XalanMemMgrAutoPtr<ThisType, false> theGuard( theManager , (ThisType*)theManager.allocate(sizeof(ThisType)));
ThisType* theResult = theGuard.get();
new (theResult) ThisType(theManager);
theGuard.release();
return theResult;
}
ICUFormatNumberFunctor::~ICUFormatNumberFunctor()
{
XALAN_USING_STD(for_each)
for_each(
m_decimalFormatCache.begin(),
m_decimalFormatCache.end(),
DecimalFormatCacheStruct::DecimalFormatDeleteFunctor(m_memoryManager));
}
void
ICUFormatNumberFunctor::operator() (
XPathExecutionContext& executionContext,
double theNumber,
const XalanDOMString& thePattern,
const XalanDecimalFormatSymbols* theDFS,
XalanDOMString& theResult,
const XalanNode* context,
const LocatorType* locator) const
{
if (!doFormat(theNumber, thePattern, theResult, theDFS))
{
const XPathExecutionContext::GetCachedString theGuard(executionContext);
executionContext.warn(
XalanMessageLoader::getMessage(
theGuard.get(),
XalanMessages::FormatNumberFailed),
context,
locator);
}
}
DecimalFormatType *
ICUFormatNumberFunctor::getCachedDecimalFormat(const XalanDecimalFormatSymbols &theDFS) const
{
XALAN_USING_STD(find_if)
DecimalFormatCacheListType& theNonConstCache =
#if defined(XALAN_NO_MUTABLE)
(DecimalFormatCacheListType&)m_decimalFormatCache;
#else
m_decimalFormatCache;
#endif
DecimalFormatCacheListType::iterator i =
find_if(
theNonConstCache.begin(),
theNonConstCache.end(),
DecimalFormatCacheStruct::DecimalFormatFindFunctor(&theDFS));
if (i == theNonConstCache.end())
{
return 0;
}
else
{
// Let's do a quick check to see if we found the first entry.
// If so, we don't have to update the cache, so just return the
// appropriate value...
const DecimalFormatCacheListType::iterator theBegin =
theNonConstCache.begin();
if (i == theBegin)
{
return (*i).m_formatter;
}
else
{
// Save the formatter, because splice() may invalidate
// i.
DecimalFormatType* const theFormatter = (*i).m_formatter;
// Move the entry to the beginning the cache
theNonConstCache.splice(theBegin, theNonConstCache, i);
return theFormatter;
}
}
}
bool
ICUFormatNumberFunctor::doFormat(
double theNumber,
const XalanDOMString& thePattern,
XalanDOMString& theResult,
const XalanDecimalFormatSymbols* theDFS) const
{
if (theDFS == 0)
{
return doICUFormat(theNumber, thePattern, theResult);
}
XalanDOMString nonLocalPattern(m_memoryManager);
UnlocalizePatternFunctor formatter(*theDFS);
formatter(thePattern, nonLocalPattern, m_memoryManager);
DecimalFormatType* const theFormatter =
getCachedDecimalFormat(*theDFS);
if (theFormatter != 0)
{
return doICUFormat(
theNumber,
nonLocalPattern,
theResult,
theFormatter);
}
else
{
DFAutoPtrType theDecimalFormatGuard(
m_memoryManager,
createDecimalFormat(*theDFS, m_memoryManager));
if (theDecimalFormatGuard.get() != 0)
{
// OK, there was no error, so cache the instance...
cacheDecimalFormat(theDecimalFormatGuard.get(), *theDFS);
// Release the collator, since it's in the cache and
// will be controlled by the cache...
DecimalFormatType* const theDecimalFormat =
theDecimalFormatGuard.releasePtr();
return doICUFormat(
theNumber,
nonLocalPattern,
theResult,
theDecimalFormat);
}
else
{
return doICUFormat(theNumber,nonLocalPattern,theResult);
}
}
}
DecimalFormatType*
ICUFormatNumberFunctor::createDecimalFormat(
const XalanDecimalFormatSymbols& theXalanDFS,
MemoryManager& theManager)
{
UErrorCode theStatus = U_ZERO_ERROR;
// Use a XalanAutoPtr, to keep this safe until we construct the DecimalFormat instance.
XalanAutoPtr<DecimalFormatSymbols> theDFS(new DecimalFormatSymbols(theStatus));
// We got a XalanDecimalFormatSymbols, so set the
// corresponding data in the ICU DecimalFormatSymbols.
theDFS->setSymbol(
DecimalFormatSymbols::kZeroDigitSymbol,
UChar(theXalanDFS.getZeroDigit()));
theDFS->setSymbol(
DecimalFormatSymbols::kGroupingSeparatorSymbol,
UChar(theXalanDFS.getGroupingSeparator()));
theDFS->setSymbol(
DecimalFormatSymbols::kDecimalSeparatorSymbol,
UChar(theXalanDFS.getDecimalSeparator()));
theDFS->setSymbol(
DecimalFormatSymbols::kPerMillSymbol,
UChar(theXalanDFS.getPerMill()));
theDFS->setSymbol(
DecimalFormatSymbols::kPercentSymbol,
UChar(theXalanDFS.getPercent()));
theDFS->setSymbol(
DecimalFormatSymbols::kDigitSymbol,
UChar(theXalanDFS.getDigit()));
theDFS->setSymbol(
DecimalFormatSymbols::kPatternSeparatorSymbol,
UChar(theXalanDFS.getPatternSeparator()));
theDFS->setSymbol(
DecimalFormatSymbols::kInfinitySymbol,
ICUBridge::XalanDOMStringToUnicodeString(
theManager,
theXalanDFS.getInfinity()));
theDFS->setSymbol(
DecimalFormatSymbols::kNaNSymbol,
ICUBridge::XalanDOMStringToUnicodeString(
theManager,
theXalanDFS.getNaN()));
theDFS->setSymbol(
DecimalFormatSymbols::kMinusSignSymbol,
UChar(theXalanDFS.getMinusSign()));
theDFS->setSymbol(
DecimalFormatSymbols::kCurrencySymbol,
ICUBridge::XalanDOMStringToUnicodeString(
theManager,
theXalanDFS.getCurrencySymbol()));
theDFS->setSymbol(
DecimalFormatSymbols::kIntlCurrencySymbol,
ICUBridge::XalanDOMStringToUnicodeString(
theManager,
theXalanDFS.getInternationalCurrencySymbol()));
theDFS->setSymbol(
DecimalFormatSymbols::kMonetarySeparatorSymbol,
UChar(theXalanDFS.getMonetaryDecimalSeparator()));
// Construct a DecimalFormat instance.
DecimalFormatType* theFormatter = 0;
XalanConstruct(
theManager,
theFormatter,
theStatus);
// Guard this, just in case something happens before
// we return it.
DFAutoPtrType theGuard(theManager, theFormatter);
if (U_SUCCESS(theStatus))
{
// Note that we release the XalanAutoPtr, since the
// DecimalFormat will adopt the DecimalFormatSymbols instance.
theGuard->adoptDecimalFormatSymbols(theDFS.release());
return theGuard.releasePtr();
}
else
{
return 0;
}
}
void
ICUFormatNumberFunctor::cacheDecimalFormat(
DecimalFormatType * theFormatter,
const XalanDecimalFormatSymbols& theDFS) const
{
assert(theFormatter != 0);
DecimalFormatCacheListType& theNonConstCache =
#if defined(XALAN_NO_MUTABLE)
(DecimalFormatCacheListType&)m_decimalFormatCache;
#else
m_decimalFormatCache;
#endif
// Is the cache full?
if (theNonConstCache.size() == eCacheMax)
{
// Yes, so guard the collator instance, in case pop_back() throws...
DFAutoPtrType theDecimalFormatGuard(
m_memoryManager,
theNonConstCache.back().m_formatter);
theNonConstCache.pop_back();
}
const DecimalFormatCacheListType::value_type emptyDFC(m_memoryManager);
theNonConstCache.push_front(emptyDFC);
DecimalFormatCacheListType::value_type& theEntry =
theNonConstCache.front();
theEntry.m_formatter = theFormatter;
theEntry.m_DFS = theDFS;
}
bool
ICUFormatNumberFunctor::doICUFormat(
double theNumber,
const XalanDOMString& thePattern,
XalanDOMString& theResult,
DecimalFormatType* theFormatter) const
{
UErrorCode theStatus = U_ZERO_ERROR;
if (theFormatter == 0)
{
if (m_defaultDecimalFormat.get() != 0)
{
theFormatter = m_defaultDecimalFormat.get();
}
else
{
return false;
}
}
theFormatter->applyPattern(
ICUBridge::XalanDOMStringToUnicodeString(m_memoryManager, thePattern),
theStatus);
if (U_SUCCESS(theStatus))
{
// Do the format...
UnicodeString theUnicodeResult;
theFormatter->format(theNumber, theUnicodeResult);
ICUBridge::UnicodeStringToXalanDOMString(theUnicodeResult, theResult);
}
return U_SUCCESS(theStatus) ? true : false;
}
XalanDOMString&
ICUFormatNumberFunctor::UnlocalizePatternFunctor::operator()(
const XalanDOMString& thePattern,
XalanDOMString& theResult,
MemoryManager& theManager) const
{
XalanDecimalFormatSymbols defaultDFS(theManager);
XalanDOMString::const_iterator iterator = thePattern.begin();
while( iterator != thePattern.end())
{
if( m_DFS.getDecimalSeparator() == *iterator )
{
theResult.push_back(defaultDFS.getDecimalSeparator());
}
else if(m_DFS.getDigit() == *iterator)
{
theResult.push_back(defaultDFS.getDigit());
}
else if(m_DFS.getGroupingSeparator() == *iterator)
{
theResult.push_back(defaultDFS.getGroupingSeparator());
}
else if(m_DFS.getMinusSign() == *iterator)
{
theResult.push_back(defaultDFS.getMinusSign());
}
else if(m_DFS.getPatternSeparator() == *iterator)
{
theResult.push_back(defaultDFS.getPatternSeparator());
}
else if(m_DFS.getPercent() == *iterator)
{
theResult.push_back(defaultDFS.getPercent());
}
else if(m_DFS.getPerMill() == *iterator)
{
theResult.push_back(defaultDFS.getPerMill());
}
else if(m_DFS.getZeroDigit() == *iterator)
{
theResult.push_back(defaultDFS.getZeroDigit());
}
else
{
switch(*iterator)
{
case XalanUnicode::charFullStop:
case XalanUnicode::charNumberSign:
case XalanUnicode::charComma:
case XalanUnicode::charHyphenMinus:
case XalanUnicode::charSemicolon:
case XalanUnicode::charPercentSign:
case XalanUnicode::charPerMilleSign:
case XalanUnicode::charDigit_0:
{
theResult.push_back(XalanUnicode::charAmpersand);
theResult.push_back(*iterator);
theResult.push_back(XalanUnicode::charAmpersand);
}
}
}
iterator++;
}
return theResult;
}
XALAN_CPP_NAMESPACE_END
<commit_msg>Fix for a defect XALANC-606<commit_after>/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "ICUFormatNumberFunctor.hpp"
#include <algorithm>
#include <xalanc/ICUBridge/ICUBridge.hpp>
#include <xalanc/Include/XalanAutoPtr.hpp>
#include <xalanc/PlatformSupport/DOMStringHelper.hpp>
#include <xalanc/PlatformSupport/XalanDecimalFormatSymbols.hpp>
#include <xalanc/PlatformSupport/XalanMessageLoader.hpp>
#include <xalanc/XPath/XPathExecutionContext.hpp>
XALAN_CPP_NAMESPACE_BEGIN
ICUFormatNumberFunctor::ICUFormatNumberFunctor(MemoryManagerType& theManager) :
m_decimalFormatCache(theManager),
m_defaultDecimalFormat(theManager, createDecimalFormat(theManager)),
m_memoryManager(theManager)
{
}
ICUFormatNumberFunctor*
ICUFormatNumberFunctor::create(MemoryManagerType& theManager)
{
typedef ICUFormatNumberFunctor ThisType;
XalanMemMgrAutoPtr<ThisType, false> theGuard( theManager , (ThisType*)theManager.allocate(sizeof(ThisType)));
ThisType* theResult = theGuard.get();
new (theResult) ThisType(theManager);
theGuard.release();
return theResult;
}
ICUFormatNumberFunctor::~ICUFormatNumberFunctor()
{
XALAN_USING_STD(for_each)
for_each(
m_decimalFormatCache.begin(),
m_decimalFormatCache.end(),
DecimalFormatCacheStruct::DecimalFormatDeleteFunctor(m_memoryManager));
}
void
ICUFormatNumberFunctor::operator() (
XPathExecutionContext& executionContext,
double theNumber,
const XalanDOMString& thePattern,
const XalanDecimalFormatSymbols* theDFS,
XalanDOMString& theResult,
const XalanNode* context,
const LocatorType* locator) const
{
if (!doFormat(theNumber, thePattern, theResult, theDFS))
{
const XPathExecutionContext::GetCachedString theGuard(executionContext);
executionContext.warn(
XalanMessageLoader::getMessage(
theGuard.get(),
XalanMessages::FormatNumberFailed),
context,
locator);
}
}
DecimalFormatType *
ICUFormatNumberFunctor::getCachedDecimalFormat(const XalanDecimalFormatSymbols &theDFS) const
{
XALAN_USING_STD(find_if)
DecimalFormatCacheListType& theNonConstCache =
#if defined(XALAN_NO_MUTABLE)
(DecimalFormatCacheListType&)m_decimalFormatCache;
#else
m_decimalFormatCache;
#endif
DecimalFormatCacheListType::iterator i =
find_if(
theNonConstCache.begin(),
theNonConstCache.end(),
DecimalFormatCacheStruct::DecimalFormatFindFunctor(&theDFS));
if (i == theNonConstCache.end())
{
return 0;
}
else
{
// Let's do a quick check to see if we found the first entry.
// If so, we don't have to update the cache, so just return the
// appropriate value...
const DecimalFormatCacheListType::iterator theBegin =
theNonConstCache.begin();
if (i == theBegin)
{
return (*i).m_formatter;
}
else
{
// Save the formatter, because splice() may invalidate
// i.
DecimalFormatType* const theFormatter = (*i).m_formatter;
// Move the entry to the beginning the cache
theNonConstCache.splice(theBegin, theNonConstCache, i);
return theFormatter;
}
}
}
bool
ICUFormatNumberFunctor::doFormat(
double theNumber,
const XalanDOMString& thePattern,
XalanDOMString& theResult,
const XalanDecimalFormatSymbols* theDFS) const
{
if (theDFS == 0)
{
return doICUFormat(theNumber, thePattern, theResult);
}
XalanDOMString nonLocalPattern(m_memoryManager);
UnlocalizePatternFunctor formatter(*theDFS);
formatter(thePattern, nonLocalPattern, m_memoryManager);
DecimalFormatType* const theFormatter =
getCachedDecimalFormat(*theDFS);
if (theFormatter != 0)
{
return doICUFormat(
theNumber,
nonLocalPattern,
theResult,
theFormatter);
}
else
{
DFAutoPtrType theDecimalFormatGuard(
m_memoryManager,
createDecimalFormat(*theDFS, m_memoryManager));
if (theDecimalFormatGuard.get() != 0)
{
// OK, there was no error, so cache the instance...
cacheDecimalFormat(theDecimalFormatGuard.get(), *theDFS);
// Release the collator, since it's in the cache and
// will be controlled by the cache...
DecimalFormatType* const theDecimalFormat =
theDecimalFormatGuard.releasePtr();
return doICUFormat(
theNumber,
nonLocalPattern,
theResult,
theDecimalFormat);
}
else
{
return doICUFormat(theNumber,nonLocalPattern,theResult);
}
}
}
DecimalFormatType*
ICUFormatNumberFunctor::createDecimalFormat(
const XalanDecimalFormatSymbols& theXalanDFS,
MemoryManager& theManager)
{
UErrorCode theStatus = U_ZERO_ERROR;
// Use a XalanAutoPtr, to keep this safe until we construct the DecimalFormat instance.
XalanAutoPtr<DecimalFormatSymbols> theDFS(new DecimalFormatSymbols(theStatus));
// We got a XalanDecimalFormatSymbols, so set the
// corresponding data in the ICU DecimalFormatSymbols.
theDFS->setSymbol(
DecimalFormatSymbols::kZeroDigitSymbol,
UChar(theXalanDFS.getZeroDigit()));
theDFS->setSymbol(
DecimalFormatSymbols::kGroupingSeparatorSymbol,
UChar(theXalanDFS.getGroupingSeparator()));
theDFS->setSymbol(
DecimalFormatSymbols::kDecimalSeparatorSymbol,
UChar(theXalanDFS.getDecimalSeparator()));
theDFS->setSymbol(
DecimalFormatSymbols::kPerMillSymbol,
UChar(theXalanDFS.getPerMill()));
theDFS->setSymbol(
DecimalFormatSymbols::kPercentSymbol,
UChar(theXalanDFS.getPercent()));
theDFS->setSymbol(
DecimalFormatSymbols::kDigitSymbol,
UChar(theXalanDFS.getDigit()));
theDFS->setSymbol(
DecimalFormatSymbols::kPatternSeparatorSymbol,
UChar(theXalanDFS.getPatternSeparator()));
theDFS->setSymbol(
DecimalFormatSymbols::kInfinitySymbol,
ICUBridge::XalanDOMStringToUnicodeString(
theManager,
theXalanDFS.getInfinity()));
theDFS->setSymbol(
DecimalFormatSymbols::kNaNSymbol,
ICUBridge::XalanDOMStringToUnicodeString(
theManager,
theXalanDFS.getNaN()));
theDFS->setSymbol(
DecimalFormatSymbols::kMinusSignSymbol,
UChar(theXalanDFS.getMinusSign()));
theDFS->setSymbol(
DecimalFormatSymbols::kCurrencySymbol,
ICUBridge::XalanDOMStringToUnicodeString(
theManager,
theXalanDFS.getCurrencySymbol()));
theDFS->setSymbol(
DecimalFormatSymbols::kIntlCurrencySymbol,
ICUBridge::XalanDOMStringToUnicodeString(
theManager,
theXalanDFS.getInternationalCurrencySymbol()));
theDFS->setSymbol(
DecimalFormatSymbols::kMonetarySeparatorSymbol,
UChar(theXalanDFS.getMonetaryDecimalSeparator()));
// Construct a DecimalFormat instance.
DecimalFormatType* theFormatter = 0;
XalanConstruct(
theManager,
theFormatter,
theStatus);
// Guard this, just in case something happens before
// we return it.
DFAutoPtrType theGuard(theManager, theFormatter);
if (U_SUCCESS(theStatus))
{
// Note that we release the XalanAutoPtr, since the
// DecimalFormat will adopt the DecimalFormatSymbols instance.
theGuard->adoptDecimalFormatSymbols(theDFS.release());
return theGuard.releasePtr();
}
else
{
assert(false);
return 0;
}
}
void
ICUFormatNumberFunctor::cacheDecimalFormat(
DecimalFormatType * theFormatter,
const XalanDecimalFormatSymbols& theDFS) const
{
assert(theFormatter != 0);
DecimalFormatCacheListType& theNonConstCache =
#if defined(XALAN_NO_MUTABLE)
(DecimalFormatCacheListType&)m_decimalFormatCache;
#else
m_decimalFormatCache;
#endif
// Is the cache full?
if (theNonConstCache.size() == eCacheMax)
{
// Yes, so guard the collator instance, in case pop_back() throws...
DFAutoPtrType theDecimalFormatGuard(
m_memoryManager,
theNonConstCache.back().m_formatter);
theNonConstCache.pop_back();
}
const DecimalFormatCacheListType::value_type emptyDFC(m_memoryManager);
theNonConstCache.push_front(emptyDFC);
DecimalFormatCacheListType::value_type& theEntry =
theNonConstCache.front();
theEntry.m_formatter = theFormatter;
theEntry.m_DFS = theDFS;
}
bool
ICUFormatNumberFunctor::doICUFormat(
double theNumber,
const XalanDOMString& thePattern,
XalanDOMString& theResult,
DecimalFormatType* theFormatter) const
{
UErrorCode theStatus = U_ZERO_ERROR;
if (theFormatter == 0)
{
if (m_defaultDecimalFormat.get() != 0)
{
theFormatter = m_defaultDecimalFormat.get();
}
else
{
return false;
}
}
theFormatter->applyPattern(
ICUBridge::XalanDOMStringToUnicodeString(m_memoryManager, thePattern),
theStatus);
if (U_SUCCESS(theStatus))
{
// Do the format...
UnicodeString theUnicodeResult;
theFormatter->format(theNumber, theUnicodeResult);
ICUBridge::UnicodeStringToXalanDOMString(theUnicodeResult, theResult);
}
return U_SUCCESS(theStatus) ? true : false;
}
XalanDOMString&
ICUFormatNumberFunctor::UnlocalizePatternFunctor::operator()(
const XalanDOMString& thePattern,
XalanDOMString& theResult,
MemoryManager& theManager) const
{
XalanDecimalFormatSymbols defaultDFS(theManager);
XalanDOMString::const_iterator iterator = thePattern.begin();
while( iterator != thePattern.end())
{
if( m_DFS.getDecimalSeparator() == *iterator )
{
theResult.push_back(defaultDFS.getDecimalSeparator());
}
else if(m_DFS.getDigit() == *iterator)
{
theResult.push_back(defaultDFS.getDigit());
}
else if(m_DFS.getGroupingSeparator() == *iterator)
{
theResult.push_back(defaultDFS.getGroupingSeparator());
}
else if(m_DFS.getMinusSign() == *iterator)
{
theResult.push_back(defaultDFS.getMinusSign());
}
else if(m_DFS.getPatternSeparator() == *iterator)
{
theResult.push_back(defaultDFS.getPatternSeparator());
}
else if(m_DFS.getPercent() == *iterator)
{
theResult.push_back(defaultDFS.getPercent());
}
else if(m_DFS.getPerMill() == *iterator)
{
theResult.push_back(defaultDFS.getPerMill());
}
else if(m_DFS.getZeroDigit() == *iterator)
{
theResult.push_back(defaultDFS.getZeroDigit());
}
else
{
switch(*iterator)
{
case XalanUnicode::charFullStop:
case XalanUnicode::charNumberSign:
case XalanUnicode::charComma:
case XalanUnicode::charHyphenMinus:
case XalanUnicode::charSemicolon:
case XalanUnicode::charPercentSign:
case XalanUnicode::charPerMilleSign:
case XalanUnicode::charDigit_0:
{
theResult.push_back(XalanUnicode::charAmpersand);
theResult.push_back(*iterator);
theResult.push_back(XalanUnicode::charAmpersand);
}
}
}
iterator++;
}
return theResult;
}
XALAN_CPP_NAMESPACE_END
<|endoftext|>
|
<commit_before>#include <iostream>
#define BOOST_TEST_DYN_LINK
#define BOOST_TEST_MODULE Main
#include <boost/test/unit_test.hpp>
#include <apr.h>
#include "akumuli.h"
#include "storage_engine/blockstore.h"
#include "storage_engine/volume.h"
#include "storage_engine/nbtree.h"
#include "log_iface.h"
void test_logger(aku_LogLevel tag, const char* msg) {
BOOST_MESSAGE(msg);
}
struct AkumuliInitializer {
AkumuliInitializer() {
apr_initialize();
Akumuli::Logger::set_logger(&test_logger);
}
};
AkumuliInitializer initializer;
using namespace Akumuli;
using namespace Akumuli::StorageEngine;
static const std::vector<u32> CAPACITIES = { 8, 8 }; // two 64KB volumes
static const std::vector<std::string> VOLPATH = { "volume0", "volume1" };
static const std::string METAPATH = "metavolume";
static void create_blockstore() {
Volume::create_new(VOLPATH[0].c_str(), CAPACITIES[0]);
Volume::create_new(VOLPATH[1].c_str(), CAPACITIES[1]);
MetaVolume::create_new(METAPATH.c_str(), 2, CAPACITIES.data());
}
static std::shared_ptr<FixedSizeFileStorage> open_blockstore() {
auto bstore = FixedSizeFileStorage::open(METAPATH, VOLPATH);
return bstore;
}
static void delete_blockstore() {
apr_pool_t* pool;
apr_pool_create(&pool, nullptr);
apr_file_remove(METAPATH.c_str(), pool);
apr_file_remove(VOLPATH[0].c_str(), pool);
apr_file_remove(VOLPATH[1].c_str(), pool);
apr_pool_destroy(pool);
}
void test_nbtree_forward(const int N) {
delete_blockstore();
create_blockstore();
auto bstore = open_blockstore();
NBTree tree(42, bstore);
for (int i = 0; i < N; i++) {
tree.append(i, i*0.1);
}
NBTreeCursor cursor(tree, 0, N);
aku_Timestamp curr = 0ull;
bool first = true;
int index = 0;
while(!cursor.is_eof()) {
for (size_t ix = 0; ix < cursor.size(); ix++) {
aku_Timestamp ts;
double value;
aku_Status status;
std::tie(status, ts, value) = cursor.at(ix);
BOOST_REQUIRE(status == AKU_SUCCESS);
if (first) {
first = false;
curr = ts;
}
if (curr != ts) {
BOOST_FAIL("Invalid timestamp, expected: " << curr <<
" actual " << ts << " index " << index);
}
BOOST_REQUIRE_EQUAL(curr*0.1, value);
curr++;
index++;
}
cursor.proceed();
}
BOOST_REQUIRE_EQUAL(curr, N);
delete_blockstore();
}
BOOST_AUTO_TEST_CASE(Test_nbtree_forward_0) {
test_nbtree_forward(11);
}
BOOST_AUTO_TEST_CASE(Test_nbtree_forward_1) {
test_nbtree_forward(117);
}
BOOST_AUTO_TEST_CASE(Test_nbtree_forward_2) {
test_nbtree_forward(11771);
}
BOOST_AUTO_TEST_CASE(Test_nbtree_forward_3) {
test_nbtree_forward(100000);
}
void test_nbtree_roots_collection(u32 N) {
std::shared_ptr<BlockStore> bstore = BlockStoreBuilder::create_memstore();
std::vector<LogicAddr> addrlist; // should be empty at first
auto collection = std::make_shared<NBTreeRootsCollection>(42, addrlist, bstore);
for (u32 i = 0; i < N; i++) {
collection->append(i, 0.5*i);
}
// Read data back
std::vector<aku_Timestamp> ts(N, 0);
std::vector<double> xs(N, 0);
auto it = collection->search(0, N);
aku_Status status;
size_t sz;
std::tie(status, sz) = it->read(ts.data(), xs.data(), N);
BOOST_REQUIRE_EQUAL(sz, N);
BOOST_REQUIRE_EQUAL(status, AKU_SUCCESS);
for (u32 i = 0; i < N; i++) {
if (ts[i] != i) {
BOOST_FAIL("Invalid timestamp at " << i << ", actual: " << ts[i]);
}
if (xs[i] != 0.5*i) {
BOOST_FAIL("Invalid value at " << i << ", expected: " << (0.5*i) << ", actual: " << xs[i]);
}
}
}
BOOST_AUTO_TEST_CASE(Test_nbtree_rc_append_1) {
test_nbtree_roots_collection(100);
}
<commit_msg>WIP: nbtree iteration fail-case added<commit_after>#include <iostream>
#define BOOST_TEST_DYN_LINK
#define BOOST_TEST_MODULE Main
#include <boost/test/unit_test.hpp>
#include <apr.h>
#include "akumuli.h"
#include "storage_engine/blockstore.h"
#include "storage_engine/volume.h"
#include "storage_engine/nbtree.h"
#include "log_iface.h"
void test_logger(aku_LogLevel tag, const char* msg) {
BOOST_MESSAGE(msg);
}
struct AkumuliInitializer {
AkumuliInitializer() {
apr_initialize();
Akumuli::Logger::set_logger(&test_logger);
}
};
AkumuliInitializer initializer;
using namespace Akumuli;
using namespace Akumuli::StorageEngine;
static const std::vector<u32> CAPACITIES = { 8, 8 }; // two 64KB volumes
static const std::vector<std::string> VOLPATH = { "volume0", "volume1" };
static const std::string METAPATH = "metavolume";
static void create_blockstore() {
Volume::create_new(VOLPATH[0].c_str(), CAPACITIES[0]);
Volume::create_new(VOLPATH[1].c_str(), CAPACITIES[1]);
MetaVolume::create_new(METAPATH.c_str(), 2, CAPACITIES.data());
}
static std::shared_ptr<FixedSizeFileStorage> open_blockstore() {
auto bstore = FixedSizeFileStorage::open(METAPATH, VOLPATH);
return bstore;
}
static void delete_blockstore() {
apr_pool_t* pool;
apr_pool_create(&pool, nullptr);
apr_file_remove(METAPATH.c_str(), pool);
apr_file_remove(VOLPATH[0].c_str(), pool);
apr_file_remove(VOLPATH[1].c_str(), pool);
apr_pool_destroy(pool);
}
void test_nbtree_forward(const int N) {
delete_blockstore();
create_blockstore();
auto bstore = open_blockstore();
NBTree tree(42, bstore);
for (int i = 0; i < N; i++) {
tree.append(i, i*0.1);
}
NBTreeCursor cursor(tree, 0, N);
aku_Timestamp curr = 0ull;
bool first = true;
int index = 0;
while(!cursor.is_eof()) {
for (size_t ix = 0; ix < cursor.size(); ix++) {
aku_Timestamp ts;
double value;
aku_Status status;
std::tie(status, ts, value) = cursor.at(ix);
BOOST_REQUIRE(status == AKU_SUCCESS);
if (first) {
first = false;
curr = ts;
}
if (curr != ts) {
BOOST_FAIL("Invalid timestamp, expected: " << curr <<
" actual " << ts << " index " << index);
}
BOOST_REQUIRE_EQUAL(curr*0.1, value);
curr++;
index++;
}
cursor.proceed();
}
BOOST_REQUIRE_EQUAL(curr, N);
delete_blockstore();
}
BOOST_AUTO_TEST_CASE(Test_nbtree_forward_0) {
test_nbtree_forward(11);
}
BOOST_AUTO_TEST_CASE(Test_nbtree_forward_1) {
test_nbtree_forward(117);
}
BOOST_AUTO_TEST_CASE(Test_nbtree_forward_2) {
test_nbtree_forward(11771);
}
BOOST_AUTO_TEST_CASE(Test_nbtree_forward_3) {
test_nbtree_forward(100000);
}
void test_nbtree_roots_collection(u32 N) {
std::shared_ptr<BlockStore> bstore = BlockStoreBuilder::create_memstore();
std::vector<LogicAddr> addrlist; // should be empty at first
auto collection = std::make_shared<NBTreeRootsCollection>(42, addrlist, bstore);
for (u32 i = 0; i < N; i++) {
collection->append(i, 0.5*i);
}
// Read data back
std::vector<aku_Timestamp> ts(N, 0);
std::vector<double> xs(N, 0);
auto it = collection->search(0, N);
aku_Status status;
size_t sz;
std::tie(status, sz) = it->read(ts.data(), xs.data(), N);
BOOST_REQUIRE_EQUAL(sz, N);
BOOST_REQUIRE_EQUAL(status, AKU_SUCCESS);
for (u32 i = 0; i < N; i++) {
if (ts[i] != i) {
BOOST_FAIL("Invalid timestamp at " << i << ", actual: " << ts[i]);
}
if (xs[i] != 0.5*i) {
BOOST_FAIL("Invalid value at " << i << ", expected: " << (0.5*i) << ", actual: " << xs[i]);
}
}
}
BOOST_AUTO_TEST_CASE(Test_nbtree_rc_append_1) {
test_nbtree_roots_collection(100);
}
BOOST_AUTO_TEST_CASE(Test_nbtree_rc_append_2) {
test_nbtree_roots_collection(2000);
}
<|endoftext|>
|
<commit_before>#include <iostream>
#define BOOST_TEST_DYN_LINK
#define BOOST_TEST_MODULE Main
#include <boost/test/unit_test.hpp>
#include <apr.h>
#include "akumuli.h"
#include "storage_engine/blockstore.h"
#include "storage_engine/volume.h"
#include "storage_engine/nbtree.h"
#include "log_iface.h"
void test_logger(aku_LogLevel tag, const char* msg) {
BOOST_MESSAGE(msg);
}
struct AkumuliInitializer {
AkumuliInitializer() {
apr_initialize();
Akumuli::Logger::set_logger(&test_logger);
}
};
AkumuliInitializer initializer;
using namespace Akumuli;
using namespace Akumuli::StorageEngine;
enum class ScanDir {
FWD, BWD
};
void test_nbtree_roots_collection(u32 N, u32 begin, u32 end) {
ScanDir dir = begin < end ? ScanDir::FWD : ScanDir::BWD;
std::shared_ptr<BlockStore> bstore = BlockStoreBuilder::create_memstore();
std::vector<LogicAddr> addrlist; // should be empty at first
auto collection = std::make_shared<NBTreeRootsCollection>(42, addrlist, bstore);
for (u32 i = 0; i < N; i++) {
collection->append(i, 0.5*i);
}
// Read data back
std::unique_ptr<NBTreeIterator> it = collection->search(begin, end);
aku_Status status;
size_t sz;
size_t outsz = dir == ScanDir::FWD ? end - begin : begin - end;
std::vector<aku_Timestamp> ts(outsz, 0xF0F0F0F0);
std::vector<double> xs(outsz, -1);
std::tie(status, sz) = it->read(ts.data(), xs.data(), outsz);
BOOST_REQUIRE_EQUAL(sz, outsz);
BOOST_REQUIRE_EQUAL(status, AKU_SUCCESS);
if (dir == ScanDir::FWD) {
for (u32 i = 0; i < outsz; i++) {
const auto curr = i + begin;
if (ts[i] != curr) {
BOOST_FAIL("Invalid timestamp at " << i << ", expected: " << curr << ", actual: " << ts[i]);
}
if (xs[i] != 0.5*curr) {
BOOST_FAIL("Invalid value at " << i << ", expected: " << (0.5*curr) << ", actual: " << xs[i]);
}
}
} else {
for (u32 i = 0; i < outsz; i++) {
const auto curr = begin - i;
if (ts[i] != curr) {
BOOST_FAIL("Invalid timestamp at " << i << ", expected: " << curr << ", actual: " << ts[i]);
}
if (xs[i] != 0.5*curr) {
BOOST_FAIL("Invalid value at " << i << ", expected: " << (0.5*curr) << ", actual: " << xs[i]);
}
}
}
}
BOOST_AUTO_TEST_CASE(Test_nbtree_rc_append_1) {
test_nbtree_roots_collection(100, 0, 100);
}
BOOST_AUTO_TEST_CASE(Test_nbtree_rc_append_2) {
test_nbtree_roots_collection(2000, 0, 2000);
}
BOOST_AUTO_TEST_CASE(Test_nbtree_rc_append_3) {
test_nbtree_roots_collection(200000, 0, 200000);
}
BOOST_AUTO_TEST_CASE(Test_nbtree_rc_append_4) {
test_nbtree_roots_collection(100, 99, 0);
}
BOOST_AUTO_TEST_CASE(Test_nbtree_rc_append_5) {
test_nbtree_roots_collection(2000, 1999, 0);
}
BOOST_AUTO_TEST_CASE(Test_nbtree_rc_append_6) {
test_nbtree_roots_collection(200000, 199999, 0);
}
BOOST_AUTO_TEST_CASE(Test_nbtree_rc_append_rand_read) {
for (int i = 0; i < 100; i++) {
auto N = rand() % 200000;
auto from = rand() % N;
auto to = rand() % N;
test_nbtree_roots_collection(N, from, to);
}
}
// TODO: check crash-recovery
void test_nbtree_chunked_read(u32 N, u32 begin, u32 end, u32 chunk_size) {
ScanDir dir = begin < end ? ScanDir::FWD : ScanDir::BWD;
std::shared_ptr<BlockStore> bstore = BlockStoreBuilder::create_memstore();
std::vector<LogicAddr> addrlist; // should be empty at first
auto collection = std::make_shared<NBTreeRootsCollection>(42, addrlist, bstore);
for (u32 i = 0; i < N; i++) {
collection->append(i, i);
}
// Read data back
std::unique_ptr<NBTreeIterator> it = collection->search(begin, end);
aku_Status status;
size_t sz;
std::vector<aku_Timestamp> ts(chunk_size, 0xF0F0F0F0);
std::vector<double> xs(chunk_size, -1);
u32 total_size = 0u;
aku_Timestamp ts_seen = begin;
while(true) {
std::tie(status, sz) = it->read(ts.data(), xs.data(), chunk_size);
if (sz == 0 && status != AKU_ENO_DATA) {
BOOST_FAIL("Invalid iterator output, sz=0, status=" << status);
}
total_size += sz;
BOOST_REQUIRE(status == AKU_SUCCESS || status == AKU_ENO_DATA);
if (dir == ScanDir::FWD) {
for (u32 i = 0; i < sz; i++) {
const auto curr = ts_seen + i;
if (ts[i] != curr) {
BOOST_FAIL("Invalid timestamp at " << i << ", expected: " << curr << ", actual: " << ts[i]);
}
if (xs[i] != curr) {
BOOST_FAIL("Invalid value at " << i << ", expected: " << curr << ", actual: " << xs[i]);
}
}
ts_seen += sz;
} else {
for (u32 i = 0; i < sz; i++) {
const auto curr = ts_seen - i;
if (ts[i] != curr) {
BOOST_FAIL("Invalid timestamp at " << i << ", expected: " << curr << ", actual: " << ts[i]);
}
if (xs[i] != curr) {
BOOST_FAIL("Invalid value at " << i << ", expected: " << curr << ", actual: " << xs[i]);
}
}
ts_seen -= sz;
}
if (status == AKU_ENO_DATA || ts_seen == end) {
break;
}
}
if (ts_seen != end) {
BOOST_FAIL("Bad range, expected: " << end << ", actual: " << ts_seen);
}
size_t outsz = dir == ScanDir::FWD ? end - begin : begin - end;
BOOST_REQUIRE_EQUAL(total_size, outsz);
}
BOOST_AUTO_TEST_CASE(Test_nbtree_chunked_read) {
for (u32 i = 0; i < 100; i++) {
auto N = static_cast<u32>(rand() % 200000);
auto from = static_cast<u32>(rand()) % N;
auto to = static_cast<u32>(rand()) % N;
auto chunk = static_cast<u32>(rand()) % N;
test_nbtree_chunked_read(N, from, to, chunk);
}
}
void test_reopen_storage(u32 N) {
std::shared_ptr<BlockStore> bstore = BlockStoreBuilder::create_memstore();
std::vector<LogicAddr> addrlist; // should be empty at first
auto collection = std::make_shared<NBTreeRootsCollection>(42, addrlist, bstore);
for (u32 i = 0; i < N; i++) {
if (collection->append(i, i)) {
// addrlist changed
auto newroots = collection->get_roots();
if (newroots == addrlist) {
BOOST_FAIL("Roots collection must change");
}
std::swap(newroots, addrlist);
}
}
addrlist = collection->close();
// TODO: check attempt to open tree using wrong id!
collection = std::make_shared<NBTreeRootsCollection>(42, addrlist, bstore);
std::unique_ptr<NBTreeIterator> it = collection->search(0, N);
std::vector<aku_Timestamp> ts(N, 0);
std::vector<double> xs(N, 0);
aku_Status status = AKU_SUCCESS;
size_t sz = 0;
std::tie(status, sz) = it->read(ts.data(), xs.data(), N);
BOOST_REQUIRE(sz == N);
BOOST_REQUIRE(status == AKU_SUCCESS);
for (u32 i = 0; i < N; i++) {
if (ts[i] != i) {
BOOST_FAIL("Invalid timestamp at " << i);
}
if (xs[i] != static_cast<double>(i)) {
BOOST_FAIL("Invalid timestamp at " << i);
}
}
}
BOOST_AUTO_TEST_CASE(Test_nbtree_reopen_1) {
test_reopen_storage(100);
}
BOOST_AUTO_TEST_CASE(Test_nbtree_reopen_2) {
test_reopen_storage(2000);
}
BOOST_AUTO_TEST_CASE(Test_nbtree_reopen_3) {
test_reopen_storage(200000);
}
//! Reopen storage that has been closed without final commit.
void test_storage_recovery(u32 N) {
std::shared_ptr<BlockStore> bstore = BlockStoreBuilder::create_memstore();
std::vector<LogicAddr> addrlist; // should be empty at first
auto collection = std::make_shared<NBTreeRootsCollection>(42, addrlist, bstore);
for (u32 i = 0; i < N; i++) {
if (collection->append(i, i)) {
// addrlist changed
auto newroots = collection->get_roots();
if (newroots == addrlist) {
BOOST_FAIL("Roots collection must change");
}
std::swap(newroots, addrlist);
}
}
addrlist = collection->get_roots();
// delete roots collection
collection.reset();
// TODO: check attempt to open tree using wrong id!
collection = std::make_shared<NBTreeRootsCollection>(42, addrlist, bstore);
std::unique_ptr<NBTreeIterator> it = collection->search(0, N);
std::vector<aku_Timestamp> ts(N, 0);
std::vector<double> xs(N, 0);
aku_Status status = AKU_SUCCESS;
size_t sz = 0;
std::tie(status, sz) = it->read(ts.data(), xs.data(), N);
if (addrlist.empty()) {
// Expect zero, data was stored in single leaf-node.
BOOST_REQUIRE(sz == 0);
} else {
// `sz` value can't be equal to N because some data should be lost!
BOOST_REQUIRE(sz < N);
}
BOOST_REQUIRE(status == AKU_SUCCESS);
for (u32 i = 0; i < sz; i++) {
if (ts[i] != i) {
BOOST_FAIL("Invalid timestamp at " << i);
}
if (xs[i] != static_cast<double>(i)) {
BOOST_FAIL("Invalid timestamp at " << i);
}
}
}
BOOST_AUTO_TEST_CASE(Test_nbtree_recovery_1) {
test_storage_recovery(100);
}
BOOST_AUTO_TEST_CASE(Test_nbtree_recovery_2) {
test_storage_recovery(2000);
}
<commit_msg>Fixed error in test<commit_after>#include <iostream>
#define BOOST_TEST_DYN_LINK
#define BOOST_TEST_MODULE Main
#include <boost/test/unit_test.hpp>
#include <apr.h>
#include "akumuli.h"
#include "storage_engine/blockstore.h"
#include "storage_engine/volume.h"
#include "storage_engine/nbtree.h"
#include "log_iface.h"
void test_logger(aku_LogLevel tag, const char* msg) {
BOOST_MESSAGE(msg);
}
struct AkumuliInitializer {
AkumuliInitializer() {
apr_initialize();
Akumuli::Logger::set_logger(&test_logger);
}
};
AkumuliInitializer initializer;
using namespace Akumuli;
using namespace Akumuli::StorageEngine;
enum class ScanDir {
FWD, BWD
};
void test_nbtree_roots_collection(u32 N, u32 begin, u32 end) {
ScanDir dir = begin < end ? ScanDir::FWD : ScanDir::BWD;
std::shared_ptr<BlockStore> bstore = BlockStoreBuilder::create_memstore();
std::vector<LogicAddr> addrlist; // should be empty at first
auto collection = std::make_shared<NBTreeRootsCollection>(42, addrlist, bstore);
for (u32 i = 0; i < N; i++) {
collection->append(i, 0.5*i);
}
// Read data back
std::unique_ptr<NBTreeIterator> it = collection->search(begin, end);
aku_Status status;
size_t sz;
size_t outsz = dir == ScanDir::FWD ? end - begin : begin - end;
std::vector<aku_Timestamp> ts(outsz, 0xF0F0F0F0);
std::vector<double> xs(outsz, -1);
std::tie(status, sz) = it->read(ts.data(), xs.data(), outsz);
BOOST_REQUIRE_EQUAL(sz, outsz);
BOOST_REQUIRE_EQUAL(status, AKU_SUCCESS);
if (dir == ScanDir::FWD) {
for (u32 i = 0; i < outsz; i++) {
const auto curr = i + begin;
if (ts[i] != curr) {
BOOST_FAIL("Invalid timestamp at " << i << ", expected: " << curr << ", actual: " << ts[i]);
}
if (xs[i] != 0.5*curr) {
BOOST_FAIL("Invalid value at " << i << ", expected: " << (0.5*curr) << ", actual: " << xs[i]);
}
}
} else {
for (u32 i = 0; i < outsz; i++) {
const auto curr = begin - i;
if (ts[i] != curr) {
BOOST_FAIL("Invalid timestamp at " << i << ", expected: " << curr << ", actual: " << ts[i]);
}
if (xs[i] != 0.5*curr) {
BOOST_FAIL("Invalid value at " << i << ", expected: " << (0.5*curr) << ", actual: " << xs[i]);
}
}
}
}
BOOST_AUTO_TEST_CASE(Test_nbtree_rc_append_1) {
test_nbtree_roots_collection(100, 0, 100);
}
BOOST_AUTO_TEST_CASE(Test_nbtree_rc_append_2) {
test_nbtree_roots_collection(2000, 0, 2000);
}
BOOST_AUTO_TEST_CASE(Test_nbtree_rc_append_3) {
test_nbtree_roots_collection(200000, 0, 200000);
}
BOOST_AUTO_TEST_CASE(Test_nbtree_rc_append_4) {
test_nbtree_roots_collection(100, 99, 0);
}
BOOST_AUTO_TEST_CASE(Test_nbtree_rc_append_5) {
test_nbtree_roots_collection(2000, 1999, 0);
}
BOOST_AUTO_TEST_CASE(Test_nbtree_rc_append_6) {
test_nbtree_roots_collection(200000, 199999, 0);
}
BOOST_AUTO_TEST_CASE(Test_nbtree_rc_append_rand_read) {
for (int i = 0; i < 100; i++) {
auto N = rand() % 200000;
auto from = rand() % N;
auto to = rand() % N;
test_nbtree_roots_collection(N, from, to);
}
}
// TODO: check crash-recovery
void test_nbtree_chunked_read(u32 N, u32 begin, u32 end, u32 chunk_size) {
ScanDir dir = begin < end ? ScanDir::FWD : ScanDir::BWD;
std::shared_ptr<BlockStore> bstore = BlockStoreBuilder::create_memstore();
std::vector<LogicAddr> addrlist; // should be empty at first
auto collection = std::make_shared<NBTreeRootsCollection>(42, addrlist, bstore);
for (u32 i = 0; i < N; i++) {
collection->append(i, i);
}
// Read data back
std::unique_ptr<NBTreeIterator> it = collection->search(begin, end);
aku_Status status;
size_t sz;
std::vector<aku_Timestamp> ts(chunk_size, 0xF0F0F0F0);
std::vector<double> xs(chunk_size, -1);
u32 total_size = 0u;
aku_Timestamp ts_seen = begin;
while(true) {
std::tie(status, sz) = it->read(ts.data(), xs.data(), chunk_size);
if (sz == 0 && status != AKU_ENO_DATA) {
BOOST_FAIL("Invalid iterator output, sz=0, status=" << status);
}
total_size += sz;
BOOST_REQUIRE(status == AKU_SUCCESS || status == AKU_ENO_DATA);
if (dir == ScanDir::FWD) {
for (u32 i = 0; i < sz; i++) {
const auto curr = ts_seen + i;
if (ts[i] != curr) {
BOOST_FAIL("Invalid timestamp at " << i << ", expected: " << curr << ", actual: " << ts[i]);
}
if (xs[i] != curr) {
BOOST_FAIL("Invalid value at " << i << ", expected: " << curr << ", actual: " << xs[i]);
}
}
ts_seen += sz;
} else {
for (u32 i = 0; i < sz; i++) {
const auto curr = ts_seen - i;
if (ts[i] != curr) {
BOOST_FAIL("Invalid timestamp at " << i << ", expected: " << curr << ", actual: " << ts[i]);
}
if (xs[i] != curr) {
BOOST_FAIL("Invalid value at " << i << ", expected: " << curr << ", actual: " << xs[i]);
}
}
ts_seen -= sz;
}
if (status == AKU_ENO_DATA || ts_seen == end) {
break;
}
}
if (ts_seen != end) {
BOOST_FAIL("Bad range, expected: " << end << ", actual: " << ts_seen);
}
size_t outsz = dir == ScanDir::FWD ? end - begin : begin - end;
BOOST_REQUIRE_EQUAL(total_size, outsz);
}
BOOST_AUTO_TEST_CASE(Test_nbtree_chunked_read) {
for (u32 i = 0; i < 100; i++) {
auto N = static_cast<u32>(rand() % 200000);
auto from = static_cast<u32>(rand()) % N;
auto to = static_cast<u32>(rand()) % N;
auto chunk = static_cast<u32>(rand()) % N;
test_nbtree_chunked_read(N, from, to, chunk);
}
}
void test_reopen_storage(u32 N) {
std::shared_ptr<BlockStore> bstore = BlockStoreBuilder::create_memstore();
std::vector<LogicAddr> addrlist; // should be empty at first
auto collection = std::make_shared<NBTreeRootsCollection>(42, addrlist, bstore);
for (u32 i = 0; i < N; i++) {
if (collection->append(i, i)) {
// addrlist changed
auto newroots = collection->get_roots();
if (newroots == addrlist) {
BOOST_FAIL("Roots collection must change");
}
std::swap(newroots, addrlist);
}
}
addrlist = collection->close();
// TODO: check attempt to open tree using wrong id!
collection = std::make_shared<NBTreeRootsCollection>(42, addrlist, bstore);
std::unique_ptr<NBTreeIterator> it = collection->search(0, N);
std::vector<aku_Timestamp> ts(N, 0);
std::vector<double> xs(N, 0);
aku_Status status = AKU_SUCCESS;
size_t sz = 0;
std::tie(status, sz) = it->read(ts.data(), xs.data(), N);
BOOST_REQUIRE(sz == N);
BOOST_REQUIRE(status == AKU_SUCCESS);
for (u32 i = 0; i < N; i++) {
if (ts[i] != i) {
BOOST_FAIL("Invalid timestamp at " << i);
}
if (xs[i] != static_cast<double>(i)) {
BOOST_FAIL("Invalid timestamp at " << i);
}
}
}
BOOST_AUTO_TEST_CASE(Test_nbtree_reopen_1) {
test_reopen_storage(100);
}
BOOST_AUTO_TEST_CASE(Test_nbtree_reopen_2) {
test_reopen_storage(2000);
}
BOOST_AUTO_TEST_CASE(Test_nbtree_reopen_3) {
test_reopen_storage(200000);
}
//! Reopen storage that has been closed without final commit.
void test_storage_recovery(u32 N) {
std::shared_ptr<BlockStore> bstore = BlockStoreBuilder::create_memstore();
std::vector<LogicAddr> addrlist; // should be empty at first
auto collection = std::make_shared<NBTreeRootsCollection>(42, addrlist, bstore);
for (u32 i = 0; i < N; i++) {
if (collection->append(i, i)) {
// addrlist changed
auto newroots = collection->get_roots();
if (newroots == addrlist) {
BOOST_FAIL("Roots collection must change");
}
std::swap(newroots, addrlist);
}
}
addrlist = collection->get_roots();
// delete roots collection
collection.reset();
// TODO: check attempt to open tree using wrong id!
collection = std::make_shared<NBTreeRootsCollection>(42, addrlist, bstore);
std::unique_ptr<NBTreeIterator> it = collection->search(0, N);
std::vector<aku_Timestamp> ts(N, 0);
std::vector<double> xs(N, 0);
aku_Status status = AKU_SUCCESS;
size_t sz = 0;
std::tie(status, sz) = it->read(ts.data(), xs.data(), N);
if (addrlist.empty()) {
// Expect zero, data was stored in single leaf-node.
BOOST_REQUIRE(sz == 0);
} else {
// `sz` value can't be equal to N because some data should be lost!
BOOST_REQUIRE(sz < N);
}
// Note: `status` should be equal to AKU_SUCCESS if size of the destination
// is equal to array's length. Otherwise iterator should return AKU_ENO_DATA
// as an indication that all data-elements have ben read.
BOOST_REQUIRE(status == AKU_ENO_DATA || status == AKU_SUCCESS);
for (u32 i = 0; i < sz; i++) {
if (ts[i] != i) {
BOOST_FAIL("Invalid timestamp at " << i);
}
if (xs[i] != static_cast<double>(i)) {
BOOST_FAIL("Invalid timestamp at " << i);
}
}
}
BOOST_AUTO_TEST_CASE(Test_nbtree_recovery_1) {
test_storage_recovery(100);
}
BOOST_AUTO_TEST_CASE(Test_nbtree_recovery_2) {
test_storage_recovery(2000);
}
BOOST_AUTO_TEST_CASE(Test_nbtree_recovery_3) {
test_storage_recovery(200000);
}
<|endoftext|>
|
<commit_before>#ifndef __AJOKKI_CONSOLE_CALLBACKS_HPP_INCLUDED
#define __AJOKKI_CONSOLE_CALLBACKS_HPP_INCLUDED
#include "code/ylikuutio/console/command_and_callback_struct.hpp"
#include "code/ylikuutio/common/globals.hpp"
// Include standard headers
#include <string> // std::string
#include <vector> // std::vector
namespace ajokki
{
datatypes::AnyValue* version(
console::Console*,
std::vector<std::string>& command_parameters);
datatypes::AnyValue* quit(
console::Console*,
std::vector<std::string>& command_parameters);
}
#endif
<commit_msg>Console command callbacks `version` & `quit`: `ontology::Universe*`.<commit_after>#ifndef __AJOKKI_CONSOLE_CALLBACKS_HPP_INCLUDED
#define __AJOKKI_CONSOLE_CALLBACKS_HPP_INCLUDED
#include "code/ylikuutio/console/command_and_callback_struct.hpp"
#include "code/ylikuutio/common/globals.hpp"
// Include standard headers
#include <string> // std::string
#include <vector> // std::vector
namespace ajokki
{
datatypes::AnyValue* version(
console::Console*,
ontology::Universe*,
std::vector<std::string>& command_parameters);
datatypes::AnyValue* quit(
console::Console*,
ontology::Universe*,
std::vector<std::string>& command_parameters);
}
#endif
<|endoftext|>
|
<commit_before>#include "ffmpeg_video_source.h"
extern "C" {
#include <libavutil/imgutils.h>
#include <libavutil/timestamp.h>
}
namespace gg
{
VideoSourceFFmpeg::VideoSourceFFmpeg()
{
// nop
}
VideoSourceFFmpeg::VideoSourceFFmpeg(std::string source_path,
enum ColourSpace colour_space)
: IVideoSource(colour_space)
, src_filename(nullptr)
, fmt_ctx(nullptr)
, video_stream_idx(-1)
, refcount(0)
, video_stream(nullptr)
, video_dec_ctx(nullptr)
, frame(nullptr)
, video_frame_count(0)
, _data(nullptr)
, _data_length(0)
{
int ret = 0;
std::string error_msg = "";
src_filename = const_cast<char *>(source_path.c_str());
av_register_all();
if (avformat_open_input(&fmt_ctx, src_filename, nullptr, nullptr) < 0)
{
error_msg.append("Could not open video source ")
.append(source_path);
throw VideoSourceError(error_msg);
}
if (avformat_find_stream_info(fmt_ctx, nullptr) < 0)
throw VideoSourceError("Could not find stream information");
if (open_codec_context(&video_stream_idx, fmt_ctx,
AVMEDIA_TYPE_VIDEO, error_msg) >= 0)
{
video_stream = fmt_ctx->streams[video_stream_idx];
video_dec_ctx = video_stream->codec;
/* allocate image where the decoded image will be put */
width = video_dec_ctx->width;
height = video_dec_ctx->height;
pix_fmt = video_dec_ctx->pix_fmt;
ret = av_image_alloc(video_dst_data, video_dst_linesize,
width, height, pix_fmt, 1);
if (ret < 0)
throw VideoSourceError("Could not allocate"
" raw video buffer");
video_dst_bufsize = ret;
}
else
throw VideoSourceError(error_msg);
// TODO
av_dump_format(fmt_ctx, 0, src_filename, 0);
if (video_stream == nullptr)
throw VideoSourceError("Could not find video stream in source");
frame = av_frame_alloc();
if (frame == nullptr)
throw VideoSourceError("Could not allocate frame");
/* initialize packet, set data to NULL, let the demuxer fill it */
av_init_packet(&pkt);
pkt.data = nullptr;
pkt.size = 0;
}
VideoSourceFFmpeg::~VideoSourceFFmpeg()
{
// TODO
}
bool VideoSourceFFmpeg::get_frame_dimensions(int & width, int & height)
{
// TODO
return false;
}
bool VideoSourceFFmpeg::get_frame(VideoFrame & frame)
{
// TODO
return false;
}
double VideoSourceFFmpeg::get_frame_rate()
{
// TODO
return 0.0;
}
void VideoSourceFFmpeg::set_sub_frame(int x, int y, int width, int height)
{
// TODO
}
void VideoSourceFFmpeg::get_full_frame()
{
// TODO
}
int VideoSourceFFmpeg::open_codec_context(
int * stream_idx, AVFormatContext * fmt_ctx,
enum AVMediaType type, std::string & error_msg)
{
// TODO
return -1;
}
}
<commit_msg>Issue #74: implemented VideoSourceFFmpeg destructor<commit_after>#include "ffmpeg_video_source.h"
extern "C" {
#include <libavutil/imgutils.h>
#include <libavutil/timestamp.h>
}
namespace gg
{
VideoSourceFFmpeg::VideoSourceFFmpeg()
{
// nop
}
VideoSourceFFmpeg::VideoSourceFFmpeg(std::string source_path,
enum ColourSpace colour_space)
: IVideoSource(colour_space)
, src_filename(nullptr)
, fmt_ctx(nullptr)
, video_stream_idx(-1)
, refcount(0)
, video_stream(nullptr)
, video_dec_ctx(nullptr)
, frame(nullptr)
, video_frame_count(0)
, _data(nullptr)
, _data_length(0)
{
int ret = 0;
std::string error_msg = "";
src_filename = const_cast<char *>(source_path.c_str());
av_register_all();
if (avformat_open_input(&fmt_ctx, src_filename, nullptr, nullptr) < 0)
{
error_msg.append("Could not open video source ")
.append(source_path);
throw VideoSourceError(error_msg);
}
if (avformat_find_stream_info(fmt_ctx, nullptr) < 0)
throw VideoSourceError("Could not find stream information");
if (open_codec_context(&video_stream_idx, fmt_ctx,
AVMEDIA_TYPE_VIDEO, error_msg) >= 0)
{
video_stream = fmt_ctx->streams[video_stream_idx];
video_dec_ctx = video_stream->codec;
/* allocate image where the decoded image will be put */
width = video_dec_ctx->width;
height = video_dec_ctx->height;
pix_fmt = video_dec_ctx->pix_fmt;
ret = av_image_alloc(video_dst_data, video_dst_linesize,
width, height, pix_fmt, 1);
if (ret < 0)
throw VideoSourceError("Could not allocate"
" raw video buffer");
video_dst_bufsize = ret;
}
else
throw VideoSourceError(error_msg);
// TODO
av_dump_format(fmt_ctx, 0, src_filename, 0);
if (video_stream == nullptr)
throw VideoSourceError("Could not find video stream in source");
frame = av_frame_alloc();
if (frame == nullptr)
throw VideoSourceError("Could not allocate frame");
/* initialize packet, set data to NULL, let the demuxer fill it */
av_init_packet(&pkt);
pkt.data = nullptr;
pkt.size = 0;
}
VideoSourceFFmpeg::~VideoSourceFFmpeg()
{
// TODO: is this part needed?
int got_frame;
/* flush cached frames */
pkt.data = nullptr;
pkt.size = 0;
std::string error_msg = "";
do
decode_packet(&got_frame, 1, error_msg);
while (got_frame);
avcodec_close(video_dec_ctx);
avformat_close_input(&fmt_ctx);
av_frame_free(&frame);
av_free(video_dst_data[0]);
if (_data_length > 0)
{
free(_data);
_data_length = 0;
}
}
bool VideoSourceFFmpeg::get_frame_dimensions(int & width, int & height)
{
// TODO
return false;
}
bool VideoSourceFFmpeg::get_frame(VideoFrame & frame)
{
// TODO
return false;
}
double VideoSourceFFmpeg::get_frame_rate()
{
// TODO
return 0.0;
}
void VideoSourceFFmpeg::set_sub_frame(int x, int y, int width, int height)
{
// TODO
}
void VideoSourceFFmpeg::get_full_frame()
{
// TODO
}
int VideoSourceFFmpeg::open_codec_context(
int * stream_idx, AVFormatContext * fmt_ctx,
enum AVMediaType type, std::string & error_msg)
{
// TODO
return -1;
}
}
<|endoftext|>
|
<commit_before>/**
* @copyright
* ========================================================================
* Copyright FLWOR Foundation
* ========================================================================
*
* @author Sorin Nasoi ([email protected])
* @file misc/MiscImpl.cpp
*
*/
#include <vector>
#include "system/globalenv.h"
#include "runtime/nodes/NodesImpl.h"
#include "store/api/item_factory.h"
#include "runtime/context/ContextImpl.h"
#include "runtime/api/runtimecb.h"
#include "context/dynamic_context.h"
#include "store/api/store.h"
#include "store/api/collection.h"
#include "store/api/iterator.h"
using namespace std;
namespace zorba {
// 14.2 fn:local-name
//---------------------
store::Item_t FnLocalNameIterator::nextImpl(PlanState& planState) const
{
store::Item_t inNode;
xqp_string strRes = "";
PlanIteratorState *state;
DEFAULT_STACK_INIT(PlanIteratorState, state, planState);
inNode = consumeNext(theChildren[0].getp(), planState);
if (inNode != NULL)
{
if (inNode->getNodeKind() == store::StoreConsts::elementNode)
STACK_PUSH(GENV_ITEMFACTORY->createString(inNode->getNodeName()->getLocalName().getStore()), state);
}
else
STACK_PUSH(GENV_ITEMFACTORY->createString(strRes.getStore()), state);
STACK_END (state);
}
// 14.3 fn:namespace-uri
//---------------------
store::Item_t FnNamespaceUriIterator::nextImpl(PlanState& planState) const
{
store::Item_t inNode;
PlanIteratorState *state;
DEFAULT_STACK_INIT(PlanIteratorState, state, planState);
inNode = consumeNext(theChildren[0].getp(), planState);
if (inNode != NULL)
STACK_PUSH(GENV_ITEMFACTORY->createAnyURI(inNode->getNamespace().getStore()), state);
STACK_END (state);
}
// 14.5 fn:lang
//---------------------
store::Item_t FnLangIterator::nextImpl(PlanState& planState) const
{
//TODO the store does not implement support for the languages
PlanIteratorState *state;
DEFAULT_STACK_INIT(PlanIteratorState, state, planState);
STACK_END (state);
}
// 15.5.6 fn:collection
//---------------------
void
FnCollectionIteratorState::init(PlanState& planState)
{
PlanIteratorState::init(planState);
theIterator = NULL;
}
void
FnCollectionIteratorState::reset(PlanState& planState)
{
PlanIteratorState::reset(planState);
theIterator = NULL;
}
store::Item_t FnCollectionIterator::nextImpl(PlanState& planState) const
{
store::Item_t itemArg;
store::Item_t itemColl;
xqp_string uri;
store::Collection_t theColl;
FnCollectionIteratorState *state;
DEFAULT_STACK_INIT(FnCollectionIteratorState, state, planState);
itemArg = consumeNext(theChildren[0].getp(), planState);
if (itemArg != NULL)
uri = itemArg->getStringValue().getp();
else
{
uri = planState.theRuntimeCB->theDynamicContext->get_default_collection();
if(uri.empty())
ZORBA_ERROR_LOC_DESC(ZorbaError::FODC0002, loc,
"Default collection is undefined in the dynamic context.");
}
theColl = GENV_STORE.getCollection(uri.getStore());
if(theColl == NULL)
ZORBA_ERROR_LOC_DESC(ZorbaError::FODC0004, loc,
"Invalid argument to fn:collection.");
state->theIterator = theColl->getIterator(false);
while((itemColl = state->theIterator->next()) != NULL )
STACK_PUSH (itemColl, state);
STACK_END (state);
}
} /* namespace zorba */
<commit_msg>Solved an error in the fn:namespace-uri().<commit_after>/**
* @copyright
* ========================================================================
* Copyright FLWOR Foundation
* ========================================================================
*
* @author Sorin Nasoi ([email protected])
* @file misc/MiscImpl.cpp
*
*/
#include <vector>
#include "system/globalenv.h"
#include "runtime/nodes/NodesImpl.h"
#include "store/api/item_factory.h"
#include "runtime/context/ContextImpl.h"
#include "runtime/api/runtimecb.h"
#include "context/dynamic_context.h"
#include "store/api/store.h"
#include "store/api/collection.h"
#include "store/api/iterator.h"
using namespace std;
namespace zorba {
// 14.2 fn:local-name
//---------------------
store::Item_t FnLocalNameIterator::nextImpl(PlanState& planState) const
{
store::Item_t inNode;
xqp_string strRes = "";
PlanIteratorState *state;
DEFAULT_STACK_INIT(PlanIteratorState, state, planState);
inNode = consumeNext(theChildren[0].getp(), planState);
if (inNode != NULL)
{
if (inNode->getNodeKind() == store::StoreConsts::elementNode)
STACK_PUSH(GENV_ITEMFACTORY->createString(inNode->getNodeName()->getLocalName().getStore()), state);
}
else
STACK_PUSH(GENV_ITEMFACTORY->createString(strRes.getStore()), state);
STACK_END (state);
}
// 14.3 fn:namespace-uri
//---------------------
store::Item_t FnNamespaceUriIterator::nextImpl(PlanState& planState) const
{
store::Item_t inNode;
PlanIteratorState *state;
DEFAULT_STACK_INIT(PlanIteratorState, state, planState);
inNode = consumeNext(theChildren[0].getp(), planState);
if (inNode != NULL)
{
if(inNode->getNodeKind() == store::StoreConsts::elementNode ||
inNode->getNodeKind() == store::StoreConsts::attributeNode)
STACK_PUSH(GENV_ITEMFACTORY->createAnyURI(inNode->getNodeName()->getNamespace().getStore()), state);
else
STACK_PUSH(GENV_ITEMFACTORY->createAnyURI(xqp_string().getStore()), state);
}
STACK_END (state);
}
// 14.5 fn:lang
//---------------------
store::Item_t FnLangIterator::nextImpl(PlanState& planState) const
{
//TODO the store does not implement support for the languages
PlanIteratorState *state;
DEFAULT_STACK_INIT(PlanIteratorState, state, planState);
STACK_END (state);
}
// 15.5.6 fn:collection
//---------------------
void
FnCollectionIteratorState::init(PlanState& planState)
{
PlanIteratorState::init(planState);
theIterator = NULL;
}
void
FnCollectionIteratorState::reset(PlanState& planState)
{
PlanIteratorState::reset(planState);
theIterator = NULL;
}
store::Item_t FnCollectionIterator::nextImpl(PlanState& planState) const
{
store::Item_t itemArg;
store::Item_t itemColl;
xqp_string uri;
store::Collection_t theColl;
FnCollectionIteratorState *state;
DEFAULT_STACK_INIT(FnCollectionIteratorState, state, planState);
itemArg = consumeNext(theChildren[0].getp(), planState);
if (itemArg != NULL)
uri = itemArg->getStringValue().getp();
else
{
uri = planState.theRuntimeCB->theDynamicContext->get_default_collection();
if(uri.empty())
ZORBA_ERROR_LOC_DESC(ZorbaError::FODC0002, loc,
"Default collection is undefined in the dynamic context.");
}
theColl = GENV_STORE.getCollection(uri.getStore());
if(theColl == NULL)
ZORBA_ERROR_LOC_DESC(ZorbaError::FODC0004, loc,
"Invalid argument to fn:collection.");
state->theIterator = theColl->getIterator(false);
while((itemColl = state->theIterator->next()) != NULL )
STACK_PUSH (itemColl, state);
STACK_END (state);
}
} /* namespace zorba */
<|endoftext|>
|
<commit_before>/*
* Copyright (c) 2010-2012 OTClient <https://github.com/edubart/otclient>
*
* 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 "uiwidget.h"
#include <framework/graphics/painter.h>
#include <framework/graphics/texture.h>
#include <framework/graphics/texturemanager.h>
#include <framework/graphics/graphics.h>
void UIWidget::initImage()
{
m_imageCoordsBuffer.enableHardwareCaching();
}
void UIWidget::parseImageStyle(const OTMLNodePtr& styleNode)
{
for(const OTMLNodePtr& node : styleNode->children()) {
if(node->tag() == "image-source")
setImageSource(stdext::resolve_path(node->value(), node->source()));
else if(node->tag() == "image-offset-x")
setImageOffsetX(node->value<int>());
else if(node->tag() == "image-offset-y")
setImageOffsetY(node->value<int>());
else if(node->tag() == "image-offset")
setImageOffset(node->value<Point>());
else if(node->tag() == "image-width")
setImageWidth(node->value<int>());
else if(node->tag() == "image-height")
setImageHeight(node->value<int>());
else if(node->tag() == "image-size")
setImageSize(node->value<Size>());
else if(node->tag() == "image-rect")
setImageRect(node->value<Rect>());
else if(node->tag() == "image-clip")
setImageClip(node->value<Rect>());
else if(node->tag() == "image-fixed-ratio")
setImageFixedRatio(node->value<bool>());
else if(node->tag() == "image-repeated")
setImageRepeated(node->value<bool>());
else if(node->tag() == "image-smooth")
setImageSmooth(node->value<bool>());
else if(node->tag() == "image-color")
setImageColor(node->value<Color>());
else if(node->tag() == "image-border-top")
setImageBorderTop(node->value<int>());
else if(node->tag() == "image-border-right")
setImageBorderRight(node->value<int>());
else if(node->tag() == "image-border-bottom")
setImageBorderBottom(node->value<int>());
else if(node->tag() == "image-border-left")
setImageBorderLeft(node->value<int>());
else if(node->tag() == "image-border") {
setImageBorder(node->value<int>());
}
}
}
void UIWidget::drawImage(const Rect& screenCoords)
{
if(!m_imageTexture || !screenCoords.isValid())
return;
// cache vertex buffers
if(m_imageCachedScreenCoords != screenCoords || m_imageMustRecache) {
m_imageCoordsBuffer.clear();
m_imageCachedScreenCoords = screenCoords;
m_imageMustRecache = false;
Rect drawRect = screenCoords;
drawRect.translate(m_imageRect.topLeft());
if(m_imageRect.isValid())
drawRect.resize(m_imageRect.size());
if(!m_imageBordered) {
if(m_imageFixedRatio) {
Size textureSize = m_imageTexture->getSize();
Size textureClipSize = drawRect.size();
textureClipSize.scale(textureSize, Fw::KeepAspectRatio);
Point texCoordsOffset;
if(textureSize.height() > textureClipSize.height())
texCoordsOffset.y = (textureSize.height() - textureClipSize.height())/2;
else if(textureSize.width() > textureClipSize.width())
texCoordsOffset.x = (textureSize.width() - textureClipSize.width())/2;
Rect textureClipRect(texCoordsOffset, textureClipSize);
m_imageCoordsBuffer.addRect(drawRect, textureClipRect);
} else {
if(m_imageRepeated)
m_imageCoordsBuffer.addRepeatedRects(drawRect, m_imageClipRect);
else
m_imageCoordsBuffer.addRect(drawRect, m_imageClipRect);
}
} else {
int top = m_imageBorder.top;
int bottom = m_imageBorder.bottom;
int left = m_imageBorder.left;
int right = m_imageBorder.right;
// calculates border coords
const Rect clip = m_imageClipRect;
Rect leftBorder(clip.left(), clip.top() + top, left, clip.height() - top - bottom);
Rect rightBorder(clip.right() - right + 1, clip.top() + top, right, clip.height() - top - bottom);
Rect topBorder(clip.left() + left, clip.top(), clip.width() - right - left, top);
Rect bottomBorder(clip.left() + left, clip.bottom() - bottom + 1, clip.width() - right - left, bottom);
Rect topLeftCorner(clip.left(), clip.top(), left, top);
Rect topRightCorner(clip.right() - right + 1, clip.top(), right, top);
Rect bottomLeftCorner(clip.left(), clip.bottom() - bottom + 1, left, bottom);
Rect bottomRightCorner(clip.right() - right + 1, clip.bottom() - bottom + 1, right, bottom);
Rect center(clip.left() + left, clip.top() + top, clip.width() - right - left, clip.height() - top - bottom);
Size bordersSize(leftBorder.width() + rightBorder.width(), topBorder.height() + bottomBorder.height());
Size centerSize = drawRect.size() - bordersSize;
Rect rectCoords;
// first the center
if(centerSize.area() > 0) {
rectCoords = Rect(drawRect.left() + leftBorder.width(), drawRect.top() + topBorder.height(), centerSize);
m_imageCoordsBuffer.addRepeatedRects(rectCoords, center);
}
// top left corner
rectCoords = Rect(drawRect.topLeft(), topLeftCorner.size());
m_imageCoordsBuffer.addRepeatedRects(rectCoords, topLeftCorner);
// top
rectCoords = Rect(drawRect.left() + topLeftCorner.width(), drawRect.topLeft().y, centerSize.width(), topBorder.height());
m_imageCoordsBuffer.addRepeatedRects(rectCoords, topBorder);
// top right corner
rectCoords = Rect(drawRect.left() + topLeftCorner.width() + centerSize.width(), drawRect.top(), topRightCorner.size());
m_imageCoordsBuffer.addRepeatedRects(rectCoords, topRightCorner);
// left
rectCoords = Rect(drawRect.left(), drawRect.top() + topLeftCorner.height(), leftBorder.width(), centerSize.height());
m_imageCoordsBuffer.addRepeatedRects(rectCoords, leftBorder);
// right
rectCoords = Rect(drawRect.left() + leftBorder.width() + centerSize.width(), drawRect.top() + topRightCorner.height(), rightBorder.width(), centerSize.height());
m_imageCoordsBuffer.addRepeatedRects(rectCoords, rightBorder);
// bottom left corner
rectCoords = Rect(drawRect.left(), drawRect.top() + topLeftCorner.height() + centerSize.height(), bottomLeftCorner.size());
m_imageCoordsBuffer.addRepeatedRects(rectCoords, bottomLeftCorner);
// bottom
rectCoords = Rect(drawRect.left() + bottomLeftCorner.width(), drawRect.top() + topBorder.height() + centerSize.height(), centerSize.width(), bottomBorder.height());
m_imageCoordsBuffer.addRepeatedRects(rectCoords, bottomBorder);
// bottom right corner
rectCoords = Rect(drawRect.left() + bottomLeftCorner.width() + centerSize.width(), drawRect.top() + topRightCorner.height() + centerSize.height(), bottomRightCorner.size());
m_imageCoordsBuffer.addRepeatedRects(rectCoords, bottomRightCorner);
}
}
m_imageTexture->setSmooth(m_imageSmooth);
g_painter->setColor(m_imageColor);
g_painter->drawTextureCoords(m_imageCoordsBuffer, m_imageTexture);
}
void UIWidget::setImageSource(const std::string& source)
{
m_imageTexture = g_textures.getTexture(source);
if(!m_imageClipRect.isValid())
m_imageClipRect = Rect(0, 0, m_imageTexture->getSize());
}
<commit_msg>Improve image clip rects calculation<commit_after>/*
* Copyright (c) 2010-2012 OTClient <https://github.com/edubart/otclient>
*
* 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 "uiwidget.h"
#include <framework/graphics/painter.h>
#include <framework/graphics/texture.h>
#include <framework/graphics/texturemanager.h>
#include <framework/graphics/graphics.h>
void UIWidget::initImage()
{
m_imageCoordsBuffer.enableHardwareCaching();
}
void UIWidget::parseImageStyle(const OTMLNodePtr& styleNode)
{
for(const OTMLNodePtr& node : styleNode->children()) {
if(node->tag() == "image-source")
setImageSource(stdext::resolve_path(node->value(), node->source()));
else if(node->tag() == "image-offset-x")
setImageOffsetX(node->value<int>());
else if(node->tag() == "image-offset-y")
setImageOffsetY(node->value<int>());
else if(node->tag() == "image-offset")
setImageOffset(node->value<Point>());
else if(node->tag() == "image-width")
setImageWidth(node->value<int>());
else if(node->tag() == "image-height")
setImageHeight(node->value<int>());
else if(node->tag() == "image-size")
setImageSize(node->value<Size>());
else if(node->tag() == "image-rect")
setImageRect(node->value<Rect>());
else if(node->tag() == "image-clip")
setImageClip(node->value<Rect>());
else if(node->tag() == "image-fixed-ratio")
setImageFixedRatio(node->value<bool>());
else if(node->tag() == "image-repeated")
setImageRepeated(node->value<bool>());
else if(node->tag() == "image-smooth")
setImageSmooth(node->value<bool>());
else if(node->tag() == "image-color")
setImageColor(node->value<Color>());
else if(node->tag() == "image-border-top")
setImageBorderTop(node->value<int>());
else if(node->tag() == "image-border-right")
setImageBorderRight(node->value<int>());
else if(node->tag() == "image-border-bottom")
setImageBorderBottom(node->value<int>());
else if(node->tag() == "image-border-left")
setImageBorderLeft(node->value<int>());
else if(node->tag() == "image-border") {
setImageBorder(node->value<int>());
}
}
}
void UIWidget::drawImage(const Rect& screenCoords)
{
if(!m_imageTexture || !screenCoords.isValid())
return;
// cache vertex buffers
if(m_imageCachedScreenCoords != screenCoords || m_imageMustRecache) {
m_imageCoordsBuffer.clear();
m_imageCachedScreenCoords = screenCoords;
m_imageMustRecache = false;
Rect drawRect = screenCoords;
drawRect.translate(m_imageRect.topLeft());
if(m_imageRect.isValid())
drawRect.resize(m_imageRect.size());
Rect clipRect = m_imageClipRect.isValid() ? m_imageClipRect : Rect(0, 0, m_imageTexture->getSize());
if(!m_imageBordered) {
if(m_imageFixedRatio) {
Size textureSize = m_imageTexture->getSize();
Size textureClipSize = drawRect.size();
textureClipSize.scale(textureSize, Fw::KeepAspectRatio);
Point texCoordsOffset;
if(textureSize.height() > textureClipSize.height())
texCoordsOffset.y = (textureSize.height() - textureClipSize.height())/2;
else if(textureSize.width() > textureClipSize.width())
texCoordsOffset.x = (textureSize.width() - textureClipSize.width())/2;
Rect textureClipRect(texCoordsOffset, textureClipSize);
m_imageCoordsBuffer.addRect(drawRect, textureClipRect);
} else {
if(m_imageRepeated)
m_imageCoordsBuffer.addRepeatedRects(drawRect, clipRect);
else
m_imageCoordsBuffer.addRect(drawRect, clipRect);
}
} else {
int top = m_imageBorder.top;
int bottom = m_imageBorder.bottom;
int left = m_imageBorder.left;
int right = m_imageBorder.right;
// calculates border coords
const Rect clip = clipRect;
Rect leftBorder(clip.left(), clip.top() + top, left, clip.height() - top - bottom);
Rect rightBorder(clip.right() - right + 1, clip.top() + top, right, clip.height() - top - bottom);
Rect topBorder(clip.left() + left, clip.top(), clip.width() - right - left, top);
Rect bottomBorder(clip.left() + left, clip.bottom() - bottom + 1, clip.width() - right - left, bottom);
Rect topLeftCorner(clip.left(), clip.top(), left, top);
Rect topRightCorner(clip.right() - right + 1, clip.top(), right, top);
Rect bottomLeftCorner(clip.left(), clip.bottom() - bottom + 1, left, bottom);
Rect bottomRightCorner(clip.right() - right + 1, clip.bottom() - bottom + 1, right, bottom);
Rect center(clip.left() + left, clip.top() + top, clip.width() - right - left, clip.height() - top - bottom);
Size bordersSize(leftBorder.width() + rightBorder.width(), topBorder.height() + bottomBorder.height());
Size centerSize = drawRect.size() - bordersSize;
Rect rectCoords;
// first the center
if(centerSize.area() > 0) {
rectCoords = Rect(drawRect.left() + leftBorder.width(), drawRect.top() + topBorder.height(), centerSize);
m_imageCoordsBuffer.addRepeatedRects(rectCoords, center);
}
// top left corner
rectCoords = Rect(drawRect.topLeft(), topLeftCorner.size());
m_imageCoordsBuffer.addRepeatedRects(rectCoords, topLeftCorner);
// top
rectCoords = Rect(drawRect.left() + topLeftCorner.width(), drawRect.topLeft().y, centerSize.width(), topBorder.height());
m_imageCoordsBuffer.addRepeatedRects(rectCoords, topBorder);
// top right corner
rectCoords = Rect(drawRect.left() + topLeftCorner.width() + centerSize.width(), drawRect.top(), topRightCorner.size());
m_imageCoordsBuffer.addRepeatedRects(rectCoords, topRightCorner);
// left
rectCoords = Rect(drawRect.left(), drawRect.top() + topLeftCorner.height(), leftBorder.width(), centerSize.height());
m_imageCoordsBuffer.addRepeatedRects(rectCoords, leftBorder);
// right
rectCoords = Rect(drawRect.left() + leftBorder.width() + centerSize.width(), drawRect.top() + topRightCorner.height(), rightBorder.width(), centerSize.height());
m_imageCoordsBuffer.addRepeatedRects(rectCoords, rightBorder);
// bottom left corner
rectCoords = Rect(drawRect.left(), drawRect.top() + topLeftCorner.height() + centerSize.height(), bottomLeftCorner.size());
m_imageCoordsBuffer.addRepeatedRects(rectCoords, bottomLeftCorner);
// bottom
rectCoords = Rect(drawRect.left() + bottomLeftCorner.width(), drawRect.top() + topBorder.height() + centerSize.height(), centerSize.width(), bottomBorder.height());
m_imageCoordsBuffer.addRepeatedRects(rectCoords, bottomBorder);
// bottom right corner
rectCoords = Rect(drawRect.left() + bottomLeftCorner.width() + centerSize.width(), drawRect.top() + topRightCorner.height() + centerSize.height(), bottomRightCorner.size());
m_imageCoordsBuffer.addRepeatedRects(rectCoords, bottomRightCorner);
}
}
m_imageTexture->setSmooth(m_imageSmooth);
g_painter->setColor(m_imageColor);
g_painter->drawTextureCoords(m_imageCoordsBuffer, m_imageTexture);
}
void UIWidget::setImageSource(const std::string& source)
{
m_imageTexture = g_textures.getTexture(source);
m_imageMustRecache = true;
}
<|endoftext|>
|
<commit_before>
/*
* Copyright 2011 Google Inc.
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include "gl/GLTestContext.h"
#define GL_GLEXT_PROTOTYPES
#include <GLES2/gl2.h>
#include <EGL/egl.h>
#include <EGL/eglext.h>
#include "gl/GrGLDefines.h"
#include "gl/GrGLUtil.h"
namespace {
// TODO: Share this class with ANGLE if/when it gets support for EGL_KHR_fence_sync.
class EGLFenceSync : public sk_gpu_test::FenceSync {
public:
static std::unique_ptr<EGLFenceSync> MakeIfSupported(EGLDisplay);
sk_gpu_test::PlatformFence SK_WARN_UNUSED_RESULT insertFence() const override;
bool waitFence(sk_gpu_test::PlatformFence fence) const override;
void deleteFence(sk_gpu_test::PlatformFence fence) const override;
private:
EGLFenceSync(EGLDisplay display);
PFNEGLCREATESYNCKHRPROC fEGLCreateSyncKHR;
PFNEGLCLIENTWAITSYNCKHRPROC fEGLClientWaitSyncKHR;
PFNEGLDESTROYSYNCKHRPROC fEGLDestroySyncKHR;
EGLDisplay fDisplay;
typedef sk_gpu_test::FenceSync INHERITED;
};
std::function<void()> context_restorer() {
auto display = eglGetCurrentDisplay();
auto dsurface = eglGetCurrentSurface(EGL_DRAW);
auto rsurface = eglGetCurrentSurface(EGL_READ);
auto context = eglGetCurrentContext();
return [display, dsurface, rsurface, context] {
eglMakeCurrent(display, dsurface, rsurface, context);
};
}
class EGLGLTestContext : public sk_gpu_test::GLTestContext {
public:
EGLGLTestContext(GrGLStandard forcedGpuAPI, EGLGLTestContext* shareContext);
~EGLGLTestContext() override;
GrEGLImage texture2DToEGLImage(GrGLuint texID) const override;
void destroyEGLImage(GrEGLImage) const override;
GrGLuint eglImageToExternalTexture(GrEGLImage) const override;
std::unique_ptr<sk_gpu_test::GLTestContext> makeNew() const override;
private:
void destroyGLContext();
void onPlatformMakeCurrent() const override;
std::function<void()> onPlatformGetAutoContextRestore() const override;
void onPlatformSwapBuffers() const override;
GrGLFuncPtr onPlatformGetProcAddress(const char*) const override;
EGLContext fContext;
EGLDisplay fDisplay;
EGLSurface fSurface;
};
EGLGLTestContext::EGLGLTestContext(GrGLStandard forcedGpuAPI, EGLGLTestContext* shareContext)
: fContext(EGL_NO_CONTEXT)
, fDisplay(EGL_NO_DISPLAY)
, fSurface(EGL_NO_SURFACE) {
EGLContext eglShareContext = shareContext ? shareContext->fContext : nullptr;
static const EGLint kEGLContextAttribsForOpenGL[] = {
EGL_NONE
};
static const EGLint kEGLContextAttribsForOpenGLES[] = {
EGL_CONTEXT_CLIENT_VERSION, 2,
EGL_NONE
};
static const struct {
const EGLint* fContextAttribs;
EGLenum fAPI;
EGLint fRenderableTypeBit;
GrGLStandard fStandard;
} kAPIs[] = {
{ // OpenGL
kEGLContextAttribsForOpenGL,
EGL_OPENGL_API,
EGL_OPENGL_BIT,
kGL_GrGLStandard
},
{ // OpenGL ES. This seems to work for both ES2 and 3 (when available).
kEGLContextAttribsForOpenGLES,
EGL_OPENGL_ES_API,
EGL_OPENGL_ES2_BIT,
kGLES_GrGLStandard
},
};
size_t apiLimit = SK_ARRAY_COUNT(kAPIs);
size_t api = 0;
if (forcedGpuAPI == kGL_GrGLStandard) {
apiLimit = 1;
} else if (forcedGpuAPI == kGLES_GrGLStandard) {
api = 1;
}
SkASSERT(forcedGpuAPI == kNone_GrGLStandard || kAPIs[api].fStandard == forcedGpuAPI);
sk_sp<const GrGLInterface> gl;
for (; nullptr == gl.get() && api < apiLimit; ++api) {
fDisplay = eglGetDisplay(EGL_DEFAULT_DISPLAY);
EGLint majorVersion;
EGLint minorVersion;
eglInitialize(fDisplay, &majorVersion, &minorVersion);
#if 0
SkDebugf("VENDOR: %s\n", eglQueryString(fDisplay, EGL_VENDOR));
SkDebugf("APIS: %s\n", eglQueryString(fDisplay, EGL_CLIENT_APIS));
SkDebugf("VERSION: %s\n", eglQueryString(fDisplay, EGL_VERSION));
SkDebugf("EXTENSIONS %s\n", eglQueryString(fDisplay, EGL_EXTENSIONS));
#endif
if (!eglBindAPI(kAPIs[api].fAPI)) {
continue;
}
EGLint numConfigs = 0;
const EGLint configAttribs[] = {
EGL_SURFACE_TYPE, EGL_PBUFFER_BIT,
EGL_RENDERABLE_TYPE, kAPIs[api].fRenderableTypeBit,
EGL_RED_SIZE, 8,
EGL_GREEN_SIZE, 8,
EGL_BLUE_SIZE, 8,
EGL_ALPHA_SIZE, 8,
EGL_NONE
};
EGLConfig surfaceConfig;
if (!eglChooseConfig(fDisplay, configAttribs, &surfaceConfig, 1, &numConfigs)) {
SkDebugf("eglChooseConfig failed. EGL Error: 0x%08x\n", eglGetError());
continue;
}
if (0 == numConfigs) {
SkDebugf("No suitable EGL config found.\n");
continue;
}
fContext = eglCreateContext(fDisplay, surfaceConfig, eglShareContext,
kAPIs[api].fContextAttribs);
if (EGL_NO_CONTEXT == fContext) {
SkDebugf("eglCreateContext failed. EGL Error: 0x%08x\n", eglGetError());
continue;
}
static const EGLint kSurfaceAttribs[] = {
EGL_WIDTH, 1,
EGL_HEIGHT, 1,
EGL_NONE
};
fSurface = eglCreatePbufferSurface(fDisplay, surfaceConfig, kSurfaceAttribs);
if (EGL_NO_SURFACE == fSurface) {
SkDebugf("eglCreatePbufferSurface failed. EGL Error: 0x%08x\n", eglGetError());
this->destroyGLContext();
continue;
}
SkScopeExit restorer(context_restorer());
if (!eglMakeCurrent(fDisplay, fSurface, fSurface, fContext)) {
SkDebugf("eglMakeCurrent failed. EGL Error: 0x%08x\n", eglGetError());
this->destroyGLContext();
continue;
}
gl = GrGLMakeNativeInterface();
if (!gl) {
SkDebugf("Failed to create gl interface.\n");
this->destroyGLContext();
continue;
}
if (!gl->validate()) {
SkDebugf("Failed to validate gl interface.\n");
this->destroyGLContext();
continue;
}
this->init(std::move(gl), EGLFenceSync::MakeIfSupported(fDisplay));
break;
}
}
EGLGLTestContext::~EGLGLTestContext() {
this->teardown();
this->destroyGLContext();
}
void EGLGLTestContext::destroyGLContext() {
if (fDisplay) {
if (fContext) {
if (eglGetCurrentContext() == fContext) {
// This will ensure that the context is immediately deleted.
eglMakeCurrent(fDisplay, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);
}
eglDestroyContext(fDisplay, fContext);
fContext = EGL_NO_CONTEXT;
}
if (fSurface) {
eglDestroySurface(fDisplay, fSurface);
fSurface = EGL_NO_SURFACE;
}
//TODO should we close the display?
fDisplay = EGL_NO_DISPLAY;
}
}
GrEGLImage EGLGLTestContext::texture2DToEGLImage(GrGLuint texID) const {
if (!this->gl()->hasExtension("EGL_KHR_gl_texture_2D_image")) {
return GR_EGL_NO_IMAGE;
}
GrEGLImage img;
GrEGLint attribs[] = { GR_EGL_GL_TEXTURE_LEVEL, 0, GR_EGL_NONE };
GrEGLClientBuffer clientBuffer = reinterpret_cast<GrEGLClientBuffer>(texID);
GR_GL_CALL_RET(this->gl(), img,
EGLCreateImage(fDisplay, fContext, GR_EGL_GL_TEXTURE_2D, clientBuffer, attribs));
return img;
}
void EGLGLTestContext::destroyEGLImage(GrEGLImage image) const {
GR_GL_CALL(this->gl(), EGLDestroyImage(fDisplay, image));
}
GrGLuint EGLGLTestContext::eglImageToExternalTexture(GrEGLImage image) const {
GrGLClearErr(this->gl());
if (!this->gl()->hasExtension("GL_OES_EGL_image_external")) {
return 0;
}
typedef GrGLvoid (*EGLImageTargetTexture2DProc)(GrGLenum, GrGLeglImage);
EGLImageTargetTexture2DProc glEGLImageTargetTexture2D =
(EGLImageTargetTexture2DProc) eglGetProcAddress("glEGLImageTargetTexture2DOES");
if (!glEGLImageTargetTexture2D) {
return 0;
}
GrGLuint texID;
GR_GL_CALL(this->gl(), GenTextures(1, &texID));
if (!texID) {
return 0;
}
GR_GL_CALL_NOERRCHECK(this->gl(), BindTexture(GR_GL_TEXTURE_EXTERNAL, texID));
if (GR_GL_GET_ERROR(this->gl()) != GR_GL_NO_ERROR) {
GR_GL_CALL(this->gl(), DeleteTextures(1, &texID));
return 0;
}
glEGLImageTargetTexture2D(GR_GL_TEXTURE_EXTERNAL, image);
if (GR_GL_GET_ERROR(this->gl()) != GR_GL_NO_ERROR) {
GR_GL_CALL(this->gl(), DeleteTextures(1, &texID));
return 0;
}
return texID;
}
std::unique_ptr<sk_gpu_test::GLTestContext> EGLGLTestContext::makeNew() const {
std::unique_ptr<sk_gpu_test::GLTestContext> ctx(new EGLGLTestContext(this->gl()->fStandard,
nullptr));
if (ctx) {
ctx->makeCurrent();
}
return ctx;
}
void EGLGLTestContext::onPlatformMakeCurrent() const {
if (!eglMakeCurrent(fDisplay, fSurface, fSurface, fContext)) {
SkDebugf("Could not set the context.\n");
}
}
std::function<void()> EGLGLTestContext::onPlatformGetAutoContextRestore() const {
if (eglGetCurrentContext() == fContext) {
return nullptr;
}
return context_restorer();
}
void EGLGLTestContext::onPlatformSwapBuffers() const {
if (!eglSwapBuffers(fDisplay, fSurface)) {
SkDebugf("Could not complete eglSwapBuffers.\n");
}
}
GrGLFuncPtr EGLGLTestContext::onPlatformGetProcAddress(const char* procName) const {
return eglGetProcAddress(procName);
}
static bool supports_egl_extension(EGLDisplay display, const char* extension) {
size_t extensionLength = strlen(extension);
const char* extensionsStr = eglQueryString(display, EGL_EXTENSIONS);
while (const char* match = strstr(extensionsStr, extension)) {
// Ensure the string we found is its own extension, not a substring of a larger extension
// (e.g. GL_ARB_occlusion_query / GL_ARB_occlusion_query2).
if ((match == extensionsStr || match[-1] == ' ') &&
(match[extensionLength] == ' ' || match[extensionLength] == '\0')) {
return true;
}
extensionsStr = match + extensionLength;
}
return false;
}
std::unique_ptr<EGLFenceSync> EGLFenceSync::MakeIfSupported(EGLDisplay display) {
if (!display || !supports_egl_extension(display, "EGL_KHR_fence_sync")) {
return nullptr;
}
return std::unique_ptr<EGLFenceSync>(new EGLFenceSync(display));
}
EGLFenceSync::EGLFenceSync(EGLDisplay display)
: fDisplay(display) {
fEGLCreateSyncKHR = (PFNEGLCREATESYNCKHRPROC) eglGetProcAddress("eglCreateSyncKHR");
fEGLClientWaitSyncKHR = (PFNEGLCLIENTWAITSYNCKHRPROC) eglGetProcAddress("eglClientWaitSyncKHR");
fEGLDestroySyncKHR = (PFNEGLDESTROYSYNCKHRPROC) eglGetProcAddress("eglDestroySyncKHR");
SkASSERT(fEGLCreateSyncKHR && fEGLClientWaitSyncKHR && fEGLDestroySyncKHR);
}
sk_gpu_test::PlatformFence EGLFenceSync::insertFence() const {
EGLSyncKHR eglsync = fEGLCreateSyncKHR(fDisplay, EGL_SYNC_FENCE_KHR, nullptr);
return reinterpret_cast<sk_gpu_test::PlatformFence>(eglsync);
}
bool EGLFenceSync::waitFence(sk_gpu_test::PlatformFence platformFence) const {
EGLSyncKHR eglsync = reinterpret_cast<EGLSyncKHR>(platformFence);
return EGL_CONDITION_SATISFIED_KHR ==
fEGLClientWaitSyncKHR(fDisplay,
eglsync,
EGL_SYNC_FLUSH_COMMANDS_BIT_KHR,
EGL_FOREVER_KHR);
}
void EGLFenceSync::deleteFence(sk_gpu_test::PlatformFence platformFence) const {
EGLSyncKHR eglsync = reinterpret_cast<EGLSyncKHR>(platformFence);
fEGLDestroySyncKHR(fDisplay, eglsync);
}
GR_STATIC_ASSERT(sizeof(EGLSyncKHR) <= sizeof(sk_gpu_test::PlatformFence));
} // anonymous namespace
namespace sk_gpu_test {
GLTestContext *CreatePlatformGLTestContext(GrGLStandard forcedGpuAPI,
GLTestContext *shareContext) {
EGLGLTestContext* eglShareContext = reinterpret_cast<EGLGLTestContext*>(shareContext);
EGLGLTestContext *ctx = new EGLGLTestContext(forcedGpuAPI, eglShareContext);
if (!ctx->isValid()) {
delete ctx;
return nullptr;
}
return ctx;
}
} // namespace sk_gpu_test
<commit_msg>CreatePlatformGLTestContext_egl: Try GLES 3, then GLES 2.<commit_after>
/*
* Copyright 2011 Google Inc.
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include "gl/GLTestContext.h"
#define GL_GLEXT_PROTOTYPES
#include <GLES2/gl2.h>
#include <EGL/egl.h>
#include <EGL/eglext.h>
#include "gl/GrGLDefines.h"
#include "gl/GrGLUtil.h"
namespace {
// TODO: Share this class with ANGLE if/when it gets support for EGL_KHR_fence_sync.
class EGLFenceSync : public sk_gpu_test::FenceSync {
public:
static std::unique_ptr<EGLFenceSync> MakeIfSupported(EGLDisplay);
sk_gpu_test::PlatformFence SK_WARN_UNUSED_RESULT insertFence() const override;
bool waitFence(sk_gpu_test::PlatformFence fence) const override;
void deleteFence(sk_gpu_test::PlatformFence fence) const override;
private:
EGLFenceSync(EGLDisplay display);
PFNEGLCREATESYNCKHRPROC fEGLCreateSyncKHR;
PFNEGLCLIENTWAITSYNCKHRPROC fEGLClientWaitSyncKHR;
PFNEGLDESTROYSYNCKHRPROC fEGLDestroySyncKHR;
EGLDisplay fDisplay;
typedef sk_gpu_test::FenceSync INHERITED;
};
std::function<void()> context_restorer() {
auto display = eglGetCurrentDisplay();
auto dsurface = eglGetCurrentSurface(EGL_DRAW);
auto rsurface = eglGetCurrentSurface(EGL_READ);
auto context = eglGetCurrentContext();
return [display, dsurface, rsurface, context] {
eglMakeCurrent(display, dsurface, rsurface, context);
};
}
class EGLGLTestContext : public sk_gpu_test::GLTestContext {
public:
EGLGLTestContext(GrGLStandard forcedGpuAPI, EGLGLTestContext* shareContext);
~EGLGLTestContext() override;
GrEGLImage texture2DToEGLImage(GrGLuint texID) const override;
void destroyEGLImage(GrEGLImage) const override;
GrGLuint eglImageToExternalTexture(GrEGLImage) const override;
std::unique_ptr<sk_gpu_test::GLTestContext> makeNew() const override;
private:
void destroyGLContext();
void onPlatformMakeCurrent() const override;
std::function<void()> onPlatformGetAutoContextRestore() const override;
void onPlatformSwapBuffers() const override;
GrGLFuncPtr onPlatformGetProcAddress(const char*) const override;
EGLContext fContext;
EGLDisplay fDisplay;
EGLSurface fSurface;
};
static EGLContext create_gles_egl_context(EGLDisplay display,
EGLConfig surfaceConfig,
EGLContext eglShareContext,
EGLint eglContextClientVersion) {
const EGLint contextAttribsForOpenGLES[] = {
EGL_CONTEXT_CLIENT_VERSION,
eglContextClientVersion,
EGL_NONE
};
return eglCreateContext(display, surfaceConfig, eglShareContext, contextAttribsForOpenGLES);
}
static EGLContext create_gl_egl_context(EGLDisplay display,
EGLConfig surfaceConfig,
EGLContext eglShareContext) {
const EGLint contextAttribsForOpenGL[] = {
EGL_NONE
};
return eglCreateContext(display, surfaceConfig, eglShareContext, contextAttribsForOpenGL);
}
EGLGLTestContext::EGLGLTestContext(GrGLStandard forcedGpuAPI, EGLGLTestContext* shareContext)
: fContext(EGL_NO_CONTEXT)
, fDisplay(EGL_NO_DISPLAY)
, fSurface(EGL_NO_SURFACE) {
EGLContext eglShareContext = shareContext ? shareContext->fContext : nullptr;
static const GrGLStandard kStandards[] = {
kGL_GrGLStandard,
kGLES_GrGLStandard,
};
size_t apiLimit = SK_ARRAY_COUNT(kStandards);
size_t api = 0;
if (forcedGpuAPI == kGL_GrGLStandard) {
apiLimit = 1;
} else if (forcedGpuAPI == kGLES_GrGLStandard) {
api = 1;
}
SkASSERT(forcedGpuAPI == kNone_GrGLStandard || kStandards[api] == forcedGpuAPI);
sk_sp<const GrGLInterface> gl;
for (; nullptr == gl.get() && api < apiLimit; ++api) {
fDisplay = eglGetDisplay(EGL_DEFAULT_DISPLAY);
EGLint majorVersion;
EGLint minorVersion;
eglInitialize(fDisplay, &majorVersion, &minorVersion);
#if 0
SkDebugf("VENDOR: %s\n", eglQueryString(fDisplay, EGL_VENDOR));
SkDebugf("APIS: %s\n", eglQueryString(fDisplay, EGL_CLIENT_APIS));
SkDebugf("VERSION: %s\n", eglQueryString(fDisplay, EGL_VERSION));
SkDebugf("EXTENSIONS %s\n", eglQueryString(fDisplay, EGL_EXTENSIONS));
#endif
bool gles = kGLES_GrGLStandard == kStandards[api];
if (!eglBindAPI(gles ? EGL_OPENGL_ES_API : EGL_OPENGL_API)) {
continue;
}
EGLint numConfigs = 0;
const EGLint configAttribs[] = {
EGL_SURFACE_TYPE, EGL_PBUFFER_BIT,
EGL_RENDERABLE_TYPE, gles ? EGL_OPENGL_ES2_BIT : EGL_OPENGL_BIT,
EGL_RED_SIZE, 8,
EGL_GREEN_SIZE, 8,
EGL_BLUE_SIZE, 8,
EGL_ALPHA_SIZE, 8,
EGL_NONE
};
EGLConfig surfaceConfig;
if (!eglChooseConfig(fDisplay, configAttribs, &surfaceConfig, 1, &numConfigs)) {
SkDebugf("eglChooseConfig failed. EGL Error: 0x%08x\n", eglGetError());
continue;
}
if (0 == numConfigs) {
SkDebugf("No suitable EGL config found.\n");
continue;
}
if (gles) {
fContext = create_gles_egl_context(fDisplay, surfaceConfig, eglShareContext, 3);
if (EGL_NO_CONTEXT == fContext) {
fContext = create_gles_egl_context(fDisplay, surfaceConfig, eglShareContext, 2);
}
} else {
fContext = create_gl_egl_context(fDisplay, surfaceConfig, eglShareContext);
}
if (EGL_NO_CONTEXT == fContext) {
SkDebugf("eglCreateContext failed. EGL Error: 0x%08x\n", eglGetError());
continue;
}
static const EGLint kSurfaceAttribs[] = {
EGL_WIDTH, 1,
EGL_HEIGHT, 1,
EGL_NONE
};
fSurface = eglCreatePbufferSurface(fDisplay, surfaceConfig, kSurfaceAttribs);
if (EGL_NO_SURFACE == fSurface) {
SkDebugf("eglCreatePbufferSurface failed. EGL Error: 0x%08x\n", eglGetError());
this->destroyGLContext();
continue;
}
SkScopeExit restorer(context_restorer());
if (!eglMakeCurrent(fDisplay, fSurface, fSurface, fContext)) {
SkDebugf("eglMakeCurrent failed. EGL Error: 0x%08x\n", eglGetError());
this->destroyGLContext();
continue;
}
gl = GrGLMakeNativeInterface();
if (!gl) {
SkDebugf("Failed to create gl interface.\n");
this->destroyGLContext();
continue;
}
if (!gl->validate()) {
SkDebugf("Failed to validate gl interface.\n");
this->destroyGLContext();
continue;
}
this->init(std::move(gl), EGLFenceSync::MakeIfSupported(fDisplay));
break;
}
}
EGLGLTestContext::~EGLGLTestContext() {
this->teardown();
this->destroyGLContext();
}
void EGLGLTestContext::destroyGLContext() {
if (fDisplay) {
if (fContext) {
if (eglGetCurrentContext() == fContext) {
// This will ensure that the context is immediately deleted.
eglMakeCurrent(fDisplay, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);
}
eglDestroyContext(fDisplay, fContext);
fContext = EGL_NO_CONTEXT;
}
if (fSurface) {
eglDestroySurface(fDisplay, fSurface);
fSurface = EGL_NO_SURFACE;
}
//TODO should we close the display?
fDisplay = EGL_NO_DISPLAY;
}
}
GrEGLImage EGLGLTestContext::texture2DToEGLImage(GrGLuint texID) const {
if (!this->gl()->hasExtension("EGL_KHR_gl_texture_2D_image")) {
return GR_EGL_NO_IMAGE;
}
GrEGLImage img;
GrEGLint attribs[] = { GR_EGL_GL_TEXTURE_LEVEL, 0, GR_EGL_NONE };
GrEGLClientBuffer clientBuffer = reinterpret_cast<GrEGLClientBuffer>(texID);
GR_GL_CALL_RET(this->gl(), img,
EGLCreateImage(fDisplay, fContext, GR_EGL_GL_TEXTURE_2D, clientBuffer, attribs));
return img;
}
void EGLGLTestContext::destroyEGLImage(GrEGLImage image) const {
GR_GL_CALL(this->gl(), EGLDestroyImage(fDisplay, image));
}
GrGLuint EGLGLTestContext::eglImageToExternalTexture(GrEGLImage image) const {
GrGLClearErr(this->gl());
if (!this->gl()->hasExtension("GL_OES_EGL_image_external")) {
return 0;
}
typedef GrGLvoid (*EGLImageTargetTexture2DProc)(GrGLenum, GrGLeglImage);
EGLImageTargetTexture2DProc glEGLImageTargetTexture2D =
(EGLImageTargetTexture2DProc) eglGetProcAddress("glEGLImageTargetTexture2DOES");
if (!glEGLImageTargetTexture2D) {
return 0;
}
GrGLuint texID;
GR_GL_CALL(this->gl(), GenTextures(1, &texID));
if (!texID) {
return 0;
}
GR_GL_CALL_NOERRCHECK(this->gl(), BindTexture(GR_GL_TEXTURE_EXTERNAL, texID));
if (GR_GL_GET_ERROR(this->gl()) != GR_GL_NO_ERROR) {
GR_GL_CALL(this->gl(), DeleteTextures(1, &texID));
return 0;
}
glEGLImageTargetTexture2D(GR_GL_TEXTURE_EXTERNAL, image);
if (GR_GL_GET_ERROR(this->gl()) != GR_GL_NO_ERROR) {
GR_GL_CALL(this->gl(), DeleteTextures(1, &texID));
return 0;
}
return texID;
}
std::unique_ptr<sk_gpu_test::GLTestContext> EGLGLTestContext::makeNew() const {
std::unique_ptr<sk_gpu_test::GLTestContext> ctx(new EGLGLTestContext(this->gl()->fStandard,
nullptr));
if (ctx) {
ctx->makeCurrent();
}
return ctx;
}
void EGLGLTestContext::onPlatformMakeCurrent() const {
if (!eglMakeCurrent(fDisplay, fSurface, fSurface, fContext)) {
SkDebugf("Could not set the context.\n");
}
}
std::function<void()> EGLGLTestContext::onPlatformGetAutoContextRestore() const {
if (eglGetCurrentContext() == fContext) {
return nullptr;
}
return context_restorer();
}
void EGLGLTestContext::onPlatformSwapBuffers() const {
if (!eglSwapBuffers(fDisplay, fSurface)) {
SkDebugf("Could not complete eglSwapBuffers.\n");
}
}
GrGLFuncPtr EGLGLTestContext::onPlatformGetProcAddress(const char* procName) const {
return eglGetProcAddress(procName);
}
static bool supports_egl_extension(EGLDisplay display, const char* extension) {
size_t extensionLength = strlen(extension);
const char* extensionsStr = eglQueryString(display, EGL_EXTENSIONS);
while (const char* match = strstr(extensionsStr, extension)) {
// Ensure the string we found is its own extension, not a substring of a larger extension
// (e.g. GL_ARB_occlusion_query / GL_ARB_occlusion_query2).
if ((match == extensionsStr || match[-1] == ' ') &&
(match[extensionLength] == ' ' || match[extensionLength] == '\0')) {
return true;
}
extensionsStr = match + extensionLength;
}
return false;
}
std::unique_ptr<EGLFenceSync> EGLFenceSync::MakeIfSupported(EGLDisplay display) {
if (!display || !supports_egl_extension(display, "EGL_KHR_fence_sync")) {
return nullptr;
}
return std::unique_ptr<EGLFenceSync>(new EGLFenceSync(display));
}
EGLFenceSync::EGLFenceSync(EGLDisplay display)
: fDisplay(display) {
fEGLCreateSyncKHR = (PFNEGLCREATESYNCKHRPROC) eglGetProcAddress("eglCreateSyncKHR");
fEGLClientWaitSyncKHR = (PFNEGLCLIENTWAITSYNCKHRPROC) eglGetProcAddress("eglClientWaitSyncKHR");
fEGLDestroySyncKHR = (PFNEGLDESTROYSYNCKHRPROC) eglGetProcAddress("eglDestroySyncKHR");
SkASSERT(fEGLCreateSyncKHR && fEGLClientWaitSyncKHR && fEGLDestroySyncKHR);
}
sk_gpu_test::PlatformFence EGLFenceSync::insertFence() const {
EGLSyncKHR eglsync = fEGLCreateSyncKHR(fDisplay, EGL_SYNC_FENCE_KHR, nullptr);
return reinterpret_cast<sk_gpu_test::PlatformFence>(eglsync);
}
bool EGLFenceSync::waitFence(sk_gpu_test::PlatformFence platformFence) const {
EGLSyncKHR eglsync = reinterpret_cast<EGLSyncKHR>(platformFence);
return EGL_CONDITION_SATISFIED_KHR ==
fEGLClientWaitSyncKHR(fDisplay,
eglsync,
EGL_SYNC_FLUSH_COMMANDS_BIT_KHR,
EGL_FOREVER_KHR);
}
void EGLFenceSync::deleteFence(sk_gpu_test::PlatformFence platformFence) const {
EGLSyncKHR eglsync = reinterpret_cast<EGLSyncKHR>(platformFence);
fEGLDestroySyncKHR(fDisplay, eglsync);
}
GR_STATIC_ASSERT(sizeof(EGLSyncKHR) <= sizeof(sk_gpu_test::PlatformFence));
} // anonymous namespace
namespace sk_gpu_test {
GLTestContext *CreatePlatformGLTestContext(GrGLStandard forcedGpuAPI,
GLTestContext *shareContext) {
EGLGLTestContext* eglShareContext = reinterpret_cast<EGLGLTestContext*>(shareContext);
EGLGLTestContext *ctx = new EGLGLTestContext(forcedGpuAPI, eglShareContext);
if (!ctx->isValid()) {
delete ctx;
return nullptr;
}
return ctx;
}
} // namespace sk_gpu_test
<|endoftext|>
|
<commit_before>#include "line_segment.hpp"
// Include standard headers
#include <string> // std::string
#include <vector> // std::vector
namespace ylikuutio
{
namespace geometry
{
/*
LineSegment::LineSegment(const std::vector<float> point1, const std::vector<float> point2)
{
// constructor.
// can be used for creating n-dimensional line segments.
}
*/
std::string LineSegment::get_equation()
{
std::string line_segment_equation;
return line_segment_equation;
}
}
}
<commit_msg>Removed obsolete commented out code.<commit_after>#include "line_segment.hpp"
// Include standard headers
#include <string> // std::string
#include <vector> // std::vector
namespace ylikuutio
{
namespace geometry
{
std::string LineSegment::get_equation()
{
std::string line_segment_equation;
return line_segment_equation;
}
}
}
<|endoftext|>
|
<commit_before>#include "catch.hpp"
#include "etl/fast_vector.hpp"
//{{{ Init tests
TEST_CASE( "fast_vector/init_1", "fast_vector::fast_vector(T)" ) {
etl::fast_vector<double, 4> test_vector(3.3);
REQUIRE(test_vector.size() == 4);
for(std::size_t i = 0; i < test_vector.size(); ++i){
REQUIRE(test_vector[i] == 3.3);
}
}
TEST_CASE( "fast_vector/init_2", "fast_vector::operator=(T)" ) {
etl::fast_vector<double, 4> test_vector;
test_vector = 3.3;
REQUIRE(test_vector.size() == 4);
for(std::size_t i = 0; i < test_vector.size(); ++i){
REQUIRE(test_vector[i] == 3.3);
}
}
TEST_CASE( "fast_vector/init_3", "fast_vector::fast_vector(initializer_list)" ) {
etl::fast_vector<double, 3> test_vector = {1.0, 2.0, 3.0};
REQUIRE(test_vector.size() == 3);
REQUIRE(test_vector[0] == 1.0);
REQUIRE(test_vector[1] == 2.0);
REQUIRE(test_vector[2] == 3.0);
}
//}}} Init tests
//{{{ Binary operators test
TEST_CASE( "fast_vector/add_scalar_1", "fast_vector::operator+" ) {
etl::fast_vector<double, 3> test_vector = {-1.0, 2.0, 5.5};
test_vector = 1.0 + test_vector;
REQUIRE(test_vector[0] == 0.0);
REQUIRE(test_vector[1] == 3.0);
REQUIRE(test_vector[2] == 6.5);
}
TEST_CASE( "fast_vector/add_scalar_2", "fast_vector::operator+" ) {
etl::fast_vector<double, 3> test_vector = {-1.0, 2.0, 5.5};
test_vector = test_vector + 1.0;
REQUIRE(test_vector[0] == 0.0);
REQUIRE(test_vector[1] == 3.0);
REQUIRE(test_vector[2] == 6.5);
}
TEST_CASE( "fast_vector/add", "fast_vector::operator+" ) {
etl::fast_vector<double, 3> a = {-1.0, 2.0, 5.0};
etl::fast_vector<double, 3> b = {2.5, 3.0, 4.0};
etl::fast_vector<double, 3> c = a + b;
REQUIRE(c[0] == 1.5);
REQUIRE(c[1] == 5.0);
REQUIRE(c[2] == 9.0);
}
TEST_CASE( "fast_vector/sub_scalar_1", "fast_vector::operator+" ) {
etl::fast_vector<double, 3> test_vector = {-1.0, 2.0, 5.5};
test_vector = 1.0 - test_vector;
REQUIRE(test_vector[0] == 2.0);
REQUIRE(test_vector[1] == -1.0);
REQUIRE(test_vector[2] == -4.5);
}
TEST_CASE( "fast_vector/sub_scalar_2", "fast_vector::operator+" ) {
etl::fast_vector<double, 3> test_vector = {-1.0, 2.0, 5.5};
test_vector = test_vector - 1.0;
REQUIRE(test_vector[0] == -2.0);
REQUIRE(test_vector[1] == 1.0);
REQUIRE(test_vector[2] == 4.5);
}
TEST_CASE( "fast_vector/sub", "fast_vector::operator-" ) {
etl::fast_vector<double, 3> a = {-1.0, 2.0, 5.0};
etl::fast_vector<double, 3> b = {2.5, 3.0, 4.0};
etl::fast_vector<double, 3> c = a - b;
REQUIRE(c[0] == -3.5);
REQUIRE(c[1] == -1.0);
REQUIRE(c[2] == 1.0);
}
TEST_CASE( "fast_vector/mul_scalar_1", "fast_vector::operator*" ) {
etl::fast_vector<double, 3> test_vector = {-1.0, 2.0, 5.0};
test_vector = 2.5 * test_vector;
REQUIRE(test_vector[0] == -2.5);
REQUIRE(test_vector[1] == 5.0);
REQUIRE(test_vector[2] == 12.5);
}
TEST_CASE( "fast_vector/mul_scalar_2", "fast_vector::operator*" ) {
etl::fast_vector<double, 3> test_vector = {-1.0, 2.0, 5.0};
test_vector = test_vector * 2.5;
REQUIRE(test_vector[0] == -2.5);
REQUIRE(test_vector[1] == 5.0);
REQUIRE(test_vector[2] == 12.5);
}
TEST_CASE( "fast_vector/mul", "fast_vector::operator*" ) {
etl::fast_vector<double, 3> a = {-1.0, 2.0, 5.0};
etl::fast_vector<double, 3> b = {2.5, 3.0, 4.0};
etl::fast_vector<double, 3> c = a * b;
REQUIRE(c[0] == -2.5);
REQUIRE(c[1] == 6.0);
REQUIRE(c[2] == 20.0);
}
TEST_CASE( "fast_vector/div_scalar_1", "fast_vector::operator/" ) {
etl::fast_vector<double, 3> test_vector = {-1.0, 2.0, 5.0};
test_vector = test_vector / 2.5;
REQUIRE(test_vector[0] == -1.0 / 2.5);
REQUIRE(test_vector[1] == 2.0 / 2.5);
REQUIRE(test_vector[2] == 5.0 / 2.5);
}
TEST_CASE( "fast_vector/div_scalar_2", "fast_vector::operator/" ) {
etl::fast_vector<double, 3> test_vector = {-1.0, 2.0, 5.0};
test_vector = 2.5 / test_vector;
REQUIRE(test_vector[0] == 2.5 / -1.0);
REQUIRE(test_vector[1] == 2.5 / 2.0);
REQUIRE(test_vector[2] == 2.5 / 5.0);
}
TEST_CASE( "fast_vector/div", "fast_vector::operator/" ) {
etl::fast_vector<double, 3> a = {-1.0, 2.0, 5.0};
etl::fast_vector<double, 3> b = {2.5, 3.0, 4.0};
etl::fast_vector<double, 3> c = a / b;
REQUIRE(c[0] == -1.0 / 2.5);
REQUIRE(c[1] == 2.0 / 3.0);
REQUIRE(c[2] == 5.0 / 4.0);
}
TEST_CASE( "fast_vector/mod_scalar_1", "fast_vector::operator%" ) {
etl::fast_vector<int, 3> test_vector = {-1, 2, 5};
test_vector = test_vector % 2;
REQUIRE(test_vector[0] == -1 % 2);
REQUIRE(test_vector[1] == 2 % 2);
REQUIRE(test_vector[2] == 5 % 2);
}
TEST_CASE( "fast_vector/mod_scalar_2", "fast_vector::operator%" ) {
etl::fast_vector<int, 3> test_vector = {-1, 2, 5};
test_vector = 2 % test_vector;
REQUIRE(test_vector[0] == 2 % -1);
REQUIRE(test_vector[1] == 2 % 2);
REQUIRE(test_vector[2] == 2 % 5);
}
TEST_CASE( "fast_vector/mod", "fast_vector::operator*" ) {
etl::fast_vector<int, 3> a = {-1, 2, 5};
etl::fast_vector<int, 3> b = {2, 3, 4};
etl::fast_vector<int, 3> c = a % b;
REQUIRE(c[0] == -1 % 2);
REQUIRE(c[1] == 2 % 3);
REQUIRE(c[2] == 5 % 4);
}
//}}} Binary operator tests
//{{{ Unary operator tests
TEST_CASE( "fast_vector/log", "fast_vector::abs" ) {
etl::fast_vector<double, 3> a = {-1.0, 2.0, 5.0};
etl::fast_vector<double, 3> d = log(a);
REQUIRE(d[0] == log(-1.0));
REQUIRE(d[1] == log(2.0));
REQUIRE(d[2] == log(5.0));
}
TEST_CASE( "fast_vector/abs", "fast_vector::abs" ) {
etl::fast_vector<double, 3> a = {-1.0, 2.0, 0.0};
etl::fast_vector<double, 3> d = abs(a);
REQUIRE(d[0] == 1.0);
REQUIRE(d[1] == 2.0);
REQUIRE(d[2] == 0.0);
}
TEST_CASE( "fast_vector/sign", "fast_vector::abs" ) {
etl::fast_vector<double, 3> a = {-1.0, 2.0, 0.0};
etl::fast_vector<double, 3> d = sign(a);
REQUIRE(d[0] == -1.0);
REQUIRE(d[1] == 1.0);
REQUIRE(d[2] == 0.0);
}
TEST_CASE( "fast_vector/unary_unary", "fast_vector::abs" ) {
etl::fast_vector<double, 3> a = {-1.0, 2.0, 0.0};
etl::fast_vector<double, 3> d = abs(sign(a));
REQUIRE(d[0] == 1.0);
REQUIRE(d[1] == 1.0);
REQUIRE(d[2] == 0.0);
}
//}}} Unary operators test
TEST_CASE( "fast_vector/complex", "fast_vector::complex" ) {
etl::fast_vector<double, 3> a = {-1.0, 2.0, 5.0};
etl::fast_vector<double, 3> b = {2.5, 3.0, 4.0};
etl::fast_vector<double, 3> c = {1.2, -3.0, 3.5};
etl::fast_vector<double, 3> d = 2.5 * ((a * b) / (a + c)) / (1.5 * a * b / c);
REQUIRE(d[0] == Approx(10.0));
REQUIRE(d[1] == Approx(5.0));
REQUIRE(d[2] == Approx(0.68627));
}
TEST_CASE( "fast_vector/complex_2", "fast_vector::complex" ) {
etl::fast_vector<double, 3> a = {-1.0, 2.0, 5.0};
etl::fast_vector<double, 3> b = {2.5, 3.0, 4.0};
etl::fast_vector<double, 3> c = {1.2, -3.0, 3.5};
etl::fast_vector<double, 3> d = 2.5 * ((a * b) / (log(a) * abs(c))) / (1.5 * a * sign(b) / c) + 2.111 / log(c);
REQUIRE(d[0] == Approx(10.0));
REQUIRE(d[1] == Approx(5.0));
REQUIRE(d[2] == Approx(0.68627));
}
TEST_CASE( "fast_vector/complex_3", "fast_vector::complex" ) {
etl::fast_vector<double, 3> a = {-1.0, 2.0, 5.0};
etl::fast_vector<double, 3> b = {2.5, 3.0, 4.0};
etl::fast_vector<double, 3> c = {1.2, -3.0, 3.5};
etl::fast_vector<double, 3> d = 2.5 / (a * b);
REQUIRE(d[0] == Approx(10.0));
REQUIRE(d[1] == Approx(5.0));
REQUIRE(d[2] == Approx(0.68627));
}<commit_msg>Test unary(binary)<commit_after>#include "catch.hpp"
#include "etl/fast_vector.hpp"
//{{{ Init tests
TEST_CASE( "fast_vector/init_1", "fast_vector::fast_vector(T)" ) {
etl::fast_vector<double, 4> test_vector(3.3);
REQUIRE(test_vector.size() == 4);
for(std::size_t i = 0; i < test_vector.size(); ++i){
REQUIRE(test_vector[i] == 3.3);
}
}
TEST_CASE( "fast_vector/init_2", "fast_vector::operator=(T)" ) {
etl::fast_vector<double, 4> test_vector;
test_vector = 3.3;
REQUIRE(test_vector.size() == 4);
for(std::size_t i = 0; i < test_vector.size(); ++i){
REQUIRE(test_vector[i] == 3.3);
}
}
TEST_CASE( "fast_vector/init_3", "fast_vector::fast_vector(initializer_list)" ) {
etl::fast_vector<double, 3> test_vector = {1.0, 2.0, 3.0};
REQUIRE(test_vector.size() == 3);
REQUIRE(test_vector[0] == 1.0);
REQUIRE(test_vector[1] == 2.0);
REQUIRE(test_vector[2] == 3.0);
}
//}}} Init tests
//{{{ Binary operators test
TEST_CASE( "fast_vector/add_scalar_1", "fast_vector::operator+" ) {
etl::fast_vector<double, 3> test_vector = {-1.0, 2.0, 5.5};
test_vector = 1.0 + test_vector;
REQUIRE(test_vector[0] == 0.0);
REQUIRE(test_vector[1] == 3.0);
REQUIRE(test_vector[2] == 6.5);
}
TEST_CASE( "fast_vector/add_scalar_2", "fast_vector::operator+" ) {
etl::fast_vector<double, 3> test_vector = {-1.0, 2.0, 5.5};
test_vector = test_vector + 1.0;
REQUIRE(test_vector[0] == 0.0);
REQUIRE(test_vector[1] == 3.0);
REQUIRE(test_vector[2] == 6.5);
}
TEST_CASE( "fast_vector/add", "fast_vector::operator+" ) {
etl::fast_vector<double, 3> a = {-1.0, 2.0, 5.0};
etl::fast_vector<double, 3> b = {2.5, 3.0, 4.0};
etl::fast_vector<double, 3> c = a + b;
REQUIRE(c[0] == 1.5);
REQUIRE(c[1] == 5.0);
REQUIRE(c[2] == 9.0);
}
TEST_CASE( "fast_vector/sub_scalar_1", "fast_vector::operator+" ) {
etl::fast_vector<double, 3> test_vector = {-1.0, 2.0, 5.5};
test_vector = 1.0 - test_vector;
REQUIRE(test_vector[0] == 2.0);
REQUIRE(test_vector[1] == -1.0);
REQUIRE(test_vector[2] == -4.5);
}
TEST_CASE( "fast_vector/sub_scalar_2", "fast_vector::operator+" ) {
etl::fast_vector<double, 3> test_vector = {-1.0, 2.0, 5.5};
test_vector = test_vector - 1.0;
REQUIRE(test_vector[0] == -2.0);
REQUIRE(test_vector[1] == 1.0);
REQUIRE(test_vector[2] == 4.5);
}
TEST_CASE( "fast_vector/sub", "fast_vector::operator-" ) {
etl::fast_vector<double, 3> a = {-1.0, 2.0, 5.0};
etl::fast_vector<double, 3> b = {2.5, 3.0, 4.0};
etl::fast_vector<double, 3> c = a - b;
REQUIRE(c[0] == -3.5);
REQUIRE(c[1] == -1.0);
REQUIRE(c[2] == 1.0);
}
TEST_CASE( "fast_vector/mul_scalar_1", "fast_vector::operator*" ) {
etl::fast_vector<double, 3> test_vector = {-1.0, 2.0, 5.0};
test_vector = 2.5 * test_vector;
REQUIRE(test_vector[0] == -2.5);
REQUIRE(test_vector[1] == 5.0);
REQUIRE(test_vector[2] == 12.5);
}
TEST_CASE( "fast_vector/mul_scalar_2", "fast_vector::operator*" ) {
etl::fast_vector<double, 3> test_vector = {-1.0, 2.0, 5.0};
test_vector = test_vector * 2.5;
REQUIRE(test_vector[0] == -2.5);
REQUIRE(test_vector[1] == 5.0);
REQUIRE(test_vector[2] == 12.5);
}
TEST_CASE( "fast_vector/mul", "fast_vector::operator*" ) {
etl::fast_vector<double, 3> a = {-1.0, 2.0, 5.0};
etl::fast_vector<double, 3> b = {2.5, 3.0, 4.0};
etl::fast_vector<double, 3> c = a * b;
REQUIRE(c[0] == -2.5);
REQUIRE(c[1] == 6.0);
REQUIRE(c[2] == 20.0);
}
TEST_CASE( "fast_vector/div_scalar_1", "fast_vector::operator/" ) {
etl::fast_vector<double, 3> test_vector = {-1.0, 2.0, 5.0};
test_vector = test_vector / 2.5;
REQUIRE(test_vector[0] == -1.0 / 2.5);
REQUIRE(test_vector[1] == 2.0 / 2.5);
REQUIRE(test_vector[2] == 5.0 / 2.5);
}
TEST_CASE( "fast_vector/div_scalar_2", "fast_vector::operator/" ) {
etl::fast_vector<double, 3> test_vector = {-1.0, 2.0, 5.0};
test_vector = 2.5 / test_vector;
REQUIRE(test_vector[0] == 2.5 / -1.0);
REQUIRE(test_vector[1] == 2.5 / 2.0);
REQUIRE(test_vector[2] == 2.5 / 5.0);
}
TEST_CASE( "fast_vector/div", "fast_vector::operator/" ) {
etl::fast_vector<double, 3> a = {-1.0, 2.0, 5.0};
etl::fast_vector<double, 3> b = {2.5, 3.0, 4.0};
etl::fast_vector<double, 3> c = a / b;
REQUIRE(c[0] == -1.0 / 2.5);
REQUIRE(c[1] == 2.0 / 3.0);
REQUIRE(c[2] == 5.0 / 4.0);
}
TEST_CASE( "fast_vector/mod_scalar_1", "fast_vector::operator%" ) {
etl::fast_vector<int, 3> test_vector = {-1, 2, 5};
test_vector = test_vector % 2;
REQUIRE(test_vector[0] == -1 % 2);
REQUIRE(test_vector[1] == 2 % 2);
REQUIRE(test_vector[2] == 5 % 2);
}
TEST_CASE( "fast_vector/mod_scalar_2", "fast_vector::operator%" ) {
etl::fast_vector<int, 3> test_vector = {-1, 2, 5};
test_vector = 2 % test_vector;
REQUIRE(test_vector[0] == 2 % -1);
REQUIRE(test_vector[1] == 2 % 2);
REQUIRE(test_vector[2] == 2 % 5);
}
TEST_CASE( "fast_vector/mod", "fast_vector::operator*" ) {
etl::fast_vector<int, 3> a = {-1, 2, 5};
etl::fast_vector<int, 3> b = {2, 3, 4};
etl::fast_vector<int, 3> c = a % b;
REQUIRE(c[0] == -1 % 2);
REQUIRE(c[1] == 2 % 3);
REQUIRE(c[2] == 5 % 4);
}
//}}} Binary operator tests
//{{{ Unary operator tests
TEST_CASE( "fast_vector/log", "fast_vector::abs" ) {
etl::fast_vector<double, 3> a = {-1.0, 2.0, 5.0};
etl::fast_vector<double, 3> d = log(a);
REQUIRE(d[0] == log(-1.0));
REQUIRE(d[1] == log(2.0));
REQUIRE(d[2] == log(5.0));
}
TEST_CASE( "fast_vector/abs", "fast_vector::abs" ) {
etl::fast_vector<double, 3> a = {-1.0, 2.0, 0.0};
etl::fast_vector<double, 3> d = abs(a);
REQUIRE(d[0] == 1.0);
REQUIRE(d[1] == 2.0);
REQUIRE(d[2] == 0.0);
}
TEST_CASE( "fast_vector/sign", "fast_vector::abs" ) {
etl::fast_vector<double, 3> a = {-1.0, 2.0, 0.0};
etl::fast_vector<double, 3> d = sign(a);
REQUIRE(d[0] == -1.0);
REQUIRE(d[1] == 1.0);
REQUIRE(d[2] == 0.0);
}
TEST_CASE( "fast_vector/unary_unary", "fast_vector::abs" ) {
etl::fast_vector<double, 3> a = {-1.0, 2.0, 0.0};
etl::fast_vector<double, 3> d = abs(sign(a));
REQUIRE(d[0] == 1.0);
REQUIRE(d[1] == 1.0);
REQUIRE(d[2] == 0.0);
}
TEST_CASE( "fast_vector/unary_binary", "fast_vector::abs" ) {
etl::fast_vector<double, 3> a = {-1.0, 2.0, 0.0};
etl::fast_vector<double, 3> d = abs(a + a);
REQUIRE(d[0] == 2.0);
REQUIRE(d[1] == 4.0);
REQUIRE(d[2] == 0.0);
}
//}}} Unary operators test
TEST_CASE( "fast_vector/complex", "fast_vector::complex" ) {
etl::fast_vector<double, 3> a = {-1.0, 2.0, 5.0};
etl::fast_vector<double, 3> b = {2.5, 3.0, 4.0};
etl::fast_vector<double, 3> c = {1.2, -3.0, 3.5};
etl::fast_vector<double, 3> d = 2.5 * ((a * b) / (a + c)) / (1.5 * a * b / c);
REQUIRE(d[0] == Approx(10.0));
REQUIRE(d[1] == Approx(5.0));
REQUIRE(d[2] == Approx(0.68627));
}
TEST_CASE( "fast_vector/complex_2", "fast_vector::complex" ) {
etl::fast_vector<double, 3> a = {-1.0, 2.0, 5.0};
etl::fast_vector<double, 3> b = {2.5, 3.0, 4.0};
etl::fast_vector<double, 3> c = {1.2, -3.0, 3.5};
etl::fast_vector<double, 3> d = 2.5 * ((a * b) / (log(a) * abs(c))) / (1.5 * a * sign(b) / c) + 2.111 / log(c);
REQUIRE(d[0] == Approx(10.0));
REQUIRE(d[1] == Approx(5.0));
REQUIRE(d[2] == Approx(0.68627));
}
TEST_CASE( "fast_vector/complex_3", "fast_vector::complex" ) {
etl::fast_vector<double, 3> a = {-1.0, 2.0, 5.0};
etl::fast_vector<double, 3> b = {2.5, 3.0, 4.0};
etl::fast_vector<double, 3> c = {1.2, -3.0, 3.5};
etl::fast_vector<double, 3> d = 2.5 / (a * b);
REQUIRE(d[0] == Approx(10.0));
REQUIRE(d[1] == Approx(5.0));
REQUIRE(d[2] == Approx(0.68627));
}<|endoftext|>
|
<commit_before>/**
* Copyright (c) 2014 - 2016 Tolga Cakir <[email protected]>
*
* This source file is part of Sidewinder daemon and is distributed under the
* MIT License. For more information, see LICENSE file.
*/
#include <csignal>
#include <iostream>
#include <fcntl.h>
#include <unistd.h>
#include <sys/file.h>
#include <sys/stat.h>
#include <process.hpp>
std::atomic<bool> Process::isActive_;
bool Process::isActive() {
return isActive_;
}
void Process::setActive(bool isActive) {
isActive_ = isActive;
}
int Process::createPid(std::string pidPath) {
pidPath_ = pidPath;
pidFd_ = open(pidPath_.c_str(), O_CREAT | O_RDWR, S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH);
if (pidFd_ < 0) {
std::cerr << "PID file could not be created." << std::endl;
return -1;
}
if (flock(pidFd_, LOCK_EX | LOCK_NB) < 0) {
std::cerr << "Could not lock PID file, another instance is already running." << std::endl;
close(pidFd_);
return -1;
}
hasPid_ = true;
return pidFd_;
}
void Process::destroyPid() {
if (pidFd_) {
flock(pidFd_, LOCK_UN);
close(pidFd_);
}
if (hasPid_) {
unlink(pidPath_.c_str());
hasPid_ = false;
}
}
int Process::createFifo(std::string fifoPath) {
fifoPath_ = fifoPath;
if (mkfifo(fifoPath_.c_str(), 0644)) {
std::cerr << "Error creating FIFO." << std::endl;
return 1;
}
// TODO unblock, when signal has been received
hasFifo_ = true;
std::cerr << fifoPath << " has been created. Waiting for user to open it." << std::endl;
fifoFd_ = open(fifoPath_.c_str(), O_WRONLY);
return 0;
}
void Process::destroyFifo() {
if (fifoFd_) {
close(fifoFd_);
}
if (hasFifo_) {
unlink(fifoPath_.c_str());
hasFifo_ = false;
}
}
void Process::streamToFifo(GCHD *gchd) {
// immediately return, if FIFO hasn't been opened yet
if (!fifoFd_) {
return;
}
setActive(true);
std::cerr << "Streaming data from device now." << std::endl;
// receive audio and video from device
while (isActive() && fifoFd_) {
unsigned char data[DATA_BUF] = {0};
gchd->stream(data, DATA_BUF);
write(fifoFd_, (char *)data, DATA_BUF);
}
}
void Process::streamToDisk(GCHD *gchd, std::__cxx11::string outputPath) {
// TODO implementation
}
void Process::sigHandler_(int sig) {
std::cerr << std::endl << "Stop signal received." << std::endl;
switch(sig) {
case SIGINT:
setActive(false);
break;
case SIGTERM:
setActive(false);
break;
}
}
Process::Process() {
isActive_ = false;
hasPid_ = false;
hasFifo_ = false;
pidFd_ = 0;
fifoFd_ = 0;
// signal handling
struct sigaction action;
action.sa_handler = sigHandler_;
sigaction(SIGINT, &action, nullptr);
sigaction(SIGTERM, &action, nullptr);
// ignore SIGPIPE, else program terminates on unsuccessful write()
struct sigaction ignore;
ignore.sa_handler = SIG_IGN;
sigaction(SIGPIPE, &ignore, nullptr);
}
Process::~Process() {
destroyFifo();
destroyPid();
}
<commit_msg>implemented streamToDisk()<commit_after>/**
* Copyright (c) 2014 - 2016 Tolga Cakir <[email protected]>
*
* This source file is part of Sidewinder daemon and is distributed under the
* MIT License. For more information, see LICENSE file.
*/
#include <csignal>
#include <fstream>
#include <iostream>
#include <fcntl.h>
#include <unistd.h>
#include <sys/file.h>
#include <sys/stat.h>
#include <process.hpp>
std::atomic<bool> Process::isActive_;
bool Process::isActive() {
return isActive_;
}
void Process::setActive(bool isActive) {
isActive_ = isActive;
}
int Process::createPid(std::string pidPath) {
pidPath_ = pidPath;
pidFd_ = open(pidPath_.c_str(), O_CREAT | O_RDWR, S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH);
if (pidFd_ < 0) {
std::cerr << "PID file could not be created." << std::endl;
return -1;
}
if (flock(pidFd_, LOCK_EX | LOCK_NB) < 0) {
std::cerr << "Could not lock PID file, another instance is already running." << std::endl;
close(pidFd_);
return -1;
}
hasPid_ = true;
return pidFd_;
}
void Process::destroyPid() {
if (pidFd_) {
flock(pidFd_, LOCK_UN);
close(pidFd_);
}
if (hasPid_) {
unlink(pidPath_.c_str());
hasPid_ = false;
}
}
int Process::createFifo(std::string fifoPath) {
fifoPath_ = fifoPath;
if (mkfifo(fifoPath_.c_str(), 0644)) {
std::cerr << "Error creating FIFO." << std::endl;
return 1;
}
// TODO unblock, when signal has been received
hasFifo_ = true;
std::cerr << fifoPath << " has been created. Waiting for user to open it." << std::endl;
fifoFd_ = open(fifoPath_.c_str(), O_WRONLY);
return 0;
}
void Process::destroyFifo() {
if (fifoFd_) {
close(fifoFd_);
}
if (hasFifo_) {
unlink(fifoPath_.c_str());
hasFifo_ = false;
}
}
void Process::streamToFifo(GCHD *gchd) {
// immediately return, if FIFO hasn't been opened yet
if (!fifoFd_) {
return;
}
setActive(true);
std::cerr << "Streaming data from device now." << std::endl;
// receive audio and video from device
while (isActive() && fifoFd_) {
unsigned char data[DATA_BUF] = {0};
gchd->stream(data, DATA_BUF);
write(fifoFd_, (char *)data, DATA_BUF);
}
}
void Process::streamToDisk(GCHD *gchd, std::string outputPath) {
std::ofstream output(outputPath, std::ofstream::binary);
setActive(true);
std::cerr << "Streaming data from device now." << std::endl;
// receive audio and video from device
while (isActive() && fifoFd_) {
unsigned char data[DATA_BUF] = {0};
gchd->stream(data, DATA_BUF);
output.write((char *)data, DATA_BUF);
}
output.close();
}
void Process::sigHandler_(int sig) {
std::cerr << std::endl << "Stop signal received." << std::endl;
switch(sig) {
case SIGINT:
setActive(false);
break;
case SIGTERM:
setActive(false);
break;
}
}
Process::Process() {
isActive_ = false;
hasPid_ = false;
hasFifo_ = false;
pidFd_ = 0;
fifoFd_ = 0;
// signal handling
struct sigaction action;
action.sa_handler = sigHandler_;
sigaction(SIGINT, &action, nullptr);
sigaction(SIGTERM, &action, nullptr);
// ignore SIGPIPE, else program terminates on unsuccessful write()
struct sigaction ignore;
ignore.sa_handler = SIG_IGN;
sigaction(SIGPIPE, &ignore, nullptr);
}
Process::~Process() {
destroyFifo();
destroyPid();
}
<|endoftext|>
|
<commit_before>/*******************************************************************************
*
* X testing environment - Google Test environment feat. dummy x server
*
* Copyright (C) 2011, 2012 Canonical Ltd.
*
* 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.
*
******************************************************************************/
#include "xorg/gtest/xorg-gtest-process.h"
#include <sys/prctl.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
#include <algorithm>
#include <cerrno>
#include <csignal>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <stdexcept>
#include <vector>
struct xorg::testing::Process::Private {
pid_t pid;
enum State state;
};
xorg::testing::Process::Process() : d_(new Private) {
d_->pid = -1;
d_->state = NONE;
}
enum xorg::testing::Process::State xorg::testing::Process::GetState() {
if (d_->state == RUNNING) {
int status;
int pid = waitpid(Pid(), &status, WNOHANG);
if (pid == Pid()) {
if (WIFEXITED(status)) {
d_->pid = -1;
d_->state = WEXITSTATUS(status) ? FINISHED_FAILURE : FINISHED_SUCCESS;
}
}
}
return d_->state;
}
void xorg::testing::Process::Start(const std::string &program, const std::vector<std::string> &argv) {
if (d_->pid != -1)
throw std::runtime_error("Attempting to start an already started process");
d_->pid = fork();
if (d_->pid == -1) {
d_->state = ERROR;
throw std::runtime_error("Failed to fork child process");
} else if (d_->pid == 0) { /* Child */
close(0);
if (getenv("XORG_GTEST_CHILD_STDOUT") == NULL) {
close(1);
close(2);
}
#ifdef __linux
prctl(PR_SET_PDEATHSIG, SIGTERM);
#endif
std::vector<char*> args;
std::vector<std::string>::const_iterator it;
args.push_back(strdup(program.c_str()));
for (it = argv.begin(); it != argv.end(); it++)
args.push_back(strdup(it->c_str()));
args.push_back(NULL);
execvp(program.c_str(), &args[0]);
d_->state = ERROR;
throw std::runtime_error("Failed to start process");
}
d_->state = RUNNING;
}
void xorg::testing::Process::Start(const std::string& program, va_list args) {
std::vector<std::string> argv;
if (args) {
char *arg;
do {
arg = va_arg(args, char*);
if (arg)
argv.push_back(std::string(arg));
} while (arg);
}
Start(program, argv);
}
void xorg::testing::Process::Start(const std::string& program, ...) {
va_list list;
va_start(list, program);
Start(program, list);
va_end(list); /* Shouldn't get here */
}
bool xorg::testing::Process::WaitForExit(unsigned int timeout) {
for (int i = 0; i < 10; i++) {
int status;
int pid = waitpid(Pid(), &status, WNOHANG);
if (pid == Pid())
return true;
usleep(timeout * 100);
}
return false;
}
bool xorg::testing::Process::KillSelf(int signal, unsigned int timeout) {
bool wait_success = true;
enum State state = GetState();
switch (state) {
case FINISHED_SUCCESS:
case FINISHED_FAILURE:
case TERMINATED:
return true;
case ERROR:
case NONE:
return false;
default:
break;
}
if (d_->pid == -1) {
return false;
} else if (d_->pid == 0) {
/* Child */
throw std::runtime_error("Child process tried to kill itself");
} else { /* Parent */
if (kill(d_->pid, signal) < 0) {
d_->pid = -1;
d_->state = ERROR;
return false;
}
if (timeout > 0)
wait_success = WaitForExit(timeout);
d_->pid = -1;
}
d_->state = TERMINATED;
return wait_success;
}
bool xorg::testing::Process::Terminate(unsigned int timeout) {
return KillSelf(SIGTERM, timeout);
}
bool xorg::testing::Process::Kill(unsigned int timeout) {
return KillSelf(SIGKILL, timeout);
}
void xorg::testing::Process::SetEnv(const std::string& name,
const std::string& value, bool overwrite) {
if (setenv(name.c_str(), value.c_str(), overwrite) != 0)
throw std::runtime_error("Failed to set environment variable in process");
return;
}
std::string xorg::testing::Process::GetEnv(const std::string& name,
bool* exists) {
const char* var = getenv(name.c_str());
if (exists != NULL)
*exists = (var != NULL);
return std::string(var);
}
pid_t xorg::testing::Process::Pid() const {
return d_->pid;
}
<commit_msg>process: reduce wait time for process termination<commit_after>/*******************************************************************************
*
* X testing environment - Google Test environment feat. dummy x server
*
* Copyright (C) 2011, 2012 Canonical Ltd.
*
* 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.
*
******************************************************************************/
#include "xorg/gtest/xorg-gtest-process.h"
#include <sys/prctl.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
#include <algorithm>
#include <cerrno>
#include <csignal>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <stdexcept>
#include <vector>
struct xorg::testing::Process::Private {
pid_t pid;
enum State state;
};
xorg::testing::Process::Process() : d_(new Private) {
d_->pid = -1;
d_->state = NONE;
}
enum xorg::testing::Process::State xorg::testing::Process::GetState() {
if (d_->state == RUNNING) {
int status;
int pid = waitpid(Pid(), &status, WNOHANG);
if (pid == Pid()) {
if (WIFEXITED(status)) {
d_->pid = -1;
d_->state = WEXITSTATUS(status) ? FINISHED_FAILURE : FINISHED_SUCCESS;
}
}
}
return d_->state;
}
void xorg::testing::Process::Start(const std::string &program, const std::vector<std::string> &argv) {
if (d_->pid != -1)
throw std::runtime_error("Attempting to start an already started process");
d_->pid = fork();
if (d_->pid == -1) {
d_->state = ERROR;
throw std::runtime_error("Failed to fork child process");
} else if (d_->pid == 0) { /* Child */
close(0);
if (getenv("XORG_GTEST_CHILD_STDOUT") == NULL) {
close(1);
close(2);
}
#ifdef __linux
prctl(PR_SET_PDEATHSIG, SIGTERM);
#endif
std::vector<char*> args;
std::vector<std::string>::const_iterator it;
args.push_back(strdup(program.c_str()));
for (it = argv.begin(); it != argv.end(); it++)
args.push_back(strdup(it->c_str()));
args.push_back(NULL);
execvp(program.c_str(), &args[0]);
d_->state = ERROR;
throw std::runtime_error("Failed to start process");
}
d_->state = RUNNING;
}
void xorg::testing::Process::Start(const std::string& program, va_list args) {
std::vector<std::string> argv;
if (args) {
char *arg;
do {
arg = va_arg(args, char*);
if (arg)
argv.push_back(std::string(arg));
} while (arg);
}
Start(program, argv);
}
void xorg::testing::Process::Start(const std::string& program, ...) {
va_list list;
va_start(list, program);
Start(program, list);
va_end(list); /* Shouldn't get here */
}
bool xorg::testing::Process::WaitForExit(unsigned int timeout) {
for (int i = 0; i < timeout * 100; i++) {
int status;
int pid = waitpid(Pid(), &status, WNOHANG);
if (pid == Pid())
return true;
usleep(10);
}
return false;
}
bool xorg::testing::Process::KillSelf(int signal, unsigned int timeout) {
bool wait_success = true;
enum State state = GetState();
switch (state) {
case FINISHED_SUCCESS:
case FINISHED_FAILURE:
case TERMINATED:
return true;
case ERROR:
case NONE:
return false;
default:
break;
}
if (d_->pid == -1) {
return false;
} else if (d_->pid == 0) {
/* Child */
throw std::runtime_error("Child process tried to kill itself");
} else { /* Parent */
if (kill(d_->pid, signal) < 0) {
d_->pid = -1;
d_->state = ERROR;
return false;
}
if (timeout > 0)
wait_success = WaitForExit(timeout);
d_->pid = -1;
}
d_->state = TERMINATED;
return wait_success;
}
bool xorg::testing::Process::Terminate(unsigned int timeout) {
return KillSelf(SIGTERM, timeout);
}
bool xorg::testing::Process::Kill(unsigned int timeout) {
return KillSelf(SIGKILL, timeout);
}
void xorg::testing::Process::SetEnv(const std::string& name,
const std::string& value, bool overwrite) {
if (setenv(name.c_str(), value.c_str(), overwrite) != 0)
throw std::runtime_error("Failed to set environment variable in process");
return;
}
std::string xorg::testing::Process::GetEnv(const std::string& name,
bool* exists) {
const char* var = getenv(name.c_str());
if (exists != NULL)
*exists = (var != NULL);
return std::string(var);
}
pid_t xorg::testing::Process::Pid() const {
return d_->pid;
}
<|endoftext|>
|
<commit_before>// -*- Mode: C++; c-basic-offset: 2; indent-tabs-mode: nil -*-
// Copyright (c) 2005, Google Inc.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
// ---
// Author: Sanjay Ghemawat
// Chris Demetriou (refactoring)
//
// Profile current program by sampling stack-trace every so often
#include "config.h"
#include "getpc.h" // should be first to get the _GNU_SOURCE dfn
#include <signal.h>
#include <assert.h>
#include <stdio.h>
#include <errno.h>
#include <string.h>
#ifdef HAVE_UNISTD_H
#include <unistd.h> // for getpid()
#endif
#if defined(HAVE_SYS_UCONTEXT_H)
#include <sys/ucontext.h>
#elif defined(HAVE_UCONTEXT_H)
#include <ucontext.h>
#elif defined(HAVE_CYGWIN_SIGNAL_H)
#include <cygwin/signal.h>
typedef ucontext ucontext_t;
#else
typedef int ucontext_t; // just to quiet the compiler, mostly
#endif
#include <sys/time.h>
#include <string>
#include <gperftools/profiler.h>
#include <gperftools/stacktrace.h>
#include "base/commandlineflags.h"
#include "base/logging.h"
#include "base/googleinit.h"
#include "base/spinlock.h"
#include "base/sysinfo.h" /* for GetUniquePathFromEnv, etc */
#include "profiledata.h"
#include "profile-handler.h"
#ifdef HAVE_CONFLICT_SIGNAL_H
#include "conflict-signal.h" /* used on msvc machines */
#endif
using std::string;
DEFINE_bool(cpu_profiler_unittest,
EnvToBool("PERFTOOLS_UNITTEST", true),
"Determines whether or not we are running under the \
control of a unit test. This allows us to include or \
exclude certain behaviours.");
// Collects up all profile data. This is a singleton, which is
// initialized by a constructor at startup. If no cpu profiler
// signal is specified then the profiler lifecycle is either
// manaully controlled via the API or attached to the scope of
// the singleton (program scope). Otherwise the cpu toggle is
// used to allow for user selectable control via signal generation.
// This is very useful for profiling a daemon process without
// having to start and stop the daemon or having to modify the
// source code to use the cpu profiler API.
class CpuProfiler {
public:
CpuProfiler();
~CpuProfiler();
// Start profiler to write profile info into fname
bool Start(const char* fname, const ProfilerOptions* options);
// Stop profiling and write the data to disk.
void Stop();
// Write the data to disk (and continue profiling).
void FlushTable();
bool Enabled();
void GetCurrentState(ProfilerState* state);
static CpuProfiler instance_;
private:
// This lock implements the locking requirements described in the ProfileData
// documentation, specifically:
//
// lock_ is held all over all collector_ method calls except for the 'Add'
// call made from the signal handler, to protect against concurrent use of
// collector_'s control routines. Code other than signal handler must
// unregister the signal handler before calling any collector_ method.
// 'Add' method in the collector is protected by a guarantee from
// ProfileHandle that only one instance of prof_handler can run at a time.
SpinLock lock_;
ProfileData collector_;
// Filter function and its argument, if any. (NULL means include all
// samples). Set at start, read-only while running. Written while holding
// lock_, read and executed in the context of SIGPROF interrupt.
int (*filter_)(void*);
void* filter_arg_;
// Opaque token returned by the profile handler. To be used when calling
// ProfileHandlerUnregisterCallback.
ProfileHandlerToken* prof_handler_token_;
// Sets up a callback to receive SIGPROF interrupt.
void EnableHandler();
// Disables receiving SIGPROF interrupt.
void DisableHandler();
// Signal handler that records the interrupted pc in the profile data.
static void prof_handler(int sig, siginfo_t*, void* signal_ucontext,
void* cpu_profiler);
};
// Signal handler that is registered when a user selectable signal
// number is defined in the environment variable CPUPROFILESIGNAL.
static void CpuProfilerSwitch(int signal_number)
{
bool static started = false;
static unsigned profile_count = 0;
static char base_profile_name[1024] = "\0";
if (base_profile_name[0] == '\0') {
if (!GetUniquePathFromEnv("CPUPROFILE", base_profile_name)) {
RAW_LOG(FATAL,"Cpu profiler switch is registered but no CPUPROFILE is defined");
return;
}
}
if (!started)
{
char full_profile_name[1024];
snprintf(full_profile_name, sizeof(full_profile_name), "%s.%u",
base_profile_name, profile_count++);
if(!ProfilerStart(full_profile_name))
{
RAW_LOG(FATAL, "Can't turn on cpu profiling for '%s': %s\n",
full_profile_name, strerror(errno));
}
}
else
{
ProfilerStop();
}
started = !started;
}
// Profile data structure singleton: Constructor will check to see if
// profiling should be enabled. Destructor will write profile data
// out to disk.
CpuProfiler CpuProfiler::instance_;
// Initialize profiling: activated if getenv("CPUPROFILE") exists.
CpuProfiler::CpuProfiler()
: prof_handler_token_(NULL) {
// TODO(cgd) Move this code *out* of the CpuProfile constructor into a
// separate object responsible for initialization. With ProfileHandler there
// is no need to limit the number of profilers.
if (getenv("CPUPROFILE") == NULL) {
if (!FLAGS_cpu_profiler_unittest) {
RAW_LOG(WARNING, "CPU profiler linked but no valid CPUPROFILE environment variable found\n");
}
return;
}
// We don't enable profiling if setuid -- it's a security risk
#ifdef HAVE_GETEUID
if (getuid() != geteuid()) {
if (!FLAGS_cpu_profiler_unittest) {
RAW_LOG(WARNING, "Cannot perform CPU profiling when running with setuid\n");
}
return;
}
#endif
char *signal_number_str = getenv("CPUPROFILESIGNAL");
if (signal_number_str != NULL) {
long int signal_number = strtol(signal_number_str, NULL, 10);
if (signal_number >= 1 && signal_number <= 64) {
intptr_t old_signal_handler = reinterpret_cast<intptr_t>(signal(signal_number, CpuProfilerSwitch));
if (old_signal_handler == 0) {
RAW_LOG(INFO,"Using signal %d as cpu profiling switch", signal_number);
} else {
RAW_LOG(FATAL, "Signal %d already in use\n", signal_number);
}
} else {
RAW_LOG(FATAL, "Signal number %s is invalid\n", signal_number_str);
}
} else {
char fname[PATH_MAX];
if (!GetUniquePathFromEnv("CPUPROFILE", fname)) {
if (!FLAGS_cpu_profiler_unittest) {
RAW_LOG(WARNING, "CPU profiler linked but no valid CPUPROFILE environment variable found\n");
}
return;
}
if (!Start(fname, NULL)) {
RAW_LOG(FATAL, "Can't turn on cpu profiling for '%s': %s\n",
fname, strerror(errno));
}
}
}
bool CpuProfiler::Start(const char* fname, const ProfilerOptions* options) {
SpinLockHolder cl(&lock_);
if (collector_.enabled()) {
return false;
}
ProfileHandlerState prof_handler_state;
ProfileHandlerGetState(&prof_handler_state);
ProfileData::Options collector_options;
collector_options.set_frequency(prof_handler_state.frequency);
if (!collector_.Start(fname, collector_options)) {
return false;
}
filter_ = NULL;
if (options != NULL && options->filter_in_thread != NULL) {
filter_ = options->filter_in_thread;
filter_arg_ = options->filter_in_thread_arg;
}
// Setup handler for SIGPROF interrupts
EnableHandler();
return true;
}
CpuProfiler::~CpuProfiler() {
Stop();
}
// Stop profiling and write out any collected profile data
void CpuProfiler::Stop() {
SpinLockHolder cl(&lock_);
if (!collector_.enabled()) {
return;
}
// Unregister prof_handler to stop receiving SIGPROF interrupts before
// stopping the collector.
DisableHandler();
// DisableHandler waits for the currently running callback to complete and
// guarantees no future invocations. It is safe to stop the collector.
collector_.Stop();
}
void CpuProfiler::FlushTable() {
SpinLockHolder cl(&lock_);
if (!collector_.enabled()) {
return;
}
// Unregister prof_handler to stop receiving SIGPROF interrupts before
// flushing the profile data.
DisableHandler();
// DisableHandler waits for the currently running callback to complete and
// guarantees no future invocations. It is safe to flush the profile data.
collector_.FlushTable();
EnableHandler();
}
bool CpuProfiler::Enabled() {
SpinLockHolder cl(&lock_);
return collector_.enabled();
}
void CpuProfiler::GetCurrentState(ProfilerState* state) {
ProfileData::State collector_state;
{
SpinLockHolder cl(&lock_);
collector_.GetCurrentState(&collector_state);
}
state->enabled = collector_state.enabled;
state->start_time = static_cast<time_t>(collector_state.start_time);
state->samples_gathered = collector_state.samples_gathered;
int buf_size = sizeof(state->profile_name);
strncpy(state->profile_name, collector_state.profile_name, buf_size);
state->profile_name[buf_size-1] = '\0';
}
void CpuProfiler::EnableHandler() {
RAW_CHECK(prof_handler_token_ == NULL, "SIGPROF handler already registered");
prof_handler_token_ = ProfileHandlerRegisterCallback(prof_handler, this);
RAW_CHECK(prof_handler_token_ != NULL, "Failed to set up SIGPROF handler");
}
void CpuProfiler::DisableHandler() {
RAW_CHECK(prof_handler_token_ != NULL, "SIGPROF handler is not registered");
ProfileHandlerUnregisterCallback(prof_handler_token_);
prof_handler_token_ = NULL;
}
// Signal handler that records the pc in the profile-data structure. We do no
// synchronization here. profile-handler.cc guarantees that at most one
// instance of prof_handler() will run at a time. All other routines that
// access the data touched by prof_handler() disable this signal handler before
// accessing the data and therefore cannot execute concurrently with
// prof_handler().
void CpuProfiler::prof_handler(int sig, siginfo_t*, void* signal_ucontext,
void* cpu_profiler) {
CpuProfiler* instance = static_cast<CpuProfiler*>(cpu_profiler);
if (instance->filter_ == NULL ||
(*instance->filter_)(instance->filter_arg_)) {
void* stack[ProfileData::kMaxStackDepth];
// The top-most active routine doesn't show up as a normal
// frame, but as the "pc" value in the signal handler context.
stack[0] = GetPC(*reinterpret_cast<ucontext_t*>(signal_ucontext));
// We skip the top two stack trace entries (this function and one
// signal handler frame) since they are artifacts of profiling and
// should not be measured. Other profiling related frames may be
// removed by "pprof" at analysis time. Instead of skipping the top
// frames, we could skip nothing, but that would increase the
// profile size unnecessarily.
int depth = GetStackTraceWithContext(stack + 1, arraysize(stack) - 1,
2, signal_ucontext);
depth++; // To account for pc value in stack[0];
instance->collector_.Add(depth, stack);
}
}
#if !(defined(__CYGWIN__) || defined(__CYGWIN32__))
extern "C" PERFTOOLS_DLL_DECL void ProfilerRegisterThread() {
ProfileHandlerRegisterThread();
}
extern "C" PERFTOOLS_DLL_DECL void ProfilerFlush() {
CpuProfiler::instance_.FlushTable();
}
extern "C" PERFTOOLS_DLL_DECL int ProfilingIsEnabledForAllThreads() {
return CpuProfiler::instance_.Enabled();
}
extern "C" PERFTOOLS_DLL_DECL int ProfilerStart(const char* fname) {
return CpuProfiler::instance_.Start(fname, NULL);
}
extern "C" PERFTOOLS_DLL_DECL int ProfilerStartWithOptions(
const char *fname, const ProfilerOptions *options) {
return CpuProfiler::instance_.Start(fname, options);
}
extern "C" PERFTOOLS_DLL_DECL void ProfilerStop() {
CpuProfiler::instance_.Stop();
}
extern "C" PERFTOOLS_DLL_DECL void ProfilerGetCurrentState(
ProfilerState* state) {
CpuProfiler::instance_.GetCurrentState(state);
}
#else // OS_CYGWIN
// ITIMER_PROF doesn't work under cygwin. ITIMER_REAL is available, but doesn't
// work as well for profiling, and also interferes with alarm(). Because of
// these issues, unless a specific need is identified, profiler support is
// disabled under Cygwin.
extern "C" void ProfilerRegisterThread() { }
extern "C" void ProfilerFlush() { }
extern "C" int ProfilingIsEnabledForAllThreads() { return 0; }
extern "C" int ProfilerStart(const char* fname) { return 0; }
extern "C" int ProfilerStartWithOptions(const char *fname,
const ProfilerOptions *options) {
return 0;
}
extern "C" void ProfilerStop() { }
extern "C" void ProfilerGetCurrentState(ProfilerState* state) {
memset(state, 0, sizeof(*state));
}
#endif // OS_CYGWIN
// DEPRECATED routines
extern "C" PERFTOOLS_DLL_DECL void ProfilerEnable() { }
extern "C" PERFTOOLS_DLL_DECL void ProfilerDisable() { }
<commit_msg>don't add leaf function twice to profile under libunwind<commit_after>// -*- Mode: C++; c-basic-offset: 2; indent-tabs-mode: nil -*-
// Copyright (c) 2005, Google Inc.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
// ---
// Author: Sanjay Ghemawat
// Chris Demetriou (refactoring)
//
// Profile current program by sampling stack-trace every so often
#include "config.h"
#include "getpc.h" // should be first to get the _GNU_SOURCE dfn
#include <signal.h>
#include <assert.h>
#include <stdio.h>
#include <errno.h>
#include <string.h>
#ifdef HAVE_UNISTD_H
#include <unistd.h> // for getpid()
#endif
#if defined(HAVE_SYS_UCONTEXT_H)
#include <sys/ucontext.h>
#elif defined(HAVE_UCONTEXT_H)
#include <ucontext.h>
#elif defined(HAVE_CYGWIN_SIGNAL_H)
#include <cygwin/signal.h>
typedef ucontext ucontext_t;
#else
typedef int ucontext_t; // just to quiet the compiler, mostly
#endif
#include <sys/time.h>
#include <string>
#include <gperftools/profiler.h>
#include <gperftools/stacktrace.h>
#include "base/commandlineflags.h"
#include "base/logging.h"
#include "base/googleinit.h"
#include "base/spinlock.h"
#include "base/sysinfo.h" /* for GetUniquePathFromEnv, etc */
#include "profiledata.h"
#include "profile-handler.h"
#ifdef HAVE_CONFLICT_SIGNAL_H
#include "conflict-signal.h" /* used on msvc machines */
#endif
using std::string;
DEFINE_bool(cpu_profiler_unittest,
EnvToBool("PERFTOOLS_UNITTEST", true),
"Determines whether or not we are running under the \
control of a unit test. This allows us to include or \
exclude certain behaviours.");
// Collects up all profile data. This is a singleton, which is
// initialized by a constructor at startup. If no cpu profiler
// signal is specified then the profiler lifecycle is either
// manaully controlled via the API or attached to the scope of
// the singleton (program scope). Otherwise the cpu toggle is
// used to allow for user selectable control via signal generation.
// This is very useful for profiling a daemon process without
// having to start and stop the daemon or having to modify the
// source code to use the cpu profiler API.
class CpuProfiler {
public:
CpuProfiler();
~CpuProfiler();
// Start profiler to write profile info into fname
bool Start(const char* fname, const ProfilerOptions* options);
// Stop profiling and write the data to disk.
void Stop();
// Write the data to disk (and continue profiling).
void FlushTable();
bool Enabled();
void GetCurrentState(ProfilerState* state);
static CpuProfiler instance_;
private:
// This lock implements the locking requirements described in the ProfileData
// documentation, specifically:
//
// lock_ is held all over all collector_ method calls except for the 'Add'
// call made from the signal handler, to protect against concurrent use of
// collector_'s control routines. Code other than signal handler must
// unregister the signal handler before calling any collector_ method.
// 'Add' method in the collector is protected by a guarantee from
// ProfileHandle that only one instance of prof_handler can run at a time.
SpinLock lock_;
ProfileData collector_;
// Filter function and its argument, if any. (NULL means include all
// samples). Set at start, read-only while running. Written while holding
// lock_, read and executed in the context of SIGPROF interrupt.
int (*filter_)(void*);
void* filter_arg_;
// Opaque token returned by the profile handler. To be used when calling
// ProfileHandlerUnregisterCallback.
ProfileHandlerToken* prof_handler_token_;
// Sets up a callback to receive SIGPROF interrupt.
void EnableHandler();
// Disables receiving SIGPROF interrupt.
void DisableHandler();
// Signal handler that records the interrupted pc in the profile data.
static void prof_handler(int sig, siginfo_t*, void* signal_ucontext,
void* cpu_profiler);
};
// Signal handler that is registered when a user selectable signal
// number is defined in the environment variable CPUPROFILESIGNAL.
static void CpuProfilerSwitch(int signal_number)
{
bool static started = false;
static unsigned profile_count = 0;
static char base_profile_name[1024] = "\0";
if (base_profile_name[0] == '\0') {
if (!GetUniquePathFromEnv("CPUPROFILE", base_profile_name)) {
RAW_LOG(FATAL,"Cpu profiler switch is registered but no CPUPROFILE is defined");
return;
}
}
if (!started)
{
char full_profile_name[1024];
snprintf(full_profile_name, sizeof(full_profile_name), "%s.%u",
base_profile_name, profile_count++);
if(!ProfilerStart(full_profile_name))
{
RAW_LOG(FATAL, "Can't turn on cpu profiling for '%s': %s\n",
full_profile_name, strerror(errno));
}
}
else
{
ProfilerStop();
}
started = !started;
}
// Profile data structure singleton: Constructor will check to see if
// profiling should be enabled. Destructor will write profile data
// out to disk.
CpuProfiler CpuProfiler::instance_;
// Initialize profiling: activated if getenv("CPUPROFILE") exists.
CpuProfiler::CpuProfiler()
: prof_handler_token_(NULL) {
// TODO(cgd) Move this code *out* of the CpuProfile constructor into a
// separate object responsible for initialization. With ProfileHandler there
// is no need to limit the number of profilers.
if (getenv("CPUPROFILE") == NULL) {
if (!FLAGS_cpu_profiler_unittest) {
RAW_LOG(WARNING, "CPU profiler linked but no valid CPUPROFILE environment variable found\n");
}
return;
}
// We don't enable profiling if setuid -- it's a security risk
#ifdef HAVE_GETEUID
if (getuid() != geteuid()) {
if (!FLAGS_cpu_profiler_unittest) {
RAW_LOG(WARNING, "Cannot perform CPU profiling when running with setuid\n");
}
return;
}
#endif
char *signal_number_str = getenv("CPUPROFILESIGNAL");
if (signal_number_str != NULL) {
long int signal_number = strtol(signal_number_str, NULL, 10);
if (signal_number >= 1 && signal_number <= 64) {
intptr_t old_signal_handler = reinterpret_cast<intptr_t>(signal(signal_number, CpuProfilerSwitch));
if (old_signal_handler == 0) {
RAW_LOG(INFO,"Using signal %d as cpu profiling switch", signal_number);
} else {
RAW_LOG(FATAL, "Signal %d already in use\n", signal_number);
}
} else {
RAW_LOG(FATAL, "Signal number %s is invalid\n", signal_number_str);
}
} else {
char fname[PATH_MAX];
if (!GetUniquePathFromEnv("CPUPROFILE", fname)) {
if (!FLAGS_cpu_profiler_unittest) {
RAW_LOG(WARNING, "CPU profiler linked but no valid CPUPROFILE environment variable found\n");
}
return;
}
if (!Start(fname, NULL)) {
RAW_LOG(FATAL, "Can't turn on cpu profiling for '%s': %s\n",
fname, strerror(errno));
}
}
}
bool CpuProfiler::Start(const char* fname, const ProfilerOptions* options) {
SpinLockHolder cl(&lock_);
if (collector_.enabled()) {
return false;
}
ProfileHandlerState prof_handler_state;
ProfileHandlerGetState(&prof_handler_state);
ProfileData::Options collector_options;
collector_options.set_frequency(prof_handler_state.frequency);
if (!collector_.Start(fname, collector_options)) {
return false;
}
filter_ = NULL;
if (options != NULL && options->filter_in_thread != NULL) {
filter_ = options->filter_in_thread;
filter_arg_ = options->filter_in_thread_arg;
}
// Setup handler for SIGPROF interrupts
EnableHandler();
return true;
}
CpuProfiler::~CpuProfiler() {
Stop();
}
// Stop profiling and write out any collected profile data
void CpuProfiler::Stop() {
SpinLockHolder cl(&lock_);
if (!collector_.enabled()) {
return;
}
// Unregister prof_handler to stop receiving SIGPROF interrupts before
// stopping the collector.
DisableHandler();
// DisableHandler waits for the currently running callback to complete and
// guarantees no future invocations. It is safe to stop the collector.
collector_.Stop();
}
void CpuProfiler::FlushTable() {
SpinLockHolder cl(&lock_);
if (!collector_.enabled()) {
return;
}
// Unregister prof_handler to stop receiving SIGPROF interrupts before
// flushing the profile data.
DisableHandler();
// DisableHandler waits for the currently running callback to complete and
// guarantees no future invocations. It is safe to flush the profile data.
collector_.FlushTable();
EnableHandler();
}
bool CpuProfiler::Enabled() {
SpinLockHolder cl(&lock_);
return collector_.enabled();
}
void CpuProfiler::GetCurrentState(ProfilerState* state) {
ProfileData::State collector_state;
{
SpinLockHolder cl(&lock_);
collector_.GetCurrentState(&collector_state);
}
state->enabled = collector_state.enabled;
state->start_time = static_cast<time_t>(collector_state.start_time);
state->samples_gathered = collector_state.samples_gathered;
int buf_size = sizeof(state->profile_name);
strncpy(state->profile_name, collector_state.profile_name, buf_size);
state->profile_name[buf_size-1] = '\0';
}
void CpuProfiler::EnableHandler() {
RAW_CHECK(prof_handler_token_ == NULL, "SIGPROF handler already registered");
prof_handler_token_ = ProfileHandlerRegisterCallback(prof_handler, this);
RAW_CHECK(prof_handler_token_ != NULL, "Failed to set up SIGPROF handler");
}
void CpuProfiler::DisableHandler() {
RAW_CHECK(prof_handler_token_ != NULL, "SIGPROF handler is not registered");
ProfileHandlerUnregisterCallback(prof_handler_token_);
prof_handler_token_ = NULL;
}
// Signal handler that records the pc in the profile-data structure. We do no
// synchronization here. profile-handler.cc guarantees that at most one
// instance of prof_handler() will run at a time. All other routines that
// access the data touched by prof_handler() disable this signal handler before
// accessing the data and therefore cannot execute concurrently with
// prof_handler().
void CpuProfiler::prof_handler(int sig, siginfo_t*, void* signal_ucontext,
void* cpu_profiler) {
CpuProfiler* instance = static_cast<CpuProfiler*>(cpu_profiler);
if (instance->filter_ == NULL ||
(*instance->filter_)(instance->filter_arg_)) {
void* stack[ProfileData::kMaxStackDepth];
// The top-most active routine doesn't show up as a normal
// frame, but as the "pc" value in the signal handler context.
stack[0] = GetPC(*reinterpret_cast<ucontext_t*>(signal_ucontext));
// We skip the top two stack trace entries (this function and one
// signal handler frame) since they are artifacts of profiling and
// should not be measured. Other profiling related frames may be
// removed by "pprof" at analysis time. Instead of skipping the top
// frames, we could skip nothing, but that would increase the
// profile size unnecessarily.
int depth = GetStackTraceWithContext(stack + 1, arraysize(stack) - 1,
2, signal_ucontext);
void **used_stack;
if (stack[1] == stack[0]) {
// in case of libunwind we will have PC in stack[1].
// We don't want this double PC entry
used_stack = stack + 1;
} else {
used_stack = stack;
depth++; // To account for pc value in stack[0];
}
instance->collector_.Add(depth, used_stack);
}
}
#if !(defined(__CYGWIN__) || defined(__CYGWIN32__))
extern "C" PERFTOOLS_DLL_DECL void ProfilerRegisterThread() {
ProfileHandlerRegisterThread();
}
extern "C" PERFTOOLS_DLL_DECL void ProfilerFlush() {
CpuProfiler::instance_.FlushTable();
}
extern "C" PERFTOOLS_DLL_DECL int ProfilingIsEnabledForAllThreads() {
return CpuProfiler::instance_.Enabled();
}
extern "C" PERFTOOLS_DLL_DECL int ProfilerStart(const char* fname) {
return CpuProfiler::instance_.Start(fname, NULL);
}
extern "C" PERFTOOLS_DLL_DECL int ProfilerStartWithOptions(
const char *fname, const ProfilerOptions *options) {
return CpuProfiler::instance_.Start(fname, options);
}
extern "C" PERFTOOLS_DLL_DECL void ProfilerStop() {
CpuProfiler::instance_.Stop();
}
extern "C" PERFTOOLS_DLL_DECL void ProfilerGetCurrentState(
ProfilerState* state) {
CpuProfiler::instance_.GetCurrentState(state);
}
#else // OS_CYGWIN
// ITIMER_PROF doesn't work under cygwin. ITIMER_REAL is available, but doesn't
// work as well for profiling, and also interferes with alarm(). Because of
// these issues, unless a specific need is identified, profiler support is
// disabled under Cygwin.
extern "C" void ProfilerRegisterThread() { }
extern "C" void ProfilerFlush() { }
extern "C" int ProfilingIsEnabledForAllThreads() { return 0; }
extern "C" int ProfilerStart(const char* fname) { return 0; }
extern "C" int ProfilerStartWithOptions(const char *fname,
const ProfilerOptions *options) {
return 0;
}
extern "C" void ProfilerStop() { }
extern "C" void ProfilerGetCurrentState(ProfilerState* state) {
memset(state, 0, sizeof(*state));
}
#endif // OS_CYGWIN
// DEPRECATED routines
extern "C" PERFTOOLS_DLL_DECL void ProfilerEnable() { }
extern "C" PERFTOOLS_DLL_DECL void ProfilerDisable() { }
<|endoftext|>
|
<commit_before>// Copyright (c) 2005, Google Inc.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
// ---
// Author: Sanjay Ghemawat
// Chris Demetriou (refactoring)
//
// Profile current program by sampling stack-trace every so often
#include "config.h"
#include "getpc.h" // should be first to get the _GNU_SOURCE dfn
#include <signal.h>
#include <assert.h>
#include <stdio.h>
#include <errno.h>
#include <string.h>
#ifdef HAVE_UNISTD_H
#include <unistd.h> // for getpid()
#endif
#if defined(HAVE_SYS_UCONTEXT_H)
#include <sys/ucontext.h>
#elif defined(HAVE_UCONTEXT_H)
#include <ucontext.h>
#elif defined(HAVE_CYGWIN_SIGNAL_H)
#include <cygwin/signal.h>
typedef ucontext ucontext_t;
#else
typedef int ucontext_t; // just to quiet the compiler, mostly
#endif
#include <sys/time.h>
#include <string>
#include <gperftools/profiler.h>
#include <gperftools/stacktrace.h>
#include "base/commandlineflags.h"
#include "base/logging.h"
#include "base/googleinit.h"
#include "base/spinlock.h"
#include "base/sysinfo.h" /* for GetUniquePathFromEnv, etc */
#include "profiledata.h"
#include "profile-handler.h"
#ifdef HAVE_CONFLICT_SIGNAL_H
#include "conflict-signal.h" /* used on msvc machines */
#endif
using std::string;
DEFINE_bool(cpu_profiler_unittest,
EnvToBool("PERFTOOLS_UNITTEST", true),
"Determines whether or not we are running under the \
control of a unit test. This allows us to include or \
exclude certain behaviours.");
// Collects up all profile data. This is a singleton, which is
// initialized by a constructor at startup. If no cpu profiler
// signal is specified then the profiler lifecycle is either
// manaully controlled via the API or attached to the scope of
// the singleton (program scope). Otherwise the cpu toggle is
// used to allow for user selectable control via signal generation.
// This is very useful for profiling a daemon process without
// having to start and stop the daemon or having to modify the
// source code to use the cpu profiler API.
class CpuProfiler {
public:
CpuProfiler();
~CpuProfiler();
// Start profiler to write profile info into fname
bool Start(const char* fname, const ProfilerOptions* options);
// Stop profiling and write the data to disk.
void Stop();
// Write the data to disk (and continue profiling).
void FlushTable();
bool Enabled();
void GetCurrentState(ProfilerState* state);
static CpuProfiler instance_;
private:
// This lock implements the locking requirements described in the ProfileData
// documentation, specifically:
//
// lock_ is held all over all collector_ method calls except for the 'Add'
// call made from the signal handler, to protect against concurrent use of
// collector_'s control routines. Code other than signal handler must
// unregister the signal handler before calling any collector_ method.
// 'Add' method in the collector is protected by a guarantee from
// ProfileHandle that only one instance of prof_handler can run at a time.
SpinLock lock_;
ProfileData collector_;
// Filter function and its argument, if any. (NULL means include all
// samples). Set at start, read-only while running. Written while holding
// lock_, read and executed in the context of SIGPROF interrupt.
int (*filter_)(void*);
void* filter_arg_;
// Opaque token returned by the profile handler. To be used when calling
// ProfileHandlerUnregisterCallback.
ProfileHandlerToken* prof_handler_token_;
// Sets up a callback to receive SIGPROF interrupt.
void EnableHandler();
// Disables receiving SIGPROF interrupt.
void DisableHandler();
// Signal handler that records the interrupted pc in the profile data.
static void prof_handler(int sig, siginfo_t*, void* signal_ucontext,
void* cpu_profiler);
};
// Signal handler that is registered when a user selectable signal
// number is defined in the environment variable CPUPROFILESIGNAL.
static void CpuProfilerSwitch(int signal_number)
{
bool static started = false;
static unsigned profile_count = 0;
static char base_profile_name[1024] = "\0";
if (base_profile_name[0] == '\0') {
if (!GetUniquePathFromEnv("CPUPROFILE", base_profile_name)) {
RAW_LOG(FATAL,"Cpu profiler switch is registered but no CPUPROFILE is defined");
return;
}
}
if (!started)
{
char full_profile_name[1024];
snprintf(full_profile_name, sizeof(full_profile_name), "%s.%u",
base_profile_name, profile_count++);
if(!ProfilerStart(full_profile_name))
{
RAW_LOG(FATAL, "Can't turn on cpu profiling for '%s': %s\n",
full_profile_name, strerror(errno));
}
}
else
{
ProfilerStop();
}
started = !started;
}
// Profile data structure singleton: Constructor will check to see if
// profiling should be enabled. Destructor will write profile data
// out to disk.
CpuProfiler CpuProfiler::instance_;
// Initialize profiling: activated if getenv("CPUPROFILE") exists.
CpuProfiler::CpuProfiler()
: prof_handler_token_(NULL) {
// TODO(cgd) Move this code *out* of the CpuProfile constructor into a
// separate object responsible for initialization. With ProfileHandler there
// is no need to limit the number of profilers.
if (getenv("CPUPROFILE") == NULL) {
if (!FLAGS_cpu_profiler_unittest) {
RAW_LOG(WARNING, "CPU profiler linked but no valid CPUPROFILE environment variable found\n");
}
return;
}
// We don't enable profiling if setuid -- it's a security risk
#ifdef HAVE_GETEUID
if (getuid() != geteuid()) {
if (!FLAGS_cpu_profiler_unittest) {
RAW_LOG(WARNING, "Cannot perform CPU profiling when running with setuid\n");
}
return;
}
#endif
char *signal_number_str = getenv("CPUPROFILESIGNAL");
if (signal_number_str != NULL)
{
long int signal_number = strtol(signal_number_str, NULL, 10);
printf("<debug> signal_number=%ld\n", signal_number);
if (signal_number >=1 && signal_number <=64)
{
sighandler_t old_signal_handler = signal(signal_number, CpuProfilerSwitch);
if (old_signal_handler == NULL)
{
RAW_LOG(INFO,"Using signal %d as cpu profiling switch", signal_number);
}
else
{
RAW_LOG(FATAL, "Signal %d already in use\n", signal_number);
}
}
else
{
RAW_LOG(FATAL, "Signal number %s is invalid\n", signal_number_str);
}
}
else
{
char fname[PATH_MAX];
if (!GetUniquePathFromEnv("CPUPROFILE", fname)) {
if (!FLAGS_cpu_profiler_unittest) {
RAW_LOG(WARNING, "CPU profiler linked but no valid CPUPROFILE environment variable found\n");
}
return;
}
if (!Start(fname, NULL)) {
RAW_LOG(FATAL, "Can't turn on cpu profiling for '%s': %s\n",
fname, strerror(errno));
}
}
}
bool CpuProfiler::Start(const char* fname, const ProfilerOptions* options) {
SpinLockHolder cl(&lock_);
if (collector_.enabled()) {
return false;
}
ProfileHandlerState prof_handler_state;
ProfileHandlerGetState(&prof_handler_state);
ProfileData::Options collector_options;
collector_options.set_frequency(prof_handler_state.frequency);
if (!collector_.Start(fname, collector_options)) {
return false;
}
filter_ = NULL;
if (options != NULL && options->filter_in_thread != NULL) {
filter_ = options->filter_in_thread;
filter_arg_ = options->filter_in_thread_arg;
}
// Setup handler for SIGPROF interrupts
EnableHandler();
return true;
}
CpuProfiler::~CpuProfiler() {
Stop();
}
// Stop profiling and write out any collected profile data
void CpuProfiler::Stop() {
SpinLockHolder cl(&lock_);
if (!collector_.enabled()) {
return;
}
// Unregister prof_handler to stop receiving SIGPROF interrupts before
// stopping the collector.
DisableHandler();
// DisableHandler waits for the currently running callback to complete and
// guarantees no future invocations. It is safe to stop the collector.
collector_.Stop();
}
void CpuProfiler::FlushTable() {
SpinLockHolder cl(&lock_);
if (!collector_.enabled()) {
return;
}
// Unregister prof_handler to stop receiving SIGPROF interrupts before
// flushing the profile data.
DisableHandler();
// DisableHandler waits for the currently running callback to complete and
// guarantees no future invocations. It is safe to flush the profile data.
collector_.FlushTable();
EnableHandler();
}
bool CpuProfiler::Enabled() {
SpinLockHolder cl(&lock_);
return collector_.enabled();
}
void CpuProfiler::GetCurrentState(ProfilerState* state) {
ProfileData::State collector_state;
{
SpinLockHolder cl(&lock_);
collector_.GetCurrentState(&collector_state);
}
state->enabled = collector_state.enabled;
state->start_time = static_cast<time_t>(collector_state.start_time);
state->samples_gathered = collector_state.samples_gathered;
int buf_size = sizeof(state->profile_name);
strncpy(state->profile_name, collector_state.profile_name, buf_size);
state->profile_name[buf_size-1] = '\0';
}
void CpuProfiler::EnableHandler() {
RAW_CHECK(prof_handler_token_ == NULL, "SIGPROF handler already registered");
prof_handler_token_ = ProfileHandlerRegisterCallback(prof_handler, this);
RAW_CHECK(prof_handler_token_ != NULL, "Failed to set up SIGPROF handler");
}
void CpuProfiler::DisableHandler() {
RAW_CHECK(prof_handler_token_ != NULL, "SIGPROF handler is not registered");
ProfileHandlerUnregisterCallback(prof_handler_token_);
prof_handler_token_ = NULL;
}
// Signal handler that records the pc in the profile-data structure. We do no
// synchronization here. profile-handler.cc guarantees that at most one
// instance of prof_handler() will run at a time. All other routines that
// access the data touched by prof_handler() disable this signal handler before
// accessing the data and therefore cannot execute concurrently with
// prof_handler().
void CpuProfiler::prof_handler(int sig, siginfo_t*, void* signal_ucontext,
void* cpu_profiler) {
CpuProfiler* instance = static_cast<CpuProfiler*>(cpu_profiler);
if (instance->filter_ == NULL ||
(*instance->filter_)(instance->filter_arg_)) {
void* stack[ProfileData::kMaxStackDepth];
// The top-most active routine doesn't show up as a normal
// frame, but as the "pc" value in the signal handler context.
stack[0] = GetPC(*reinterpret_cast<ucontext_t*>(signal_ucontext));
// We skip the top two stack trace entries (this function and one
// signal handler frame) since they are artifacts of profiling and
// should not be measured. Other profiling related frames may be
// removed by "pprof" at analysis time. Instead of skipping the top
// frames, we could skip nothing, but that would increase the
// profile size unnecessarily.
int depth = GetStackTraceWithContext(stack + 1, arraysize(stack) - 1,
2, signal_ucontext);
depth++; // To account for pc value in stack[0];
instance->collector_.Add(depth, stack);
}
}
#if !(defined(__CYGWIN__) || defined(__CYGWIN32__))
extern "C" PERFTOOLS_DLL_DECL void ProfilerRegisterThread() {
ProfileHandlerRegisterThread();
}
extern "C" PERFTOOLS_DLL_DECL void ProfilerFlush() {
CpuProfiler::instance_.FlushTable();
}
extern "C" PERFTOOLS_DLL_DECL int ProfilingIsEnabledForAllThreads() {
return CpuProfiler::instance_.Enabled();
}
extern "C" PERFTOOLS_DLL_DECL int ProfilerStart(const char* fname) {
return CpuProfiler::instance_.Start(fname, NULL);
}
extern "C" PERFTOOLS_DLL_DECL int ProfilerStartWithOptions(
const char *fname, const ProfilerOptions *options) {
return CpuProfiler::instance_.Start(fname, options);
}
extern "C" PERFTOOLS_DLL_DECL void ProfilerStop() {
CpuProfiler::instance_.Stop();
}
extern "C" PERFTOOLS_DLL_DECL void ProfilerGetCurrentState(
ProfilerState* state) {
CpuProfiler::instance_.GetCurrentState(state);
}
#else // OS_CYGWIN
// ITIMER_PROF doesn't work under cygwin. ITIMER_REAL is available, but doesn't
// work as well for profiling, and also interferes with alarm(). Because of
// these issues, unless a specific need is identified, profiler support is
// disabled under Cygwin.
extern "C" void ProfilerRegisterThread() { }
extern "C" void ProfilerFlush() { }
extern "C" int ProfilingIsEnabledForAllThreads() { return 0; }
extern "C" int ProfilerStart(const char* fname) { return 0; }
extern "C" int ProfilerStartWithOptions(const char *fname,
const ProfilerOptions *options) {
return 0;
}
extern "C" void ProfilerStop() { }
extern "C" void ProfilerGetCurrentState(ProfilerState* state) {
memset(state, 0, sizeof(*state));
}
#endif // OS_CYGWIN
// DEPRECATED routines
extern "C" PERFTOOLS_DLL_DECL void ProfilerEnable() { }
extern "C" PERFTOOLS_DLL_DECL void ProfilerDisable() { }
<commit_msg>issue-559: don't depend on sighandler_t<commit_after>// Copyright (c) 2005, Google Inc.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
// ---
// Author: Sanjay Ghemawat
// Chris Demetriou (refactoring)
//
// Profile current program by sampling stack-trace every so often
#include "config.h"
#include "getpc.h" // should be first to get the _GNU_SOURCE dfn
#include <signal.h>
#include <assert.h>
#include <stdio.h>
#include <errno.h>
#include <string.h>
#ifdef HAVE_UNISTD_H
#include <unistd.h> // for getpid()
#endif
#if defined(HAVE_SYS_UCONTEXT_H)
#include <sys/ucontext.h>
#elif defined(HAVE_UCONTEXT_H)
#include <ucontext.h>
#elif defined(HAVE_CYGWIN_SIGNAL_H)
#include <cygwin/signal.h>
typedef ucontext ucontext_t;
#else
typedef int ucontext_t; // just to quiet the compiler, mostly
#endif
#include <sys/time.h>
#include <string>
#include <gperftools/profiler.h>
#include <gperftools/stacktrace.h>
#include "base/commandlineflags.h"
#include "base/logging.h"
#include "base/googleinit.h"
#include "base/spinlock.h"
#include "base/sysinfo.h" /* for GetUniquePathFromEnv, etc */
#include "profiledata.h"
#include "profile-handler.h"
#ifdef HAVE_CONFLICT_SIGNAL_H
#include "conflict-signal.h" /* used on msvc machines */
#endif
using std::string;
DEFINE_bool(cpu_profiler_unittest,
EnvToBool("PERFTOOLS_UNITTEST", true),
"Determines whether or not we are running under the \
control of a unit test. This allows us to include or \
exclude certain behaviours.");
// Collects up all profile data. This is a singleton, which is
// initialized by a constructor at startup. If no cpu profiler
// signal is specified then the profiler lifecycle is either
// manaully controlled via the API or attached to the scope of
// the singleton (program scope). Otherwise the cpu toggle is
// used to allow for user selectable control via signal generation.
// This is very useful for profiling a daemon process without
// having to start and stop the daemon or having to modify the
// source code to use the cpu profiler API.
class CpuProfiler {
public:
CpuProfiler();
~CpuProfiler();
// Start profiler to write profile info into fname
bool Start(const char* fname, const ProfilerOptions* options);
// Stop profiling and write the data to disk.
void Stop();
// Write the data to disk (and continue profiling).
void FlushTable();
bool Enabled();
void GetCurrentState(ProfilerState* state);
static CpuProfiler instance_;
private:
// This lock implements the locking requirements described in the ProfileData
// documentation, specifically:
//
// lock_ is held all over all collector_ method calls except for the 'Add'
// call made from the signal handler, to protect against concurrent use of
// collector_'s control routines. Code other than signal handler must
// unregister the signal handler before calling any collector_ method.
// 'Add' method in the collector is protected by a guarantee from
// ProfileHandle that only one instance of prof_handler can run at a time.
SpinLock lock_;
ProfileData collector_;
// Filter function and its argument, if any. (NULL means include all
// samples). Set at start, read-only while running. Written while holding
// lock_, read and executed in the context of SIGPROF interrupt.
int (*filter_)(void*);
void* filter_arg_;
// Opaque token returned by the profile handler. To be used when calling
// ProfileHandlerUnregisterCallback.
ProfileHandlerToken* prof_handler_token_;
// Sets up a callback to receive SIGPROF interrupt.
void EnableHandler();
// Disables receiving SIGPROF interrupt.
void DisableHandler();
// Signal handler that records the interrupted pc in the profile data.
static void prof_handler(int sig, siginfo_t*, void* signal_ucontext,
void* cpu_profiler);
};
// Signal handler that is registered when a user selectable signal
// number is defined in the environment variable CPUPROFILESIGNAL.
static void CpuProfilerSwitch(int signal_number)
{
bool static started = false;
static unsigned profile_count = 0;
static char base_profile_name[1024] = "\0";
if (base_profile_name[0] == '\0') {
if (!GetUniquePathFromEnv("CPUPROFILE", base_profile_name)) {
RAW_LOG(FATAL,"Cpu profiler switch is registered but no CPUPROFILE is defined");
return;
}
}
if (!started)
{
char full_profile_name[1024];
snprintf(full_profile_name, sizeof(full_profile_name), "%s.%u",
base_profile_name, profile_count++);
if(!ProfilerStart(full_profile_name))
{
RAW_LOG(FATAL, "Can't turn on cpu profiling for '%s': %s\n",
full_profile_name, strerror(errno));
}
}
else
{
ProfilerStop();
}
started = !started;
}
// Profile data structure singleton: Constructor will check to see if
// profiling should be enabled. Destructor will write profile data
// out to disk.
CpuProfiler CpuProfiler::instance_;
// Initialize profiling: activated if getenv("CPUPROFILE") exists.
CpuProfiler::CpuProfiler()
: prof_handler_token_(NULL) {
// TODO(cgd) Move this code *out* of the CpuProfile constructor into a
// separate object responsible for initialization. With ProfileHandler there
// is no need to limit the number of profilers.
if (getenv("CPUPROFILE") == NULL) {
if (!FLAGS_cpu_profiler_unittest) {
RAW_LOG(WARNING, "CPU profiler linked but no valid CPUPROFILE environment variable found\n");
}
return;
}
// We don't enable profiling if setuid -- it's a security risk
#ifdef HAVE_GETEUID
if (getuid() != geteuid()) {
if (!FLAGS_cpu_profiler_unittest) {
RAW_LOG(WARNING, "Cannot perform CPU profiling when running with setuid\n");
}
return;
}
#endif
char *signal_number_str = getenv("CPUPROFILESIGNAL");
if (signal_number_str != NULL) {
long int signal_number = strtol(signal_number_str, NULL, 10);
if (signal_number >= 1 && signal_number <= 64) {
void *old_signal_handler = reinterpret_cast<void *>(signal(signal_number, CpuProfilerSwitch));
if (old_signal_handler == NULL) {
RAW_LOG(INFO,"Using signal %d as cpu profiling switch", signal_number);
} else {
RAW_LOG(FATAL, "Signal %d already in use\n", signal_number);
}
} else {
RAW_LOG(FATAL, "Signal number %s is invalid\n", signal_number_str);
}
} else {
char fname[PATH_MAX];
if (!GetUniquePathFromEnv("CPUPROFILE", fname)) {
if (!FLAGS_cpu_profiler_unittest) {
RAW_LOG(WARNING, "CPU profiler linked but no valid CPUPROFILE environment variable found\n");
}
return;
}
if (!Start(fname, NULL)) {
RAW_LOG(FATAL, "Can't turn on cpu profiling for '%s': %s\n",
fname, strerror(errno));
}
}
}
bool CpuProfiler::Start(const char* fname, const ProfilerOptions* options) {
SpinLockHolder cl(&lock_);
if (collector_.enabled()) {
return false;
}
ProfileHandlerState prof_handler_state;
ProfileHandlerGetState(&prof_handler_state);
ProfileData::Options collector_options;
collector_options.set_frequency(prof_handler_state.frequency);
if (!collector_.Start(fname, collector_options)) {
return false;
}
filter_ = NULL;
if (options != NULL && options->filter_in_thread != NULL) {
filter_ = options->filter_in_thread;
filter_arg_ = options->filter_in_thread_arg;
}
// Setup handler for SIGPROF interrupts
EnableHandler();
return true;
}
CpuProfiler::~CpuProfiler() {
Stop();
}
// Stop profiling and write out any collected profile data
void CpuProfiler::Stop() {
SpinLockHolder cl(&lock_);
if (!collector_.enabled()) {
return;
}
// Unregister prof_handler to stop receiving SIGPROF interrupts before
// stopping the collector.
DisableHandler();
// DisableHandler waits for the currently running callback to complete and
// guarantees no future invocations. It is safe to stop the collector.
collector_.Stop();
}
void CpuProfiler::FlushTable() {
SpinLockHolder cl(&lock_);
if (!collector_.enabled()) {
return;
}
// Unregister prof_handler to stop receiving SIGPROF interrupts before
// flushing the profile data.
DisableHandler();
// DisableHandler waits for the currently running callback to complete and
// guarantees no future invocations. It is safe to flush the profile data.
collector_.FlushTable();
EnableHandler();
}
bool CpuProfiler::Enabled() {
SpinLockHolder cl(&lock_);
return collector_.enabled();
}
void CpuProfiler::GetCurrentState(ProfilerState* state) {
ProfileData::State collector_state;
{
SpinLockHolder cl(&lock_);
collector_.GetCurrentState(&collector_state);
}
state->enabled = collector_state.enabled;
state->start_time = static_cast<time_t>(collector_state.start_time);
state->samples_gathered = collector_state.samples_gathered;
int buf_size = sizeof(state->profile_name);
strncpy(state->profile_name, collector_state.profile_name, buf_size);
state->profile_name[buf_size-1] = '\0';
}
void CpuProfiler::EnableHandler() {
RAW_CHECK(prof_handler_token_ == NULL, "SIGPROF handler already registered");
prof_handler_token_ = ProfileHandlerRegisterCallback(prof_handler, this);
RAW_CHECK(prof_handler_token_ != NULL, "Failed to set up SIGPROF handler");
}
void CpuProfiler::DisableHandler() {
RAW_CHECK(prof_handler_token_ != NULL, "SIGPROF handler is not registered");
ProfileHandlerUnregisterCallback(prof_handler_token_);
prof_handler_token_ = NULL;
}
// Signal handler that records the pc in the profile-data structure. We do no
// synchronization here. profile-handler.cc guarantees that at most one
// instance of prof_handler() will run at a time. All other routines that
// access the data touched by prof_handler() disable this signal handler before
// accessing the data and therefore cannot execute concurrently with
// prof_handler().
void CpuProfiler::prof_handler(int sig, siginfo_t*, void* signal_ucontext,
void* cpu_profiler) {
CpuProfiler* instance = static_cast<CpuProfiler*>(cpu_profiler);
if (instance->filter_ == NULL ||
(*instance->filter_)(instance->filter_arg_)) {
void* stack[ProfileData::kMaxStackDepth];
// The top-most active routine doesn't show up as a normal
// frame, but as the "pc" value in the signal handler context.
stack[0] = GetPC(*reinterpret_cast<ucontext_t*>(signal_ucontext));
// We skip the top two stack trace entries (this function and one
// signal handler frame) since they are artifacts of profiling and
// should not be measured. Other profiling related frames may be
// removed by "pprof" at analysis time. Instead of skipping the top
// frames, we could skip nothing, but that would increase the
// profile size unnecessarily.
int depth = GetStackTraceWithContext(stack + 1, arraysize(stack) - 1,
2, signal_ucontext);
depth++; // To account for pc value in stack[0];
instance->collector_.Add(depth, stack);
}
}
#if !(defined(__CYGWIN__) || defined(__CYGWIN32__))
extern "C" PERFTOOLS_DLL_DECL void ProfilerRegisterThread() {
ProfileHandlerRegisterThread();
}
extern "C" PERFTOOLS_DLL_DECL void ProfilerFlush() {
CpuProfiler::instance_.FlushTable();
}
extern "C" PERFTOOLS_DLL_DECL int ProfilingIsEnabledForAllThreads() {
return CpuProfiler::instance_.Enabled();
}
extern "C" PERFTOOLS_DLL_DECL int ProfilerStart(const char* fname) {
return CpuProfiler::instance_.Start(fname, NULL);
}
extern "C" PERFTOOLS_DLL_DECL int ProfilerStartWithOptions(
const char *fname, const ProfilerOptions *options) {
return CpuProfiler::instance_.Start(fname, options);
}
extern "C" PERFTOOLS_DLL_DECL void ProfilerStop() {
CpuProfiler::instance_.Stop();
}
extern "C" PERFTOOLS_DLL_DECL void ProfilerGetCurrentState(
ProfilerState* state) {
CpuProfiler::instance_.GetCurrentState(state);
}
#else // OS_CYGWIN
// ITIMER_PROF doesn't work under cygwin. ITIMER_REAL is available, but doesn't
// work as well for profiling, and also interferes with alarm(). Because of
// these issues, unless a specific need is identified, profiler support is
// disabled under Cygwin.
extern "C" void ProfilerRegisterThread() { }
extern "C" void ProfilerFlush() { }
extern "C" int ProfilingIsEnabledForAllThreads() { return 0; }
extern "C" int ProfilerStart(const char* fname) { return 0; }
extern "C" int ProfilerStartWithOptions(const char *fname,
const ProfilerOptions *options) {
return 0;
}
extern "C" void ProfilerStop() { }
extern "C" void ProfilerGetCurrentState(ProfilerState* state) {
memset(state, 0, sizeof(*state));
}
#endif // OS_CYGWIN
// DEPRECATED routines
extern "C" PERFTOOLS_DLL_DECL void ProfilerEnable() { }
extern "C" PERFTOOLS_DLL_DECL void ProfilerDisable() { }
<|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 "multivalue.h"
#include "exception.h"
#include "length.h"
#include <assert.h>
void
StringList::unserialise(const std::string& serialised)
{
const char* ptr = serialised.data();
const char* end = serialised.data() + serialised.size();
unserialise(&ptr, end);
}
void
StringList::unserialise(const char** ptr, const char* end)
{
ssize_t length = -1;
const char* pos = *ptr;
clear();
if (!*pos++) {
try {
length = unserialise_length(&pos, end, true);
reserve(length);
while (pos != end) {
length = unserialise_length(&pos, end, true);
push_back(std::string(pos, length));
pos += length;
}
} catch(Xapian::SerialisationError) {
length = -1;
}
}
if (length == -1) {
pos = *ptr;
push_back(std::string(pos, end - pos));
}
*ptr = pos;
}
std::string
StringList::serialise() const
{
std::string serialised, values("\0");
values.append(serialise_length(size()));
StringList::const_iterator i(begin());
if (size() > 1) {
for ( ; i != end(); ++i) {
values.append(serialise_length((*i).size()));
values.append(*i);
}
serialised.append(serialise_length(values.size()));
} else if (i != end()) {
values.assign(*i);
}
serialised.append(values);
return serialised;
}
void
MultiValueCountMatchSpy::operator()(const Xapian::Document &doc, double)
{
assert(internal.get());
++(internal->total);
StringList list;
list.unserialise(doc.get_value(internal->slot));
if (is_geo) {
for (auto i = list.begin(); i != list.end(); ++i) {
if (!i->empty()) {
StringList s;
s.push_back(*i);
s.push_back(*(++i));
++(internal->values[s.serialise()]);
}
}
} else {
for (auto i = list.begin(); i != list.end(); ++i) {
if (!i->empty()) ++(internal->values[*i]);
}
}
}
Xapian::MatchSpy*
MultiValueCountMatchSpy::clone() const
{
assert(internal.get());
return new MultiValueCountMatchSpy(internal->slot);
}
std::string
MultiValueCountMatchSpy::name() const
{
return "Xapian::MultiValueCountMatchSpy";
}
std::string
MultiValueCountMatchSpy::serialise() const
{
assert(internal.get());
std::string result;
result += serialise_length(internal->slot);
return result;
}
Xapian::MatchSpy*
MultiValueCountMatchSpy::unserialise(const std::string& s, const Xapian::Registry&) const
{
const char* p = s.data();
const char* end = p + s.size();
Xapian::valueno new_slot = (Xapian::valueno)unserialise_length(&p, end, false);
if (new_slot == Xapian::BAD_VALUENO) {
throw MSG_NetworkError("Decoding error of serialised MultiValueCountMatchSpy");
}
if (p != end) {
throw MSG_NetworkError("Junk at end of serialised MultiValueCountMatchSpy");
}
return new MultiValueCountMatchSpy(new_slot);
}
std::string
MultiValueCountMatchSpy::get_description() const
{
char buffer[20];
std::string d("MultiValueCountMatchSpy(");
if (internal.get()) {
snprintf(buffer, sizeof(buffer), "%u", internal->total);
d += buffer;
d += " docs seen, looking in ";
snprintf(buffer, sizeof(buffer), "%lu", internal->values.size());
d += buffer;
d += " slots)";
} else {
d += ")";
}
return d;
}
<commit_msg>More improves unserialise list<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 "multivalue.h"
#include "exception.h"
#include "length.h"
#include <assert.h>
void
StringList::unserialise(const std::string& serialised)
{
const char* ptr = serialised.data();
const char* end = serialised.data() + serialised.size();
unserialise(&ptr, end);
}
void
StringList::unserialise(const char** ptr, const char* end)
{
ssize_t length = -1;
const char* pos = *ptr;
if (*pos++ == '\0' && pos != end) {
clear();
try {
length = unserialise_length(&pos, end, true);
reserve(length);
while (pos != end) {
length = unserialise_length(&pos, end, true);
push_back(std::string(pos, length));
pos += length;
}
} catch(Xapian::SerialisationError) {
length = -1;
}
}
if (length == -1) {
clear();
pos = *ptr;
push_back(std::string(pos, end - pos));
}
*ptr = pos;
}
std::string
StringList::serialise() const
{
std::string serialised, values("\0");
values.append(serialise_length(size()));
StringList::const_iterator i(begin());
if (size() > 1) {
for ( ; i != end(); ++i) {
values.append(serialise_length((*i).size()));
values.append(*i);
}
serialised.append(serialise_length(values.size()));
} else if (i != end()) {
values.assign(*i);
}
serialised.append(values);
return serialised;
}
void
MultiValueCountMatchSpy::operator()(const Xapian::Document &doc, double)
{
assert(internal.get());
++(internal->total);
StringList list;
list.unserialise(doc.get_value(internal->slot));
if (is_geo) {
for (auto i = list.begin(); i != list.end(); ++i) {
if (!i->empty()) {
StringList s;
s.push_back(*i);
s.push_back(*(++i));
++(internal->values[s.serialise()]);
}
}
} else {
for (auto i = list.begin(); i != list.end(); ++i) {
if (!i->empty()) ++(internal->values[*i]);
}
}
}
Xapian::MatchSpy*
MultiValueCountMatchSpy::clone() const
{
assert(internal.get());
return new MultiValueCountMatchSpy(internal->slot);
}
std::string
MultiValueCountMatchSpy::name() const
{
return "Xapian::MultiValueCountMatchSpy";
}
std::string
MultiValueCountMatchSpy::serialise() const
{
assert(internal.get());
std::string result;
result += serialise_length(internal->slot);
return result;
}
Xapian::MatchSpy*
MultiValueCountMatchSpy::unserialise(const std::string& s, const Xapian::Registry&) const
{
const char* p = s.data();
const char* end = p + s.size();
Xapian::valueno new_slot = (Xapian::valueno)unserialise_length(&p, end, false);
if (new_slot == Xapian::BAD_VALUENO) {
throw MSG_NetworkError("Decoding error of serialised MultiValueCountMatchSpy");
}
if (p != end) {
throw MSG_NetworkError("Junk at end of serialised MultiValueCountMatchSpy");
}
return new MultiValueCountMatchSpy(new_slot);
}
std::string
MultiValueCountMatchSpy::get_description() const
{
char buffer[20];
std::string d("MultiValueCountMatchSpy(");
if (internal.get()) {
snprintf(buffer, sizeof(buffer), "%u", internal->total);
d += buffer;
d += " docs seen, looking in ";
snprintf(buffer, sizeof(buffer), "%lu", internal->values.size());
d += buffer;
d += " slots)";
} else {
d += ")";
}
return d;
}
<|endoftext|>
|
<commit_before>#include "stdafx.h"
#include <openssl/cms.h>
#include <openssl/engine.h>
#include <openssl/err.h>
#include <nan.h>
#include "utils/wlog.h"
#include "pki/wkey.h"
#include "pki/wcert.h"
#include "pki/wpkcs12.h"
#include "pki/wcerts.h"
#include "pki/wcrl.h"
#include "pki/wcrls.h"
#include "pki/woid.h"
#include "pki/walg.h"
#include "pki/wattr.h"
#include "pki/wcertreginfo.h"
#include "pki/wcertreg.h"
#include "pki/wcsr.h"
#include "pki/wcipher.h"
#include "pki/wchain.h"
#include "pki/wrevocation.h"
#include "store/wpkistore.h"
#include "store/wsystem.h"
#include "store/wmicrosoft.h"
#include "store/wcashjson.h"
#include "cms/wsigned_data.h"
#include "cms/wsigner.h"
#include "cms/wsigners.h"
#include "cms/wsigner_attrs.h"
#include <node_object_wrap.h>
void init(v8::Handle<v8::Object> target) {
// logger.start("/tmp/trustedtls/node.log", -1); // -1 = all levels bits
// logger.start("logger.txt", LoggerLevel::All );
// On Windows, we can't use Node's OpenSSL, so we link
// to a standalone OpenSSL library. Therefore, we need
// to initialize OpenSSL separately.
// TODO: Do I need to free these?
// I'm not sure where to call ERR_free_strings() and EVP_cleanup()
// LOGGER_TRACE("OpenSSL init");
OpenSSL::run();
v8::Local<v8::Object> Pki = Nan::New<v8::Object>();
target->Set(Nan::New("PKI").ToLocalChecked(), Pki);
WCertificate::Init(Pki);
WCertificateCollection::Init(Pki);
WCRL::Init(Pki);
WCrlCollection::Init(Pki);
WOID::Init(Pki);
WAlgorithm::Init(Pki);
WAttribute::Init(Pki);
WKey::Init(Pki);
WCSR::Init(Pki);
WCertificationRequestInfo::Init(Pki);
WCertificationRequest::Init(Pki);
WCipher::Init(Pki);
WChain::Init(Pki);
WPkcs12::Init(Pki);
WRevocation::Init(Pki);
v8::Local<v8::Object> Cms = Nan::New<v8::Object>();
target->Set(Nan::New("CMS").ToLocalChecked(), Cms);
WSignedData::Init(Cms);
WSigner::Init(Cms);
WSignerCollection::Init(Cms);
WSignerAttributeCollection::Init(Cms);
v8::Local<v8::Object> PkiStore = Nan::New<v8::Object>();
target->Set(Nan::New("PKISTORE").ToLocalChecked(), PkiStore);
WPkiStore::Init(PkiStore);
WProvider_System::Init(PkiStore);
WProviderMicrosoft::Init(PkiStore);
WFilter::Init(PkiStore);
WPkiItem::Init(PkiStore);
WCashJson::Init(PkiStore);
// target->Set(NanNew<v8::String>("utils"), NanNew<v8::Object>());
// WLogger::Init(target->Get(NanNew<v8::String>("utils"))->ToObject());
// logger.start("log-node.txt", LoggerLevel::Debug);
}
NODE_MODULE(trusted, init)<commit_msg>Fix: camelCase for filename<commit_after>#include "stdafx.h"
#include <openssl/cms.h>
#include <openssl/engine.h>
#include <openssl/err.h>
#include <nan.h>
#include "utils/wlog.h"
#include "pki/wkey.h"
#include "pki/wcert.h"
#include "pki/wpkcs12.h"
#include "pki/wcerts.h"
#include "pki/wcrl.h"
#include "pki/wcrls.h"
#include "pki/woid.h"
#include "pki/walg.h"
#include "pki/wattr.h"
#include "pki/wcertRegInfo.h"
#include "pki/wcertReg.h"
#include "pki/wcsr.h"
#include "pki/wcipher.h"
#include "pki/wchain.h"
#include "pki/wrevocation.h"
#include "store/wpkistore.h"
#include "store/wsystem.h"
#include "store/wmicrosoft.h"
#include "store/wcashjson.h"
#include "cms/wsigned_data.h"
#include "cms/wsigner.h"
#include "cms/wsigners.h"
#include "cms/wsigner_attrs.h"
#include <node_object_wrap.h>
void init(v8::Handle<v8::Object> target) {
// logger.start("/tmp/trustedtls/node.log", -1); // -1 = all levels bits
// logger.start("logger.txt", LoggerLevel::All );
// On Windows, we can't use Node's OpenSSL, so we link
// to a standalone OpenSSL library. Therefore, we need
// to initialize OpenSSL separately.
// TODO: Do I need to free these?
// I'm not sure where to call ERR_free_strings() and EVP_cleanup()
// LOGGER_TRACE("OpenSSL init");
OpenSSL::run();
v8::Local<v8::Object> Pki = Nan::New<v8::Object>();
target->Set(Nan::New("PKI").ToLocalChecked(), Pki);
WCertificate::Init(Pki);
WCertificateCollection::Init(Pki);
WCRL::Init(Pki);
WCrlCollection::Init(Pki);
WOID::Init(Pki);
WAlgorithm::Init(Pki);
WAttribute::Init(Pki);
WKey::Init(Pki);
WCSR::Init(Pki);
WCertificationRequestInfo::Init(Pki);
WCertificationRequest::Init(Pki);
WCipher::Init(Pki);
WChain::Init(Pki);
WPkcs12::Init(Pki);
WRevocation::Init(Pki);
v8::Local<v8::Object> Cms = Nan::New<v8::Object>();
target->Set(Nan::New("CMS").ToLocalChecked(), Cms);
WSignedData::Init(Cms);
WSigner::Init(Cms);
WSignerCollection::Init(Cms);
WSignerAttributeCollection::Init(Cms);
v8::Local<v8::Object> PkiStore = Nan::New<v8::Object>();
target->Set(Nan::New("PKISTORE").ToLocalChecked(), PkiStore);
WPkiStore::Init(PkiStore);
WProvider_System::Init(PkiStore);
WProviderMicrosoft::Init(PkiStore);
WFilter::Init(PkiStore);
WPkiItem::Init(PkiStore);
WCashJson::Init(PkiStore);
// target->Set(NanNew<v8::String>("utils"), NanNew<v8::Object>());
// WLogger::Init(target->Get(NanNew<v8::String>("utils"))->ToObject());
// logger.start("log-node.txt", LoggerLevel::Debug);
}
NODE_MODULE(trusted, init)<|endoftext|>
|
<commit_before>// -*- Mode: C++; tab-width: 2; -*-
// vi: set ts=2:
//
// $Id: lineBasedFile.C,v 1.26 2003/07/09 12:55:13 amoll Exp $
#include <BALL/FORMAT/lineBasedFile.h>
#include <BALL/COMMON/exception.h>
#include <stdio.h>
using namespace std;
namespace BALL
{
LineBasedFile::LineBasedFile()
throw()
: File(),
line_number_(0)
{
}
LineBasedFile::LineBasedFile(const LineBasedFile& f)
throw(Exception::FileNotFound)
: File(),
line_number_(0)
{
if (f.getName() != "")
{
open(f.getName());
skipLines(f.line_number_ - 1);
}
}
LineBasedFile::LineBasedFile(const String& filename, File::OpenMode open_mode)
throw(Exception::FileNotFound)
: File(filename, open_mode),
line_number_(0)
{
if (!isAccessible())
{
throw Exception::FileNotFound(__FILE__, __LINE__, filename);
}
}
const LineBasedFile& LineBasedFile::operator = (const LineBasedFile& f)
throw(Exception::FileNotFound)
{
open(f.getName(), f.getOpenMode());
line_number_ = 0;
skipLines(f.line_number_ - 1);
return *this;
}
bool LineBasedFile::operator == (const LineBasedFile& f) throw()
{
return File::operator == (f);
}
bool LineBasedFile::operator != (const LineBasedFile& f) throw()
{
return !(File::operator == (f));
}
bool LineBasedFile::search(const String& text, bool return_to_start)
throw(Exception::ParseError)
{
if (!isOpen() || getOpenMode() != IN)
{
throw Exception::ParseError(__FILE__, __LINE__, String("File '") + getName() + "' not open for reading" ,
"LineBasedFile::search");
}
Position start_point = line_number_;
while (readLine())
{
if (startsWith(text))
{
return true;
}
}
if (return_to_start)
{
gotoLine(start_point);
}
return false;
}
bool LineBasedFile::search(const String& text, const String& stop, bool return_to_start)
throw(Exception::ParseError)
{
if (!isOpen() || getOpenMode() != IN)
{
throw Exception::ParseError(__FILE__, __LINE__, String("File '") + getName() + "' not open for reading" ,
"LineBasedFile::search");
}
Position start_point = line_number_;
while (readLine())
{
if (startsWith(stop))
{
if (return_to_start)
{
gotoLine(start_point);
}
return false;
}
if (startsWith(text))
{
return true;
}
}
if (return_to_start)
{
gotoLine(start_point);
}
return false;
}
bool LineBasedFile::readLine()
throw(Exception::ParseError)
{
if (!isOpen() || getOpenMode() != IN)
{
throw Exception::ParseError(__FILE__, __LINE__, String("File '") + getName() + "' not open for reading" ,
"LineBasedFile::readLine");
}
static char buffer[BALL_MAX_LINE_LENGTH];
getFileStream().getline(buffer, BALL_MAX_LINE_LENGTH);
line_.assign(buffer);
++line_number_;
return !eof();
}
bool LineBasedFile::skipLines(Size number)
throw(Exception::ParseError)
{
for (Position i = 0; i < number +1; i++)
{
if (!readLine())
{
return false;
}
}
return true;
}
void LineBasedFile::rewind()
throw(Exception::ParseError)
{
if (!isOpen())
{
throw Exception::ParseError(__FILE__, __LINE__, String("File '") + getName() + "' not open" ,
"LineBasedFile::rewind");
}
File::reopen();
line_number_ = 0;
line_ = "";
}
bool LineBasedFile::gotoLine(Position line_number)
throw(Exception::ParseError)
{
if (!isOpen())
{
throw Exception::ParseError(__FILE__, __LINE__, String("File '") + getName() + "' not open for reading" ,
"LineBasedFile::gotoLine");
}
if (line_number == line_number_)
{
return true;
}
if (line_number < line_number_)
{
rewind();
if (line_number == 0)
{
return true;
}
return skipLines(line_number - 1);
}
return skipLines(line_number - line_number_ - 1);
}
void LineBasedFile::clear()
throw()
{
line_ = "";
line_number_ = 0;
File::clear();
}
void LineBasedFile::test(const char* file, int line, bool condition, const String& msg)
const throw(Exception::ParseError)
{
if (!condition)
{
throw Exception::ParseError(file, line, String("File '") + getName() + "' while parsing line " + String(getLineNumber()), msg);
}
}
String LineBasedFile::getField(Index pos, const String& quotes, const String& delimiters)
const throw(Exception::IndexUnderflow)
{
if (quotes == "")
{
return line_.getField(pos, delimiters.c_str());
}
return line_.getFieldQuoted(pos, delimiters.c_str(), quotes.c_str());
}
Index LineBasedFile::switchString(const vector<String>& data)
const throw()
{
for (Index i = 0; i < (Index) data.size(); i++)
{
if (line_ == data[i])
{
return i;
}
}
return (-1);
}
bool LineBasedFile::startsWith(const String& text)
const throw()
{
return line_.hasPrefix(text);
}
bool LineBasedFile::has(const String& text)
const throw()
{
return line_.hasSubstring(text);
}
bool LineBasedFile::parseColumnFormat(const char* format, Position start, Size length, void* ptr)
{
// the number of entries parsed
int read = 0;
// make sure the specified section of the string exists
if (getLine().size() >= (start + length))
{
const Size max_len = 16384;
static char buf[max_len + 1];
length = std::min(length, max_len);
// copy the specified string section into the buffer...
strncpy(buf, line_.c_str() + start, length);
buf[length] = '\0';
// ...and try to parse it.
read = sscanf(buf, format, ptr);
}
else
{
Log.warn() << "LineBasedFile::parseColumnFormat: undefined position while parsing line ("
<< start << "-" << start + length << " in line of length " << getLine().size() << ")" << std::endl;
}
// return true if exactly one entry was read
return (read == 1);
}
# ifdef BALL_NO_INLINE_FUNCTIONS
# include <BALL/FORMAT/lineBasedFile.iC>
# endif
} // namespace BALL
<commit_msg>no message<commit_after>// -*- Mode: C++; tab-width: 2; -*-
// vi: set ts=2:
//
// $Id: lineBasedFile.C,v 1.27 2003/07/11 14:03:14 amoll Exp $
#include <BALL/FORMAT/lineBasedFile.h>
#include <BALL/COMMON/exception.h>
#include <stdio.h>
using namespace std;
namespace BALL
{
LineBasedFile::LineBasedFile()
throw()
: File(),
line_number_(0),
trim_whitespaces_(false)
{
}
LineBasedFile::LineBasedFile(const LineBasedFile& f)
throw(Exception::FileNotFound)
: File(),
line_number_(0),
trim_whitespaces_(f.trim_whitespaces_)
{
if (f.getName() != "")
{
open(f.getName());
skipLines(f.line_number_ - 1);
}
}
LineBasedFile::LineBasedFile(const String& filename, File::OpenMode open_mode, bool trim_whitespaces)
throw(Exception::FileNotFound)
: File(filename, open_mode),
line_number_(0),
trim_whitespaces_(trim_whitespaces)
{
if (!isAccessible())
{
throw Exception::FileNotFound(__FILE__, __LINE__, filename);
}
}
const LineBasedFile& LineBasedFile::operator = (const LineBasedFile& f)
throw(Exception::FileNotFound)
{
open(f.getName(), f.getOpenMode());
line_number_ = 0;
trim_whitespaces_ = f.trim_whitespaces_;
skipLines(f.line_number_ - 1);
return *this;
}
bool LineBasedFile::operator == (const LineBasedFile& f) throw()
{
return File::operator == (f);
}
bool LineBasedFile::operator != (const LineBasedFile& f) throw()
{
return !(File::operator == (f));
}
bool LineBasedFile::search(const String& text, bool return_to_start)
throw(Exception::ParseError)
{
if (!isOpen() || getOpenMode() != IN)
{
throw Exception::ParseError(__FILE__, __LINE__, String("File '") + getName() + "' not open for reading" ,
"LineBasedFile::search");
}
Position start_point = line_number_;
while (readLine())
{
if (startsWith(text))
{
return true;
}
}
if (return_to_start)
{
gotoLine(start_point);
}
return false;
}
bool LineBasedFile::search(const String& text, const String& stop, bool return_to_start)
throw(Exception::ParseError)
{
if (!isOpen() || getOpenMode() != IN)
{
throw Exception::ParseError(__FILE__, __LINE__, String("File '") + getName() + "' not open for reading" ,
"LineBasedFile::search");
}
Position start_point = line_number_;
while (readLine())
{
if (startsWith(stop))
{
if (return_to_start)
{
gotoLine(start_point);
}
return false;
}
if (startsWith(text))
{
return true;
}
}
if (return_to_start)
{
gotoLine(start_point);
}
return false;
}
bool LineBasedFile::readLine()
throw(Exception::ParseError)
{
if (!isOpen() || getOpenMode() != IN)
{
throw Exception::ParseError(__FILE__, __LINE__, String("File '") + getName() + "' not open for reading" ,
"LineBasedFile::readLine");
}
static char buffer[BALL_MAX_LINE_LENGTH];
getFileStream().getline(buffer, BALL_MAX_LINE_LENGTH);
line_.assign(buffer);
if (trim_whitespaces_) line_.trim();
++line_number_;
return !eof();
}
bool LineBasedFile::skipLines(Size number)
throw(Exception::ParseError)
{
for (Position i = 0; i < number +1; i++)
{
if (!readLine())
{
return false;
}
}
return true;
}
void LineBasedFile::rewind()
throw(Exception::ParseError)
{
if (!isOpen())
{
throw Exception::ParseError(__FILE__, __LINE__, String("File '") + getName() + "' not open" ,
"LineBasedFile::rewind");
}
File::reopen();
line_number_ = 0;
line_ = "";
}
bool LineBasedFile::gotoLine(Position line_number)
throw(Exception::ParseError)
{
if (!isOpen())
{
throw Exception::ParseError(__FILE__, __LINE__, String("File '") + getName() + "' not open for reading" ,
"LineBasedFile::gotoLine");
}
if (line_number == line_number_)
{
return true;
}
if (line_number < line_number_)
{
rewind();
if (line_number == 0)
{
return true;
}
return skipLines(line_number - 1);
}
return skipLines(line_number - line_number_ - 1);
}
void LineBasedFile::clear()
throw()
{
line_ = "";
line_number_ = 0;
File::clear();
trim_whitespaces_ = false;
}
void LineBasedFile::test(const char* file, int line, bool condition, const String& msg)
const throw(Exception::ParseError)
{
if (!condition)
{
throw Exception::ParseError(file, line, String("File '") + getName() + "' while parsing line " + String(getLineNumber()), msg);
}
}
String LineBasedFile::getField(Index pos, const String& quotes, const String& delimiters)
const throw(Exception::IndexUnderflow)
{
if (quotes == "")
{
return line_.getField(pos, delimiters.c_str());
}
return line_.getFieldQuoted(pos, delimiters.c_str(), quotes.c_str());
}
Index LineBasedFile::switchString(const vector<String>& data)
const throw()
{
for (Index i = 0; i < (Index) data.size(); i++)
{
if (line_ == data[i])
{
return i;
}
}
return (-1);
}
bool LineBasedFile::startsWith(const String& text)
const throw()
{
return line_.hasPrefix(text);
}
bool LineBasedFile::has(const String& text)
const throw()
{
return line_.hasSubstring(text);
}
bool LineBasedFile::parseColumnFormat(const char* format, Position start, Size length, void* ptr)
{
// the number of entries parsed
int read = 0;
// make sure the specified section of the string exists
if (getLine().size() >= (start + length))
{
const Size max_len = 16384;
static char buf[max_len + 1];
length = std::min(length, max_len);
// copy the specified string section into the buffer...
strncpy(buf, line_.c_str() + start, length);
buf[length] = '\0';
// ...and try to parse it.
read = sscanf(buf, format, ptr);
}
else
{
Log.warn() << "LineBasedFile::parseColumnFormat: undefined position while parsing line ("
<< start << "-" << start + length << " in line of length " << getLine().size() << ")" << std::endl;
}
// return true if exactly one entry was read
return (read == 1);
}
void LineBasedFile::enableTrimWhitespaces(bool state)
throw()
{
trim_whitespaces_ = state;
}
bool LineBasedFile::trimWhiteSpacesEnabled() const
throw()
{
return trim_whitespaces_;
}
# ifdef BALL_NO_INLINE_FUNCTIONS
# include <BALL/FORMAT/lineBasedFile.iC>
# endif
} // namespace BALL
<|endoftext|>
|
<commit_before>/*************************************************************************
*
* $RCSfile: valuenodeaccess.hxx,v $
*
* $Revision: 1.3 $
*
* last change: $Author: vg $ $Date: 2003-04-01 13:35:21 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the "License"); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#ifndef CONFIGMGR_VALUENODEACCESS_HXX
#define CONFIGMGR_VALUENODEACCESS_HXX
#ifndef CONFIGMGR_NODEACCESS_HXX
#include "nodeaccess.hxx"
#endif
namespace configmgr
{
// -----------------------------------------------------------------------------
namespace data
{
// -------------------------------------------------------------------------
class ValueNodeAccess
{
public:
typedef NodeAccess::Name Name;
typedef NodeAccess::Attributes Attributes;
typedef ValueNodeAddress NodeAddressType;
typedef ValueNodeAddress::AddressType AddressType;
typedef ValueNodeAddress::DataType const DataType;
typedef DataType * NodePointerType;
ValueNodeAccess(Accessor const& _aAccessor, NodeAddressType const& _aNodeRef)
: m_aAccessor(_aAccessor)
, m_pData(_aNodeRef.m_pData)
{}
ValueNodeAccess(Accessor const& _aAccessor, NodePointerType _pNode)
: m_aAccessor(_aAccessor)
, m_pData(check(_aAccessor,_pNode))
{}
explicit
ValueNodeAccess(NodeAccess const & _aNode)
: m_aAccessor(_aNode.accessor())
, m_pData(check(_aNode))
{
}
explicit
ValueNodeAccess(NodeAccessRef const & _aNode)
: m_aAccessor(_aNode.accessor())
, m_pData(check(_aNode))
{
}
static bool isInstance(NodeAccessRef const & _aNode)
{
return check(_aNode) != NULL;
}
bool isValid() const { return m_pData != NULL; }
Name getName() const;
Attributes getAttributes() const;
bool isEmpty() const { return data().isEmpty(); }
bool isNull() const { return data().isNull(); }
bool isDefault() const;
bool isLocalized() const;
bool hasUsableDefault() const { return data().hasUsableDefault(); }
uno::Type getValueType() const { return data().getValueType(); }
uno::Any getValue() const;
uno::Any getUserValue() const;
uno::Any getDefaultValue() const;
static void setValue(memory::UpdateAccessor & _aUpdater, NodeAddressType _aValueNode, uno::Any const& _aValue);
static void setToDefault(memory::UpdateAccessor & _aUpdater, NodeAddressType _aValueNode);
static void changeDefault(memory::UpdateAccessor & _aUpdater, NodeAddressType _aValueNode, uno::Any const& _aValue);
NodeAddressType address() const { return NodeAddressType(m_pData); }
Accessor const& accessor() const { return m_aAccessor; }
DataType& data() const { return *static_cast<NodePointerType>(m_aAccessor.validate(m_pData)); }
operator NodeAccessRef() const { return NodeAccessRef(&m_aAccessor,NodeAddress(m_pData)); }
private:
static AddressType check(Accessor const& _acc, NodePointerType _p) { return _acc.address(_p); }
static AddressType check(NodeAccessRef const& _aNodeData);
Accessor m_aAccessor;
AddressType m_pData;
};
ValueNodeAddress toValueNodeAddress(memory::Accessor const & _aAccess, NodeAddress const & _aNodeAddr);
ValueNodeAddress toValueNodeAddress(memory::UpdateAccessor & _aAccess, NodeAddress const & _aNodeAddr);
// -------------------------------------------------------------------------
inline
NodeAccess::Name ValueNodeAccess::getName() const
{ return NodeAccess::wrapName( data().info.getName(m_aAccessor) ); }
inline
NodeAccess::Attributes ValueNodeAccess::getAttributes() const
{ return sharable::node(data()).getAttributes(); }
inline
bool ValueNodeAccess::isDefault() const
{ return data().info.isDefault(); }
inline
bool ValueNodeAccess::isLocalized() const
{ return data().info.isLocalized(); }
inline
uno::Any ValueNodeAccess::getValue() const
{ return data().getValue(m_aAccessor); }
inline
uno::Any ValueNodeAccess::getUserValue() const
{ return data().getUserValue(m_aAccessor); }
inline
uno::Any ValueNodeAccess::getDefaultValue() const
{ return data().getDefaultValue(m_aAccessor); }
// -------------------------------------------------------------------------
}
// -----------------------------------------------------------------------------
} // namespace configmgr
#endif // CONFIGMGR_VALUENODEACCESS_HXX
<commit_msg>INTEGRATION: CWS ooo19126 (1.3.190); FILE MERGED 2005/09/05 17:04:43 rt 1.3.190.1: #i54170# Change license header: remove SISSL<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: valuenodeaccess.hxx,v $
*
* $Revision: 1.4 $
*
* last change: $Author: rt $ $Date: 2005-09-08 04:02:20 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#ifndef CONFIGMGR_VALUENODEACCESS_HXX
#define CONFIGMGR_VALUENODEACCESS_HXX
#ifndef CONFIGMGR_NODEACCESS_HXX
#include "nodeaccess.hxx"
#endif
namespace configmgr
{
// -----------------------------------------------------------------------------
namespace data
{
// -------------------------------------------------------------------------
class ValueNodeAccess
{
public:
typedef NodeAccess::Name Name;
typedef NodeAccess::Attributes Attributes;
typedef ValueNodeAddress NodeAddressType;
typedef ValueNodeAddress::AddressType AddressType;
typedef ValueNodeAddress::DataType const DataType;
typedef DataType * NodePointerType;
ValueNodeAccess(Accessor const& _aAccessor, NodeAddressType const& _aNodeRef)
: m_aAccessor(_aAccessor)
, m_pData(_aNodeRef.m_pData)
{}
ValueNodeAccess(Accessor const& _aAccessor, NodePointerType _pNode)
: m_aAccessor(_aAccessor)
, m_pData(check(_aAccessor,_pNode))
{}
explicit
ValueNodeAccess(NodeAccess const & _aNode)
: m_aAccessor(_aNode.accessor())
, m_pData(check(_aNode))
{
}
explicit
ValueNodeAccess(NodeAccessRef const & _aNode)
: m_aAccessor(_aNode.accessor())
, m_pData(check(_aNode))
{
}
static bool isInstance(NodeAccessRef const & _aNode)
{
return check(_aNode) != NULL;
}
bool isValid() const { return m_pData != NULL; }
Name getName() const;
Attributes getAttributes() const;
bool isEmpty() const { return data().isEmpty(); }
bool isNull() const { return data().isNull(); }
bool isDefault() const;
bool isLocalized() const;
bool hasUsableDefault() const { return data().hasUsableDefault(); }
uno::Type getValueType() const { return data().getValueType(); }
uno::Any getValue() const;
uno::Any getUserValue() const;
uno::Any getDefaultValue() const;
static void setValue(memory::UpdateAccessor & _aUpdater, NodeAddressType _aValueNode, uno::Any const& _aValue);
static void setToDefault(memory::UpdateAccessor & _aUpdater, NodeAddressType _aValueNode);
static void changeDefault(memory::UpdateAccessor & _aUpdater, NodeAddressType _aValueNode, uno::Any const& _aValue);
NodeAddressType address() const { return NodeAddressType(m_pData); }
Accessor const& accessor() const { return m_aAccessor; }
DataType& data() const { return *static_cast<NodePointerType>(m_aAccessor.validate(m_pData)); }
operator NodeAccessRef() const { return NodeAccessRef(&m_aAccessor,NodeAddress(m_pData)); }
private:
static AddressType check(Accessor const& _acc, NodePointerType _p) { return _acc.address(_p); }
static AddressType check(NodeAccessRef const& _aNodeData);
Accessor m_aAccessor;
AddressType m_pData;
};
ValueNodeAddress toValueNodeAddress(memory::Accessor const & _aAccess, NodeAddress const & _aNodeAddr);
ValueNodeAddress toValueNodeAddress(memory::UpdateAccessor & _aAccess, NodeAddress const & _aNodeAddr);
// -------------------------------------------------------------------------
inline
NodeAccess::Name ValueNodeAccess::getName() const
{ return NodeAccess::wrapName( data().info.getName(m_aAccessor) ); }
inline
NodeAccess::Attributes ValueNodeAccess::getAttributes() const
{ return sharable::node(data()).getAttributes(); }
inline
bool ValueNodeAccess::isDefault() const
{ return data().info.isDefault(); }
inline
bool ValueNodeAccess::isLocalized() const
{ return data().info.isLocalized(); }
inline
uno::Any ValueNodeAccess::getValue() const
{ return data().getValue(m_aAccessor); }
inline
uno::Any ValueNodeAccess::getUserValue() const
{ return data().getUserValue(m_aAccessor); }
inline
uno::Any ValueNodeAccess::getDefaultValue() const
{ return data().getDefaultValue(m_aAccessor); }
// -------------------------------------------------------------------------
}
// -----------------------------------------------------------------------------
} // namespace configmgr
#endif // CONFIGMGR_VALUENODEACCESS_HXX
<|endoftext|>
|
<commit_before>/*************************************************************************
*
* $RCSfile: AKey.cxx,v $
*
* $Revision: 1.17 $
*
* last change: $Author: oj $ $Date: 2002-07-11 06:56:38 $
*
* 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 _CONNECTIVITY_ADO_KEY_HXX_
#include "ado/AKey.hxx"
#endif
#ifndef _COM_SUN_STAR_SDBC_XROW_HPP_
#include <com/sun/star/sdbc/XRow.hpp>
#endif
#ifndef _COM_SUN_STAR_SDBC_XRESULTSET_HPP_
#include <com/sun/star/sdbc/XResultSet.hpp>
#endif
#ifndef _CPPUHELPER_TYPEPROVIDER_HXX_
#include <cppuhelper/typeprovider.hxx>
#endif
#ifndef _COMPHELPER_SEQUENCE_HXX_
#include <comphelper/sequence.hxx>
#endif
#ifndef _CONNECTIVITY_ADO_COLUMNS_HXX_
#include "ado/AColumns.hxx"
#endif
#ifndef _CONNECTIVITY_ADO_ACONNECTION_HXX_
#include "ado/AConnection.hxx"
#endif
using namespace connectivity::ado;
using namespace com::sun::star::uno;
using namespace com::sun::star::lang;
using namespace com::sun::star::beans;
using namespace com::sun::star::sdbc;
using namespace com::sun::star::sdbcx;
// -------------------------------------------------------------------------
OAdoKey::OAdoKey(sal_Bool _bCase,OConnection* _pConnection, ADOKey* _pKey)
: OKey_ADO(_bCase)
,m_pConnection(_pConnection)
{
construct();
m_aKey = WpADOKey(_pKey);
fillPropertyValues();
}
// -------------------------------------------------------------------------
OAdoKey::OAdoKey(sal_Bool _bCase,OConnection* _pConnection)
: OKey_ADO(_bCase)
,m_pConnection(_pConnection)
{
construct();
m_aKey.Create();
}
// -------------------------------------------------------------------------
void OAdoKey::refreshColumns()
{
TStringVector aVector;
WpADOColumns aColumns;
if ( m_aKey.IsValid() )
{
aColumns = m_aKey.get_Columns();
aColumns.fillElementNames(aVector);
}
if(m_pColumns)
m_pColumns->reFill(aVector);
else
m_pColumns = new OColumns(*this,m_aMutex,aVector,aColumns,isCaseSensitive(),m_pConnection);
}
// -------------------------------------------------------------------------
Sequence< sal_Int8 > OAdoKey::getUnoTunnelImplementationId()
{
static ::cppu::OImplementationId * pId = 0;
if (! pId)
{
::osl::MutexGuard aGuard( ::osl::Mutex::getGlobalMutex() );
if (! pId)
{
static ::cppu::OImplementationId aId;
pId = &aId;
}
}
return pId->getImplementationId();
}
// com::sun::star::lang::XUnoTunnel
//------------------------------------------------------------------
sal_Int64 OAdoKey::getSomething( const Sequence< sal_Int8 > & rId ) throw (RuntimeException)
{
return (rId.getLength() == 16 && 0 == rtl_compareMemory(getUnoTunnelImplementationId().getConstArray(), rId.getConstArray(), 16 ) )
?
(sal_Int64)this
:
OKey_ADO::getSomething(rId);
}
// -------------------------------------------------------------------------
void OAdoKey::setFastPropertyValue_NoBroadcast(sal_Int32 nHandle,const Any& rValue)throw (Exception)
{
if(m_aKey.IsValid())
{
switch(nHandle)
{
case PROPERTY_ID_NAME:
{
::rtl::OUString aVal;
rValue >>= aVal;
m_aKey.put_Name(aVal);
ADOS::ThrowException(*m_pConnection->getConnection(),*this);
}
break;
case PROPERTY_ID_TYPE:
{
sal_Int32 nVal=0;
rValue >>= nVal;
m_aKey.put_Type(Map2KeyRule(nVal));
ADOS::ThrowException(*m_pConnection->getConnection(),*this);
}
break;
case PROPERTY_ID_REFERENCEDTABLE:
{
::rtl::OUString aVal;
rValue >>= aVal;
m_aKey.put_RelatedTable(aVal);
ADOS::ThrowException(*m_pConnection->getConnection(),*this);
}
break;
case PROPERTY_ID_UPDATERULE:
{
sal_Int32 nVal=0;
rValue >>= nVal;
m_aKey.put_UpdateRule(Map2Rule(nVal));
ADOS::ThrowException(*m_pConnection->getConnection(),*this);
}
break;
case PROPERTY_ID_DELETERULE:
{
sal_Int32 nVal=0;
rValue >>= nVal;
m_aKey.put_DeleteRule(Map2Rule(nVal));
ADOS::ThrowException(*m_pConnection->getConnection(),*this);
}
break;
}
}
OKey_ADO::setFastPropertyValue_NoBroadcast(nHandle,rValue);
}
// -------------------------------------------------------------------------
// -----------------------------------------------------------------------------
void SAL_CALL OAdoKey::acquire() throw(::com::sun::star::uno::RuntimeException)
{
OKey_ADO::acquire();
}
// -----------------------------------------------------------------------------
void SAL_CALL OAdoKey::release() throw(::com::sun::star::uno::RuntimeException)
{
OKey_ADO::release();
}
// -----------------------------------------------------------------------------
<commit_msg>INTEGRATION: CWS ooo19126 (1.17.326); FILE MERGED 2005/09/05 17:23:15 rt 1.17.326.1: #i54170# Change license header: remove SISSL<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: AKey.cxx,v $
*
* $Revision: 1.18 $
*
* last change: $Author: rt $ $Date: 2005-09-08 05:29:25 $
*
* 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 _CONNECTIVITY_ADO_KEY_HXX_
#include "ado/AKey.hxx"
#endif
#ifndef _COM_SUN_STAR_SDBC_XROW_HPP_
#include <com/sun/star/sdbc/XRow.hpp>
#endif
#ifndef _COM_SUN_STAR_SDBC_XRESULTSET_HPP_
#include <com/sun/star/sdbc/XResultSet.hpp>
#endif
#ifndef _CPPUHELPER_TYPEPROVIDER_HXX_
#include <cppuhelper/typeprovider.hxx>
#endif
#ifndef _COMPHELPER_SEQUENCE_HXX_
#include <comphelper/sequence.hxx>
#endif
#ifndef _CONNECTIVITY_ADO_COLUMNS_HXX_
#include "ado/AColumns.hxx"
#endif
#ifndef _CONNECTIVITY_ADO_ACONNECTION_HXX_
#include "ado/AConnection.hxx"
#endif
using namespace connectivity::ado;
using namespace com::sun::star::uno;
using namespace com::sun::star::lang;
using namespace com::sun::star::beans;
using namespace com::sun::star::sdbc;
using namespace com::sun::star::sdbcx;
// -------------------------------------------------------------------------
OAdoKey::OAdoKey(sal_Bool _bCase,OConnection* _pConnection, ADOKey* _pKey)
: OKey_ADO(_bCase)
,m_pConnection(_pConnection)
{
construct();
m_aKey = WpADOKey(_pKey);
fillPropertyValues();
}
// -------------------------------------------------------------------------
OAdoKey::OAdoKey(sal_Bool _bCase,OConnection* _pConnection)
: OKey_ADO(_bCase)
,m_pConnection(_pConnection)
{
construct();
m_aKey.Create();
}
// -------------------------------------------------------------------------
void OAdoKey::refreshColumns()
{
TStringVector aVector;
WpADOColumns aColumns;
if ( m_aKey.IsValid() )
{
aColumns = m_aKey.get_Columns();
aColumns.fillElementNames(aVector);
}
if(m_pColumns)
m_pColumns->reFill(aVector);
else
m_pColumns = new OColumns(*this,m_aMutex,aVector,aColumns,isCaseSensitive(),m_pConnection);
}
// -------------------------------------------------------------------------
Sequence< sal_Int8 > OAdoKey::getUnoTunnelImplementationId()
{
static ::cppu::OImplementationId * pId = 0;
if (! pId)
{
::osl::MutexGuard aGuard( ::osl::Mutex::getGlobalMutex() );
if (! pId)
{
static ::cppu::OImplementationId aId;
pId = &aId;
}
}
return pId->getImplementationId();
}
// com::sun::star::lang::XUnoTunnel
//------------------------------------------------------------------
sal_Int64 OAdoKey::getSomething( const Sequence< sal_Int8 > & rId ) throw (RuntimeException)
{
return (rId.getLength() == 16 && 0 == rtl_compareMemory(getUnoTunnelImplementationId().getConstArray(), rId.getConstArray(), 16 ) )
?
(sal_Int64)this
:
OKey_ADO::getSomething(rId);
}
// -------------------------------------------------------------------------
void OAdoKey::setFastPropertyValue_NoBroadcast(sal_Int32 nHandle,const Any& rValue)throw (Exception)
{
if(m_aKey.IsValid())
{
switch(nHandle)
{
case PROPERTY_ID_NAME:
{
::rtl::OUString aVal;
rValue >>= aVal;
m_aKey.put_Name(aVal);
ADOS::ThrowException(*m_pConnection->getConnection(),*this);
}
break;
case PROPERTY_ID_TYPE:
{
sal_Int32 nVal=0;
rValue >>= nVal;
m_aKey.put_Type(Map2KeyRule(nVal));
ADOS::ThrowException(*m_pConnection->getConnection(),*this);
}
break;
case PROPERTY_ID_REFERENCEDTABLE:
{
::rtl::OUString aVal;
rValue >>= aVal;
m_aKey.put_RelatedTable(aVal);
ADOS::ThrowException(*m_pConnection->getConnection(),*this);
}
break;
case PROPERTY_ID_UPDATERULE:
{
sal_Int32 nVal=0;
rValue >>= nVal;
m_aKey.put_UpdateRule(Map2Rule(nVal));
ADOS::ThrowException(*m_pConnection->getConnection(),*this);
}
break;
case PROPERTY_ID_DELETERULE:
{
sal_Int32 nVal=0;
rValue >>= nVal;
m_aKey.put_DeleteRule(Map2Rule(nVal));
ADOS::ThrowException(*m_pConnection->getConnection(),*this);
}
break;
}
}
OKey_ADO::setFastPropertyValue_NoBroadcast(nHandle,rValue);
}
// -------------------------------------------------------------------------
// -----------------------------------------------------------------------------
void SAL_CALL OAdoKey::acquire() throw(::com::sun::star::uno::RuntimeException)
{
OKey_ADO::acquire();
}
// -----------------------------------------------------------------------------
void SAL_CALL OAdoKey::release() throw(::com::sun::star::uno::RuntimeException)
{
OKey_ADO::release();
}
// -----------------------------------------------------------------------------
<|endoftext|>
|
<commit_before>//=================================================================================================
//
// MJP's DX11 Sample Framework
// http://mynameismjp.wordpress.com/
//
// All code and content licensed under Microsoft Public License (Ms-PL)
//
//=================================================================================================
/**
* Modified for use in The Halfling Project - A Graphics Engine and Projects
* The Halfling Project is the legal property of Adrian Astley
* Copyright Adrian Astley 2013
*/
#include "common/sprite_font.h"
#include "common/halfling_sys.h"
#include "common/d3d_util.h"
#include <d3d11.h>
#include <algorithm>
namespace Common {
SpriteFont::SpriteFont()
: m_size(0),
m_texHeight(0),
m_spaceWidth(0),
m_charHeight(0) {
}
SpriteFont::~SpriteFont() {
}
void SpriteFont::Initialize(const wchar *fontName, float fontSize, UINT fontStyle, bool antiAliased, ID3D11Device *device) {
m_size = fontSize;
Gdiplus::TextRenderingHint hint = antiAliased ? Gdiplus::TextRenderingHintAntiAliasGridFit : Gdiplus::TextRenderingHintSingleBitPerPixelGridFit;
// Init GDI+
ULONG_PTR token = NULL;
Gdiplus::GdiplusStartupInput startupInput(NULL, true, true);
Gdiplus::GdiplusStartupOutput startupOutput;
HR(GdiplusStartup(&token, &startupInput, &startupOutput));
// Create the font
Gdiplus::Font font(fontName, fontSize, fontStyle, Gdiplus::UnitPixel, NULL);
// Check for error during construction
HR(font.GetLastStatus());
// Create a temporary Bitmap and Graphics for figuring out the rough size required
// for drawing all of the characters
int size = static_cast<int>(fontSize * NumChars * 2) + 1;
Gdiplus::Bitmap sizeBitmap(size, size, PixelFormat32bppARGB);
HR(sizeBitmap.GetLastStatus());
Gdiplus::Graphics sizeGraphics(&sizeBitmap);
HR(sizeGraphics.GetLastStatus());
HR(sizeGraphics.SetTextRenderingHint(hint));
m_charHeight = font.GetHeight(&sizeGraphics) * 1.5f;
wchar allChars[NumChars + 1];
for (wchar i = 0; i < NumChars; ++i) {
allChars[i] = i + StartChar;
}
allChars[NumChars] = 0;
Gdiplus::RectF sizeRect;
HR(sizeGraphics.MeasureString(allChars, NumChars, &font, Gdiplus::PointF(0, 0), &sizeRect));
int numRows = static_cast<int>(sizeRect.Width / TexWidth) + 1;
int texHeight = static_cast<int>(numRows * m_charHeight) + 1;
// Create a temporary Bitmap and Graphics for drawing the characters one by one
int tempSize = static_cast<int>(fontSize * 2);
Gdiplus::Bitmap drawBitmap(tempSize, tempSize, PixelFormat32bppARGB);
HR(drawBitmap.GetLastStatus());
Gdiplus::Graphics drawGraphics(&drawBitmap);
HR(drawGraphics.GetLastStatus());
HR(drawGraphics.SetTextRenderingHint(hint));
// Create a temporary Bitmap + Graphics for creating a full character set
Gdiplus::Bitmap textBitmap(TexWidth, texHeight, PixelFormat32bppARGB);
HR(textBitmap.GetLastStatus());
Gdiplus::Graphics textGraphics(&textBitmap);
HR(textGraphics.GetLastStatus());
HR(textGraphics.Clear(Gdiplus::Color(0, 255, 255, 255)));
HR(textGraphics.SetCompositingMode(Gdiplus::CompositingModeSourceCopy));
// Solid brush for text rendering
Gdiplus::SolidBrush brush(Gdiplus::Color(255, 255, 255, 255));
HR(brush.GetLastStatus());
// Draw all of the characters, and copy them to the full character set
wchar charString [2];
charString[1] = 0;
int currentX = 0;
int currentY = 0;
for (uint64 i = 0; i < NumChars; ++i) {
charString[0] = static_cast<wchar>(i + StartChar);
// Draw the character
HR(drawGraphics.Clear(Gdiplus::Color(0, 255, 255, 255)));
HR(drawGraphics.DrawString(charString, 1, &font, Gdiplus::PointF(0, 0), &brush));
// Figure out the amount of blank space before the character
int minX = 0;
for (int x = 0; x < tempSize; ++x) {
for (int y = 0; y < tempSize; ++y) {
Gdiplus::Color color;
HR(drawBitmap.GetPixel(x, y, &color));
if (color.GetAlpha() > 0) {
minX = x;
x = tempSize;
break;
}
}
}
// Figure out the amount of blank space after the character
int maxX = tempSize - 1;
for (int x = tempSize - 1; x >= 0; --x) {
for (int y = 0; y < tempSize; ++y) {
Gdiplus::Color color;
HR(drawBitmap.GetPixel(x, y, &color));
if (color.GetAlpha() > 0) {
maxX = x;
x = -1;
break;
}
}
}
int charWidth = maxX - minX + 1;
// Figure out if we need to move to the next row
if (currentX + charWidth >= TexWidth) {
currentX = 0;
currentY += static_cast<int>(m_charHeight) + 1;
}
// Fill out the structure describing the character position
m_charDescs[i].X = static_cast<float>(currentX);
m_charDescs[i].Y = static_cast<float>(currentY);
m_charDescs[i].Width = static_cast<float>(charWidth);
m_charDescs[i].Height = static_cast<float>(m_charHeight);
// Copy the character over
int height = static_cast<int>(m_charHeight + 1);
HR(textGraphics.DrawImage(&drawBitmap, currentX, currentY, minX, 0, charWidth, height, Gdiplus::UnitPixel));
currentX += charWidth + 1;
}
// Figure out the width of a space character
charString[0] = ' ';
charString[1] = 0;
HR(drawGraphics.MeasureString(charString, 1, &font, Gdiplus::PointF(0, 0), &sizeRect));
m_spaceWidth = sizeRect.Width;
// Lock the bitmap for direct memory access
Gdiplus::BitmapData bmData;
HR(textBitmap.LockBits(&Gdiplus::Rect(0, 0, TexWidth, texHeight), Gdiplus::ImageLockModeRead, PixelFormat32bppARGB, &bmData));
// Create a D3D texture, initalized with the bitmap data
D3D11_TEXTURE2D_DESC texDesc;
texDesc.Width = TexWidth;
texDesc.Height = texHeight;
texDesc.MipLevels = 1;
texDesc.ArraySize = 1;
texDesc.Format = DXGI_FORMAT_B8G8R8A8_UNORM;
texDesc.SampleDesc.Count = 1;
texDesc.SampleDesc.Quality = 0;
texDesc.Usage = D3D11_USAGE_IMMUTABLE;
texDesc.BindFlags = D3D11_BIND_SHADER_RESOURCE;
texDesc.CPUAccessFlags = 0;
texDesc.MiscFlags = 0;
D3D11_SUBRESOURCE_DATA data;
data.pSysMem = bmData.Scan0;
data.SysMemPitch = TexWidth * 4;
data.SysMemSlicePitch = 0;
HR(device->CreateTexture2D(&texDesc, &data, &m_texture));
HR(textBitmap.UnlockBits(&bmData));
// Create the shader resource view
D3D11_SHADER_RESOURCE_VIEW_DESC srDesc;
srDesc.Format = DXGI_FORMAT_B8G8R8A8_UNORM;
srDesc.ViewDimension = D3D11_SRV_DIMENSION_TEXTURE2D;
srDesc.Texture2D.MipLevels = 1;
srDesc.Texture2D.MostDetailedMip = 0;
HR(device->CreateShaderResourceView(m_texture, &srDesc, &m_SRV));
// Shutdown GDI+
//Gdiplus::GdiplusShutdown(token);
// TODO: Figure out why this throws exceptions
}
ID3D11ShaderResourceView *SpriteFont::SRView() const {
return m_SRV;
}
const SpriteFont::CharDesc *SpriteFont::CharDescriptors() const {
return m_charDescs;
}
const SpriteFont::CharDesc &SpriteFont::GetCharDescriptor(wchar character) const {
assert(character >= StartChar && character <= EndChar);
return m_charDescs[character - StartChar];
}
float SpriteFont::Size() const {
return m_size;
}
uint SpriteFont::TextureWidth() const {
return TexWidth;
}
uint SpriteFont::TextureHeight() const {
return m_texHeight;
}
float SpriteFont::SpaceWidth() const {
return m_spaceWidth;
}
float SpriteFont::CharHeight() const {
return m_charHeight;
}
ID3D11Texture2D *SpriteFont::Texture() const {
return m_texture;
}
DirectX::XMFLOAT2 SpriteFont::MeasureText(const wchar *text, uint maxWidth) const {
DirectX::XMFLOAT2 size(0.0f, 0.0f);
DirectX::XMFLOAT2 curPos(0.0f, 0.0f);;
size_t length = wcslen(text);
for (uint64 i = 0; i < length; ++i) {
wchar character = text[i];
if (character == ' ') {
// Check for wrapping
if (maxWidth != 0U && curPos.x + m_spaceWidth > maxWidth) {
size.x = std::max(size.x, curPos.x);
curPos.y += m_charHeight;
curPos.x = 0;
}
curPos.x += m_spaceWidth;
} else if (character == '\t') {
// Check for wrapping
if (maxWidth != 0U && curPos.x + 4.0f * m_spaceWidth > maxWidth) {
curPos.y += m_charHeight;
curPos.x = 0;
}
curPos.x += 4.0f * m_spaceWidth;
} else if (character == '\n' || character == '\r') {
size.x = std::max(size.x, curPos.x);
curPos.y += m_charHeight;
curPos.x = 0;
} else {
SpriteFont::CharDesc desc = GetCharDescriptor(character);
// Check for wrapping
if (maxWidth != 0U && curPos.x + desc.Width + 1 > maxWidth) {
size.x = std::max(size.x, curPos.x);
curPos.y += m_charHeight;
curPos.x = 0;
}
curPos.x += desc.Width + 1;
}
size.x = std::max(curPos.x, size.x);
size.y = curPos.y;
}
return size;
}
}<commit_msg>COMMON: Add the final line height in the measurement<commit_after>//=================================================================================================
//
// MJP's DX11 Sample Framework
// http://mynameismjp.wordpress.com/
//
// All code and content licensed under Microsoft Public License (Ms-PL)
//
//=================================================================================================
/**
* Modified for use in The Halfling Project - A Graphics Engine and Projects
* The Halfling Project is the legal property of Adrian Astley
* Copyright Adrian Astley 2013
*/
#include "common/sprite_font.h"
#include "common/halfling_sys.h"
#include "common/d3d_util.h"
#include <d3d11.h>
#include <algorithm>
namespace Common {
SpriteFont::SpriteFont()
: m_size(0),
m_texHeight(0),
m_spaceWidth(0),
m_charHeight(0) {
}
SpriteFont::~SpriteFont() {
}
void SpriteFont::Initialize(const wchar *fontName, float fontSize, UINT fontStyle, bool antiAliased, ID3D11Device *device) {
m_size = fontSize;
Gdiplus::TextRenderingHint hint = antiAliased ? Gdiplus::TextRenderingHintAntiAliasGridFit : Gdiplus::TextRenderingHintSingleBitPerPixelGridFit;
// Init GDI+
ULONG_PTR token = NULL;
Gdiplus::GdiplusStartupInput startupInput(NULL, true, true);
Gdiplus::GdiplusStartupOutput startupOutput;
HR(GdiplusStartup(&token, &startupInput, &startupOutput));
// Create the font
Gdiplus::Font font(fontName, fontSize, fontStyle, Gdiplus::UnitPixel, NULL);
// Check for error during construction
HR(font.GetLastStatus());
// Create a temporary Bitmap and Graphics for figuring out the rough size required
// for drawing all of the characters
int size = static_cast<int>(fontSize * NumChars * 2) + 1;
Gdiplus::Bitmap sizeBitmap(size, size, PixelFormat32bppARGB);
HR(sizeBitmap.GetLastStatus());
Gdiplus::Graphics sizeGraphics(&sizeBitmap);
HR(sizeGraphics.GetLastStatus());
HR(sizeGraphics.SetTextRenderingHint(hint));
m_charHeight = font.GetHeight(&sizeGraphics) * 1.5f;
wchar allChars[NumChars + 1];
for (wchar i = 0; i < NumChars; ++i) {
allChars[i] = i + StartChar;
}
allChars[NumChars] = 0;
Gdiplus::RectF sizeRect;
HR(sizeGraphics.MeasureString(allChars, NumChars, &font, Gdiplus::PointF(0, 0), &sizeRect));
int numRows = static_cast<int>(sizeRect.Width / TexWidth) + 1;
int texHeight = static_cast<int>(numRows * m_charHeight) + 1;
// Create a temporary Bitmap and Graphics for drawing the characters one by one
int tempSize = static_cast<int>(fontSize * 2);
Gdiplus::Bitmap drawBitmap(tempSize, tempSize, PixelFormat32bppARGB);
HR(drawBitmap.GetLastStatus());
Gdiplus::Graphics drawGraphics(&drawBitmap);
HR(drawGraphics.GetLastStatus());
HR(drawGraphics.SetTextRenderingHint(hint));
// Create a temporary Bitmap + Graphics for creating a full character set
Gdiplus::Bitmap textBitmap(TexWidth, texHeight, PixelFormat32bppARGB);
HR(textBitmap.GetLastStatus());
Gdiplus::Graphics textGraphics(&textBitmap);
HR(textGraphics.GetLastStatus());
HR(textGraphics.Clear(Gdiplus::Color(0, 255, 255, 255)));
HR(textGraphics.SetCompositingMode(Gdiplus::CompositingModeSourceCopy));
// Solid brush for text rendering
Gdiplus::SolidBrush brush(Gdiplus::Color(255, 255, 255, 255));
HR(brush.GetLastStatus());
// Draw all of the characters, and copy them to the full character set
wchar charString [2];
charString[1] = 0;
int currentX = 0;
int currentY = 0;
for (uint64 i = 0; i < NumChars; ++i) {
charString[0] = static_cast<wchar>(i + StartChar);
// Draw the character
HR(drawGraphics.Clear(Gdiplus::Color(0, 255, 255, 255)));
HR(drawGraphics.DrawString(charString, 1, &font, Gdiplus::PointF(0, 0), &brush));
// Figure out the amount of blank space before the character
int minX = 0;
for (int x = 0; x < tempSize; ++x) {
for (int y = 0; y < tempSize; ++y) {
Gdiplus::Color color;
HR(drawBitmap.GetPixel(x, y, &color));
if (color.GetAlpha() > 0) {
minX = x;
x = tempSize;
break;
}
}
}
// Figure out the amount of blank space after the character
int maxX = tempSize - 1;
for (int x = tempSize - 1; x >= 0; --x) {
for (int y = 0; y < tempSize; ++y) {
Gdiplus::Color color;
HR(drawBitmap.GetPixel(x, y, &color));
if (color.GetAlpha() > 0) {
maxX = x;
x = -1;
break;
}
}
}
int charWidth = maxX - minX + 1;
// Figure out if we need to move to the next row
if (currentX + charWidth >= TexWidth) {
currentX = 0;
currentY += static_cast<int>(m_charHeight) + 1;
}
// Fill out the structure describing the character position
m_charDescs[i].X = static_cast<float>(currentX);
m_charDescs[i].Y = static_cast<float>(currentY);
m_charDescs[i].Width = static_cast<float>(charWidth);
m_charDescs[i].Height = static_cast<float>(m_charHeight);
// Copy the character over
int height = static_cast<int>(m_charHeight + 1);
HR(textGraphics.DrawImage(&drawBitmap, currentX, currentY, minX, 0, charWidth, height, Gdiplus::UnitPixel));
currentX += charWidth + 1;
}
// Figure out the width of a space character
charString[0] = ' ';
charString[1] = 0;
HR(drawGraphics.MeasureString(charString, 1, &font, Gdiplus::PointF(0, 0), &sizeRect));
m_spaceWidth = sizeRect.Width;
// Lock the bitmap for direct memory access
Gdiplus::BitmapData bmData;
HR(textBitmap.LockBits(&Gdiplus::Rect(0, 0, TexWidth, texHeight), Gdiplus::ImageLockModeRead, PixelFormat32bppARGB, &bmData));
// Create a D3D texture, initalized with the bitmap data
D3D11_TEXTURE2D_DESC texDesc;
texDesc.Width = TexWidth;
texDesc.Height = texHeight;
texDesc.MipLevels = 1;
texDesc.ArraySize = 1;
texDesc.Format = DXGI_FORMAT_B8G8R8A8_UNORM;
texDesc.SampleDesc.Count = 1;
texDesc.SampleDesc.Quality = 0;
texDesc.Usage = D3D11_USAGE_IMMUTABLE;
texDesc.BindFlags = D3D11_BIND_SHADER_RESOURCE;
texDesc.CPUAccessFlags = 0;
texDesc.MiscFlags = 0;
D3D11_SUBRESOURCE_DATA data;
data.pSysMem = bmData.Scan0;
data.SysMemPitch = TexWidth * 4;
data.SysMemSlicePitch = 0;
HR(device->CreateTexture2D(&texDesc, &data, &m_texture));
HR(textBitmap.UnlockBits(&bmData));
// Create the shader resource view
D3D11_SHADER_RESOURCE_VIEW_DESC srDesc;
srDesc.Format = DXGI_FORMAT_B8G8R8A8_UNORM;
srDesc.ViewDimension = D3D11_SRV_DIMENSION_TEXTURE2D;
srDesc.Texture2D.MipLevels = 1;
srDesc.Texture2D.MostDetailedMip = 0;
HR(device->CreateShaderResourceView(m_texture, &srDesc, &m_SRV));
// Shutdown GDI+
//Gdiplus::GdiplusShutdown(token);
// TODO: Figure out why this throws exceptions
}
ID3D11ShaderResourceView *SpriteFont::SRView() const {
return m_SRV;
}
const SpriteFont::CharDesc *SpriteFont::CharDescriptors() const {
return m_charDescs;
}
const SpriteFont::CharDesc &SpriteFont::GetCharDescriptor(wchar character) const {
assert(character >= StartChar && character <= EndChar);
return m_charDescs[character - StartChar];
}
float SpriteFont::Size() const {
return m_size;
}
uint SpriteFont::TextureWidth() const {
return TexWidth;
}
uint SpriteFont::TextureHeight() const {
return m_texHeight;
}
float SpriteFont::SpaceWidth() const {
return m_spaceWidth;
}
float SpriteFont::CharHeight() const {
return m_charHeight;
}
ID3D11Texture2D *SpriteFont::Texture() const {
return m_texture;
}
DirectX::XMFLOAT2 SpriteFont::MeasureText(const wchar *text, uint maxWidth) const {
DirectX::XMFLOAT2 size(0.0f, 0.0f);
DirectX::XMFLOAT2 curPos(0.0f, 0.0f);;
size_t length = wcslen(text);
for (uint64 i = 0; i < length; ++i) {
wchar character = text[i];
if (character == ' ') {
// Check for wrapping
if (maxWidth != 0U && curPos.x + m_spaceWidth > maxWidth) {
size.x = std::max(size.x, curPos.x);
curPos.y += m_charHeight;
curPos.x = 0;
}
curPos.x += m_spaceWidth;
} else if (character == '\t') {
// Check for wrapping
if (maxWidth != 0U && curPos.x + 4.0f * m_spaceWidth > maxWidth) {
curPos.y += m_charHeight;
curPos.x = 0;
}
curPos.x += 4.0f * m_spaceWidth;
} else if (character == '\n' || character == '\r') {
size.x = std::max(size.x, curPos.x);
curPos.y += m_charHeight;
curPos.x = 0;
} else {
SpriteFont::CharDesc desc = GetCharDescriptor(character);
// Check for wrapping
if (maxWidth != 0U && curPos.x + desc.Width + 1 > maxWidth) {
size.x = std::max(size.x, curPos.x);
curPos.y += m_charHeight;
curPos.x = 0;
}
curPos.x += desc.Width + 1;
}
size.x = std::max(curPos.x, size.x);
size.y = curPos.y + m_charHeight;
}
return size;
}
}<|endoftext|>
|
<commit_before>/*
* PrenexLink.cc
*
* Copyright (C) 2017 Linas Vepstas
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License v3 as
* published by the Free Software Foundation and including the
* exceptions at http://opencog.org/wiki/Licenses
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public
* License along with this program; if not, write to:
* Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
#include <string>
#include <opencog/util/mt19937ar.h>
#include <opencog/util/random.h>
#include <opencog/util/Logger.h>
#include <opencog/atoms/base/ClassServer.h>
#include <opencog/atoms/core/TypeNode.h>
#include <opencog/atomutils/TypeUtils.h>
#include <opencog/atomutils/FindUtils.h>
#include "PrenexLink.h"
using namespace opencog;
void PrenexLink::init(void)
{
Type t = get_type();
if (not classserver().isA(t, PRENEX_LINK))
{
const std::string& tname = classserver().getTypeName(t);
throw InvalidParamException(TRACE_INFO,
"Expecting a PrenexLink, got %s", tname.c_str());
}
}
PrenexLink::PrenexLink(const Handle& vars, const Handle& body)
: RewriteLink(HandleSeq({vars, body}), PRENEX_LINK)
{
init();
}
PrenexLink::PrenexLink(const HandleSeq& oset, Type t)
: RewriteLink(oset, t)
{
if (skip_init(t)) return;
init();
}
PrenexLink::PrenexLink(const Link &l)
: RewriteLink(l)
{
if (skip_init(l.get_type())) return;
init();
}
/* ================================================================= */
Handle PrenexLink::reassemble(const HandleMap& vm,
const HandleSeq& final_varlist) const
{
const Variables& vtool = get_variables();
// Now get the new body...
Handle newbod = vtool.substitute(_body, vm, _silent);
if (0 < final_varlist.size())
{
Handle vdecl;
if (1 == final_varlist.size())
vdecl = final_varlist[0];
else
vdecl = Handle(createVariableList(final_varlist));
return Handle(createLink(get_type(), vdecl, newbod));
}
return newbod;
}
/* ================================================================= */
static Handle collect(const Variables& vtool,
const Handle& origvar, const Handle& newvar,
HandleSeq& final_varlist,
HandleSet& used_vars,
HandleMap& issued_vars)
{
// If we've already issued this variable, do not re-issue it.
const auto& pr = issued_vars.find(newvar);
if (pr != issued_vars.end())
return pr->second;
// Is there a naming collision?
if (used_vars.find(newvar) == used_vars.end())
{
final_varlist.emplace_back(vtool.get_type_decl(origvar, newvar));
used_vars.insert(newvar);
issued_vars.insert({newvar, newvar});
return Handle::UNDEFINED;
}
// Aiiee, there is a collision, make a new name!
Handle alt;
do
{
std::string altname = randstr(newvar->get_name() + "-");
alt = createNode(VARIABLE_NODE, altname);
} while (used_vars.find(alt) != used_vars.end());
final_varlist.emplace_back(vtool.get_type_decl(origvar, alt));
used_vars.insert(alt);
issued_vars.insert({newvar, alt});
return alt;
}
/* ================================================================= */
Handle PrenexLink::beta_reduce(const HandleSeq& seq) const
{
// Test for a special case: eta reduction on the supplied
// function. We can recognize this if we don't get fewer
// arguments than we expected.
const Variables& vtool = get_variables();
size_t seqsize = seq.size();
if (seqsize == vtool.size())
{
// Not an eta reduction. Do the normal thing.
return RewriteLink::beta_reduce(seq);
}
// If its an eta, there must be just one argument, and it must
// must be a ScopeLink.
if (1 != seqsize or
not classserver().isA(seq[0]->get_type(), SCOPE_LINK))
{
if (_silent) return Handle::UNDEFINED;
throw SyntaxException(TRACE_INFO,
"PrenexLink is badly formed");
}
// If its an eta, it had better have the right size.
ScopeLinkPtr lam(ScopeLinkCast(seq[0]));
const Handle& body = lam->get_body();
if (body->get_arity() != vtool.size() or
body->get_type() != LIST_LINK)
{
if (_silent) return Handle::UNDEFINED;
throw SyntaxException(TRACE_INFO,
"PrenexLink has mismatched eta, expecting %lu == %lu",
vtool.size(), body->get_arity());
}
// If we are here, we have a valid eta reduction to perform.
HandleSeq final_varlist;
HandleSet used_vars;
HandleMap issued;
// First, figure out what the new variables will be.
Variables bound = lam->get_variables();
for (const Handle& bv: bound.varseq)
{
collect(bound, bv, bv, final_varlist, used_vars, issued);
}
// Next, figure out what substitutions will be made.
HandleMap vm;
const HandleSeq& oset = body->getOutgoingSet();
for (size_t i=0; i<vtool.size(); i++)
{
vm.insert({vtool.varseq[i], oset[i]});
}
// Almost done. The final_varlist holds the variable declarations,
// and the vm holds what needs to be substituted in. Substitute,
// and create the reduced link.
return reassemble(vm, final_varlist);
}
/* ================================================================= */
Handle PrenexLink::beta_reduce(const HandleMap& vmap) const
{
HandleMap vm = vmap;
// If any of the mapped values are ScopeLinks, we need to discover
// and collect up the variables that they bind. We also need to
// make sure that they are "fresh", i.e. don't have naming
// collisions.
HandleSeq final_varlist;
HandleSet used_vars;
Variables vtool = get_variables();
for (const Handle& var : vtool.varseq)
{
// If we are not substituting for this variable, copy it
// over to the final list.
const auto& pare = vm.find(var);
if (vm.find(var) == vm.end())
{
HandleMap issued; // empty
Handle alt = collect(vtool, var, var,
final_varlist, used_vars, issued);
if (alt)
vm.insert({var, alt});
continue;
}
Type valuetype = pare->second->get_type();
// If we are here, then var will be beta-reduced.
// But if the value is another variable, then alpha-convert,
// instead.
if (VARIABLE_NODE == valuetype)
{
HandleMap issued; // empty
Handle alt = collect(vtool, var, pare->second,
final_varlist, used_vars, issued);
if (alt)
vm[var] = alt;
continue;
}
// If we are here, then var will be beta-reduced.
// Is the value a ScopeLink? If so, handle it.
if (classserver().isA(valuetype, SCOPE_LINK))
{
ScopeLinkPtr sc = ScopeLinkCast(pare->second);
Variables bound = sc->get_variables();
Handle body = sc->get_body();
HandleMap issued;
for (const Handle& bv : bound.varseq)
{
Handle alt = collect(bound, bv, bv,
final_varlist, used_vars, issued);
if (alt)
{
// In the body of the scope link, rename
// the bond variable to its new name.
HandleMap alpha;
alpha[bv] = alt;
body = bound.substitute_nocheck(body, alpha);
}
}
vm[pare->first] = body;
}
}
// Almost done. The final_varlist holds the variable declarations,
// and the vm holds what needs to be substituted in. Substitute,
// and create the reduced link.
return reassemble(vm, final_varlist);
}
/* ================================================================= */
DEFINE_LINK_FACTORY(PrenexLink, PRENEX_LINK);
/* ===================== END OF FILE ===================== */
<commit_msg>Another bug-fix<commit_after>/*
* PrenexLink.cc
*
* Copyright (C) 2017 Linas Vepstas
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License v3 as
* published by the Free Software Foundation and including the
* exceptions at http://opencog.org/wiki/Licenses
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public
* License along with this program; if not, write to:
* Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
#include <string>
#include <opencog/util/mt19937ar.h>
#include <opencog/util/random.h>
#include <opencog/util/Logger.h>
#include <opencog/atoms/base/ClassServer.h>
#include <opencog/atoms/core/TypeNode.h>
#include <opencog/atomutils/TypeUtils.h>
#include <opencog/atomutils/FindUtils.h>
#include "PrenexLink.h"
using namespace opencog;
void PrenexLink::init(void)
{
Type t = get_type();
if (not classserver().isA(t, PRENEX_LINK))
{
const std::string& tname = classserver().getTypeName(t);
throw InvalidParamException(TRACE_INFO,
"Expecting a PrenexLink, got %s", tname.c_str());
}
}
PrenexLink::PrenexLink(const Handle& vars, const Handle& body)
: RewriteLink(HandleSeq({vars, body}), PRENEX_LINK)
{
init();
}
PrenexLink::PrenexLink(const HandleSeq& oset, Type t)
: RewriteLink(oset, t)
{
if (skip_init(t)) return;
init();
}
PrenexLink::PrenexLink(const Link &l)
: RewriteLink(l)
{
if (skip_init(l.get_type())) return;
init();
}
/* ================================================================= */
Handle PrenexLink::reassemble(const HandleMap& vm,
const HandleSeq& final_varlist) const
{
const Variables& vtool = get_variables();
// Now get the new body...
Handle newbod = vtool.substitute(_body, vm, _silent);
if (0 < final_varlist.size())
{
Handle vdecl;
if (1 == final_varlist.size())
vdecl = final_varlist[0];
else
vdecl = Handle(createVariableList(final_varlist));
return Handle(createLink(get_type(), vdecl, newbod));
}
return newbod;
}
/* ================================================================= */
static Handle collect(const Variables& vtool,
const Handle& origvar, const Handle& newvar,
HandleSeq& final_varlist,
HandleSet& used_vars,
HandleMap& issued_vars)
{
// If we've already issued this variable, do not re-issue it.
const auto& pr = issued_vars.find(newvar);
if (pr != issued_vars.end())
return pr->second;
// Is there a naming collision?
if (used_vars.find(newvar) == used_vars.end())
{
final_varlist.emplace_back(vtool.get_type_decl(origvar, newvar));
used_vars.insert(newvar);
issued_vars.insert({newvar, newvar});
return Handle::UNDEFINED;
}
// Aiiee, there is a collision, make a new name!
Handle alt;
do
{
std::string altname = randstr(newvar->get_name() + "-");
alt = createNode(VARIABLE_NODE, altname);
} while (used_vars.find(alt) != used_vars.end());
final_varlist.emplace_back(vtool.get_type_decl(origvar, alt));
used_vars.insert(alt);
issued_vars.insert({newvar, alt});
return alt;
}
/* ================================================================= */
Handle PrenexLink::beta_reduce(const HandleSeq& seq) const
{
// Test for a special case: eta reduction on the supplied
// function. We can recognize this if we don't get fewer
// arguments than we expected.
const Variables& vtool = get_variables();
size_t seqsize = seq.size();
if (seqsize == vtool.size())
{
// Not an eta reduction. Do the normal thing.
return RewriteLink::beta_reduce(seq);
}
// If its an eta, there must be just one argument, and it must
// must be a ScopeLink.
if (1 != seqsize or
not classserver().isA(seq[0]->get_type(), SCOPE_LINK))
{
if (_silent) return Handle::UNDEFINED;
throw SyntaxException(TRACE_INFO,
"PrenexLink is badly formed");
}
// If its an eta, it had better have the right size.
ScopeLinkPtr lam(ScopeLinkCast(seq[0]));
const Handle& body = lam->get_body();
if (body->get_arity() != vtool.size() or
body->get_type() != LIST_LINK)
{
if (_silent) return Handle::UNDEFINED;
throw SyntaxException(TRACE_INFO,
"PrenexLink has mismatched eta, expecting %lu == %lu",
vtool.size(), body->get_arity());
}
// If we are here, we have a valid eta reduction to perform.
HandleSeq final_varlist;
HandleSet used_vars;
HandleMap issued;
// First, figure out what the new variables will be.
Variables bound = lam->get_variables();
for (const Handle& bv: bound.varseq)
{
collect(bound, bv, bv, final_varlist, used_vars, issued);
}
// Next, figure out what substitutions will be made.
HandleMap vm;
const HandleSeq& oset = body->getOutgoingSet();
for (size_t i=0; i<vtool.size(); i++)
{
vm.insert({vtool.varseq[i], oset[i]});
}
// Almost done. The final_varlist holds the variable declarations,
// and the vm holds what needs to be substituted in. Substitute,
// and create the reduced link.
return reassemble(vm, final_varlist);
}
/* ================================================================= */
Handle PrenexLink::beta_reduce(const HandleMap& vmap) const
{
HandleMap vm = vmap;
// If any of the mapped values are ScopeLinks, we need to discover
// and collect up the variables that they bind. We also need to
// make sure that they are "fresh", i.e. don't have naming
// collisions.
HandleSeq final_varlist;
HandleSet used_vars;
HandleMap issued;
Variables vtool = get_variables();
for (const Handle& var : vtool.varseq)
{
// If we are not substituting for this variable, copy it
// over to the final list.
const auto& pare = vm.find(var);
if (vm.find(var) == vm.end())
{
Handle alt = collect(vtool, var, var,
final_varlist, used_vars, issued);
if (alt)
vm.insert({var, alt});
continue;
}
Type valuetype = pare->second->get_type();
// If we are here, then var will be beta-reduced.
// But if the value is another variable, then alpha-convert,
// instead.
if (VARIABLE_NODE == valuetype)
{
Handle alt = collect(vtool, var, pare->second,
final_varlist, used_vars, issued);
if (alt)
vm[var] = alt;
continue;
}
// If we are here, then var will be beta-reduced.
// Is the value a ScopeLink? If so, handle it.
if (classserver().isA(valuetype, SCOPE_LINK))
{
ScopeLinkPtr sc = ScopeLinkCast(pare->second);
Variables bound = sc->get_variables();
Handle body = sc->get_body();
HandleMap scopissued;
for (const Handle& bv : bound.varseq)
{
Handle alt = collect(bound, bv, bv,
final_varlist, used_vars, scopissued);
if (alt)
{
// In the body of the scope link, rename
// the bond variable to its new name.
HandleMap alpha;
alpha[bv] = alt;
body = bound.substitute_nocheck(body, alpha);
}
}
vm[pare->first] = body;
}
}
// Almost done. The final_varlist holds the variable declarations,
// and the vm holds what needs to be substituted in. Substitute,
// and create the reduced link.
return reassemble(vm, final_varlist);
}
/* ================================================================= */
DEFINE_LINK_FACTORY(PrenexLink, PRENEX_LINK);
/* ===================== END OF FILE ===================== */
<|endoftext|>
|
<commit_before>/*
-----------------------------------------------------------------------------
This source file is part of OGRE
(Object-oriented Graphics Rendering Engine)
For the latest info, see http://www.ogre3d.org/
Copyright (c) 2000-2014 Torus Knot Software Ltd
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 "OgreD3D11VideoModeList.h"
#include "OgreException.h"
#include "OgreD3D11Driver.h"
#include "OgreD3D11VideoMode.h"
namespace Ogre
{
//---------------------------------------------------------------------
D3D11VideoModeList::D3D11VideoModeList( D3D11Driver* pDriver )
{
if( NULL == pDriver )
OGRE_EXCEPT( Exception::ERR_INVALIDPARAMS, "pDriver parameter is NULL", "D3D11VideoModeList::D3D11VideoModeList" );
mDriver = pDriver;
enumerate();
}
//---------------------------------------------------------------------
D3D11VideoModeList::~D3D11VideoModeList()
{
mDriver = NULL;
mModeList.clear();
}
//---------------------------------------------------------------------
BOOL D3D11VideoModeList::enumerate()
{
// int pD3D = mDriver->getD3D();
UINT adapter = mDriver->getAdapterNumber();
HRESULT hr;
IDXGIOutput *pOutput;
for( int iOutput = 0; ; ++iOutput )
{
//AIZTODO: one output for a single monitor ,to be handled for mulimon
hr = mDriver->getDeviceAdapter()->EnumOutputs( iOutput, &pOutput );
if( DXGI_ERROR_NOT_FOUND == hr )
{
return false;
}
else if (FAILED(hr))
{
return false; //Something bad happened.
}
else //Success!
{
DXGI_OUTPUT_DESC OutputDesc;
pOutput->GetDesc(&OutputDesc);
UINT NumModes = 0;
hr = pOutput->GetDisplayModeList(DXGI_FORMAT_R8G8B8A8_UNORM,
0,
&NumModes,
NULL );
DXGI_MODE_DESC *pDesc = new DXGI_MODE_DESC[ NumModes ];
ZeroMemory(pDesc, sizeof(DXGI_MODE_DESC) * NumModes);
hr = pOutput->GetDisplayModeList(DXGI_FORMAT_R8G8B8A8_UNORM,
0,
&NumModes,
pDesc );
SAFE_RELEASE(pOutput);
// display mode list can not be obtained when working over terminal session
if(FAILED(hr))
{
NumModes = 0;
if(hr == DXGI_ERROR_NOT_CURRENTLY_AVAILABLE)
{
pDesc[0].Width = 800;
pDesc[0].Height = 600;
pDesc[0].RefreshRate.Numerator = 60;
pDesc[0].RefreshRate.Denominator = 1;
pDesc[0].Format = DXGI_FORMAT_R8G8B8A8_UNORM;
pDesc[0].ScanlineOrdering = DXGI_MODE_SCANLINE_ORDER_PROGRESSIVE;
pDesc[0].Scaling = DXGI_MODE_SCALING_UNSPECIFIED;
NumModes = 1;
}
}
for( UINT m=0; m<NumModes; m++ )
{
DXGI_MODE_DESC displayMode=pDesc[m];
// Filter out low-resolutions
if( displayMode.Width < 640 || displayMode.Height < 400 )
continue;
// Check to see if it is already in the list (to filter out refresh rates)
BOOL found = FALSE;
vector<D3D11VideoMode>::type::iterator it;
for( it = mModeList.begin(); it != mModeList.end(); it++ )
{
DXGI_OUTPUT_DESC oldOutput= it->getDisplayMode();
DXGI_MODE_DESC oldDisp = it->getModeDesc();
if(//oldOutput.Monitor==OutputDesc.Monitor &&
oldDisp.Width == displayMode.Width &&
oldDisp.Height == displayMode.Height// &&
//oldDisp.Format == displayMode.Format
)
{
// Check refresh rate and favour higher if poss
//if (oldDisp.RefreshRate < displayMode.RefreshRate)
// it->increaseRefreshRate(displayMode.RefreshRate);
found = TRUE;
break;
}
}
if( !found )
mModeList.push_back( D3D11VideoMode( OutputDesc,displayMode ) );
}
delete [] pDesc;
}
}
/*
UINT iMode;
for( iMode=0; iMode < pD3D->GetAdapterModeCount( adapter, D3DFMT_R5G6B5 ); iMode++ )
{
DXGI_OUTPUT_DESC displayMode;
pD3D->EnumAdapterModes( adapter, D3DFMT_R5G6B5, iMode, &displayMode );
// Filter out low-resolutions
if( displayMode.Width < 640 || displayMode.Height < 400 )
continue;
// Check to see if it is already in the list (to filter out refresh rates)
BOOL found = FALSE;
vector<D3D11VideoMode>::type::iterator it;
for( it = mModeList.begin(); it != mModeList.end(); it++ )
{
DXGI_OUTPUT_DESC oldDisp = it->getDisplayMode();
if( oldDisp.Width == displayMode.Width &&
oldDisp.Height == displayMode.Height &&
oldDisp.Format == displayMode.Format )
{
// Check refresh rate and favour higher if poss
if (oldDisp.RefreshRate < displayMode.RefreshRate)
it->increaseRefreshRate(displayMode.RefreshRate);
found = TRUE;
break;
}
}
if( !found )
mModeList.push_back( D3D11VideoMode( displayMode ) );
}
for( iMode=0; iMode < pD3D->GetAdapterModeCount( adapter, D3DFMT_X8R8G8B8 ); iMode++ )
{
DXGI_OUTPUT_DESC displayMode;
pD3D->EnumAdapterModes( adapter, D3DFMT_X8R8G8B8, iMode, &displayMode );
// Filter out low-resolutions
if( displayMode.Width < 640 || displayMode.Height < 400 )
continue;
// Check to see if it is already in the list (to filter out refresh rates)
BOOL found = FALSE;
vector<D3D11VideoMode>::type::iterator it;
for( it = mModeList.begin(); it != mModeList.end(); it++ )
{
DXGI_OUTPUT_DESC oldDisp = it->getDisplayMode();
if( oldDisp.Width == displayMode.Width &&
oldDisp.Height == displayMode.Height &&
oldDisp.Format == displayMode.Format )
{
// Check refresh rate and favour higher if poss
if (oldDisp.RefreshRate < displayMode.RefreshRate)
it->increaseRefreshRate(displayMode.RefreshRate);
found = TRUE;
break;
}
}
if( !found )
mModeList.push_back( D3D11VideoMode( displayMode ) );
}
*/
return TRUE;
}
//---------------------------------------------------------------------
size_t D3D11VideoModeList::count()
{
return mModeList.size();
}
//---------------------------------------------------------------------
D3D11VideoMode* D3D11VideoModeList::item( size_t index )
{
vector<D3D11VideoMode>::type::iterator p = mModeList.begin();
return &p[index];
}
//---------------------------------------------------------------------
D3D11VideoMode* D3D11VideoModeList::item( const String &name )
{
vector<D3D11VideoMode>::type::iterator it = mModeList.begin();
if (it == mModeList.end())
return NULL;
for (;it != mModeList.end(); ++it)
{
if (it->getDescription() == name)
return &(*it);
}
return NULL;
}
//---------------------------------------------------------------------
}
<commit_msg>Fixing VideoModeList to gracefully handle working over terminal sessions, for example when using Windows 8 simulator for app development.<commit_after>/*
-----------------------------------------------------------------------------
This source file is part of OGRE
(Object-oriented Graphics Rendering Engine)
For the latest info, see http://www.ogre3d.org/
Copyright (c) 2000-2014 Torus Knot Software Ltd
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 "OgreD3D11VideoModeList.h"
#include "OgreException.h"
#include "OgreD3D11Driver.h"
#include "OgreD3D11VideoMode.h"
namespace Ogre
{
//---------------------------------------------------------------------
D3D11VideoModeList::D3D11VideoModeList( D3D11Driver* pDriver )
{
if( NULL == pDriver )
OGRE_EXCEPT( Exception::ERR_INVALIDPARAMS, "pDriver parameter is NULL", "D3D11VideoModeList::D3D11VideoModeList" );
mDriver = pDriver;
enumerate();
}
//---------------------------------------------------------------------
D3D11VideoModeList::~D3D11VideoModeList()
{
mDriver = NULL;
mModeList.clear();
}
//---------------------------------------------------------------------
BOOL D3D11VideoModeList::enumerate()
{
// int pD3D = mDriver->getD3D();
UINT adapter = mDriver->getAdapterNumber();
HRESULT hr;
IDXGIOutput *pOutput;
for( int iOutput = 0; ; ++iOutput )
{
//AIZTODO: one output for a single monitor ,to be handled for mulimon
hr = mDriver->getDeviceAdapter()->EnumOutputs( iOutput, &pOutput );
if( DXGI_ERROR_NOT_FOUND == hr )
{
return false;
}
else if (FAILED(hr))
{
return false; //Something bad happened.
}
else //Success!
{
DXGI_OUTPUT_DESC OutputDesc;
pOutput->GetDesc(&OutputDesc);
UINT NumModes = 0;
hr = pOutput->GetDisplayModeList(DXGI_FORMAT_R8G8B8A8_UNORM,
0,
&NumModes,
NULL);
// If working over a terminal session, for example using the Simulator for deployment/development, display modes cannot be obtained.
if (hr == DXGI_ERROR_NOT_CURRENTLY_AVAILABLE)
{
DXGI_MODE_DESC fullScreenMode;
fullScreenMode.Width = OutputDesc.DesktopCoordinates.right - OutputDesc.DesktopCoordinates.left;
fullScreenMode.Height = OutputDesc.DesktopCoordinates.bottom - OutputDesc.DesktopCoordinates.top;
fullScreenMode.RefreshRate.Numerator = 60;
fullScreenMode.RefreshRate.Denominator = 1;
fullScreenMode.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
fullScreenMode.ScanlineOrdering = DXGI_MODE_SCANLINE_ORDER_PROGRESSIVE;
fullScreenMode.Scaling = DXGI_MODE_SCALING_UNSPECIFIED;
mModeList.push_back(D3D11VideoMode(OutputDesc, fullScreenMode));
}
else if (hr == S_OK)
{
if (NumModes > 0)
{
// Create an array to store Display Mode information
DXGI_MODE_DESC *pDesc = new DXGI_MODE_DESC[NumModes];
ZeroMemory(pDesc, sizeof(DXGI_MODE_DESC)* NumModes);
// Populate our array with information
hr = pOutput->GetDisplayModeList(DXGI_FORMAT_R8G8B8A8_UNORM,
0,
&NumModes,
pDesc);
for (UINT m = 0; m < NumModes; m++)
{
DXGI_MODE_DESC displayMode = pDesc[m];
// Filter out low-resolutions
if (displayMode.Width < 640 || displayMode.Height < 400)
continue;
// Check to see if it is already in the list (to filter out refresh rates)
BOOL found = FALSE;
vector<D3D11VideoMode>::type::iterator it;
for (it = mModeList.begin(); it != mModeList.end(); it++)
{
DXGI_OUTPUT_DESC oldOutput = it->getDisplayMode();
DXGI_MODE_DESC oldDisp = it->getModeDesc();
if (//oldOutput.Monitor==OutputDesc.Monitor &&
oldDisp.Width == displayMode.Width &&
oldDisp.Height == displayMode.Height// &&
//oldDisp.Format == displayMode.Format
)
{
// Check refresh rate and favour higher if poss
//if (oldDisp.RefreshRate < displayMode.RefreshRate)
// it->increaseRefreshRate(displayMode.RefreshRate);
found = TRUE;
break;
}
}
if (!found)
mModeList.push_back(D3D11VideoMode(OutputDesc, displayMode));
}
delete[] pDesc;
}
}
SAFE_RELEASE(pOutput);
}
}
/*
UINT iMode;
for( iMode=0; iMode < pD3D->GetAdapterModeCount( adapter, D3DFMT_R5G6B5 ); iMode++ )
{
DXGI_OUTPUT_DESC displayMode;
pD3D->EnumAdapterModes( adapter, D3DFMT_R5G6B5, iMode, &displayMode );
// Filter out low-resolutions
if( displayMode.Width < 640 || displayMode.Height < 400 )
continue;
// Check to see if it is already in the list (to filter out refresh rates)
BOOL found = FALSE;
vector<D3D11VideoMode>::type::iterator it;
for( it = mModeList.begin(); it != mModeList.end(); it++ )
{
DXGI_OUTPUT_DESC oldDisp = it->getDisplayMode();
if( oldDisp.Width == displayMode.Width &&
oldDisp.Height == displayMode.Height &&
oldDisp.Format == displayMode.Format )
{
// Check refresh rate and favour higher if poss
if (oldDisp.RefreshRate < displayMode.RefreshRate)
it->increaseRefreshRate(displayMode.RefreshRate);
found = TRUE;
break;
}
}
if( !found )
mModeList.push_back( D3D11VideoMode( displayMode ) );
}
for( iMode=0; iMode < pD3D->GetAdapterModeCount( adapter, D3DFMT_X8R8G8B8 ); iMode++ )
{
DXGI_OUTPUT_DESC displayMode;
pD3D->EnumAdapterModes( adapter, D3DFMT_X8R8G8B8, iMode, &displayMode );
// Filter out low-resolutions
if( displayMode.Width < 640 || displayMode.Height < 400 )
continue;
// Check to see if it is already in the list (to filter out refresh rates)
BOOL found = FALSE;
vector<D3D11VideoMode>::type::iterator it;
for( it = mModeList.begin(); it != mModeList.end(); it++ )
{
DXGI_OUTPUT_DESC oldDisp = it->getDisplayMode();
if( oldDisp.Width == displayMode.Width &&
oldDisp.Height == displayMode.Height &&
oldDisp.Format == displayMode.Format )
{
// Check refresh rate and favour higher if poss
if (oldDisp.RefreshRate < displayMode.RefreshRate)
it->increaseRefreshRate(displayMode.RefreshRate);
found = TRUE;
break;
}
}
if( !found )
mModeList.push_back( D3D11VideoMode( displayMode ) );
}
*/
return TRUE;
}
//---------------------------------------------------------------------
size_t D3D11VideoModeList::count()
{
return mModeList.size();
}
//---------------------------------------------------------------------
D3D11VideoMode* D3D11VideoModeList::item( size_t index )
{
vector<D3D11VideoMode>::type::iterator p = mModeList.begin();
return &p[index];
}
//---------------------------------------------------------------------
D3D11VideoMode* D3D11VideoModeList::item( const String &name )
{
vector<D3D11VideoMode>::type::iterator it = mModeList.begin();
if (it == mModeList.end())
return NULL;
for (;it != mModeList.end(); ++it)
{
if (it->getDescription() == name)
return &(*it);
}
return NULL;
}
//---------------------------------------------------------------------
}
<|endoftext|>
|
<commit_before>/*****************************************************************************
* Media Library
*****************************************************************************
* Copyright (C) 2015-2019 Hugo Beauzée-Luyssen, Videolabs, VideoLAN
*
* Authors: Hugo Beauzée-Luyssen <[email protected]>
*
* This program 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 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 Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
*****************************************************************************/
#if HAVE_CONFIG_H
# include "config.h"
#endif
#include "Common.h"
#include "ParserWorker.h"
#include "Parser.h"
#include "parser/Task.h"
#include "Media.h"
#include "medialibrary/filesystem/Errors.h"
#include "Folder.h"
namespace medialibrary
{
namespace parser
{
Worker::Worker()
: m_ml( nullptr )
, m_parserCb( nullptr )
, m_stopParser( false )
, m_paused( false )
, m_idle( true )
{
}
void Worker::start()
{
// This function is called from a locked context.
// Ensure we don't start multiple times.
assert( m_thread.joinable() == false );
m_thread = compat::Thread{ &Worker::mainloop, this };
}
void Worker::pause()
{
std::lock_guard<compat::Mutex> lock( m_lock );
m_paused = true;
}
void Worker::resume()
{
std::lock_guard<compat::Mutex> lock( m_lock );
m_paused = false;
m_cond.notify_all();
}
void Worker::signalStop()
{
{
std::lock_guard<compat::Mutex> lock( m_lock );
m_stopParser = true;
}
m_cond.notify_all();
m_service->stop();
}
void Worker::stop()
{
if ( m_thread.joinable() == true )
m_thread.join();
}
void Worker::parse( std::shared_ptr<Task> t )
{
// Avoid flickering from idle/not idle when not many tasks are running.
// The thread calling parse for the next parser step might not have
// something left to do and would turn idle, potentially causing all
// services to be idle for a very short time, until this parser
// thread awakes/starts, causing the global parser idle state to be
// restored back to false.
// Since we are queuing a task, we already know that this thread is
// not idle
setIdle( false );
// Even if no threads appear to be started, we need to lock this in case
// we're currently doing a stop/start
{
std::lock_guard<compat::Mutex> lock( m_lock );
m_tasks.push( std::move( t ) );
if ( m_thread.get_id() == compat::Thread::id{} )
{
start();
return;
}
}
m_cond.notify_all();
}
bool Worker::initialize( MediaLibrary* ml, IParserCb* parserCb,
std::shared_ptr<IParserService> service )
{
m_ml = ml;
m_service = std::move( service );
m_parserCb = parserCb;
// Run the service specific initializer
return m_service->initialize( ml );
}
bool Worker::isIdle() const
{
return m_idle;
}
void Worker::flush()
{
std::unique_lock<compat::Mutex> lock( m_lock );
assert( m_paused == true || m_thread.get_id() == compat::Thread::id{} );
m_idleCond.wait( lock, [this]() {
return m_idle == true;
});
while ( m_tasks.empty() == false )
m_tasks.pop();
m_service->onFlushing();
}
void Worker::restart()
{
m_service->onRestarted();
}
void Worker::mainloop()
{
// It would be unsafe to call name() at the end of this function, since
// we might stop the thread during ParserService destruction. This implies
// that the underlying service has been deleted already.
std::string serviceName = m_service->name();
LOG_INFO("Entering ParserService [", serviceName, "] thread");
setIdle( false );
while ( true )
{
std::shared_ptr<Task> task;
ML_UNHANDLED_EXCEPTION_INIT
{
{
std::unique_lock<compat::Mutex> lock( m_lock );
if ( m_stopParser == true )
break;
if ( m_tasks.empty() == true || m_paused == true )
{
LOG_DEBUG( "Halting ParserService [", serviceName, "] mainloop" );
setIdle( true );
m_idleCond.notify_all();
m_cond.wait( lock, [this]() {
return ( m_tasks.empty() == false && m_paused == false )
|| m_stopParser == true;
});
LOG_DEBUG( "Resuming ParserService [", serviceName, "] mainloop" );
// We might have been woken up because the parser is being destroyed
if ( m_stopParser == true )
break;
setIdle( false );
}
// Otherwise it's safe to assume we have at least one element.
LOG_DEBUG('[', serviceName, "] has ", m_tasks.size(), " tasks remaining" );
task = std::move( m_tasks.front() );
m_tasks.pop();
}
// Special case to restore uncompleted tasks from a parser thread
if ( task == nullptr )
{
restoreTasks();
continue;
}
if ( task->isStepCompleted( m_service->targetedStep() ) == true )
{
LOG_DEBUG( "Skipping completed task [", serviceName, "] on ", task->mrl() );
m_parserCb->done( std::move( task ), Status::Success );
continue;
}
Status status;
try
{
LOG_DEBUG( "Executing ", serviceName, " task on ", task->mrl() );
auto chrono = std::chrono::steady_clock::now();
auto file = std::static_pointer_cast<File>( task->file() );
if ( file != nullptr && file->isRemovable() )
{
auto folder = Folder::fetch( m_ml, file->folderId() );
assert( folder != nullptr );
if ( folder == nullptr || folder->isPresent() == false )
{
LOG_DEBUG( "Postponing parsing of ", file->rawMrl(),
" until the device containing it gets mounted back" );
m_parserCb->done( std::move( task ), Status::TemporaryUnavailable );
continue;
}
}
task->startParserStep();
status = m_service->run( *task );
auto duration = std::chrono::steady_clock::now() - chrono;
LOG_DEBUG( "Done executing ", serviceName, " task on ", task->mrl(), " in ",
std::chrono::duration_cast<std::chrono::milliseconds>( duration ).count(),
"ms. Result: ",
static_cast<std::underlying_type_t<parser::Status>>( status ) );
}
catch ( const fs::errors::DeviceRemoved& )
{
LOG_ERROR( "Parsing of ", task->mrl(), " was interrupted "
"due to its containing device being unmounted" );
status = Status::TemporaryUnavailable;
}
catch ( const fs::errors::Exception& ex )
{
LOG_ERROR( "Caught an FS exception during ", task->mrl(), " [", serviceName, "] parsing: ", ex.what() );
status = Status::Fatal;
}
if ( handleServiceResult( *task, status ) == false )
status = Status::Fatal;
m_parserCb->done( std::move( task ), status );
}
ML_UNHANDLED_EXCEPTION_BODY( serviceName.c_str() )
}
LOG_INFO("Exiting ParserService [", serviceName, "] thread");
setIdle( true );
}
void Worker::setIdle(bool isIdle)
{
// Calling the idleChanged callback will trigger a call to isIdle, so set the value before
// invoking it, otherwise we have an incoherent state.
if ( m_idle != isIdle )
{
m_idle = isIdle;
m_parserCb->onIdleChanged( isIdle );
}
}
bool Worker::handleServiceResult( Task& task, Status status )
{
if ( status == Status::Success )
{
task.markStepCompleted( m_service->targetedStep() );
// We don't want to save the extraction step in database, as restarting a
// task with extraction completed but analysis uncompleted wouldn't run
// the extraction again, causing the analysis to run with no info.
if ( m_service->targetedStep() != Step::MetadataExtraction )
return task.saveParserStep();
// We don't want to reset the entire retry count, as we would be stuck in
// a "loop" in case the metadata analysis fails (we'd always reset the retry
// count to zero, then fail, then run the extraction again, reset the retry,
// fail the analysis, and so on.
// We can't not increment the retry count for metadata extraction, since
// in case a file makes (lib)VLC crash, we would always try again, and
// therefor we would keep on crashing.
// However we don't want to just increment the retry count, since it
// would reach the maximum value too quickly (extraction would set retry
// count to 1, analysis to 2, and in case of failure, next run would set
// it over 3, while we only tried 2 times. Instead we just decrement it
// when the extraction step succeeds
return task.decrementRetryCount();
}
else if ( status == Status::Completed )
{
task.markStepCompleted( Step::Completed );
return task.saveParserStep();
}
else if ( status == Status::Discarded )
{
return Task::destroy( m_ml, task.id() );
}
return true;
}
void Worker::restoreTasks()
{
auto tasks = Task::fetchUncompleted( m_ml );
if ( tasks.size() > 0 )
LOG_INFO( "Resuming parsing on ", tasks.size(), " tasks" );
else
LOG_DEBUG( "No task to resume." );
for ( auto& t : tasks )
{
{
std::lock_guard<compat::Mutex> lock( m_lock );
if ( m_stopParser == true )
break;
}
if ( t->restoreLinkedEntities() == false )
continue;
m_parserCb->parse( std::move( t ) );
}
}
}
}
<commit_msg>ParserWorker.cpp: Refine required inclusions<commit_after>/*****************************************************************************
* Media Library
*****************************************************************************
* Copyright (C) 2015-2019 Hugo Beauzée-Luyssen, Videolabs, VideoLAN
*
* Authors: Hugo Beauzée-Luyssen <[email protected]>
*
* This program 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 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 Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
*****************************************************************************/
#if HAVE_CONFIG_H
# include "config.h"
#endif
#include "Common.h"
#include "ParserWorker.h"
#include "Parser.h"
#include "parser/Task.h"
#include "File.h"
#include "medialibrary/filesystem/Errors.h"
#include "Folder.h"
namespace medialibrary
{
namespace parser
{
Worker::Worker()
: m_ml( nullptr )
, m_parserCb( nullptr )
, m_stopParser( false )
, m_paused( false )
, m_idle( true )
{
}
void Worker::start()
{
// This function is called from a locked context.
// Ensure we don't start multiple times.
assert( m_thread.joinable() == false );
m_thread = compat::Thread{ &Worker::mainloop, this };
}
void Worker::pause()
{
std::lock_guard<compat::Mutex> lock( m_lock );
m_paused = true;
}
void Worker::resume()
{
std::lock_guard<compat::Mutex> lock( m_lock );
m_paused = false;
m_cond.notify_all();
}
void Worker::signalStop()
{
{
std::lock_guard<compat::Mutex> lock( m_lock );
m_stopParser = true;
}
m_cond.notify_all();
m_service->stop();
}
void Worker::stop()
{
if ( m_thread.joinable() == true )
m_thread.join();
}
void Worker::parse( std::shared_ptr<Task> t )
{
// Avoid flickering from idle/not idle when not many tasks are running.
// The thread calling parse for the next parser step might not have
// something left to do and would turn idle, potentially causing all
// services to be idle for a very short time, until this parser
// thread awakes/starts, causing the global parser idle state to be
// restored back to false.
// Since we are queuing a task, we already know that this thread is
// not idle
setIdle( false );
// Even if no threads appear to be started, we need to lock this in case
// we're currently doing a stop/start
{
std::lock_guard<compat::Mutex> lock( m_lock );
m_tasks.push( std::move( t ) );
if ( m_thread.get_id() == compat::Thread::id{} )
{
start();
return;
}
}
m_cond.notify_all();
}
bool Worker::initialize( MediaLibrary* ml, IParserCb* parserCb,
std::shared_ptr<IParserService> service )
{
m_ml = ml;
m_service = std::move( service );
m_parserCb = parserCb;
// Run the service specific initializer
return m_service->initialize( ml );
}
bool Worker::isIdle() const
{
return m_idle;
}
void Worker::flush()
{
std::unique_lock<compat::Mutex> lock( m_lock );
assert( m_paused == true || m_thread.get_id() == compat::Thread::id{} );
m_idleCond.wait( lock, [this]() {
return m_idle == true;
});
while ( m_tasks.empty() == false )
m_tasks.pop();
m_service->onFlushing();
}
void Worker::restart()
{
m_service->onRestarted();
}
void Worker::mainloop()
{
// It would be unsafe to call name() at the end of this function, since
// we might stop the thread during ParserService destruction. This implies
// that the underlying service has been deleted already.
std::string serviceName = m_service->name();
LOG_INFO("Entering ParserService [", serviceName, "] thread");
setIdle( false );
while ( true )
{
std::shared_ptr<Task> task;
ML_UNHANDLED_EXCEPTION_INIT
{
{
std::unique_lock<compat::Mutex> lock( m_lock );
if ( m_stopParser == true )
break;
if ( m_tasks.empty() == true || m_paused == true )
{
LOG_DEBUG( "Halting ParserService [", serviceName, "] mainloop" );
setIdle( true );
m_idleCond.notify_all();
m_cond.wait( lock, [this]() {
return ( m_tasks.empty() == false && m_paused == false )
|| m_stopParser == true;
});
LOG_DEBUG( "Resuming ParserService [", serviceName, "] mainloop" );
// We might have been woken up because the parser is being destroyed
if ( m_stopParser == true )
break;
setIdle( false );
}
// Otherwise it's safe to assume we have at least one element.
LOG_DEBUG('[', serviceName, "] has ", m_tasks.size(), " tasks remaining" );
task = std::move( m_tasks.front() );
m_tasks.pop();
}
// Special case to restore uncompleted tasks from a parser thread
if ( task == nullptr )
{
restoreTasks();
continue;
}
if ( task->isStepCompleted( m_service->targetedStep() ) == true )
{
LOG_DEBUG( "Skipping completed task [", serviceName, "] on ", task->mrl() );
m_parserCb->done( std::move( task ), Status::Success );
continue;
}
Status status;
try
{
LOG_DEBUG( "Executing ", serviceName, " task on ", task->mrl() );
auto chrono = std::chrono::steady_clock::now();
auto file = std::static_pointer_cast<File>( task->file() );
if ( file != nullptr && file->isRemovable() )
{
auto folder = Folder::fetch( m_ml, file->folderId() );
assert( folder != nullptr );
if ( folder == nullptr || folder->isPresent() == false )
{
LOG_DEBUG( "Postponing parsing of ", file->rawMrl(),
" until the device containing it gets mounted back" );
m_parserCb->done( std::move( task ), Status::TemporaryUnavailable );
continue;
}
}
task->startParserStep();
status = m_service->run( *task );
auto duration = std::chrono::steady_clock::now() - chrono;
LOG_DEBUG( "Done executing ", serviceName, " task on ", task->mrl(), " in ",
std::chrono::duration_cast<std::chrono::milliseconds>( duration ).count(),
"ms. Result: ",
static_cast<std::underlying_type_t<parser::Status>>( status ) );
}
catch ( const fs::errors::DeviceRemoved& )
{
LOG_ERROR( "Parsing of ", task->mrl(), " was interrupted "
"due to its containing device being unmounted" );
status = Status::TemporaryUnavailable;
}
catch ( const fs::errors::Exception& ex )
{
LOG_ERROR( "Caught an FS exception during ", task->mrl(), " [", serviceName, "] parsing: ", ex.what() );
status = Status::Fatal;
}
if ( handleServiceResult( *task, status ) == false )
status = Status::Fatal;
m_parserCb->done( std::move( task ), status );
}
ML_UNHANDLED_EXCEPTION_BODY( serviceName.c_str() )
}
LOG_INFO("Exiting ParserService [", serviceName, "] thread");
setIdle( true );
}
void Worker::setIdle(bool isIdle)
{
// Calling the idleChanged callback will trigger a call to isIdle, so set the value before
// invoking it, otherwise we have an incoherent state.
if ( m_idle != isIdle )
{
m_idle = isIdle;
m_parserCb->onIdleChanged( isIdle );
}
}
bool Worker::handleServiceResult( Task& task, Status status )
{
if ( status == Status::Success )
{
task.markStepCompleted( m_service->targetedStep() );
// We don't want to save the extraction step in database, as restarting a
// task with extraction completed but analysis uncompleted wouldn't run
// the extraction again, causing the analysis to run with no info.
if ( m_service->targetedStep() != Step::MetadataExtraction )
return task.saveParserStep();
// We don't want to reset the entire retry count, as we would be stuck in
// a "loop" in case the metadata analysis fails (we'd always reset the retry
// count to zero, then fail, then run the extraction again, reset the retry,
// fail the analysis, and so on.
// We can't not increment the retry count for metadata extraction, since
// in case a file makes (lib)VLC crash, we would always try again, and
// therefor we would keep on crashing.
// However we don't want to just increment the retry count, since it
// would reach the maximum value too quickly (extraction would set retry
// count to 1, analysis to 2, and in case of failure, next run would set
// it over 3, while we only tried 2 times. Instead we just decrement it
// when the extraction step succeeds
return task.decrementRetryCount();
}
else if ( status == Status::Completed )
{
task.markStepCompleted( Step::Completed );
return task.saveParserStep();
}
else if ( status == Status::Discarded )
{
return Task::destroy( m_ml, task.id() );
}
return true;
}
void Worker::restoreTasks()
{
auto tasks = Task::fetchUncompleted( m_ml );
if ( tasks.size() > 0 )
LOG_INFO( "Resuming parsing on ", tasks.size(), " tasks" );
else
LOG_DEBUG( "No task to resume." );
for ( auto& t : tasks )
{
{
std::lock_guard<compat::Mutex> lock( m_lock );
if ( m_stopParser == true )
break;
}
if ( t->restoreLinkedEntities() == false )
continue;
m_parserCb->parse( std::move( t ) );
}
}
}
}
<|endoftext|>
|
<commit_before>/*************************************************************************
*
* $RCSfile: viewcontactoftextobj.cxx,v $
*
* $Revision: 1.2 $
*
* last change: $Author: rt $ $Date: 2003-11-24 16:46:19 $
*
* 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 _SDR_CONTACT_VIEWCONTACTOFTEXTOBJ_HXX
#include <svx/sdr/contact/viewcontactoftextobj.hxx>
#endif
#ifndef _SVDOTEXT_HXX
#include <svdotext.hxx>
#endif
//////////////////////////////////////////////////////////////////////////////
namespace sdr
{
namespace contact
{
ViewContactOfTextObj::ViewContactOfTextObj(SdrTextObj& rTextObj)
: ViewContactOfSdrObj(rTextObj)
{
}
ViewContactOfTextObj::~ViewContactOfTextObj()
{
}
} // end of namespace contact
} // end of namespace sdr
//////////////////////////////////////////////////////////////////////////////
// eof
<commit_msg>INTEGRATION: CWS ooo19126 (1.2.1096); FILE MERGED 2005/09/05 14:26:31 rt 1.2.1096.1: #i54170# Change license header: remove SISSL<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: viewcontactoftextobj.cxx,v $
*
* $Revision: 1.3 $
*
* last change: $Author: rt $ $Date: 2005-09-09 00:06:50 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#ifndef _SDR_CONTACT_VIEWCONTACTOFTEXTOBJ_HXX
#include <svx/sdr/contact/viewcontactoftextobj.hxx>
#endif
#ifndef _SVDOTEXT_HXX
#include <svdotext.hxx>
#endif
//////////////////////////////////////////////////////////////////////////////
namespace sdr
{
namespace contact
{
ViewContactOfTextObj::ViewContactOfTextObj(SdrTextObj& rTextObj)
: ViewContactOfSdrObj(rTextObj)
{
}
ViewContactOfTextObj::~ViewContactOfTextObj()
{
}
} // end of namespace contact
} // end of namespace sdr
//////////////////////////////////////////////////////////////////////////////
// eof
<|endoftext|>
|
<commit_before>// Time: ctor: O(m * n)
// lookup: O(1)
// Space: O(m * n)
class NumMatrix {
public:
NumMatrix(vector<vector<int>> &matrix) {
if (matrix.empty()) {
return;
}
const auto m = matrix.size(), n = matrix[0].size();
for (int i = 0; i <= m; ++i) {
sums.emplace_back(n + 1, 0);
}
for (int i = 1; i <= m; ++i) {
for (int j = 0; j <= n; ++j) {
sums[i][j] = sums[i][j - 1] + matrix[i - 1][j - 1];
}
}
for (int j = 0; j <= n; ++j) {
for (int i = 1; i <= m; ++i) {
sums[i][j] += sums[i - 1][j];
}
}
}
int sumRegion(int row1, int col1, int row2, int col2) {
return sums[row2 + 1][col2 + 1] - sums[row2 + 1][col1] -
sums[row1][col2 + 1] + sums[row1][col1];
}
private:
vector<vector<int>> sums;
};
// Your NumMatrix object will be instantiated and called as such:
// NumMatrix numMatrix(matrix);
// numMatrix.sumRegion(0, 1, 2, 3);
// numMatrix.sumRegion(1, 2, 3, 4);
<commit_msg>Update range-sum-query-2d-immutable.cpp<commit_after>// Time: ctor: O(m * n),
// lookup: O(1)
// Space: O(m * n)
class NumMatrix {
public:
NumMatrix(vector<vector<int>> &matrix) {
if (matrix.empty()) {
return;
}
const auto m = matrix.size(), n = matrix[0].size();
for (int i = 0; i <= m; ++i) {
sums_.emplace_back(n + 1, 0);
}
for (int i = 1; i <= m; ++i) {
for (int j = 0; j <= n; ++j) {
sums_[i][j] = sums_[i][j - 1] + matrix[i - 1][j - 1];
}
}
for (int j = 0; j <= n; ++j) {
for (int i = 1; i <= m; ++i) {
sums_[i][j] += sums_[i - 1][j];
}
}
}
int sumRegion(int row1, int col1, int row2, int col2) {
return sums_[row2 + 1][col2 + 1] - sums_[row2 + 1][col1] -
sums_[row1][col2 + 1] + sums_[row1][col1];
}
private:
vector<vector<int>> sums_;
};
// Your NumMatrix object will be instantiated and called as such:
// NumMatrix numMatrix(matrix);
// numMatrix.sumRegion(0, 1, 2, 3);
// numMatrix.sumRegion(1, 2, 3, 4);
<|endoftext|>
|
<commit_before>/*
Copyright (C) 2008 by Marten Svanfeldt
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Library General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Library General Public License for more details.
You should have received a copy of the GNU Library General Public
License along with this library; if not, write to the Free
Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
#include "cssysdef.h"
#include "csutil/ref.h"
#include "iengine/engine.h"
#include "imap/services.h"
#include "imesh/animesh.h"
#include "imesh/object.h"
#include "iutil/stringarray.h"
#include "iutil/document.h"
#include "iutil/plugin.h"
#include "ivaria/reporter.h"
#include "imap/ldrctxt.h"
#include "iengine/mesh.h"
#include "imesh/skeleton2.h"
#include "imesh/skeleton2anim.h"
#include "animeshldr.h"
CS_IMPLEMENT_PLUGIN
CS_PLUGIN_NAMESPACE_BEGIN(Animeshldr)
{
SCF_IMPLEMENT_FACTORY(AnimeshFactoryLoader);
SCF_IMPLEMENT_FACTORY(AnimeshObjectLoader);
SCF_IMPLEMENT_FACTORY(AnimeshFactorySaver);
SCF_IMPLEMENT_FACTORY(AnimeshObjectSaver);
AnimeshFactoryLoader::AnimeshFactoryLoader (iBase* parent)
: scfImplementationType (this, parent)
{
}
static const char* msgidFactory = "crystalspace.animeshfactoryloader";
csPtr<iBase> AnimeshFactoryLoader::Parse (iDocumentNode* node,
iStreamSource* ssource, iLoaderContext* ldr_context,
iBase* context)
{
csRef<iMeshObjectType> type = csLoadPluginCheck<iMeshObjectType> (
object_reg, "crystalspace.mesh.object.animesh", false);
if (!type)
{
synldr->ReportError (msgidFactory, node,
"Could not load the animesh object plugin!");
return 0;
}
// Create a factory
csRef<iMeshObjectFactory> fact = type->NewFactory ();
csRef<iAnimatedMeshFactory> amfact =
scfQueryInterfaceSafe<iAnimatedMeshFactory> (fact);
if (!amfact)
{
synldr->ReportError (msgidFactory, node,
"Could not load the animesh object plugin!");
return 0;
}
csRef<iDocumentNodeIterator> it = node->GetNodes ();
while (it->HasNext ())
{
csRef<iDocumentNode> child = it->Next ();
if (child->GetType () != CS_NODE_ELEMENT) continue;
const char* value = child->GetValue ();
csStringID id = xmltokens.Request (value);
switch (id)
{
case XMLTOKEN_MATERIAL:
{
const char* matname = child->GetContentsValue ();
iMaterialWrapper* mat = ldr_context->FindMaterial (matname);
if (!mat)
{
synldr->ReportError (msgidFactory, child, "Couldn't find material '%s'!",
matname);
return 0;
}
fact->SetMaterialWrapper (mat);
}
break;
case XMLTOKEN_MIXMODE:
{
uint mm;
if (!synldr->ParseMixmode (child, mm))
return 0;
fact->SetMixMode (mm);
}
break;
case XMLTOKEN_VERTEX:
{
csRef<iRenderBuffer> rb = synldr->ParseRenderBuffer (child);
if (!rb)
{
synldr->ReportError (msgidFactory, child, "Could not parse render buffer!");
return 0;
}
amfact->SetVertices (rb);
}
break;
case XMLTOKEN_TEXCOORD:
{
csRef<iRenderBuffer> rb = synldr->ParseRenderBuffer (child);
if (!rb)
{
synldr->ReportError (msgidFactory, child, "Could not parse render buffer!");
return 0;
}
amfact->SetTexCoords (rb);
}
break;
case XMLTOKEN_NORMAL:
{
csRef<iRenderBuffer> rb = synldr->ParseRenderBuffer (child);
if (!rb)
{
synldr->ReportError (msgidFactory, child, "Could not parse render buffer!");
return 0;
}
amfact->SetNormals (rb);
}
break;
case XMLTOKEN_TANGENT:
{
csRef<iRenderBuffer> rb = synldr->ParseRenderBuffer (child);
if (!rb)
{
synldr->ReportError (msgidFactory, child, "Could not parse render buffer!");
return 0;
}
amfact->SetTangents (rb);
}
break;
case XMLTOKEN_BINORMAL:
{
csRef<iRenderBuffer> rb = synldr->ParseRenderBuffer (child);
if (!rb)
{
synldr->ReportError (msgidFactory, child, "Could not parse render buffer!");
return 0;
}
amfact->SetBinormals (rb);
}
break;
case XMLTOKEN_COLOR:
{
csRef<iRenderBuffer> rb = synldr->ParseRenderBuffer (child);
if (!rb)
{
synldr->ReportError (msgidFactory, child, "Could not parse render buffer!");
return 0;
}
amfact->SetColors (rb);
}
break;
case XMLTOKEN_BONEINFLUENCES:
{
int wantedPerVertex = child->GetAttributeValueAsInt ("bonespervertex");
if (!wantedPerVertex)
amfact->SetBoneInfluencesPerVertex (wantedPerVertex);
int realPerVertex = amfact->GetBoneInfluencesPerVertex ();
int numVerts = amfact->GetVertexCount ();
int currInfl = 0;
csAnimatedMeshBoneInfluence* bi = amfact->GetBoneInfluences ();
csRef<iDocumentNodeIterator> it = child->GetNodes ();
while (it->HasNext ())
{
csRef<iDocumentNode> child2 = it->Next ();
if (child2->GetType () != CS_NODE_ELEMENT) continue;
const char* value = child2->GetValue ();
csStringID id = xmltokens.Request (value);
switch (id)
{
case XMLTOKEN_BI:
{
if (currInfl > numVerts*realPerVertex)
{
synldr->ReportError (msgidFactory, child,
"Too many bone vertex influences %d, expected %d", currInfl, numVerts*realPerVertex);
return 0;
}
bi[currInfl].bone = child2->GetAttributeValueAsInt("bone");
bi[currInfl].influenceWeight = child2->GetAttributeValueAsFloat ("weight");
currInfl++;
}
break;
default:
synldr->ReportBadToken (child2);
return 0;
}
}
}
break;
case XMLTOKEN_SUBMESH:
{
// Handle submesh
csRef<iRenderBuffer> indexBuffer;
csRef<iDocumentNodeIterator> it = child->GetNodes ();
while (it->HasNext ())
{
csRef<iDocumentNode> child2 = it->Next ();
if (child2->GetType () != CS_NODE_ELEMENT) continue;
const char* value = child2->GetValue ();
csStringID id = xmltokens.Request (value);
switch (id)
{
case XMLTOKEN_INDEX:
{
indexBuffer = synldr->ParseRenderBuffer (child2);
if (!indexBuffer)
{
synldr->ReportError (msgidFactory, child2, "Could not parse render buffer!");
return 0;
}
}
break;
default:
synldr->ReportBadToken (child2);
return 0;
}
}
if (indexBuffer)
{
amfact->CreateSubMesh (indexBuffer);
}
}
break;
case XMLTOKEN_SKELETON:
{
if (!skelMgr)
{
skelMgr = csQueryRegistry<iSkeletonManager2> (object_reg);
if (!skelMgr)
{
synldr->ReportError (msgidFactory, child, "Could not find any loaded skeletons");
return 0;
}
}
const char* skelName = child->GetContentsValue ();
iSkeletonFactory2* skelFact = skelMgr->FindSkeletonFactory (skelName);
if (!skelFact)
{
synldr->ReportError (msgidFactory, child, "Could not find skeleton %s", skelName);
return 0;
}
amfact->SetSkeletonFactory (skelFact);
}
break;
case XMLTOKEN_MORPHTARGET:
if (!ParseMorphTarget (child, amfact))
return 0;
break;
case XMLTOKEN_SOCKET:
csReversibleTransform transform;
BoneID bone = child->GetAttributeValueAsInt ("bone");
const char* name = child->GetAttributeValue ("name");
csRef<iDocumentNode> tnode = child->GetNode ("transform");
if (tnode)
{
csRef<iDocumentNode> vnode = tnode->GetNode ("vector");
if (vnode)
{
csVector3 v;
synldr->ParseVector (vnode, v);
transform.SetOrigin (v);
}
csRef<iDocumentNode> mnode = tnode->GetNode ("matrix");
if (mnode)
{
csMatrix3 m;
synldr->ParseMatrix (mnode, m);
transform.SetO2T (m);
}
}
amfact->CreateSocket (bone, transform, name);
break;
default:
synldr->ReportBadToken (child);
return 0;
}
}
// Recalc stuff
amfact->Invalidate ();
return csPtr<iBase> (fact);
}
bool AnimeshFactoryLoader::ParseMorphTarget (iDocumentNode* child,
iAnimatedMeshFactory* amfact)
{
const char* name = child->GetAttributeValue ("name");
csRef<iRenderBuffer> offsetsBuffer;
csRef<iDocumentNodeIterator> it = child->GetNodes ();
while (it->HasNext ())
{
csRef<iDocumentNode> child2 = it->Next ();
if (child2->GetType () != CS_NODE_ELEMENT) continue;
const char* value = child2->GetValue ();
csStringID id = xmltokens.Request (value);
switch (id)
{
case XMLTOKEN_OFFSETS:
{
offsetsBuffer = synldr->ParseRenderBuffer (child2);
if (!offsetsBuffer)
{
synldr->ReportError (msgidFactory, child2, "Could not parse render buffer!");
return false;
}
}
break;
default:
synldr->ReportBadToken (child2);
return false;
}
}
iAnimatedMeshMorphTarget* morphTarget = amfact->CreateMorphTarget (name);
morphTarget->SetVertexOffsets (offsetsBuffer);
morphTarget->Invalidate();
return true;
}
bool AnimeshFactoryLoader::Initialize (iObjectRegistry* objReg)
{
object_reg = objReg;
synldr = csQueryRegistry<iSyntaxService> (object_reg);
InitTokenTable (xmltokens);
return true;
}
//-------------------------------------------------------------------------
AnimeshFactorySaver::AnimeshFactorySaver (iBase* parent)
: scfImplementationType (this, parent)
{}
bool AnimeshFactorySaver::WriteDown (iBase *obj, iDocumentNode* parent,
iStreamSource*)
{
return false;
}
bool AnimeshFactorySaver::Initialize (iObjectRegistry*)
{
return false;
}
AnimeshObjectLoader::AnimeshObjectLoader (iBase* parent)
: scfImplementationType (this, parent)
{}
csPtr<iBase> AnimeshObjectLoader::Parse (iDocumentNode* node,
iStreamSource* ssource, iLoaderContext* ldr_context,
iBase* context)
{
static const char* msgid = "crystalspace.animeshloader";
csRef<iMeshObject> mesh;
csRef<iAnimatedMesh> ammesh;
csRef<iDocumentNodeIterator> it = node->GetNodes ();
while (it->HasNext ())
{
csRef<iDocumentNode> child = it->Next ();
if (child->GetType () != CS_NODE_ELEMENT) continue;
const char* value = child->GetValue ();
csStringID id = xmltokens.Request (value);
switch (id)
{
case XMLTOKEN_FACTORY:
{
const char* factname = child->GetContentsValue ();
iMeshFactoryWrapper* fact = ldr_context->FindMeshFactory (factname);
if(!fact)
{
synldr->ReportError (msgid, child,
"Couldn't find factory '%s'!", factname);
return 0;
}
csRef<iAnimatedMeshFactory> amfact =
scfQueryInterface<iAnimatedMeshFactory> (fact->GetMeshObjectFactory ());
if (!amfact)
{
synldr->ReportError (msgid, child,
"Factory '%s' doesn't appear to be a animesh factory!", factname);
return 0;
}
mesh = fact->GetMeshObjectFactory ()->NewInstance ();
ammesh = scfQueryInterface<iAnimatedMesh> (mesh);
if (!ammesh)
{
synldr->ReportError (msgid, child,
"Factory '%s' doesn't appear to be a animesh factory!", factname);
return 0;
}
}
break;
case XMLTOKEN_MATERIAL:
{
const char* matname = child->GetContentsValue ();
iMaterialWrapper* mat = ldr_context->FindMaterial (matname);
if (!mat)
{
synldr->ReportError (msgid, child, "Couldn't find material '%s'!",
matname);
return 0;
}
mesh->SetMaterialWrapper (mat);
}
break;
case XMLTOKEN_MIXMODE:
{
uint mm;
if (!synldr->ParseMixmode (child, mm))
return 0;
mesh->SetMixMode (mm);
}
break;
case XMLTOKEN_SKELETON:
{
if (!skelMgr)
{
skelMgr = csQueryRegistry<iSkeletonManager2> (object_reg);
if (!skelMgr)
{
synldr->ReportError (msgid, child, "Could not find any loaded skeletons");
return 0;
}
}
const char* skelName = child->GetContentsValue ();
iSkeletonFactory2* skelFact = skelMgr->FindSkeletonFactory (skelName);
if (!skelFact)
{
synldr->ReportError (msgid, child, "Could not find skeleton %s", skelName);
return 0;
}
csRef<iSkeleton2> skeleton = skelFact->CreateSkeleton ();
ammesh->SetSkeleton (skeleton);
}
break;
case XMLTOKEN_ANIMATIONPACKET:
{
if (!skelMgr)
{
skelMgr = csQueryRegistry<iSkeletonManager2> (object_reg);
if (!skelMgr)
{
synldr->ReportError (msgid, child, "Could not find any loaded skeletons");
return 0;
}
}
iSkeleton2* skeleton = ammesh->GetSkeleton ();
if (!skeleton)
{
synldr->ReportError (msgid, child, "Mesh does not have a skeleton");
return 0;
}
const char* packetName = child->GetContentsValue ();
iSkeletonAnimPacketFactory2* packetFact = skelMgr->FindAnimPacketFactory (packetName);
if (!packetFact)
{
synldr->ReportError (msgid, child, "Could not find animation packet %s", packetName);
return 0;
}
csRef<iSkeletonAnimPacket2> packet = packetFact->CreateInstance (skeleton);
skeleton->SetAnimationPacket (packet);
}
break;
default:
synldr->ReportBadToken (child);
return 0;
}
}
return csPtr<iBase> (mesh);
}
bool AnimeshObjectLoader::Initialize (iObjectRegistry* objReg)
{
object_reg = objReg;
synldr = csQueryRegistry<iSyntaxService> (object_reg);
InitTokenTable (xmltokens);
return true;
}
AnimeshObjectSaver::AnimeshObjectSaver (iBase* parent)
: scfImplementationType (this, parent)
{}
bool AnimeshObjectSaver::WriteDown (iBase *obj, iDocumentNode* parent,
iStreamSource*)
{
return false;
}
bool AnimeshObjectSaver::Initialize (iObjectRegistry*)
{
return false;
}
}
CS_PLUGIN_NAMESPACE_END(Animeshldr)
<commit_msg>Fixed GCC compilation<commit_after>/*
Copyright (C) 2008 by Marten Svanfeldt
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Library General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Library General Public License for more details.
You should have received a copy of the GNU Library General Public
License along with this library; if not, write to the Free
Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
#include "cssysdef.h"
#include "csutil/ref.h"
#include "iengine/engine.h"
#include "imap/services.h"
#include "imesh/animesh.h"
#include "imesh/object.h"
#include "iutil/stringarray.h"
#include "iutil/document.h"
#include "iutil/plugin.h"
#include "ivaria/reporter.h"
#include "imap/ldrctxt.h"
#include "iengine/mesh.h"
#include "imesh/skeleton2.h"
#include "imesh/skeleton2anim.h"
#include "animeshldr.h"
CS_IMPLEMENT_PLUGIN
CS_PLUGIN_NAMESPACE_BEGIN(Animeshldr)
{
SCF_IMPLEMENT_FACTORY(AnimeshFactoryLoader);
SCF_IMPLEMENT_FACTORY(AnimeshObjectLoader);
SCF_IMPLEMENT_FACTORY(AnimeshFactorySaver);
SCF_IMPLEMENT_FACTORY(AnimeshObjectSaver);
AnimeshFactoryLoader::AnimeshFactoryLoader (iBase* parent)
: scfImplementationType (this, parent)
{
}
static const char* msgidFactory = "crystalspace.animeshfactoryloader";
csPtr<iBase> AnimeshFactoryLoader::Parse (iDocumentNode* node,
iStreamSource* ssource, iLoaderContext* ldr_context,
iBase* context)
{
csRef<iMeshObjectType> type = csLoadPluginCheck<iMeshObjectType> (
object_reg, "crystalspace.mesh.object.animesh", false);
if (!type)
{
synldr->ReportError (msgidFactory, node,
"Could not load the animesh object plugin!");
return 0;
}
// Create a factory
csRef<iMeshObjectFactory> fact = type->NewFactory ();
csRef<iAnimatedMeshFactory> amfact =
scfQueryInterfaceSafe<iAnimatedMeshFactory> (fact);
if (!amfact)
{
synldr->ReportError (msgidFactory, node,
"Could not load the animesh object plugin!");
return 0;
}
csRef<iDocumentNodeIterator> it = node->GetNodes ();
while (it->HasNext ())
{
csRef<iDocumentNode> child = it->Next ();
if (child->GetType () != CS_NODE_ELEMENT) continue;
const char* value = child->GetValue ();
csStringID id = xmltokens.Request (value);
switch (id)
{
case XMLTOKEN_MATERIAL:
{
const char* matname = child->GetContentsValue ();
iMaterialWrapper* mat = ldr_context->FindMaterial (matname);
if (!mat)
{
synldr->ReportError (msgidFactory, child, "Couldn't find material '%s'!",
matname);
return 0;
}
fact->SetMaterialWrapper (mat);
}
break;
case XMLTOKEN_MIXMODE:
{
uint mm;
if (!synldr->ParseMixmode (child, mm))
return 0;
fact->SetMixMode (mm);
}
break;
case XMLTOKEN_VERTEX:
{
csRef<iRenderBuffer> rb = synldr->ParseRenderBuffer (child);
if (!rb)
{
synldr->ReportError (msgidFactory, child, "Could not parse render buffer!");
return 0;
}
amfact->SetVertices (rb);
}
break;
case XMLTOKEN_TEXCOORD:
{
csRef<iRenderBuffer> rb = synldr->ParseRenderBuffer (child);
if (!rb)
{
synldr->ReportError (msgidFactory, child, "Could not parse render buffer!");
return 0;
}
amfact->SetTexCoords (rb);
}
break;
case XMLTOKEN_NORMAL:
{
csRef<iRenderBuffer> rb = synldr->ParseRenderBuffer (child);
if (!rb)
{
synldr->ReportError (msgidFactory, child, "Could not parse render buffer!");
return 0;
}
amfact->SetNormals (rb);
}
break;
case XMLTOKEN_TANGENT:
{
csRef<iRenderBuffer> rb = synldr->ParseRenderBuffer (child);
if (!rb)
{
synldr->ReportError (msgidFactory, child, "Could not parse render buffer!");
return 0;
}
amfact->SetTangents (rb);
}
break;
case XMLTOKEN_BINORMAL:
{
csRef<iRenderBuffer> rb = synldr->ParseRenderBuffer (child);
if (!rb)
{
synldr->ReportError (msgidFactory, child, "Could not parse render buffer!");
return 0;
}
amfact->SetBinormals (rb);
}
break;
case XMLTOKEN_COLOR:
{
csRef<iRenderBuffer> rb = synldr->ParseRenderBuffer (child);
if (!rb)
{
synldr->ReportError (msgidFactory, child, "Could not parse render buffer!");
return 0;
}
amfact->SetColors (rb);
}
break;
case XMLTOKEN_BONEINFLUENCES:
{
int wantedPerVertex = child->GetAttributeValueAsInt ("bonespervertex");
if (!wantedPerVertex)
amfact->SetBoneInfluencesPerVertex (wantedPerVertex);
int realPerVertex = amfact->GetBoneInfluencesPerVertex ();
int numVerts = amfact->GetVertexCount ();
int currInfl = 0;
csAnimatedMeshBoneInfluence* bi = amfact->GetBoneInfluences ();
csRef<iDocumentNodeIterator> it = child->GetNodes ();
while (it->HasNext ())
{
csRef<iDocumentNode> child2 = it->Next ();
if (child2->GetType () != CS_NODE_ELEMENT) continue;
const char* value = child2->GetValue ();
csStringID id = xmltokens.Request (value);
switch (id)
{
case XMLTOKEN_BI:
{
if (currInfl > numVerts*realPerVertex)
{
synldr->ReportError (msgidFactory, child,
"Too many bone vertex influences %d, expected %d", currInfl, numVerts*realPerVertex);
return 0;
}
bi[currInfl].bone = child2->GetAttributeValueAsInt("bone");
bi[currInfl].influenceWeight = child2->GetAttributeValueAsFloat ("weight");
currInfl++;
}
break;
default:
synldr->ReportBadToken (child2);
return 0;
}
}
}
break;
case XMLTOKEN_SUBMESH:
{
// Handle submesh
csRef<iRenderBuffer> indexBuffer;
csRef<iDocumentNodeIterator> it = child->GetNodes ();
while (it->HasNext ())
{
csRef<iDocumentNode> child2 = it->Next ();
if (child2->GetType () != CS_NODE_ELEMENT) continue;
const char* value = child2->GetValue ();
csStringID id = xmltokens.Request (value);
switch (id)
{
case XMLTOKEN_INDEX:
{
indexBuffer = synldr->ParseRenderBuffer (child2);
if (!indexBuffer)
{
synldr->ReportError (msgidFactory, child2, "Could not parse render buffer!");
return 0;
}
}
break;
default:
synldr->ReportBadToken (child2);
return 0;
}
}
if (indexBuffer)
{
amfact->CreateSubMesh (indexBuffer);
}
}
break;
case XMLTOKEN_SKELETON:
{
if (!skelMgr)
{
skelMgr = csQueryRegistry<iSkeletonManager2> (object_reg);
if (!skelMgr)
{
synldr->ReportError (msgidFactory, child, "Could not find any loaded skeletons");
return 0;
}
}
const char* skelName = child->GetContentsValue ();
iSkeletonFactory2* skelFact = skelMgr->FindSkeletonFactory (skelName);
if (!skelFact)
{
synldr->ReportError (msgidFactory, child, "Could not find skeleton %s", skelName);
return 0;
}
amfact->SetSkeletonFactory (skelFact);
}
break;
case XMLTOKEN_MORPHTARGET:
if (!ParseMorphTarget (child, amfact))
return 0;
break;
case XMLTOKEN_SOCKET:
{
csReversibleTransform transform;
BoneID bone = child->GetAttributeValueAsInt ("bone");
const char* name = child->GetAttributeValue ("name");
csRef<iDocumentNode> tnode = child->GetNode ("transform");
if (tnode)
{
csRef<iDocumentNode> vnode = tnode->GetNode ("vector");
if (vnode)
{
csVector3 v;
synldr->ParseVector (vnode, v);
transform.SetOrigin (v);
}
csRef<iDocumentNode> mnode = tnode->GetNode ("matrix");
if (mnode)
{
csMatrix3 m;
synldr->ParseMatrix (mnode, m);
transform.SetO2T (m);
}
}
amfact->CreateSocket (bone, transform, name);
}
break;
default:
synldr->ReportBadToken (child);
return 0;
}
}
// Recalc stuff
amfact->Invalidate ();
return csPtr<iBase> (fact);
}
bool AnimeshFactoryLoader::ParseMorphTarget (iDocumentNode* child,
iAnimatedMeshFactory* amfact)
{
const char* name = child->GetAttributeValue ("name");
csRef<iRenderBuffer> offsetsBuffer;
csRef<iDocumentNodeIterator> it = child->GetNodes ();
while (it->HasNext ())
{
csRef<iDocumentNode> child2 = it->Next ();
if (child2->GetType () != CS_NODE_ELEMENT) continue;
const char* value = child2->GetValue ();
csStringID id = xmltokens.Request (value);
switch (id)
{
case XMLTOKEN_OFFSETS:
{
offsetsBuffer = synldr->ParseRenderBuffer (child2);
if (!offsetsBuffer)
{
synldr->ReportError (msgidFactory, child2, "Could not parse render buffer!");
return false;
}
}
break;
default:
synldr->ReportBadToken (child2);
return false;
}
}
iAnimatedMeshMorphTarget* morphTarget = amfact->CreateMorphTarget (name);
morphTarget->SetVertexOffsets (offsetsBuffer);
morphTarget->Invalidate();
return true;
}
bool AnimeshFactoryLoader::Initialize (iObjectRegistry* objReg)
{
object_reg = objReg;
synldr = csQueryRegistry<iSyntaxService> (object_reg);
InitTokenTable (xmltokens);
return true;
}
//-------------------------------------------------------------------------
AnimeshFactorySaver::AnimeshFactorySaver (iBase* parent)
: scfImplementationType (this, parent)
{}
bool AnimeshFactorySaver::WriteDown (iBase *obj, iDocumentNode* parent,
iStreamSource*)
{
return false;
}
bool AnimeshFactorySaver::Initialize (iObjectRegistry*)
{
return false;
}
AnimeshObjectLoader::AnimeshObjectLoader (iBase* parent)
: scfImplementationType (this, parent)
{}
csPtr<iBase> AnimeshObjectLoader::Parse (iDocumentNode* node,
iStreamSource* ssource, iLoaderContext* ldr_context,
iBase* context)
{
static const char* msgid = "crystalspace.animeshloader";
csRef<iMeshObject> mesh;
csRef<iAnimatedMesh> ammesh;
csRef<iDocumentNodeIterator> it = node->GetNodes ();
while (it->HasNext ())
{
csRef<iDocumentNode> child = it->Next ();
if (child->GetType () != CS_NODE_ELEMENT) continue;
const char* value = child->GetValue ();
csStringID id = xmltokens.Request (value);
switch (id)
{
case XMLTOKEN_FACTORY:
{
const char* factname = child->GetContentsValue ();
iMeshFactoryWrapper* fact = ldr_context->FindMeshFactory (factname);
if(!fact)
{
synldr->ReportError (msgid, child,
"Couldn't find factory '%s'!", factname);
return 0;
}
csRef<iAnimatedMeshFactory> amfact =
scfQueryInterface<iAnimatedMeshFactory> (fact->GetMeshObjectFactory ());
if (!amfact)
{
synldr->ReportError (msgid, child,
"Factory '%s' doesn't appear to be a animesh factory!", factname);
return 0;
}
mesh = fact->GetMeshObjectFactory ()->NewInstance ();
ammesh = scfQueryInterface<iAnimatedMesh> (mesh);
if (!ammesh)
{
synldr->ReportError (msgid, child,
"Factory '%s' doesn't appear to be a animesh factory!", factname);
return 0;
}
}
break;
case XMLTOKEN_MATERIAL:
{
const char* matname = child->GetContentsValue ();
iMaterialWrapper* mat = ldr_context->FindMaterial (matname);
if (!mat)
{
synldr->ReportError (msgid, child, "Couldn't find material '%s'!",
matname);
return 0;
}
mesh->SetMaterialWrapper (mat);
}
break;
case XMLTOKEN_MIXMODE:
{
uint mm;
if (!synldr->ParseMixmode (child, mm))
return 0;
mesh->SetMixMode (mm);
}
break;
case XMLTOKEN_SKELETON:
{
if (!skelMgr)
{
skelMgr = csQueryRegistry<iSkeletonManager2> (object_reg);
if (!skelMgr)
{
synldr->ReportError (msgid, child, "Could not find any loaded skeletons");
return 0;
}
}
const char* skelName = child->GetContentsValue ();
iSkeletonFactory2* skelFact = skelMgr->FindSkeletonFactory (skelName);
if (!skelFact)
{
synldr->ReportError (msgid, child, "Could not find skeleton %s", skelName);
return 0;
}
csRef<iSkeleton2> skeleton = skelFact->CreateSkeleton ();
ammesh->SetSkeleton (skeleton);
}
break;
case XMLTOKEN_ANIMATIONPACKET:
{
if (!skelMgr)
{
skelMgr = csQueryRegistry<iSkeletonManager2> (object_reg);
if (!skelMgr)
{
synldr->ReportError (msgid, child, "Could not find any loaded skeletons");
return 0;
}
}
iSkeleton2* skeleton = ammesh->GetSkeleton ();
if (!skeleton)
{
synldr->ReportError (msgid, child, "Mesh does not have a skeleton");
return 0;
}
const char* packetName = child->GetContentsValue ();
iSkeletonAnimPacketFactory2* packetFact = skelMgr->FindAnimPacketFactory (packetName);
if (!packetFact)
{
synldr->ReportError (msgid, child, "Could not find animation packet %s", packetName);
return 0;
}
csRef<iSkeletonAnimPacket2> packet = packetFact->CreateInstance (skeleton);
skeleton->SetAnimationPacket (packet);
}
break;
default:
synldr->ReportBadToken (child);
return 0;
}
}
return csPtr<iBase> (mesh);
}
bool AnimeshObjectLoader::Initialize (iObjectRegistry* objReg)
{
object_reg = objReg;
synldr = csQueryRegistry<iSyntaxService> (object_reg);
InitTokenTable (xmltokens);
return true;
}
AnimeshObjectSaver::AnimeshObjectSaver (iBase* parent)
: scfImplementationType (this, parent)
{}
bool AnimeshObjectSaver::WriteDown (iBase *obj, iDocumentNode* parent,
iStreamSource*)
{
return false;
}
bool AnimeshObjectSaver::Initialize (iObjectRegistry*)
{
return false;
}
}
CS_PLUGIN_NAMESPACE_END(Animeshldr)
<|endoftext|>
|
<commit_before>// Copyright (c) 2009-2012 Bitcoin Developers
// Copyright (c) 2012-2013 The Pulse developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "init.h" // for pwalletMain
#include "bitcoinrpc.h"
#include "ui_interface.h"
#include "base58.h"
#include <boost/lexical_cast.hpp>
#include "json/json_spirit_reader_template.h"
#include "json/json_spirit_writer_template.h"
#include "json/json_spirit_utils.h"
#define printf OutputDebugStringF
// using namespace boost::asio;
using namespace json_spirit;
using namespace std;
extern Object JSONRPCError(int code, const string& message);
class CTxDump
{
public:
CBlockIndex *pindex;
int64 nValue;
bool fSpent;
CWalletTx* ptx;
int nOut;
CTxDump(CWalletTx* ptx = NULL, int nOut = -1)
{
pindex = NULL;
nValue = 0;
fSpent = false;
this->ptx = ptx;
this->nOut = nOut;
}
};
Value importprivkey(const Array& params, bool fHelp)
{
if (fHelp || params.size() < 1 || params.size() > 2)
throw runtime_error(
"importprivkey <pulseprivkey> [label]\n"
"Adds a private key (as returned by dumpprivkey) to your wallet.");
string strSecret = params[0].get_str();
string strLabel = "";
if (params.size() > 1)
strLabel = params[1].get_str();
CBitcoinSecret vchSecret;
bool fGood = vchSecret.SetString(strSecret);
if (!fGood) throw JSONRPCError(-5,"Invalid private key");
if (pwalletMain->IsLocked())
throw JSONRPCError(-13, "Error: Please enter the wallet passphrase with walletpassphrase first.");
if (fWalletUnlockMintOnly) // Pulse: no importprivkey in mint-only mode
throw JSONRPCError(-102, "Wallet is unlocked for minting only.");
CKey key;
bool fCompressed;
CSecret secret = vchSecret.GetSecret(fCompressed);
key.SetSecret(secret, fCompressed);
CKeyID vchAddress = key.GetPubKey().GetID();
{
LOCK2(cs_main, pwalletMain->cs_wallet);
pwalletMain->MarkDirty();
pwalletMain->SetAddressBookName(vchAddress, strLabel);
if (!pwalletMain->AddKey(key))
throw JSONRPCError(-4,"Error adding key to wallet");
pwalletMain->ScanForWalletTransactions(pindexGenesisBlock, true);
pwalletMain->ReacceptWalletTransactions();
}
MainFrameRepaint();
return Value::null;
}
Value dumpprivkey(const Array& params, bool fHelp)
{
if (fHelp || params.size() != 1)
throw runtime_error(
"dumpprivkey <pulseaddress>\n"
"Reveals the private key corresponding to <pulseaddress>.");
string strAddress = params[0].get_str();
CBitcoinAddress address;
if (!address.SetString(strAddress))
throw JSONRPCError(-5, "Invalid Pulse address");
if (pwalletMain->IsLocked())
throw JSONRPCError(-13, "Error: Please enter the wallet passphrase with walletpassphrase first.");
if (fWalletUnlockMintOnly) // Pulse: no dumpprivkey in mint-only mode
throw JSONRPCError(-102, "Wallet is unlocked for minting only.");
CKeyID keyID;
if (!address.GetKeyID(keyID))
throw JSONRPCError(-3, "Address does not refer to a key");
CSecret vchSecret;
bool fCompressed;
if (!pwalletMain->GetSecret(keyID, vchSecret, fCompressed))
throw JSONRPCError(-4,"Private key for address " + strAddress + " is not known");
return CBitcoinSecret(vchSecret, fCompressed).ToString();
}
<commit_msg>Update rpcdump.cpp<commit_after>// Copyright (c) 2009-2012 The Bitcoin developers
// Copyright (c) 2011-2013 The Peercoin developers
// Copyright (c) 2015 The Pulse developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "init.h" // for pwalletMain
#include "bitcoinrpc.h"
#include "ui_interface.h"
#include "base58.h"
#include <boost/lexical_cast.hpp>
#include "json/json_spirit_reader_template.h"
#include "json/json_spirit_writer_template.h"
#include "json/json_spirit_utils.h"
#define printf OutputDebugStringF
// using namespace boost::asio;
using namespace json_spirit;
using namespace std;
extern Object JSONRPCError(int code, const string& message);
class CTxDump
{
public:
CBlockIndex *pindex;
int64 nValue;
bool fSpent;
CWalletTx* ptx;
int nOut;
CTxDump(CWalletTx* ptx = NULL, int nOut = -1)
{
pindex = NULL;
nValue = 0;
fSpent = false;
this->ptx = ptx;
this->nOut = nOut;
}
};
Value importprivkey(const Array& params, bool fHelp)
{
if (fHelp || params.size() < 1 || params.size() > 2)
throw runtime_error(
"importprivkey <pulseprivkey> [label]\n"
"Adds a private key (as returned by dumpprivkey) to your wallet.");
string strSecret = params[0].get_str();
string strLabel = "";
if (params.size() > 1)
strLabel = params[1].get_str();
CBitcoinSecret vchSecret;
bool fGood = vchSecret.SetString(strSecret);
if (!fGood) throw JSONRPCError(-5,"Invalid private key");
if (pwalletMain->IsLocked())
throw JSONRPCError(-13, "Error: Please enter the wallet passphrase with walletpassphrase first.");
if (fWalletUnlockMintOnly) // Pulse: no importprivkey in mint-only mode
throw JSONRPCError(-102, "Wallet is unlocked for minting only.");
CKey key;
bool fCompressed;
CSecret secret = vchSecret.GetSecret(fCompressed);
key.SetSecret(secret, fCompressed);
CKeyID vchAddress = key.GetPubKey().GetID();
{
LOCK2(cs_main, pwalletMain->cs_wallet);
pwalletMain->MarkDirty();
pwalletMain->SetAddressBookName(vchAddress, strLabel);
if (!pwalletMain->AddKey(key))
throw JSONRPCError(-4,"Error adding key to wallet");
pwalletMain->ScanForWalletTransactions(pindexGenesisBlock, true);
pwalletMain->ReacceptWalletTransactions();
}
MainFrameRepaint();
return Value::null;
}
Value dumpprivkey(const Array& params, bool fHelp)
{
if (fHelp || params.size() != 1)
throw runtime_error(
"dumpprivkey <pulseaddress>\n"
"Reveals the private key corresponding to <pulseaddress>.");
string strAddress = params[0].get_str();
CBitcoinAddress address;
if (!address.SetString(strAddress))
throw JSONRPCError(-5, "Invalid Pulse address");
if (pwalletMain->IsLocked())
throw JSONRPCError(-13, "Error: Please enter the wallet passphrase with walletpassphrase first.");
if (fWalletUnlockMintOnly) // Pulse: no dumpprivkey in mint-only mode
throw JSONRPCError(-102, "Wallet is unlocked for minting only.");
CKeyID keyID;
if (!address.GetKeyID(keyID))
throw JSONRPCError(-3, "Address does not refer to a key");
CSecret vchSecret;
bool fCompressed;
if (!pwalletMain->GetSecret(keyID, vchSecret, fCompressed))
throw JSONRPCError(-4,"Private key for address " + strAddress + " is not known");
return CBitcoinSecret(vchSecret, fCompressed).ToString();
}
<|endoftext|>
|
<commit_before>/**************************************************************************
The MIT License (MIT)
Copyright (c) 2015 Dmitry Sovetov
https://github.com/dmsovetov
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 <Dreemchest.h>
#include "../Examples.h"
DC_USE_DREEMCHEST
using namespace Platform;
using namespace Renderer;
// Declare a skybox unit cube
f32 s_cubeVertices[] =
{
-1.0f, 1.0f, -1.0f,
-1.0f, -1.0f, -1.0f,
1.0f, -1.0f, -1.0f,
1.0f, -1.0f, -1.0f,
1.0f, 1.0f, -1.0f,
-1.0f, 1.0f, -1.0f,
-1.0f, -1.0f, 1.0f,
-1.0f, -1.0f, -1.0f,
-1.0f, 1.0f, -1.0f,
-1.0f, 1.0f, -1.0f,
-1.0f, 1.0f, 1.0f,
-1.0f, -1.0f, 1.0f,
1.0f, -1.0f, -1.0f,
1.0f, -1.0f, 1.0f,
1.0f, 1.0f, 1.0f,
1.0f, 1.0f, 1.0f,
1.0f, 1.0f, -1.0f,
1.0f, -1.0f, -1.0f,
-1.0f, -1.0f, 1.0f,
-1.0f, 1.0f, 1.0f,
1.0f, 1.0f, 1.0f,
1.0f, 1.0f, 1.0f,
1.0f, -1.0f, 1.0f,
-1.0f, -1.0f, 1.0f,
-1.0f, 1.0f, -1.0f,
1.0f, 1.0f, -1.0f,
1.0f, 1.0f, 1.0f,
1.0f, 1.0f, 1.0f,
-1.0f, 1.0f, 1.0f,
-1.0f, 1.0f, -1.0f,
-1.0f, -1.0f, -1.0f,
-1.0f, -1.0f, 1.0f,
1.0f, -1.0f, -1.0f,
1.0f, -1.0f, -1.0f,
-1.0f, -1.0f, 1.0f,
1.0f, -1.0f, 1.0f
};
static String s_vertexShader =
"cbuffer Projection projection : 0; \n"
"cbuffer Camera camera : 1; \n"
"varying vec3 v_texCoord; \n"
"void main() \n"
"{ \n"
" gl_Position = projection.transform \n"
" * camera.rotation \n"
" * gl_Vertex; \n"
" v_texCoord = gl_Vertex.xyz; \n"
"} \n"
;
static String s_fragmentShader =
"uniform samplerCube Texture0; \n"
"varying vec3 v_texCoord; \n"
"void main() \n"
"{ \n"
" gl_FragColor = textureCube(Texture0, v_texCoord); \n"
"} \n"
;
// Application delegate is now subclassed from a Examples::ViewerApplicationDelegate to add camera and arcball functionality.
class Cubemaps : public Examples::ViewerApplicationDelegate
{
StateBlock8 m_renderStates;
virtual void handleLaunched(Application* application) NIMBLE_OVERRIDE
{
Logger::setStandardLogger();
if (!initialize(800 / 4, 600 / 4))
{
application->quit(-1);
}
// Create a cube vertex buffer and bind it to a render state block
{
InputLayout inputLayout = m_renderingContext->requestInputLayout(VertexFormat::Position);
VertexBuffer_ vertexBuffer = m_renderingContext->requestVertexBuffer(s_cubeVertices, sizeof(s_cubeVertices));
m_renderStates.bindVertexBuffer(vertexBuffer);
m_renderStates.bindInputLayout(inputLayout);
}
// Load a cubemap texture and bind it to a sampler #0
{
const String envName = "MonValley_DirtRoad";
const String files[] =
{
"Assets/Textures/Environments/" + envName + "/back.tga"
, "Assets/Textures/Environments/" + envName + "/front.tga"
, "Assets/Textures/Environments/" + envName + "/top.tga"
, "Assets/Textures/Environments/" + envName + "/bottom.tga"
, "Assets/Textures/Environments/" + envName + "/right.tga"
, "Assets/Textures/Environments/" + envName + "/left.tga"
};
Examples::Surface pixels;
Examples::Image faces[6];
for (s32 i = 0; i < 6; i++)
{
faces[i] = Examples::tgaFromFile(files[i]);
pixels.insert(pixels.end(), faces[i].pixels.begin(), faces[i].pixels.end());
}
Texture_ env = m_renderingContext->requestTextureCube(&pixels[0], faces[0].width, 1, faces[0].format);
m_renderStates.bindTexture(env, 0);
}
// Create a program that consists from a vertex and fragment shaders.
Program program = m_renderingContext->requestProgram(s_vertexShader, s_fragmentShader);
m_renderStates.bindProgram(program);
}
// This method is declared inside the Examples::ViewerApplicationDelegate.
virtual void handleRenderFrame(const RenderFrame& frame, RenderCommandBuffer& commands) NIMBLE_OVERRIDE
{
commands.clear(Rgba(0.3f, 0.3f, 0.3f), ClearAll);
commands.drawPrimitives(0, PrimTriangles, 0, 36, m_renderStates);
}
};
dcDeclareApplication(new Cubemaps)
<commit_msg>Refactored: cube map example<commit_after>/**************************************************************************
The MIT License (MIT)
Copyright (c) 2015 Dmitry Sovetov
https://github.com/dmsovetov
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 <Dreemchest.h>
#include "../Examples.h"
DC_USE_DREEMCHEST
using namespace Platform;
using namespace Renderer;
static String s_vertexShader =
"cbuffer Projection projection : 0; \n"
"cbuffer Camera camera : 1; \n"
"varying vec3 v_texCoord; \n"
"void main() \n"
"{ \n"
" gl_Position = projection.transform \n"
" * camera.rotation \n"
" * gl_Vertex; \n"
" v_texCoord = gl_Vertex.xyz; \n"
"} \n"
;
static String s_fragmentShader =
"uniform samplerCube Texture0; \n"
"varying vec3 v_texCoord; \n"
"void main() \n"
"{ \n"
" gl_FragColor = textureCube(Texture0, v_texCoord); \n"
"} \n"
;
// Application delegate is now subclassed from a Examples::ViewerApplicationDelegate to add camera and arcball functionality.
class Cubemaps : public Examples::ViewerApplicationDelegate
{
StateBlock8 m_renderStates;
virtual void handleLaunched(Application* application) NIMBLE_OVERRIDE
{
Logger::setStandardLogger();
if (!initialize(800, 600))
{
application->quit(-1);
}
// Create a cube vertex buffer and bind it to a render state block
{
InputLayout inputLayout = m_renderingContext->requestInputLayout(VertexFormat::Position);
VertexBuffer_ vertexBuffer = m_renderingContext->requestVertexBuffer(Examples::UnitCube, sizeof(Examples::UnitCube));
m_renderStates.bindVertexBuffer(vertexBuffer);
m_renderStates.bindInputLayout(inputLayout);
}
// Load a cubemap texture and bind it to a sampler #0
{
const String envName = "Sierra_Madre_B";
const String files[] =
{
"Assets/Textures/Environments/" + envName + "/posx.tga"
, "Assets/Textures/Environments/" + envName + "/negx.tga"
, "Assets/Textures/Environments/" + envName + "/posy.tga"
, "Assets/Textures/Environments/" + envName + "/negy.tga"
, "Assets/Textures/Environments/" + envName + "/posz.tga"
, "Assets/Textures/Environments/" + envName + "/negz.tga"
};
Examples::Surface pixels;
Examples::Image faces[6];
for (s32 i = 0; i < 6; i++)
{
faces[i] = Examples::tgaFromFile(files[i]);
pixels.insert(pixels.end(), faces[i].pixels.begin(), faces[i].pixels.end());
}
Texture_ env = m_renderingContext->requestTextureCube(&pixels[0], faces[0].width, 1, faces[0].format);
m_renderStates.bindTexture(env, 0);
}
// Create a program that consists from a vertex and fragment shaders.
Program program = m_renderingContext->requestProgram(s_vertexShader, s_fragmentShader);
m_renderStates.bindProgram(program);
}
// This method is declared inside the Examples::ViewerApplicationDelegate.
virtual void handleRenderFrame(const RenderFrame& frame, RenderCommandBuffer& commands) NIMBLE_OVERRIDE
{
commands.clear(Rgba(0.3f, 0.3f, 0.3f), ClearAll);
commands.drawPrimitives(0, PrimTriangles, 0, 36, m_renderStates);
}
};
dcDeclareApplication(new Cubemaps)
<|endoftext|>
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.