text
stringlengths 54
60.6k
|
|---|
<commit_before>#include "ExecutionEngine.h"
#include <chrono>
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wunused-parameter"
#include <llvm/IR/LLVMContext.h>
#include <llvm/IR/Module.h>
#include <llvm/ADT/Triple.h>
#include <llvm/ExecutionEngine/ExecutionEngine.h>
#include <llvm/ExecutionEngine/SectionMemoryManager.h>
#include <llvm/ExecutionEngine/GenericValue.h>
#include <llvm/ExecutionEngine/MCJIT.h>
#include <llvm/Support/TargetSelect.h>
#include <llvm/Support/Signals.h>
#include <llvm/Support/PrettyStackTrace.h>
#include <llvm/Support/Host.h>
#pragma GCC diagnostic pop
#include "Runtime.h"
#include "Memory.h"
#include "Stack.h"
#include "Type.h"
#include "Compiler.h"
#include "Cache.h"
namespace dev
{
namespace eth
{
namespace jit
{
ReturnCode ExecutionEngine::run(bytes const& _code, RuntimeData* _data, Env* _env)
{
std::string key{reinterpret_cast<char const*>(_code.data()), _code.size()};
/*if (auto cachedExec = Cache::findExec(key))
{
return run(*cachedExec, _data, _env);
}*/
auto module = Compiler({}).compile(_code);
//module->dump();
return run(std::move(module), _data, _env, _code);
}
namespace
{
ReturnCode runEntryFunc(ExecBundle const& _exec, Runtime* _runtime)
{
// That function uses long jumps to handle "execeptions".
// Do not create any non-POD objects here
typedef ReturnCode(*EntryFuncPtr)(Runtime*);
auto entryFuncPtr = (EntryFuncPtr)_exec.engine->getFunctionAddress(_exec.mainFuncName);
//std::cerr << _exec.mainFuncName << " F: " << entryFuncPtr << "\n";
ReturnCode returnCode{};
//std::cerr << _exec.mainFuncName << " +S: " << &returnCode << "\n";
auto sj = setjmp(_runtime->getJmpBuf());
if (sj == 0)
returnCode = entryFuncPtr(_runtime);
else
returnCode = static_cast<ReturnCode>(sj);
//std::cerr << _exec.mainFuncName << " -S: " << &returnCode << "\n";
return returnCode;
}
}
ReturnCode ExecutionEngine::run(std::unique_ptr<llvm::Module> _module, RuntimeData* _data, Env* _env, bytes const& _code)
{
// TODO: Use it in evmcc
//llvm::sys::PrintStackTraceOnErrorSignal();
//static const auto program = "EVM JIT";
//llvm::PrettyStackTraceProgram X(1, &program);
static std::unique_ptr<llvm::ExecutionEngine> ee; // TODO: Use Managed Objects from LLVM?
typedef ReturnCode(*EntryFuncPtr)(Runtime*);
EntryFuncPtr entryFuncPtr{};
ExecBundle exec;
exec.mainFuncName = _module->getModuleIdentifier();
if (!ee)
{
llvm::InitializeNativeTarget();
llvm::InitializeNativeTargetAsmPrinter();
llvm::EngineBuilder builder(_module.get());
builder.setEngineKind(llvm::EngineKind::JIT);
builder.setUseMCJIT(true);
std::unique_ptr<llvm::SectionMemoryManager> memoryManager(new llvm::SectionMemoryManager);
builder.setMCJITMemoryManager(memoryManager.get());
builder.setOptLevel(llvm::CodeGenOpt::None);
auto triple = llvm::Triple(llvm::sys::getProcessTriple());
if (triple.getOS() == llvm::Triple::OSType::Win32)
triple.setObjectFormat(llvm::Triple::ObjectFormatType::ELF); // MCJIT does not support COFF format
_module->setTargetTriple(triple.str());
ee.reset(builder.create());
if (!ee)
return ReturnCode::LLVMConfigError;
_module.release(); // Successfully created llvm::ExecutionEngine takes ownership of the module
memoryManager.release(); // and memory manager
//ee->setObjectCache(Cache::getObjectCache());
}
else
{
if (entryFuncPtr = (EntryFuncPtr)ee->getFunctionAddress(_module->getModuleIdentifier()))
{
entryFuncPtr = nullptr;
}
else
{
ee->addModule(_module.get());
//std::cerr << _module->getModuleIdentifier() << "\n";
_module.release();
}
}
assert(ee);
//ExecBundle exec;
//exec.engine.reset(builder.create());
//if (!exec.engine)
// return ReturnCode::LLVMConfigError;
exec.engine = ee.get();
// TODO: Finalization not needed when llvm::ExecutionEngine::getFunctionAddress used
//auto finalizationStartTime = std::chrono::high_resolution_clock::now();
//exec.engine->finalizeObject();
//auto finalizationEndTime = std::chrono::high_resolution_clock::now();
//clog(JIT) << " + " << std::chrono::duration_cast<std::chrono::milliseconds>(finalizationEndTime - finalizationStartTime).count();
auto executionStartTime = std::chrono::high_resolution_clock::now();
std::string key{reinterpret_cast<char const*>(_code.data()), _code.size()};
//auto& cachedExec = Cache::registerExec(key, std::move(exec));
Runtime runtime(_data, _env);
auto returnCode = runEntryFunc(exec, &runtime);
if (returnCode == ReturnCode::Return)
this->returnData = runtime.getReturnData();
auto executionEndTime = std::chrono::high_resolution_clock::now();
clog(JIT) << " + " << std::chrono::duration_cast<std::chrono::milliseconds>(executionEndTime - executionStartTime).count() << " ms ";
//clog(JIT) << "Max stack size: " << Stack::maxStackSize;
clog(JIT) << "\n";
return returnCode;
}
}
}
}
<commit_msg>Clean up ExecutionEngine<commit_after>#include "ExecutionEngine.h"
#include <chrono>
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wunused-parameter"
#include <llvm/IR/LLVMContext.h>
#include <llvm/IR/Module.h>
#include <llvm/ADT/Triple.h>
#include <llvm/ExecutionEngine/ExecutionEngine.h>
#include <llvm/ExecutionEngine/SectionMemoryManager.h>
#include <llvm/ExecutionEngine/GenericValue.h>
#include <llvm/ExecutionEngine/MCJIT.h>
#include <llvm/Support/TargetSelect.h>
#include <llvm/Support/Signals.h>
#include <llvm/Support/PrettyStackTrace.h>
#include <llvm/Support/Host.h>
#pragma GCC diagnostic pop
#include "Runtime.h"
#include "Memory.h"
#include "Stack.h"
#include "Type.h"
#include "Compiler.h"
#include "Cache.h"
namespace dev
{
namespace eth
{
namespace jit
{
ReturnCode ExecutionEngine::run(bytes const& _code, RuntimeData* _data, Env* _env)
{
std::string key{reinterpret_cast<char const*>(_code.data()), _code.size()};
/*if (auto cachedExec = Cache::findExec(key))
{
return run(*cachedExec, _data, _env);
}*/
auto module = Compiler({}).compile(_code);
//module->dump();
return run(std::move(module), _data, _env, _code);
}
namespace
{
typedef ReturnCode(*EntryFuncPtr)(Runtime*);
ReturnCode runEntryFunc(EntryFuncPtr _mainFunc, Runtime* _runtime)
{
// That function uses long jumps to handle "execeptions".
// Do not create any non-POD objects here
ReturnCode returnCode{};
auto sj = setjmp(_runtime->getJmpBuf());
if (sj == 0)
returnCode = _mainFunc(_runtime);
else
returnCode = static_cast<ReturnCode>(sj);
return returnCode;
}
}
ReturnCode ExecutionEngine::run(std::unique_ptr<llvm::Module> _module, RuntimeData* _data, Env* _env, bytes const& _code)
{
// TODO: Use it in evmcc
//llvm::sys::PrintStackTraceOnErrorSignal();
//static const auto program = "EVM JIT";
//llvm::PrettyStackTraceProgram X(1, &program);
static std::unique_ptr<llvm::ExecutionEngine> ee; // TODO: Use Managed Objects from LLVM?
typedef ReturnCode(*EntryFuncPtr)(Runtime*);
EntryFuncPtr entryFuncPtr{};
auto&& mainFuncName = _module->getModuleIdentifier();
if (!ee)
{
llvm::InitializeNativeTarget();
llvm::InitializeNativeTargetAsmPrinter();
llvm::EngineBuilder builder(_module.get());
builder.setEngineKind(llvm::EngineKind::JIT);
builder.setUseMCJIT(true);
std::unique_ptr<llvm::SectionMemoryManager> memoryManager(new llvm::SectionMemoryManager);
builder.setMCJITMemoryManager(memoryManager.get());
builder.setOptLevel(llvm::CodeGenOpt::None);
auto triple = llvm::Triple(llvm::sys::getProcessTriple());
if (triple.getOS() == llvm::Triple::OSType::Win32)
triple.setObjectFormat(llvm::Triple::ObjectFormatType::ELF); // MCJIT does not support COFF format
_module->setTargetTriple(triple.str());
ee.reset(builder.create());
if (!ee)
return ReturnCode::LLVMConfigError;
_module.release(); // Successfully created llvm::ExecutionEngine takes ownership of the module
memoryManager.release(); // and memory manager
//ee->setObjectCache(Cache::getObjectCache());
}
else
{
if (entryFuncPtr = (EntryFuncPtr)ee->getFunctionAddress(_module->getModuleIdentifier()))
{
entryFuncPtr = nullptr;
}
else
{
ee->addModule(_module.get());
//std::cerr << _module->getModuleIdentifier() << "\n";
_module.release();
}
}
assert(ee);
//ExecBundle exec;
//exec.engine.reset(builder.create());
//if (!exec.engine)
// return ReturnCode::LLVMConfigError;
// TODO: Finalization not needed when llvm::ExecutionEngine::getFunctionAddress used
//auto finalizationStartTime = std::chrono::high_resolution_clock::now();
//exec.engine->finalizeObject();
//auto finalizationEndTime = std::chrono::high_resolution_clock::now();
//clog(JIT) << " + " << std::chrono::duration_cast<std::chrono::milliseconds>(finalizationEndTime - finalizationStartTime).count();
auto executionStartTime = std::chrono::high_resolution_clock::now();
std::string key{reinterpret_cast<char const*>(_code.data()), _code.size()};
//auto& cachedExec = Cache::registerExec(key, std::move(exec));
Runtime runtime(_data, _env);
auto mainFunc = (EntryFuncPtr)ee->getFunctionAddress(mainFuncName);
auto returnCode = runEntryFunc(mainFunc, &runtime);
if (returnCode == ReturnCode::Return)
this->returnData = runtime.getReturnData();
auto executionEndTime = std::chrono::high_resolution_clock::now();
clog(JIT) << " + " << std::chrono::duration_cast<std::chrono::milliseconds>(executionEndTime - executionStartTime).count() << " ms ";
//clog(JIT) << "Max stack size: " << Stack::maxStackSize;
clog(JIT) << "\n";
return returnCode;
}
}
}
}
<|endoftext|>
|
<commit_before>#include "replayState.h"
#include <deque>
#include <boost/bind.hpp>
#include <boost/thread.hpp>
#include "libwatcher/message.h"
#include "serverConnection.h"
#include "Assert.h"
#include "database.h"
#include "watcherd.h"
using namespace util;
using namespace watcher;
using namespace watcher::event;
//< default value for number of events to prefetch from the database
const unsigned int DEFAULT_BUFFER_SIZE = 10U; /* db rows */
const unsigned int DEFAULT_STEP = 250U /* ms */;
/** Internal structure used for implementing the class. Used to avoid
* dependencies for the user of the class. These would normally be private
* members of ReplayState.
*/
struct ReplayState::impl {
boost::weak_ptr<ServerConnection> conn;
std::deque<MessagePtr> events;
boost::asio::deadline_timer timer;
Timestamp ts; // the current effective time
Timestamp last_event; // timestamp of last event retrieved from db
float speed; //< playback speed
unsigned int bufsiz; //< number of database rows to prefetch
Timestamp step;
enum run_state { paused, running } state;
/*
* Lock used for event queue. This is required due to the seek() member
* function, which can be called from a different thread.
*/
boost::mutex lock;
impl(ServerConnectionPtr& ptr) :
conn(ptr), timer(ptr->io_service()), ts(0), last_event(0), bufsiz(DEFAULT_BUFFER_SIZE),
step(DEFAULT_STEP), state(paused)
{
TRACE_ENTER();
TRACE_EXIT();
}
};
ReplayState::ReplayState(ServerConnectionPtr ptr, Timestamp t, float playback_speed) :
impl_(new impl(ptr))
{
TRACE_ENTER();
Assert<Bad_arg>(t >= 0);
impl_->ts = t;
impl_->last_event = t;
speed(playback_speed);
TRACE_EXIT();
}
Timestamp ReplayState::tell() const
{
TRACE_ENTER();
TRACE_EXIT_RET(impl_->ts);
return impl_->ts;
}
ReplayState& ReplayState::pause()
{
TRACE_ENTER();
LOG_DEBUG("cancelling timer");
impl_->timer.cancel();
impl_->state = impl::paused;
TRACE_EXIT();
return *this;
}
ReplayState& ReplayState::seek(Timestamp t)
{
TRACE_ENTER();
impl::run_state oldstate;
{
boost::mutex::scoped_lock L(impl_->lock);
oldstate = impl_->state;
pause();
impl_->events.clear();
impl_->ts = t;
if (t == -1)
impl_->last_event = std::numeric_limits<Timestamp>::max();
else
impl_->last_event = t;
}
if (oldstate == impl::running)
run();
TRACE_EXIT();
return *this;
}
ReplayState& ReplayState::speed(float f)
{
TRACE_ENTER();
Assert<Bad_arg>(f != 0);
/* If speed changes direction, need to clear the event list.
* Check for sign change by noting that positive*negative==negative
*/
if (impl_->speed * f < 0) {
impl::run_state oldstate;
{
boost::mutex::scoped_lock L(impl_->lock);
oldstate = impl_->state;
pause();
impl_->events.clear();
/*
* Avoid setting .last_event when SpeedMessage is received
* prior to the first StartMessage.
*/
if (impl_->ts != 0 && impl_->ts != -1)
impl_->last_event = impl_->ts;
impl_->speed = f;
}
if (oldstate == impl::running)
run();
} else
impl_->speed = f;
LOG_DEBUG("ts=" << impl_->ts << " last_event=" << impl_->last_event);
TRACE_EXIT();
return *this;
}
ReplayState& ReplayState::buffer_size(unsigned int n)
{
TRACE_ENTER();
Assert<Bad_arg>(n != 0);
impl_->bufsiz = n;
TRACE_EXIT();
return *this;
}
ReplayState& ReplayState::time_step(unsigned int n)
{
TRACE_ENTER();
Assert<Bad_arg>(n != 0);
impl_->step = n;
TRACE_EXIT();
return *this;
}
/* function object for accepting events output from Database::getEvents() */
struct event_output {
std::deque<MessagePtr>& q;
event_output(std::deque<MessagePtr>& qq) : q(qq) {}
void operator() (MessagePtr m) { q.push_back(m); }
};
/** Schedule an asynchronous task to replay events from the database to a GUI
* client. If the local cache of upcoming events is empty, prefetch a block of
* events from the database.
*
* The code is written such that it will work when playing events forward or in
* reverse.
*/
void ReplayState::run()
{
TRACE_ENTER();
boost::mutex::scoped_lock L(impl_->lock);
if (impl_->events.empty()) {
// queue is empty, pre-fetch more items from the DB
boost::function<void(MessagePtr)> cb(event_output(impl_->events));
LOG_DEBUG("fetching events " << (impl_->speed > 0 ? "> " : "< ") << impl_->last_event);
get_db_handle().getEvents(cb,
impl_->last_event,
(impl_->speed >= 0) ? Database::forward : Database::reverse,
impl_->bufsiz);
if (!impl_->events.empty()) {
/* When starting to replay, assume that time T=0 is the time of the
* first event in the stream.
* T= -1 is EOF.
* Convert to timestamp of first item in the returned events.
*
* When playing in reverse, the first item in the list is the last event in the database.
*/
if (impl_->ts == 0 || impl_->ts == -1)
impl_->ts = impl_->events.front()->timestamp;
// save timestamp of last event retrieved to avoid duplication
impl_->last_event = impl_->events.back()->timestamp;
}
}
if (! impl_->events.empty()) {
// time until next event
Timestamp delta = impl_->events.front()->timestamp - impl_->ts;
LOG_DEBUG("Next event in " << delta << " ms");
// update our notion of the current time after the timer expires
impl_->ts = impl_->events.front()->timestamp;
/* Adjust for playback speed. Note that when playing events in reverse, both speed
* delta will be negative, which will turn delta into a positive value for the
* async_wait() call, which is exactly what is required. */
delta /= impl_->speed;
impl_->timer.expires_from_now(boost::posix_time::millisec(delta));
impl_->timer.async_wait(boost::bind(&ReplayState::timer_handler, shared_from_this(), boost::asio::placeholders::error));
impl_->state = impl::running;
} else {
/*
* FIXME what should happen when the end of the event stream is reached?
* One option would be to convert to live stream at this point.
*/
impl_->state = impl::paused;
}
TRACE_EXIT();
}
/** Replay events to a GUI client when a timer expires.
*
* The run() member function is reponsible for prefetching events from the
* database and storing them in the class object. When a timer expires, run
* through the locally stored events and send those that occurred within the
* last time slice. The task is then rescheduled when the next most recent
* event needs to be transmitted.
*/
void ReplayState::timer_handler(const boost::system::error_code& ec)
{
TRACE_ENTER();
if (ec == boost::asio::error::operation_aborted)
LOG_DEBUG("timer was cancelled");
else if (impl_->state == impl::paused) {
LOG_DEBUG("timer expired but state is paused!");
} else {
std::vector<MessagePtr> msgs;
{
boost::mutex::scoped_lock L(impl_->lock);
while (! impl_->events.empty()) {
MessagePtr m = impl_->events.front();
/* Replay all events in the current time step. Use the absolute value
* of the difference in order for forward and reverse replay to work
* properly. */
if (abs(m->timestamp - impl_->ts) >= impl_->step)
break;
msgs.push_back(m);
impl_->events.pop_front();
}
}
ServerConnectionPtr srv = impl_->conn.lock();
if (srv) { /* connection is still alive */
srv->sendMessage(msgs);
run(); // reschedule this task
}
}
TRACE_EXIT();
}
/* This is required to be defined, otherwise a the default dtor will cause a
* compiler error due to use of scoped_ptr with an incomplete type.
*/
ReplayState::~ReplayState()
{
TRACE_ENTER();
TRACE_EXIT();
}
float ReplayState::speed() const
{
return impl_->speed;
}
<commit_msg>add debug message when last row of db is fetched<commit_after>#include "replayState.h"
#include <deque>
#include <boost/bind.hpp>
#include <boost/thread.hpp>
#include "libwatcher/message.h"
#include "serverConnection.h"
#include "Assert.h"
#include "database.h"
#include "watcherd.h"
using namespace util;
using namespace watcher;
using namespace watcher::event;
//< default value for number of events to prefetch from the database
const unsigned int DEFAULT_BUFFER_SIZE = 10U; /* db rows */
const unsigned int DEFAULT_STEP = 250U /* ms */;
/** Internal structure used for implementing the class. Used to avoid
* dependencies for the user of the class. These would normally be private
* members of ReplayState.
*/
struct ReplayState::impl {
boost::weak_ptr<ServerConnection> conn;
std::deque<MessagePtr> events;
boost::asio::deadline_timer timer;
Timestamp ts; // the current effective time
Timestamp last_event; // timestamp of last event retrieved from db
float speed; //< playback speed
unsigned int bufsiz; //< number of database rows to prefetch
Timestamp step;
enum run_state { paused, running } state;
/*
* Lock used for event queue. This is required due to the seek() member
* function, which can be called from a different thread.
*/
boost::mutex lock;
impl(ServerConnectionPtr& ptr) :
conn(ptr), timer(ptr->io_service()), ts(0), last_event(0), bufsiz(DEFAULT_BUFFER_SIZE),
step(DEFAULT_STEP), state(paused)
{
TRACE_ENTER();
TRACE_EXIT();
}
};
ReplayState::ReplayState(ServerConnectionPtr ptr, Timestamp t, float playback_speed) :
impl_(new impl(ptr))
{
TRACE_ENTER();
Assert<Bad_arg>(t >= 0);
impl_->ts = t;
impl_->last_event = t;
speed(playback_speed);
TRACE_EXIT();
}
Timestamp ReplayState::tell() const
{
TRACE_ENTER();
TRACE_EXIT_RET(impl_->ts);
return impl_->ts;
}
ReplayState& ReplayState::pause()
{
TRACE_ENTER();
LOG_DEBUG("cancelling timer");
impl_->timer.cancel();
impl_->state = impl::paused;
TRACE_EXIT();
return *this;
}
ReplayState& ReplayState::seek(Timestamp t)
{
TRACE_ENTER();
impl::run_state oldstate;
{
boost::mutex::scoped_lock L(impl_->lock);
oldstate = impl_->state;
pause();
impl_->events.clear();
impl_->ts = t;
if (t == -1)
impl_->last_event = std::numeric_limits<Timestamp>::max();
else
impl_->last_event = t;
}
if (oldstate == impl::running)
run();
TRACE_EXIT();
return *this;
}
ReplayState& ReplayState::speed(float f)
{
TRACE_ENTER();
Assert<Bad_arg>(f != 0);
/* If speed changes direction, need to clear the event list.
* Check for sign change by noting that positive*negative==negative
*/
if (impl_->speed * f < 0) {
impl::run_state oldstate;
{
boost::mutex::scoped_lock L(impl_->lock);
oldstate = impl_->state;
pause();
impl_->events.clear();
/*
* Avoid setting .last_event when SpeedMessage is received
* prior to the first StartMessage.
*/
if (impl_->ts != 0 && impl_->ts != -1)
impl_->last_event = impl_->ts;
impl_->speed = f;
}
if (oldstate == impl::running)
run();
} else
impl_->speed = f;
LOG_DEBUG("ts=" << impl_->ts << " last_event=" << impl_->last_event);
TRACE_EXIT();
return *this;
}
ReplayState& ReplayState::buffer_size(unsigned int n)
{
TRACE_ENTER();
Assert<Bad_arg>(n != 0);
impl_->bufsiz = n;
TRACE_EXIT();
return *this;
}
ReplayState& ReplayState::time_step(unsigned int n)
{
TRACE_ENTER();
Assert<Bad_arg>(n != 0);
impl_->step = n;
TRACE_EXIT();
return *this;
}
/* function object for accepting events output from Database::getEvents() */
struct event_output {
std::deque<MessagePtr>& q;
event_output(std::deque<MessagePtr>& qq) : q(qq) {}
void operator() (MessagePtr m) { q.push_back(m); }
};
/** Schedule an asynchronous task to replay events from the database to a GUI
* client. If the local cache of upcoming events is empty, prefetch a block of
* events from the database.
*
* The code is written such that it will work when playing events forward or in
* reverse.
*/
void ReplayState::run()
{
TRACE_ENTER();
boost::mutex::scoped_lock L(impl_->lock);
if (impl_->events.empty()) {
// queue is empty, pre-fetch more items from the DB
boost::function<void(MessagePtr)> cb(event_output(impl_->events));
LOG_DEBUG("fetching events " << (impl_->speed > 0 ? "> " : "< ") << impl_->last_event);
get_db_handle().getEvents(cb,
impl_->last_event,
(impl_->speed >= 0) ? Database::forward : Database::reverse,
impl_->bufsiz);
if (!impl_->events.empty()) {
/* When starting to replay, assume that time T=0 is the time of the
* first event in the stream.
* T= -1 is EOF.
* Convert to timestamp of first item in the returned events.
*
* When playing in reverse, the first item in the list is the last event in the database.
*/
if (impl_->ts == 0 || impl_->ts == -1)
impl_->ts = impl_->events.front()->timestamp;
// save timestamp of last event retrieved to avoid duplication
impl_->last_event = impl_->events.back()->timestamp;
}
}
if (! impl_->events.empty()) {
// time until next event
Timestamp delta = impl_->events.front()->timestamp - impl_->ts;
LOG_DEBUG("Next event in " << delta << " ms");
// update our notion of the current time after the timer expires
impl_->ts = impl_->events.front()->timestamp;
/* Adjust for playback speed. Note that when playing events in reverse, both speed
* delta will be negative, which will turn delta into a positive value for the
* async_wait() call, which is exactly what is required. */
delta /= impl_->speed;
impl_->timer.expires_from_now(boost::posix_time::millisec(delta));
impl_->timer.async_wait(boost::bind(&ReplayState::timer_handler, shared_from_this(), boost::asio::placeholders::error));
impl_->state = impl::running;
} else {
/*
* FIXME what should happen when the end of the event stream is reached?
* One option would be to convert to live stream at this point.
*/
LOG_DEBUG("reached end of database, pausing playback");
impl_->state = impl::paused;
}
TRACE_EXIT();
}
/** Replay events to a GUI client when a timer expires.
*
* The run() member function is reponsible for prefetching events from the
* database and storing them in the class object. When a timer expires, run
* through the locally stored events and send those that occurred within the
* last time slice. The task is then rescheduled when the next most recent
* event needs to be transmitted.
*/
void ReplayState::timer_handler(const boost::system::error_code& ec)
{
TRACE_ENTER();
if (ec == boost::asio::error::operation_aborted)
LOG_DEBUG("timer was cancelled");
else if (impl_->state == impl::paused) {
LOG_DEBUG("timer expired but state is paused!");
} else {
std::vector<MessagePtr> msgs;
{
boost::mutex::scoped_lock L(impl_->lock);
while (! impl_->events.empty()) {
MessagePtr m = impl_->events.front();
/* Replay all events in the current time step. Use the absolute value
* of the difference in order for forward and reverse replay to work
* properly. */
if (abs(m->timestamp - impl_->ts) >= impl_->step)
break;
msgs.push_back(m);
impl_->events.pop_front();
}
}
ServerConnectionPtr srv = impl_->conn.lock();
if (srv) { /* connection is still alive */
srv->sendMessage(msgs);
run(); // reschedule this task
}
}
TRACE_EXIT();
}
/* This is required to be defined, otherwise a the default dtor will cause a
* compiler error due to use of scoped_ptr with an incomplete type.
*/
ReplayState::~ReplayState()
{
TRACE_ENTER();
TRACE_EXIT();
}
float ReplayState::speed() const
{
return impl_->speed;
}
<|endoftext|>
|
<commit_before>//-----------------------------------------------------------------------bl-
//--------------------------------------------------------------------------
//
// QUESO - a library to support the Quantification of Uncertainty
// for Estimation, Simulation and Optimization
//
// Copyright (C) 2008-2015 The PECOS Development Team
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the Version 2.1 GNU Lesser General
// Public License 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. 51 Franklin Street, Fifth Floor,
// Boston, MA 02110-1301 USA
//
//-----------------------------------------------------------------------el-
#include <queso/UniformJointPdf.h>
#include <queso/GslVector.h>
#include <queso/GslMatrix.h>
namespace QUESO {
// Constructor -------------------------------------
template<class V,class M>
UniformJointPdf<V,M>::UniformJointPdf(
const char* prefix,
const VectorSet<V,M>& domainSet)
:
BaseJointPdf<V,M>(((std::string)(prefix)+"uni").c_str(),
domainSet)
{
if ((m_env.subDisplayFile()) && (m_env.displayVerbosity() >= 54)) {
*m_env.subDisplayFile() << "Entering UniformJointPdf<V,M>::constructor()"
<< ": prefix = " << m_prefix
<< std::endl;
}
if ((m_env.subDisplayFile()) && (m_env.displayVerbosity() >= 54)) {
*m_env.subDisplayFile() << "Leaving UniformJointPdf<V,M>::constructor()"
<< ": prefix = " << m_prefix
<< std::endl;
}
}
// Destructor --------------------------------------
template<class V,class M>
UniformJointPdf<V,M>::~UniformJointPdf()
{
}
// Math methods-------------------------------------
template<class V, class M>
double
UniformJointPdf<V,M>::actualValue(
const V& domainVector,
const V* domainDirection,
V* gradVector,
M* hessianMatrix,
V* hessianEffect) const
{
UQ_FATAL_TEST_MACRO(domainVector.sizeLocal() != this->m_domainSet.vectorSpace().dimLocal(),
m_env.worldRank(),
"UniformJointPdf<V,M>::actualValue()",
"invalid input");
if (gradVector ) *gradVector = m_domainSet.vectorSpace().zeroVector();
if (hessianMatrix) *hessianMatrix *= 0.;
if (hessianEffect) *hessianEffect = m_domainSet.vectorSpace().zeroVector();
if (domainDirection) {}; // just to remove compiler warning
double volume = m_domainSet.volume();
if (((boost::math::isnan)(volume)) ||
(volume == -INFINITY ) ||
(volume == INFINITY ) ||
(volume <= 0. ) ||
(m_normalizationStyle != 0 )) {
volume = 1.;
}
return 1./volume; // No need to multiply by exp(m_logOfNormalizationFactor) [PDF-04]
}
//--------------------------------------------------
template<class V, class M>
double
UniformJointPdf<V,M>::lnValue(
const V& domainVector,
const V* domainDirection,
V* gradVector,
M* hessianMatrix,
V* hessianEffect) const
{
if (gradVector ) *gradVector = m_domainSet.vectorSpace().zeroVector();
if (hessianMatrix) *hessianMatrix *= 0.;
if (hessianEffect) *hessianEffect = m_domainSet.vectorSpace().zeroVector();
if (domainVector[0]) {}; // just to remove compiler warning
if (domainDirection) {}; // just to remove compiler warning
double volume = m_domainSet.volume();
if (((boost::math::isnan)(volume)) ||
(volume == -INFINITY ) ||
(volume == INFINITY ) ||
(volume <= 0. ) ||
(m_normalizationStyle != 0 )) {
volume = 1.;
}
return log(volume); // No need to add m_logOfNormalizationFactor [PDF-04]
}
//--------------------------------------------------
template<class V, class M>
double
UniformJointPdf<V,M>::computeLogOfNormalizationFactor(unsigned int numSamples, bool updateFactorInternally) const
{
double value = 0.;
if ((m_env.subDisplayFile()) && (m_env.displayVerbosity() >= 2)) {
*m_env.subDisplayFile() << "Entering UniformJointPdf<V,M>::computeLogOfNormalizationFactor()"
<< std::endl;
}
value = BaseJointPdf<V,M>::commonComputeLogOfNormalizationFactor(numSamples, updateFactorInternally);
if ((m_env.subDisplayFile()) && (m_env.displayVerbosity() >= 2)) {
*m_env.subDisplayFile() << "Leaving UniformJointPdf<V,M>::computeLogOfNormalizationFactor()"
<< ", m_logOfNormalizationFactor = " << m_logOfNormalizationFactor
<< std::endl;
}
return value;
}
} // End namespace QUESO
template class QUESO::UniformJointPdf<QUESO::GslVector, QUESO::GslMatrix>;
<commit_msg>Fix sign in log uniform pdf<commit_after>//-----------------------------------------------------------------------bl-
//--------------------------------------------------------------------------
//
// QUESO - a library to support the Quantification of Uncertainty
// for Estimation, Simulation and Optimization
//
// Copyright (C) 2008-2015 The PECOS Development Team
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the Version 2.1 GNU Lesser General
// Public License 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. 51 Franklin Street, Fifth Floor,
// Boston, MA 02110-1301 USA
//
//-----------------------------------------------------------------------el-
#include <queso/UniformJointPdf.h>
#include <queso/GslVector.h>
#include <queso/GslMatrix.h>
namespace QUESO {
// Constructor -------------------------------------
template<class V,class M>
UniformJointPdf<V,M>::UniformJointPdf(
const char* prefix,
const VectorSet<V,M>& domainSet)
:
BaseJointPdf<V,M>(((std::string)(prefix)+"uni").c_str(),
domainSet)
{
if ((m_env.subDisplayFile()) && (m_env.displayVerbosity() >= 54)) {
*m_env.subDisplayFile() << "Entering UniformJointPdf<V,M>::constructor()"
<< ": prefix = " << m_prefix
<< std::endl;
}
if ((m_env.subDisplayFile()) && (m_env.displayVerbosity() >= 54)) {
*m_env.subDisplayFile() << "Leaving UniformJointPdf<V,M>::constructor()"
<< ": prefix = " << m_prefix
<< std::endl;
}
}
// Destructor --------------------------------------
template<class V,class M>
UniformJointPdf<V,M>::~UniformJointPdf()
{
}
// Math methods-------------------------------------
template<class V, class M>
double
UniformJointPdf<V,M>::actualValue(
const V& domainVector,
const V* domainDirection,
V* gradVector,
M* hessianMatrix,
V* hessianEffect) const
{
UQ_FATAL_TEST_MACRO(domainVector.sizeLocal() != this->m_domainSet.vectorSpace().dimLocal(),
m_env.worldRank(),
"UniformJointPdf<V,M>::actualValue()",
"invalid input");
if (gradVector ) *gradVector = m_domainSet.vectorSpace().zeroVector();
if (hessianMatrix) *hessianMatrix *= 0.;
if (hessianEffect) *hessianEffect = m_domainSet.vectorSpace().zeroVector();
if (domainDirection) {}; // just to remove compiler warning
double volume = m_domainSet.volume();
if (((boost::math::isnan)(volume)) ||
(volume == -INFINITY ) ||
(volume == INFINITY ) ||
(volume <= 0. ) ||
(m_normalizationStyle != 0 )) {
volume = 1.;
}
return 1./volume; // No need to multiply by exp(m_logOfNormalizationFactor) [PDF-04]
}
//--------------------------------------------------
template<class V, class M>
double
UniformJointPdf<V,M>::lnValue(
const V& domainVector,
const V* domainDirection,
V* gradVector,
M* hessianMatrix,
V* hessianEffect) const
{
if (gradVector ) *gradVector = m_domainSet.vectorSpace().zeroVector();
if (hessianMatrix) *hessianMatrix *= 0.;
if (hessianEffect) *hessianEffect = m_domainSet.vectorSpace().zeroVector();
if (domainVector[0]) {}; // just to remove compiler warning
if (domainDirection) {}; // just to remove compiler warning
double volume = m_domainSet.volume();
if (((boost::math::isnan)(volume)) ||
(volume == -INFINITY ) ||
(volume == INFINITY ) ||
(volume <= 0. ) ||
(m_normalizationStyle != 0 )) {
volume = 1.;
}
return -log(volume);
}
//--------------------------------------------------
template<class V, class M>
double
UniformJointPdf<V,M>::computeLogOfNormalizationFactor(unsigned int numSamples, bool updateFactorInternally) const
{
double value = 0.;
if ((m_env.subDisplayFile()) && (m_env.displayVerbosity() >= 2)) {
*m_env.subDisplayFile() << "Entering UniformJointPdf<V,M>::computeLogOfNormalizationFactor()"
<< std::endl;
}
value = BaseJointPdf<V,M>::commonComputeLogOfNormalizationFactor(numSamples, updateFactorInternally);
if ((m_env.subDisplayFile()) && (m_env.displayVerbosity() >= 2)) {
*m_env.subDisplayFile() << "Leaving UniformJointPdf<V,M>::computeLogOfNormalizationFactor()"
<< ", m_logOfNormalizationFactor = " << m_logOfNormalizationFactor
<< std::endl;
}
return value;
}
} // End namespace QUESO
template class QUESO::UniformJointPdf<QUESO::GslVector, QUESO::GslMatrix>;
<|endoftext|>
|
<commit_before>/*
* Copyright 2006-2008 The FLWOR Foundation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <sstream>
#include "store/api/item.h"
#include "store/naive/item_vector.h"
namespace zorba { namespace simplestore {
ItemVector::ItemVector(std::vector<store::Item_t>& items)
{
ulong numItems = items.size();
theItems.resize(numItems);
for (ulong i = 0; i < numItems; i++)
theItems[i].transfer(items[i]);
}
xqpStringStore_t ItemVector::getStringValue() const
{
std::ostringstream ostr;
ulong numItems = theItems.size();
for (ulong i = 0; i < numItems; i++)
{
ostr << theItems[i]->getStringValue()->c_str() << " ";
}
return new xqpStringStore(ostr.str());
}
void ItemVector::getStringValue(xqpStringStore_t& strval) const
{
strval = new xqpStringStore("");
getStringValue(strval->str());
}
void ItemVector::getStringValue(std::string& buf) const
{
ulong numItems = theItems.size();
if (numItems > 0)
{
theItems[0]->getStringValue(buf);
for (ulong i = 1; i < numItems; i++)
{
buf += " ";
theItems[i]->getStringValue(buf);
}
}
}
} // namespace store
} // namespace zorba
<commit_msg>fixed bug in ItemVector::getStringValue()<commit_after>/*
* Copyright 2006-2008 The FLWOR Foundation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <sstream>
#include "store/api/item.h"
#include "store/naive/item_vector.h"
namespace zorba { namespace simplestore {
ItemVector::ItemVector(std::vector<store::Item_t>& items)
{
ulong numItems = items.size();
theItems.resize(numItems);
for (ulong i = 0; i < numItems; i++)
theItems[i].transfer(items[i]);
}
xqpStringStore_t ItemVector::getStringValue() const
{
std::ostringstream ostr;
ulong numItems = theItems.size();
if (numItems > 0)
{
ostr << theItems[0]->getStringValue()->c_str();
for (ulong i = 1; i < numItems; ++i)
{
ostr << " " << theItems[i]->getStringValue()->c_str();
}
}
return new xqpStringStore(ostr.str());
}
void ItemVector::getStringValue(xqpStringStore_t& strval) const
{
strval = new xqpStringStore("");
getStringValue(strval->str());
}
void ItemVector::getStringValue(std::string& buf) const
{
ulong numItems = theItems.size();
if (numItems > 0)
{
theItems[0]->getStringValue(buf);
for (ulong i = 1; i < numItems; i++)
{
buf += " ";
theItems[i]->getStringValue(buf);
}
}
}
} // namespace store
} // namespace zorba
<|endoftext|>
|
<commit_before>#pragma once
// C++ Standard Library
#include <sstream>
// Cereal
#include <cereal/cereal.hpp>
#include <cereal/archives/json.hpp>
#include <cereal/types/polymorphic.hpp>
// MPI
#include <mpi.h>
// Mantella
#include <mantella_bits/optimisationAlgorithm/populationBasedAlgorithm.hpp>
#include <mantella_bits/distanceFunction/euclideanDistance.hpp>
namespace mant {
template <typename ParameterType, class EuclideanDistance>
class ParallelAlgorithm : public PopulationBasedAlgorithm<ParameterType, EuclideanDistance> {
public:
explicit ParallelAlgorithm(
const std::shared_ptr<OptimisationProblem<ParameterType>> optimisationProblem,
const unsigned int& populationSize) noexcept;
unsigned int getRank() const noexcept;
unsigned int getNumberOfNodes() const noexcept;
protected:
int rank_;
int numberOfNodes_;
void optimiseImplementation() noexcept final override;
virtual void parallelOptimiseImplementation() noexcept = 0;
};
template <typename ParameterType, class EuclideanDistance>
ParallelAlgorithm<ParameterType, EuclideanDistance>::ParallelAlgorithm(
const std::shared_ptr<OptimisationProblem<ParameterType>> optimisationProblem,
const unsigned int& populationSize) noexcept
: PopulationBasedAlgorithm<ParameterType, EuclideanDistance>(optimisationProblem, populationSize) {
MPI_Comm_rank(MPI_COMM_WORLD, &rank_);
MPI_Comm_size(MPI_COMM_WORLD, &numberOfNodes_);
}
template <typename ParameterType, class EuclideanDistance>
void ParallelAlgorithm<ParameterType, EuclideanDistance>::optimiseImplementation() noexcept {
unsigned int serialisedOptimisationProblemSize;
char* serialisedOptimisationProblemBuffer;
if (rank_ == 0) {
std::ostringstream output; {
cereal::JSONOutputArchive archive(output);
archive(OptimisationAlgorithm<ParameterType, EuclideanDistance>::optimisationProblem_);
};
std::string serialisedOptimisationProblem = output.str();
serialisedOptimisationProblemSize = serialisedOptimisationProblem.size();
serialisedOptimisationProblemBuffer = std::strcpy(new char[serialisedOptimisationProblemSize + 1], serialisedOptimisationProblem.c_str());
}
MPI_Bcast(&serialisedOptimisationProblemSize, 1, MPI_UNSIGNED, 0, MPI_COMM_WORLD);
if (rank_ != 0) {
serialisedOptimisationProblemBuffer = new char[serialisedOptimisationProblemSize + 1];
}
MPI_Bcast(serialisedOptimisationProblemBuffer, serialisedOptimisationProblemSize + 1, MPI_CHAR, 0, MPI_COMM_WORLD);
if (rank_ != 0) {
std::istringstream input(serialisedOptimisationProblemBuffer); {
cereal::JSONInputArchive archive(input);
archive(OptimisationAlgorithm<ParameterType, EuclideanDistance>::optimisationProblem_);
}
}
delete[](serialisedOptimisationProblemBuffer);
parallelOptimiseImplementation();
}
template <typename ParameterType, class EuclideanDistance>
unsigned int ParallelAlgorithm<ParameterType, EuclideanDistance>::getRank() const noexcept {
return rank_;
}
template <typename ParameterType, class EuclideanDistance>
unsigned int ParallelAlgorithm<ParameterType, EuclideanDistance>::getNumberOfNodes() const noexcept {
return numberOfNodes_;
}
}
<commit_msg>devel: Templated *abstract* parallel algorithm class<commit_after>#pragma once
// C++ Standard Library
#include <sstream>
// Cereal
#include <cereal/cereal.hpp>
#include <cereal/archives/json.hpp>
#include <cereal/types/polymorphic.hpp>
// MPI
#include <mpi.h>
// Mantella
#include <mantella_bits/optimisationAlgorithm/populationBasedAlgorithm.hpp>
namespace mant {
template <typename ParameterType, class DistanceFunction>
class ParallelAlgorithm : public PopulationBasedAlgorithm<ParameterType, DistanceFunction> {
public:
explicit ParallelAlgorithm(
const std::shared_ptr<OptimisationProblem<ParameterType>> optimisationProblem,
const unsigned int& populationSize) noexcept;
unsigned int getRank() const noexcept;
unsigned int getNumberOfNodes() const noexcept;
protected:
int rank_;
int numberOfNodes_;
void optimiseImplementation() noexcept final override;
virtual void parallelOptimiseImplementation() noexcept = 0;
};
template <typename ParameterType, class DistanceFunction>
ParallelAlgorithm<ParameterType, DistanceFunction>::ParallelAlgorithm(
const std::shared_ptr<OptimisationProblem<ParameterType>> optimisationProblem,
const unsigned int& populationSize) noexcept
: PopulationBasedAlgorithm<ParameterType, DistanceFunction>(optimisationProblem, populationSize) {
MPI_Comm_rank(MPI_COMM_WORLD, &rank_);
MPI_Comm_size(MPI_COMM_WORLD, &numberOfNodes_);
}
template <typename ParameterType, class DistanceFunction>
void ParallelAlgorithm<ParameterType, DistanceFunction>::optimiseImplementation() noexcept {
unsigned int serialisedOptimisationProblemSize;
char* serialisedOptimisationProblemBuffer;
if (rank_ == 0) {
std::ostringstream output; {
cereal::JSONOutputArchive archive(output);
archive(OptimisationAlgorithm<ParameterType, DistanceFunction>::optimisationProblem_);
};
std::string serialisedOptimisationProblem = output.str();
serialisedOptimisationProblemSize = serialisedOptimisationProblem.size();
serialisedOptimisationProblemBuffer = std::strcpy(new char[serialisedOptimisationProblemSize + 1], serialisedOptimisationProblem.c_str());
}
MPI_Bcast(&serialisedOptimisationProblemSize, 1, MPI_UNSIGNED, 0, MPI_COMM_WORLD);
if (rank_ != 0) {
serialisedOptimisationProblemBuffer = new char[serialisedOptimisationProblemSize + 1];
}
MPI_Bcast(serialisedOptimisationProblemBuffer, serialisedOptimisationProblemSize + 1, MPI_CHAR, 0, MPI_COMM_WORLD);
if (rank_ != 0) {
std::istringstream input(serialisedOptimisationProblemBuffer); {
cereal::JSONInputArchive archive(input);
archive(OptimisationAlgorithm<ParameterType, DistanceFunction>::optimisationProblem_);
}
}
delete[](serialisedOptimisationProblemBuffer);
parallelOptimiseImplementation();
}
template <typename ParameterType, class DistanceFunction>
unsigned int ParallelAlgorithm<ParameterType, DistanceFunction>::getRank() const noexcept {
return rank_;
}
template <typename ParameterType, class DistanceFunction>
unsigned int ParallelAlgorithm<ParameterType, DistanceFunction>::getNumberOfNodes() const noexcept {
return numberOfNodes_;
}
}
<|endoftext|>
|
<commit_before>// This file is part of the "x0" project, http://github.com/christianparpart/x0>
// (c) 2009-2017 Christian Parpart <christian@parpart.family>
//
// Licensed under the MIT License (the "License"); you may not use this
// file except in compliance with the License. You may obtain a copy of
// the License at: http://opensource.org/licenses/MIT
#include <x0d/XzeroEventHandler.h>
#include <x0d/XzeroDaemon.h>
#include <xzero/UnixSignalInfo.h>
#include <xzero/executor/Executor.h>
#include <xzero/logging.h>
#include <signal.h>
namespace x0d {
using namespace xzero;
XzeroEventHandler::XzeroEventHandler(XzeroDaemon* daemon,
xzero::Executor* executor)
: daemon_(daemon),
signals_(UnixSignals::create(executor)),
executor_(executor),
state_(XzeroState::Inactive) {
signals_->notify(SIGHUP, std::bind(&XzeroEventHandler::onConfigReload, this, std::placeholders::_1));
signals_->notify(SIGUSR1, std::bind(&XzeroEventHandler::onCycleLogs, this, std::placeholders::_1));
signals_->notify(SIGUSR2, std::bind(&XzeroEventHandler::onUpgradeBinary, this, std::placeholders::_1));
signals_->notify(SIGQUIT, std::bind(&XzeroEventHandler::onGracefulShutdown, this, std::placeholders::_1));
signals_->notify(SIGTERM, std::bind(&XzeroEventHandler::onQuickShutdown, this, std::placeholders::_1));
signals_->notify(SIGINT, std::bind(&XzeroEventHandler::onQuickShutdown, this, std::placeholders::_1));
}
XzeroEventHandler::~XzeroEventHandler() {
}
void XzeroEventHandler::onConfigReload(const xzero::UnixSignalInfo& info) {
logNotice("x0d",
"Reloading configuration, as requested by pid $0 uid $1.",
info.pid.getOrElse(-1), info.uid.getOrElse(-1));
daemon_->reloadConfiguration();
signals_->notify(SIGHUP, std::bind(&XzeroEventHandler::onConfigReload, this, std::placeholders::_1));
}
void XzeroEventHandler::onCycleLogs(const xzero::UnixSignalInfo& info) {
logNotice("x0d", "Reload signal received.");
daemon_->onCycleLogs();
signals_->notify(SIGUSR1, std::bind(&XzeroEventHandler::onCycleLogs, this, std::placeholders::_1));
}
void XzeroEventHandler::onUpgradeBinary(const UnixSignalInfo& info) {
logNotice("x0d",
"Upgrading binary requested by pid $0 uid $1",
info.pid.getOrElse(-1), info.uid.getOrElse(-1));
/* TODO [x0d] binary upgrade
* 1. suspend the world
* 2. save state into temporary file with an inheriting file descriptor
* 3. exec into new binary
* 4. (new process) load state from file descriptor and close fd
* 5. (new process) resume the world
*/
}
void XzeroEventHandler::onQuickShutdown(const xzero::UnixSignalInfo& info) {
logNotice("x0d", "Initiating quick shutdown.");
daemon_->terminate();
}
void XzeroEventHandler::onGracefulShutdown(const xzero::UnixSignalInfo& info) {
logNotice("x0d", "Initiating graceful shutdown.");
/* 1. stop all listeners
* 2. wait until all requests have been handled.
* 3. orderly shutdown
*/
daemon_->server()->stop();
}
} // namespace x0d
<commit_msg>[x0d] log message copy'n'paste fix in SIGUSR1 handler<commit_after>// This file is part of the "x0" project, http://github.com/christianparpart/x0>
// (c) 2009-2017 Christian Parpart <christian@parpart.family>
//
// Licensed under the MIT License (the "License"); you may not use this
// file except in compliance with the License. You may obtain a copy of
// the License at: http://opensource.org/licenses/MIT
#include <x0d/XzeroEventHandler.h>
#include <x0d/XzeroDaemon.h>
#include <xzero/UnixSignalInfo.h>
#include <xzero/executor/Executor.h>
#include <xzero/logging.h>
#include <signal.h>
namespace x0d {
using namespace xzero;
XzeroEventHandler::XzeroEventHandler(XzeroDaemon* daemon,
xzero::Executor* executor)
: daemon_(daemon),
signals_(UnixSignals::create(executor)),
executor_(executor),
state_(XzeroState::Inactive) {
signals_->notify(SIGHUP, std::bind(&XzeroEventHandler::onConfigReload, this, std::placeholders::_1));
signals_->notify(SIGUSR1, std::bind(&XzeroEventHandler::onCycleLogs, this, std::placeholders::_1));
signals_->notify(SIGUSR2, std::bind(&XzeroEventHandler::onUpgradeBinary, this, std::placeholders::_1));
signals_->notify(SIGQUIT, std::bind(&XzeroEventHandler::onGracefulShutdown, this, std::placeholders::_1));
signals_->notify(SIGTERM, std::bind(&XzeroEventHandler::onQuickShutdown, this, std::placeholders::_1));
signals_->notify(SIGINT, std::bind(&XzeroEventHandler::onQuickShutdown, this, std::placeholders::_1));
}
XzeroEventHandler::~XzeroEventHandler() {
}
void XzeroEventHandler::onConfigReload(const xzero::UnixSignalInfo& info) {
logNotice("x0d",
"Reloading configuration, as requested by pid $0 uid $1.",
info.pid.getOrElse(-1), info.uid.getOrElse(-1));
daemon_->reloadConfiguration();
signals_->notify(SIGHUP, std::bind(&XzeroEventHandler::onConfigReload, this, std::placeholders::_1));
}
void XzeroEventHandler::onCycleLogs(const xzero::UnixSignalInfo& info) {
logNotice("x0d", "Cycling logs, as requested by pid $0 uid $1.",
info.pid.getOrElse(-1), info.uid.getOrElse(-1));
daemon_->onCycleLogs();
signals_->notify(SIGUSR1, std::bind(&XzeroEventHandler::onCycleLogs, this, std::placeholders::_1));
}
void XzeroEventHandler::onUpgradeBinary(const UnixSignalInfo& info) {
logNotice("x0d",
"Upgrading binary requested by pid $0 uid $1",
info.pid.getOrElse(-1), info.uid.getOrElse(-1));
/* TODO [x0d] binary upgrade
* 1. suspend the world
* 2. save state into temporary file with an inheriting file descriptor
* 3. exec into new binary
* 4. (new process) load state from file descriptor and close fd
* 5. (new process) resume the world
*/
}
void XzeroEventHandler::onQuickShutdown(const xzero::UnixSignalInfo& info) {
logNotice("x0d", "Initiating quick shutdown.");
daemon_->terminate();
}
void XzeroEventHandler::onGracefulShutdown(const xzero::UnixSignalInfo& info) {
logNotice("x0d", "Initiating graceful shutdown.");
/* 1. stop all listeners
* 2. wait until all requests have been handled.
* 3. orderly shutdown
*/
daemon_->server()->stop();
}
} // namespace x0d
<|endoftext|>
|
<commit_before>// Copyright (c) 2019-2020 Dr. Colin Hirsch and Daniel Frey
// Please see LICENSE for license or visit https://github.com/taocpp/PEGTL/
#include "test.hpp"
#include "verify_analyze.hpp"
#include "verify_rule.hpp"
namespace TAO_PEGTL_NAMESPACE
{
void unit_test()
{
verify_rule< rematch< one< 'c' > > >( __LINE__, __FILE__, "c", result_type::success );
verify_rule< rematch< one< 'c' > > >( __LINE__, __FILE__, "a", result_type::local_failure );
verify_rule< rematch< one< 'c' > > >( __LINE__, __FILE__, "b", result_type::local_failure );
verify_rule< rematch< one< 'c' > > >( __LINE__, __FILE__, "cc", result_type::success, 1 );
verify_rule< rematch< one< 'c' > > >( __LINE__, __FILE__, "bc", result_type::local_failure );
verify_analyze< rematch< alpha, digit > >( __LINE__, __FILE__, true, false );
verify_analyze< rematch< opt< alpha >, digit > >( __LINE__, __FILE__, false, false );
{
struct foo
: rematch< alnum, foo >
{};
verify_analyze< foo >( __LINE__, __FILE__, true, true );
}
{
struct foo
: rematch< alnum, alpha, foo >
{};
verify_analyze< foo >( __LINE__, __FILE__, true, true );
}
verify_rule< rematch< alnum, digit > >( __LINE__, __FILE__, "", result_type::local_failure, 0 );
verify_rule< rematch< alnum, digit > >( __LINE__, __FILE__, "1", result_type::success, 0 );
verify_rule< rematch< alnum, digit > >( __LINE__, __FILE__, "a", result_type::local_failure, 1 );
verify_rule< rematch< alnum, digit > >( __LINE__, __FILE__, "%", result_type::local_failure, 1 );
verify_rule< rematch< alnum, digit > >( __LINE__, __FILE__, "1%", result_type::success, 1 );
verify_rule< rematch< alnum, digit > >( __LINE__, __FILE__, "a%", result_type::local_failure, 2 );
verify_rule< rematch< alnum, digit > >( __LINE__, __FILE__, "12", result_type::success, 1 );
verify_rule< rematch< alnum, digit > >( __LINE__, __FILE__, "1c", result_type::success, 1 );
verify_rule< rematch< alnum, digit, success > >( __LINE__, __FILE__, "", result_type::local_failure, 0 );
verify_rule< rematch< alnum, digit, success > >( __LINE__, __FILE__, "1", result_type::success, 0 );
verify_rule< rematch< alnum, digit, success > >( __LINE__, __FILE__, "a", result_type::local_failure, 1 );
verify_rule< rematch< alnum, digit, success > >( __LINE__, __FILE__, "%", result_type::local_failure, 1 );
verify_rule< rematch< alnum, digit, success > >( __LINE__, __FILE__, "1%", result_type::success, 1 );
verify_rule< rematch< alnum, digit, success > >( __LINE__, __FILE__, "a%", result_type::local_failure, 2 );
verify_rule< rematch< alnum, digit, success > >( __LINE__, __FILE__, "12", result_type::success, 1 );
verify_rule< rematch< alnum, digit, success > >( __LINE__, __FILE__, "1c", result_type::success, 1 );
verify_rule< rematch< alnum, success, digit > >( __LINE__, __FILE__, "", result_type::local_failure, 0 );
verify_rule< rematch< alnum, success, digit > >( __LINE__, __FILE__, "1", result_type::success, 0 );
verify_rule< rematch< alnum, success, digit > >( __LINE__, __FILE__, "a", result_type::local_failure, 1 );
verify_rule< rematch< alnum, success, digit > >( __LINE__, __FILE__, "%", result_type::local_failure, 1 );
verify_rule< rematch< alnum, success, digit > >( __LINE__, __FILE__, "1%", result_type::success, 1 );
verify_rule< rematch< alnum, success, digit > >( __LINE__, __FILE__, "a%", result_type::local_failure, 2 );
verify_rule< rematch< alnum, success, digit > >( __LINE__, __FILE__, "12", result_type::success, 1 );
verify_rule< rematch< alnum, success, digit > >( __LINE__, __FILE__, "1c", result_type::success, 1 );
verify_rule< rematch< plus< alnum >, digit > >( __LINE__, __FILE__, "", result_type::local_failure );
verify_rule< rematch< plus< alnum >, digit > >( __LINE__, __FILE__, "1", result_type::success );
verify_rule< rematch< plus< alnum >, digit > >( __LINE__, __FILE__, "a", result_type::local_failure );
verify_rule< rematch< plus< alnum >, digit > >( __LINE__, __FILE__, "%", result_type::local_failure );
verify_rule< rematch< plus< alnum >, digit > >( __LINE__, __FILE__, "1%", result_type::success, 1 );
verify_rule< rematch< plus< alnum >, digit > >( __LINE__, __FILE__, "a%", result_type::local_failure );
verify_rule< rematch< plus< alnum >, digit > >( __LINE__, __FILE__, "12", result_type::success, 0 );
verify_rule< rematch< plus< alnum >, digit > >( __LINE__, __FILE__, "1c", result_type::success, 0 );
verify_rule< rematch< plus< alnum >, digit > >( __LINE__, __FILE__, "aa", result_type::local_failure, 2 );
verify_rule< rematch< plus< alnum >, digit > >( __LINE__, __FILE__, "a1", result_type::local_failure, 2 );
verify_rule< rematch< plus< alnum >, digit > >( __LINE__, __FILE__, "%%", result_type::local_failure, 2 );
verify_rule< rematch< plus< alnum >, plus< digit > > >( __LINE__, __FILE__, "", result_type::local_failure, 0 );
verify_rule< rematch< plus< alnum >, plus< digit > > >( __LINE__, __FILE__, "1", result_type::success, 0 );
verify_rule< rematch< plus< alnum >, plus< digit > > >( __LINE__, __FILE__, "a", result_type::local_failure, 1 );
verify_rule< rematch< plus< alnum >, plus< digit > > >( __LINE__, __FILE__, "%", result_type::local_failure, 1 );
verify_rule< rematch< plus< alnum >, plus< digit > > >( __LINE__, __FILE__, "1%", result_type::success, 1 );
verify_rule< rematch< plus< alnum >, plus< digit > > >( __LINE__, __FILE__, "a%", result_type::local_failure );
verify_rule< rematch< plus< alnum >, plus< digit > > >( __LINE__, __FILE__, "12", result_type::success, 0 );
verify_rule< rematch< plus< alnum >, plus< digit > > >( __LINE__, __FILE__, "1c", result_type::success, 0 );
verify_rule< rematch< plus< alnum >, plus< digit > > >( __LINE__, __FILE__, "aa", result_type::local_failure, 2 );
verify_rule< rematch< plus< alnum >, plus< digit > > >( __LINE__, __FILE__, "a1", result_type::local_failure, 2 );
verify_rule< rematch< plus< alnum >, plus< digit > > >( __LINE__, __FILE__, "%%", result_type::local_failure, 2 );
verify_rule< rematch< plus< alnum >, plus< digit > > >( __LINE__, __FILE__, "aaa", result_type::local_failure, 3 );
verify_rule< rematch< plus< alnum >, plus< digit > > >( __LINE__, __FILE__, "aaa%", result_type::local_failure, 4 );
verify_rule< rematch< plus< alnum >, plus< digit > > >( __LINE__, __FILE__, "111", result_type::success, 0 );
verify_rule< rematch< plus< alnum >, plus< digit > > >( __LINE__, __FILE__, "111%", result_type::success, 1 );
verify_rule< rematch< plus< alnum >, plus< digit > > >( __LINE__, __FILE__, "a1a", result_type::local_failure, 3 );
verify_rule< rematch< plus< alnum >, plus< digit > > >( __LINE__, __FILE__, "1a1", result_type::success, 0 );
verify_rule< rematch< plus< alnum >, seq< string< 'f', 'o', 'o' >, eof > > >( __LINE__, __FILE__, "foo", result_type::success, 0 );
verify_rule< rematch< plus< alnum >, seq< string< 'f', 'o', 'o' >, eof > > >( __LINE__, __FILE__, "foo%", result_type::success, 1 );
verify_rule< rematch< plus< alnum >, seq< string< 'f', 'o', 'o' >, eof > > >( __LINE__, __FILE__, "foo5", result_type::local_failure, 4 );
verify_rule< rematch< plus< alnum >, success, seq< string< 'f', 'o', 'o' >, eof > > >( __LINE__, __FILE__, "foo", result_type::success, 0 );
verify_rule< rematch< plus< alnum >, success, seq< string< 'f', 'o', 'o' >, eof > > >( __LINE__, __FILE__, "foo%", result_type::success, 1 );
verify_rule< rematch< plus< alnum >, success, seq< string< 'f', 'o', 'o' >, eof > > >( __LINE__, __FILE__, "foo5", result_type::local_failure, 4 );
verify_rule< rematch< plus< alnum >, seq< string< 'f', 'o', 'o' >, eof >, success > >( __LINE__, __FILE__, "foo", result_type::success, 0 );
verify_rule< rematch< plus< alnum >, seq< string< 'f', 'o', 'o' >, eof >, success > >( __LINE__, __FILE__, "foo%", result_type::success, 1 );
verify_rule< rematch< plus< alnum >, seq< string< 'f', 'o', 'o' >, eof >, success > >( __LINE__, __FILE__, "foo5", result_type::local_failure, 4 );
verify_rule< rematch< plus< alnum >, seq< string< 'f', 'o', 'o' >, eof >, string< 'f', 'o', 'o' > > >( __LINE__, __FILE__, "foo", result_type::success, 0 );
verify_rule< rematch< plus< alnum >, seq< string< 'f', 'o', 'o' >, eof >, string< 'f', 'o', 'o' > > >( __LINE__, __FILE__, "foo%", result_type::success, 1 );
verify_rule< rematch< plus< alnum >, seq< string< 'f', 'o', 'o' >, eof >, string< 'f', 'o', 'o' > > >( __LINE__, __FILE__, "foo5", result_type::local_failure, 4 );
}
} // namespace TAO_PEGTL_NAMESPACE
#include "main.hpp"
<commit_msg>More tests<commit_after>// Copyright (c) 2019-2020 Dr. Colin Hirsch and Daniel Frey
// Please see LICENSE for license or visit https://github.com/taocpp/PEGTL/
#include "test.hpp"
#include "verify_analyze.hpp"
#include "verify_rule.hpp"
namespace TAO_PEGTL_NAMESPACE
{
void unit_test()
{
verify_rule< rematch< one< 'c' > > >( __LINE__, __FILE__, "c", result_type::success );
verify_rule< rematch< one< 'c' > > >( __LINE__, __FILE__, "a", result_type::local_failure );
verify_rule< rematch< one< 'c' > > >( __LINE__, __FILE__, "b", result_type::local_failure );
verify_rule< rematch< one< 'c' > > >( __LINE__, __FILE__, "cc", result_type::success, 1 );
verify_rule< rematch< one< 'c' > > >( __LINE__, __FILE__, "bc", result_type::local_failure );
verify_analyze< rematch< alpha, digit > >( __LINE__, __FILE__, true, false );
verify_analyze< rematch< opt< alpha >, digit > >( __LINE__, __FILE__, false, false );
{
struct foo
: rematch< foo, alnum >
{};
verify_analyze< foo >( __LINE__, __FILE__, false, true );
}
{
struct foo
: rematch< alnum, foo >
{};
verify_analyze< foo >( __LINE__, __FILE__, true, true );
}
{
struct foo
: rematch< alnum, alpha, foo >
{};
verify_analyze< foo >( __LINE__, __FILE__, true, true );
}
verify_rule< rematch< alnum, digit > >( __LINE__, __FILE__, "", result_type::local_failure, 0 );
verify_rule< rematch< alnum, digit > >( __LINE__, __FILE__, "1", result_type::success, 0 );
verify_rule< rematch< alnum, digit > >( __LINE__, __FILE__, "a", result_type::local_failure, 1 );
verify_rule< rematch< alnum, digit > >( __LINE__, __FILE__, "%", result_type::local_failure, 1 );
verify_rule< rematch< alnum, digit > >( __LINE__, __FILE__, "1%", result_type::success, 1 );
verify_rule< rematch< alnum, digit > >( __LINE__, __FILE__, "a%", result_type::local_failure, 2 );
verify_rule< rematch< alnum, digit > >( __LINE__, __FILE__, "12", result_type::success, 1 );
verify_rule< rematch< alnum, digit > >( __LINE__, __FILE__, "1c", result_type::success, 1 );
verify_rule< rematch< alnum, digit, success > >( __LINE__, __FILE__, "", result_type::local_failure, 0 );
verify_rule< rematch< alnum, digit, success > >( __LINE__, __FILE__, "1", result_type::success, 0 );
verify_rule< rematch< alnum, digit, success > >( __LINE__, __FILE__, "a", result_type::local_failure, 1 );
verify_rule< rematch< alnum, digit, success > >( __LINE__, __FILE__, "%", result_type::local_failure, 1 );
verify_rule< rematch< alnum, digit, success > >( __LINE__, __FILE__, "1%", result_type::success, 1 );
verify_rule< rematch< alnum, digit, success > >( __LINE__, __FILE__, "a%", result_type::local_failure, 2 );
verify_rule< rematch< alnum, digit, success > >( __LINE__, __FILE__, "12", result_type::success, 1 );
verify_rule< rematch< alnum, digit, success > >( __LINE__, __FILE__, "1c", result_type::success, 1 );
verify_rule< rematch< alnum, success, digit > >( __LINE__, __FILE__, "", result_type::local_failure, 0 );
verify_rule< rematch< alnum, success, digit > >( __LINE__, __FILE__, "1", result_type::success, 0 );
verify_rule< rematch< alnum, success, digit > >( __LINE__, __FILE__, "a", result_type::local_failure, 1 );
verify_rule< rematch< alnum, success, digit > >( __LINE__, __FILE__, "%", result_type::local_failure, 1 );
verify_rule< rematch< alnum, success, digit > >( __LINE__, __FILE__, "1%", result_type::success, 1 );
verify_rule< rematch< alnum, success, digit > >( __LINE__, __FILE__, "a%", result_type::local_failure, 2 );
verify_rule< rematch< alnum, success, digit > >( __LINE__, __FILE__, "12", result_type::success, 1 );
verify_rule< rematch< alnum, success, digit > >( __LINE__, __FILE__, "1c", result_type::success, 1 );
verify_rule< rematch< plus< alnum >, digit > >( __LINE__, __FILE__, "", result_type::local_failure );
verify_rule< rematch< plus< alnum >, digit > >( __LINE__, __FILE__, "1", result_type::success );
verify_rule< rematch< plus< alnum >, digit > >( __LINE__, __FILE__, "a", result_type::local_failure );
verify_rule< rematch< plus< alnum >, digit > >( __LINE__, __FILE__, "%", result_type::local_failure );
verify_rule< rematch< plus< alnum >, digit > >( __LINE__, __FILE__, "1%", result_type::success, 1 );
verify_rule< rematch< plus< alnum >, digit > >( __LINE__, __FILE__, "a%", result_type::local_failure );
verify_rule< rematch< plus< alnum >, digit > >( __LINE__, __FILE__, "12", result_type::success, 0 );
verify_rule< rematch< plus< alnum >, digit > >( __LINE__, __FILE__, "1c", result_type::success, 0 );
verify_rule< rematch< plus< alnum >, digit > >( __LINE__, __FILE__, "aa", result_type::local_failure, 2 );
verify_rule< rematch< plus< alnum >, digit > >( __LINE__, __FILE__, "a1", result_type::local_failure, 2 );
verify_rule< rematch< plus< alnum >, digit > >( __LINE__, __FILE__, "%%", result_type::local_failure, 2 );
verify_rule< rematch< plus< alnum >, plus< digit > > >( __LINE__, __FILE__, "", result_type::local_failure, 0 );
verify_rule< rematch< plus< alnum >, plus< digit > > >( __LINE__, __FILE__, "1", result_type::success, 0 );
verify_rule< rematch< plus< alnum >, plus< digit > > >( __LINE__, __FILE__, "a", result_type::local_failure, 1 );
verify_rule< rematch< plus< alnum >, plus< digit > > >( __LINE__, __FILE__, "%", result_type::local_failure, 1 );
verify_rule< rematch< plus< alnum >, plus< digit > > >( __LINE__, __FILE__, "1%", result_type::success, 1 );
verify_rule< rematch< plus< alnum >, plus< digit > > >( __LINE__, __FILE__, "a%", result_type::local_failure );
verify_rule< rematch< plus< alnum >, plus< digit > > >( __LINE__, __FILE__, "12", result_type::success, 0 );
verify_rule< rematch< plus< alnum >, plus< digit > > >( __LINE__, __FILE__, "1c", result_type::success, 0 );
verify_rule< rematch< plus< alnum >, plus< digit > > >( __LINE__, __FILE__, "aa", result_type::local_failure, 2 );
verify_rule< rematch< plus< alnum >, plus< digit > > >( __LINE__, __FILE__, "a1", result_type::local_failure, 2 );
verify_rule< rematch< plus< alnum >, plus< digit > > >( __LINE__, __FILE__, "%%", result_type::local_failure, 2 );
verify_rule< rematch< plus< alnum >, plus< digit > > >( __LINE__, __FILE__, "aaa", result_type::local_failure, 3 );
verify_rule< rematch< plus< alnum >, plus< digit > > >( __LINE__, __FILE__, "aaa%", result_type::local_failure, 4 );
verify_rule< rematch< plus< alnum >, plus< digit > > >( __LINE__, __FILE__, "111", result_type::success, 0 );
verify_rule< rematch< plus< alnum >, plus< digit > > >( __LINE__, __FILE__, "111%", result_type::success, 1 );
verify_rule< rematch< plus< alnum >, plus< digit > > >( __LINE__, __FILE__, "a1a", result_type::local_failure, 3 );
verify_rule< rematch< plus< alnum >, plus< digit > > >( __LINE__, __FILE__, "1a1", result_type::success, 0 );
verify_rule< rematch< plus< alnum >, seq< string< 'f', 'o', 'o' >, eof > > >( __LINE__, __FILE__, "foo", result_type::success, 0 );
verify_rule< rematch< plus< alnum >, seq< string< 'f', 'o', 'o' >, eof > > >( __LINE__, __FILE__, "foo%", result_type::success, 1 );
verify_rule< rematch< plus< alnum >, seq< string< 'f', 'o', 'o' >, eof > > >( __LINE__, __FILE__, "foo5", result_type::local_failure, 4 );
verify_rule< rematch< plus< alnum >, success, seq< string< 'f', 'o', 'o' >, eof > > >( __LINE__, __FILE__, "foo", result_type::success, 0 );
verify_rule< rematch< plus< alnum >, success, seq< string< 'f', 'o', 'o' >, eof > > >( __LINE__, __FILE__, "foo%", result_type::success, 1 );
verify_rule< rematch< plus< alnum >, success, seq< string< 'f', 'o', 'o' >, eof > > >( __LINE__, __FILE__, "foo5", result_type::local_failure, 4 );
verify_rule< rematch< plus< alnum >, seq< string< 'f', 'o', 'o' >, eof >, success > >( __LINE__, __FILE__, "foo", result_type::success, 0 );
verify_rule< rematch< plus< alnum >, seq< string< 'f', 'o', 'o' >, eof >, success > >( __LINE__, __FILE__, "foo%", result_type::success, 1 );
verify_rule< rematch< plus< alnum >, seq< string< 'f', 'o', 'o' >, eof >, success > >( __LINE__, __FILE__, "foo5", result_type::local_failure, 4 );
verify_rule< rematch< plus< alnum >, seq< string< 'f', 'o', 'o' >, eof >, string< 'f', 'o', 'o' > > >( __LINE__, __FILE__, "foo", result_type::success, 0 );
verify_rule< rematch< plus< alnum >, seq< string< 'f', 'o', 'o' >, eof >, string< 'f', 'o', 'o' > > >( __LINE__, __FILE__, "foo%", result_type::success, 1 );
verify_rule< rematch< plus< alnum >, seq< string< 'f', 'o', 'o' >, eof >, string< 'f', 'o', 'o' > > >( __LINE__, __FILE__, "foo5", result_type::local_failure, 4 );
}
} // namespace TAO_PEGTL_NAMESPACE
#include "main.hpp"
<|endoftext|>
|
<commit_before>//-------------------------------------------------------------------------
//
// rewritersample.cpp: Source-to-source transformation sample with Clang,
// using Rewriter - the code rewriting interface.
//
// Eli Bendersky (eliben@gmail.com)
// This code is in the public domain
//
#include <cstdio>
#include <string>
#include <sstream>
#include "clang/AST/ASTConsumer.h"
#include "clang/AST/RecursiveASTVisitor.h"
#include "clang/Basic/Diagnostic.h"
#include "clang/Basic/FileManager.h"
#include "clang/Basic/SourceManager.h"
#include "clang/Basic/TargetOptions.h"
#include "clang/Basic/TargetInfo.h"
#include "clang/Frontend/CompilerInstance.h"
#include "clang/Lex/Preprocessor.h"
#include "clang/Parse/ParseAST.h"
#include "clang/Rewrite/Core/Rewriter.h"
#include "clang/Rewrite/Frontend/Rewriters.h"
#include "llvm/Support/Host.h"
#include "llvm/Support/raw_ostream.h"
using namespace clang;
using namespace std;
// By implementing RecursiveASTVisitor, we can specify which AST nodes
// we're interested in by overriding relevant methods.
class MyASTVisitor : public RecursiveASTVisitor<MyASTVisitor> {
public:
MyASTVisitor(Rewriter &R) : TheRewriter(R) {}
bool VisitStmt(Stmt *s) {
// Only care about If statements.
if (isa<IfStmt>(s)) {
IfStmt *IfStatement = cast<IfStmt>(s);
Stmt *Then = IfStatement->getThen();
TheRewriter.InsertText(Then->getLocStart(), "// the 'if' part\n", true,
true);
Stmt *Else = IfStatement->getElse();
if (Else)
TheRewriter.InsertText(Else->getLocStart(), "// the 'else' part\n",
true, true);
}
return true;
}
bool VisitFunctionDecl(FunctionDecl *f) {
// Only function definitions (with bodies), not declarations.
if (f->hasBody()) {
Stmt *FuncBody = f->getBody();
// Type name as string
QualType QT = f->getResultType();
string TypeStr = QT.getAsString();
// Function name
DeclarationName DeclName = f->getNameInfo().getName();
string FuncName = DeclName.getAsString();
// Add comment before
stringstream SSBefore;
SSBefore << "// Begin function " << FuncName << " returning " << TypeStr
<< "\n";
SourceLocation ST = f->getSourceRange().getBegin();
TheRewriter.InsertText(ST, SSBefore.str(), true, true);
// And after
stringstream SSAfter;
SSAfter << "\n// End function " << FuncName << "\n";
ST = FuncBody->getLocEnd().getLocWithOffset(1);
TheRewriter.InsertText(ST, SSAfter.str(), true, true);
}
return true;
}
private:
void AddBraces(Stmt *s);
Rewriter &TheRewriter;
};
// Implementation of the ASTConsumer interface for reading an AST produced
// by the Clang parser.
class MyASTConsumer : public ASTConsumer {
public:
MyASTConsumer(Rewriter &R) : Visitor(R) {}
// Override the method that gets called for each parsed top-level
// declaration.
virtual bool HandleTopLevelDecl(DeclGroupRef DR) {
for (DeclGroupRef::iterator b = DR.begin(), e = DR.end(); b != e; ++b)
// Traverse the declaration using our AST visitor.
Visitor.TraverseDecl(*b);
return true;
}
private:
MyASTVisitor Visitor;
};
int main(int argc, char *argv[]) {
if (argc != 2) {
llvm::errs() << "Usage: rewritersample <filename>\n";
return 1;
}
// CompilerInstance will hold the instance of the Clang compiler for us,
// managing the various objects needed to run the compiler.
CompilerInstance TheCompInst;
TheCompInst.createDiagnostics();
// Initialize target info with the default triple for our platform.
TargetOptions *TO = new TargetOptions;
TO->Triple = llvm::sys::getDefaultTargetTriple();
TargetInfo *TI =
TargetInfo::CreateTargetInfo(TheCompInst.getDiagnostics(), TO);
TheCompInst.setTarget(TI);
TheCompInst.createFileManager();
FileManager &FileMgr = TheCompInst.getFileManager();
TheCompInst.createSourceManager(FileMgr);
SourceManager &SourceMgr = TheCompInst.getSourceManager();
TheCompInst.createPreprocessor();
TheCompInst.createASTContext();
// A Rewriter helps us manage the code rewriting task.
Rewriter TheRewriter;
TheRewriter.setSourceMgr(SourceMgr, TheCompInst.getLangOpts());
//// Set the main file handled by the source manager to the input file.
const FileEntry *FileIn = FileMgr.getFile(argv[1]);
SourceMgr.createMainFileID(FileIn);
TheCompInst.getDiagnosticClient().BeginSourceFile(
TheCompInst.getLangOpts(), &TheCompInst.getPreprocessor());
// Create an AST consumer instance which is going to get called by
// ParseAST.
MyASTConsumer TheConsumer(TheRewriter);
// Parse the file to AST, registering our consumer as the AST consumer.
ParseAST(TheCompInst.getPreprocessor(), &TheConsumer,
TheCompInst.getASTContext());
//// At this point the rewriter's buffer should be full with the rewritten
//// file contents.
const RewriteBuffer *RewriteBuf =
TheRewriter.getRewriteBufferFor(SourceMgr.getMainFileID());
llvm::outs() << string(RewriteBuf->begin(), RewriteBuf->end());
return 0;
}
<commit_msg>Resilience in case of not finding the input file<commit_after>//-------------------------------------------------------------------------
//
// rewritersample.cpp: Source-to-source transformation sample with Clang,
// using Rewriter - the code rewriting interface.
//
// Eli Bendersky (eliben@gmail.com)
// This code is in the public domain
//
#include <cstdio>
#include <string>
#include <sstream>
#include "clang/AST/ASTConsumer.h"
#include "clang/AST/RecursiveASTVisitor.h"
#include "clang/Basic/Diagnostic.h"
#include "clang/Basic/FileManager.h"
#include "clang/Basic/SourceManager.h"
#include "clang/Basic/TargetOptions.h"
#include "clang/Basic/TargetInfo.h"
#include "clang/Frontend/CompilerInstance.h"
#include "clang/Lex/Preprocessor.h"
#include "clang/Parse/ParseAST.h"
#include "clang/Rewrite/Core/Rewriter.h"
#include "clang/Rewrite/Frontend/Rewriters.h"
#include "llvm/Support/Host.h"
#include "llvm/Support/raw_ostream.h"
using namespace clang;
using namespace std;
// By implementing RecursiveASTVisitor, we can specify which AST nodes
// we're interested in by overriding relevant methods.
class MyASTVisitor : public RecursiveASTVisitor<MyASTVisitor> {
public:
MyASTVisitor(Rewriter &R) : TheRewriter(R) {}
bool VisitStmt(Stmt *s) {
// Only care about If statements.
if (isa<IfStmt>(s)) {
IfStmt *IfStatement = cast<IfStmt>(s);
Stmt *Then = IfStatement->getThen();
TheRewriter.InsertText(Then->getLocStart(), "// the 'if' part\n", true,
true);
Stmt *Else = IfStatement->getElse();
if (Else)
TheRewriter.InsertText(Else->getLocStart(), "// the 'else' part\n",
true, true);
}
return true;
}
bool VisitFunctionDecl(FunctionDecl *f) {
// Only function definitions (with bodies), not declarations.
if (f->hasBody()) {
Stmt *FuncBody = f->getBody();
// Type name as string
QualType QT = f->getResultType();
string TypeStr = QT.getAsString();
// Function name
DeclarationName DeclName = f->getNameInfo().getName();
string FuncName = DeclName.getAsString();
// Add comment before
stringstream SSBefore;
SSBefore << "// Begin function " << FuncName << " returning " << TypeStr
<< "\n";
SourceLocation ST = f->getSourceRange().getBegin();
TheRewriter.InsertText(ST, SSBefore.str(), true, true);
// And after
stringstream SSAfter;
SSAfter << "\n// End function " << FuncName << "\n";
ST = FuncBody->getLocEnd().getLocWithOffset(1);
TheRewriter.InsertText(ST, SSAfter.str(), true, true);
}
return true;
}
private:
void AddBraces(Stmt *s);
Rewriter &TheRewriter;
};
// Implementation of the ASTConsumer interface for reading an AST produced
// by the Clang parser.
class MyASTConsumer : public ASTConsumer {
public:
MyASTConsumer(Rewriter &R) : Visitor(R) {}
// Override the method that gets called for each parsed top-level
// declaration.
virtual bool HandleTopLevelDecl(DeclGroupRef DR) {
for (DeclGroupRef::iterator b = DR.begin(), e = DR.end(); b != e; ++b)
// Traverse the declaration using our AST visitor.
Visitor.TraverseDecl(*b);
return true;
}
private:
MyASTVisitor Visitor;
};
int main(int argc, char *argv[]) {
if (argc != 2) {
llvm::errs() << "Usage: rewritersample <filename>\n";
return 1;
}
// CompilerInstance will hold the instance of the Clang compiler for us,
// managing the various objects needed to run the compiler.
CompilerInstance TheCompInst;
TheCompInst.createDiagnostics();
// Initialize target info with the default triple for our platform.
TargetOptions *TO = new TargetOptions;
TO->Triple = llvm::sys::getDefaultTargetTriple();
TargetInfo *TI =
TargetInfo::CreateTargetInfo(TheCompInst.getDiagnostics(), TO);
TheCompInst.setTarget(TI);
TheCompInst.createFileManager();
FileManager &FileMgr = TheCompInst.getFileManager();
TheCompInst.createSourceManager(FileMgr);
SourceManager &SourceMgr = TheCompInst.getSourceManager();
TheCompInst.createPreprocessor();
TheCompInst.createASTContext();
// A Rewriter helps us manage the code rewriting task.
Rewriter TheRewriter;
TheRewriter.setSourceMgr(SourceMgr, TheCompInst.getLangOpts());
//// Set the main file handled by the source manager to the input file.
const FileEntry *FileIn = FileMgr.getFile(argv[1]);
if (!FileIn) {
llvm::errs() << "Input file does not exist!\n";
return 1;
}
SourceMgr.createMainFileID(FileIn);
TheCompInst.getDiagnosticClient().BeginSourceFile(
TheCompInst.getLangOpts(), &TheCompInst.getPreprocessor());
// Create an AST consumer instance which is going to get called by
// ParseAST.
MyASTConsumer TheConsumer(TheRewriter);
// Parse the file to AST, registering our consumer as the AST consumer.
ParseAST(TheCompInst.getPreprocessor(), &TheConsumer,
TheCompInst.getASTContext());
//// At this point the rewriter's buffer should be full with the rewritten
//// file contents.
const RewriteBuffer *RewriteBuf =
TheRewriter.getRewriteBufferFor(SourceMgr.getMainFileID());
llvm::outs() << string(RewriteBuf->begin(), RewriteBuf->end());
return 0;
}
<|endoftext|>
|
<commit_before>#include "customizer.h"
#include <QtWidgets/QApplication>
#include <qrkernel/settingsManager.h>
using namespace interpreterCore;
QString Customizer::windowTitle() const
{
return QObject::tr("Trik Studio") + " " + productVersion();
}
QIcon Customizer::applicationIcon() const
{
return QIcon(":/icons/icon.png");
}
QImage Customizer::applicationLogo() const
{
return QImage(":/icons/splashscreen.png");
}
QString Customizer::productVersion() const
{
/// @todo other storage for it?
return "3.0.0 α10";
}
QString Customizer::aboutText() const
{
return "<b>" + windowTitle() + "<b><br><br><a href=\"http://robots.qreal.ru/\">http://robots.qreal.ru/</a>";
}
QString Customizer::examplesDirectory() const
{
return QApplication::applicationDirPath() + "/examples";
}
bool Customizer::showInterpeterButton() const
{
return false;
}
void Customizer::customizeDocks(qReal::gui::MainWindowDockInterface *dockInterface)
{
mDockInterface = dockInterface;
dockInterface->logicalModelDock()->hide();
dockInterface->tabifyDockWidget(dockInterface->graphicalModelDock(), dockInterface->propertyEditorDock());
dockInterface->graphicalModelDock()->setWindowTitle(QObject::tr("Blocks"));
}
void Customizer::placeDevicesConfig(QWidget *devicesWidget)
{
QDockWidget *devicesDock = produceDockWidget(QObject::tr("Configure devices"), devicesWidget);
mDockInterface->addDockWidget(Qt::LeftDockWidgetArea, devicesDock);
}
void Customizer::placeWatchPlugins(QDockWidget *watchWindow, QWidget *graphicsWatch)
{
mDockInterface->addDockWidget(Qt::LeftDockWidgetArea, watchWindow);
watchWindow->setFloating(false);
/// @todo: Restore plotter when everything will be fine...
Q_UNUSED(graphicsWatch)
// QDockWidget *graphWatchDock = produceDockWidget(QObject::tr("Sensors state"), graphicsWatch);
// mDockInterface->addDockWidget(Qt::LeftDockWidgetArea, graphWatchDock);
// mDockInterface->tabifyDockWidget(watchWindow, graphWatchDock);
}
QDockWidget *Customizer::produceDockWidget(QString const &title, QWidget *content) const
{
QDockWidget *dock = new QDockWidget(title);
dock->setWidget(content);
return dock;
}
QString Customizer::userPaletteTitle() const
{
return QObject::tr("Subprograms");
}
QString Customizer::userPaletteDescription() const
{
return QObject::tr("The list of all declared subprograms in the project");
}
<commit_msg>Sensors plotter enabled back<commit_after>#include "customizer.h"
#include <QtWidgets/QApplication>
#include <qrkernel/settingsManager.h>
using namespace interpreterCore;
QString Customizer::windowTitle() const
{
return QObject::tr("Trik Studio") + " " + productVersion();
}
QIcon Customizer::applicationIcon() const
{
return QIcon(":/icons/icon.png");
}
QImage Customizer::applicationLogo() const
{
return QImage(":/icons/splashscreen.png");
}
QString Customizer::productVersion() const
{
/// @todo other storage for it?
return "3.0.0 α10";
}
QString Customizer::aboutText() const
{
return "<b>" + windowTitle() + "<b><br><br><a href=\"http://robots.qreal.ru/\">http://robots.qreal.ru/</a>";
}
QString Customizer::examplesDirectory() const
{
return QApplication::applicationDirPath() + "/examples";
}
bool Customizer::showInterpeterButton() const
{
return false;
}
void Customizer::customizeDocks(qReal::gui::MainWindowDockInterface *dockInterface)
{
mDockInterface = dockInterface;
dockInterface->logicalModelDock()->hide();
dockInterface->tabifyDockWidget(dockInterface->graphicalModelDock(), dockInterface->propertyEditorDock());
dockInterface->graphicalModelDock()->setWindowTitle(QObject::tr("Blocks"));
}
void Customizer::placeDevicesConfig(QWidget *devicesWidget)
{
QDockWidget *devicesDock = produceDockWidget(QObject::tr("Configure devices"), devicesWidget);
mDockInterface->addDockWidget(Qt::LeftDockWidgetArea, devicesDock);
}
void Customizer::placeWatchPlugins(QDockWidget *watchWindow, QWidget *graphicsWatch)
{
mDockInterface->addDockWidget(Qt::LeftDockWidgetArea, watchWindow);
watchWindow->setFloating(false);
QDockWidget *graphWatchDock = produceDockWidget(QObject::tr("Sensors state"), graphicsWatch);
mDockInterface->addDockWidget(Qt::LeftDockWidgetArea, graphWatchDock);
mDockInterface->tabifyDockWidget(watchWindow, graphWatchDock);
}
QDockWidget *Customizer::produceDockWidget(QString const &title, QWidget *content) const
{
QDockWidget *dock = new QDockWidget(title);
dock->setWidget(content);
return dock;
}
QString Customizer::userPaletteTitle() const
{
return QObject::tr("Subprograms");
}
QString Customizer::userPaletteDescription() const
{
return QObject::tr("The list of all declared subprograms in the project");
}
<|endoftext|>
|
<commit_before>#include <main.h>
#include <pidData.h>
/* *** Circular buffer for PID samples queued for logging *** */
// Indexes into pidSamples; Marks index of next data point to transmit to audacy
volatile unsigned int pidSentDataPointer = 0;
// If sentDataPointer == dataPointer, buffer is empty
// If dataPointer == sentDataPointer - 1, buffer is full
volatile unsigned int pidDataPointer = 0; // Marks index of next place to read into
volatile unsigned int pidSamplesSent = 0;
volatile pidSample pidSamples[PID_BUFFER_SIZE + 10]; // Add some extra space on the end in case we overflow
volatile bool sampling = false;
elapsedMicros timeSinceLastRead;
volatile pidDumpPacket_t pidDumpPacket;
volatile uint32_t* pidDumpPacketUints = (uint32_t *) &(pidDumpPacket.header);
volatile uint16_t pidPacketChecksum = 0;
volatile unsigned int pidPacketBodyPointer = 0;
volatile bool pidPacketReady = false;
// Telemetry
volatile unsigned int pidSamplesRead = 0;
volatile unsigned int pidSamplesQueued = 0;
void write32WithChecksum(const uint16_t& in, volatile uint32_t& out, volatile uint16_t& pidBufferChecksum) {
pidBufferChecksum += in;
out = in;
}
// Checksum is updated as samples are pushed into this buffer
void writeExpandedPidSampleWithChecksum(const pidSample* in, volatile expandedPidSample* out, volatile uint16_t& pidBufferChecksum) {
assert(sizeof(pidSample) * 2 == sizeof(expandedPidSample));
assert(sizeof(pidSample) == 4 * 4 * 3);
unsigned int num_uint32 = sizeof(pidSample) / 4;
for (unsigned int i = 0; i < num_uint32; i++) {
uint32_t num = ((uint32_t *) in)[i];
((uint32_t *) out)[2 * i] = num >> 16; // msb
pidBufferChecksum += num >> 16;
((uint32_t *) out)[2 * i + 1] = num % (1 << 16); // lsb
pidBufferChecksum += num % (1 << 16);
}
}
void populateHeader() {
write32WithChecksum(0, pidDumpPacket.p_x, pidPacketChecksum);
write32WithChecksum(1, pidDumpPacket.i_x, pidPacketChecksum);
write32WithChecksum(2, pidDumpPacket.d_x, pidPacketChecksum);
write32WithChecksum(3, pidDumpPacket.p_y, pidPacketChecksum);
write32WithChecksum(4, pidDumpPacket.i_y, pidPacketChecksum);
write32WithChecksum(5, pidDumpPacket.d_y, pidPacketChecksum);
write32WithChecksum(6, pidDumpPacket.last_x, pidPacketChecksum);
write32WithChecksum(7, pidDumpPacket.last_y, pidPacketChecksum);
write32WithChecksum(8, pidDumpPacket.set_x, pidPacketChecksum);
write32WithChecksum(9, pidDumpPacket.set_y, pidPacketChecksum);
}
bool pidBufferEmpty() {
return (pidSentDataPointer % PID_BUFFER_SIZE) == (pidDataPointer % PID_BUFFER_SIZE);
}
bool pidBufferFull() {
return ((pidDataPointer + 1) % PID_BUFFER_SIZE) == (pidSentDataPointer % PID_BUFFER_SIZE);
}
// Runs in main's setup()
void pidDataSetup() {
(void) assert(((unsigned int) pidDumpPacket.body) % 4 == 0); // Check offset; Misaligned data may segfault at 0x20000000
(void) assert(((unsigned int) pidSamples) % 4 == 0);
debugPrintf("pidSamples location (we want this to be far from 0x2000000): %p to %p\n", pidSamples, pidSamples + PID_BUFFER_SIZE);
debugPrintf("pidDumpPacket location (we want this to be far from 0x2000000): memory begins %p, samples %p to %p\n", &pidDumpPacket, pidDumpPacket.body, pidDumpPacket.abcdFooter + SpiSlave::ABCD_BUFFER_SIZE);
pinMode(PID_DATA_READY_PIN, OUTPUT);
for (int i = 0; i < 10; i++) {
((uint16_t *) &pidSamples[PID_BUFFER_SIZE])[i] = 0xbeef;
((uint16_t *) pidDumpPacket.abcdFooter)[SpiSlave::ABCD_BUFFER_SIZE + i] = 0xbeef;
}
for (int i = 0; i < SpiSlave::ABCD_BUFFER_SIZE; i++) {
pidDumpPacket.abcdHeader[i] = 0xabcd;
pidDumpPacket.abcdFooter[i] = 0xabcd;
}
assert ((uint32_t) pidSamples[PID_BUFFER_SIZE].sample.c == 0xbeefbeef);
}
/*void restartSamplingIfApplicable() {
noInterrupts();
if (pidBufferEmpty() && !sampling && !tryingToRestartSampling && !pidPacketReady) {
// Start sampling again!
pidPacketBodyPointer = 0;
pidPacketChecksum = 0;
tryingToRestartSampling = true;
}
interrupts();
}
*/
//void sentTriggerPacket() {
//}
/* *** Dequeues from pidSamples and moves samples into next packet *** */
void checkDataDump() {
noInterrupts();
unsigned int pidPacketBodyPointerSave = pidPacketBodyPointer;
unsigned int pidPacketReadySave = pidPacketReady;
if(!assert((pidPacketBodyPointerSave == PID_DATA_DUMP_SIZE) == pidPacketReadySave)) {
// Likely a race condition
debugPrintf("packetBodyPointer %d, ready? %d\n", pidPacketBodyPointerSave, pidPacketReadySave);
}
if (pidPacketReady) {
interrupts();
return;
}
noInterrupts();
if ((pidPacketBodyPointer < PID_DATA_DUMP_SIZE) && !pidBufferEmpty()) {
// Move a sample from large buffer to packet buffer
if (pidPacketBodyPointer == 0) {
populateHeader();
}
pidSample sample = pidSamples[pidSentDataPointer];
writeExpandedPidSampleWithChecksum(&sample, &(pidDumpPacket.body[pidPacketBodyPointer]), pidPacketChecksum);
pidPacketBodyPointer++;
pidSentDataPointer++;
}
pidSentDataPointer = pidSentDataPointer % PID_BUFFER_SIZE;
assert(pidPacketBodyPointer <= PID_DATA_DUMP_SIZE);
if (pidPacketBodyPointer >= PID_DATA_DUMP_SIZE) {
// Packet is ready!
noInterrupts();
assert((sizeof(pidSample) * 8) % 16 == 0);
pidPacketReady = true;
digitalWriteFast(PID_DATA_READY_PIN, HIGH);
}
interrupts();
}
// Enqueue pid sample for logging
void recordPid(const volatile pidSample& s) {
if (pidBufferEmpty()) {
sampling = true;
}
if (!sampling) {
return;
}
((pidSample *) pidSamples)[pidDataPointer] = s;
pidDataPointer = (pidDataPointer + 1) % PID_BUFFER_SIZE;
pidSamplesRead++;
assert(pidDataPointer <= PID_BUFFER_SIZE);
if (pidBufferFull()) {
sampling = false;
}
}
// Runs in main loop
void taskPidData() {
if (!assert ((uint32_t) pidSamples[PID_BUFFER_SIZE].sample.c == 0xbeefbeef)) {
debugPrintf("End of buf is %x\n", pidSamples[PID_BUFFER_SIZE].sample.c);
}
assert (pidDataPointer <= PID_BUFFER_SIZE);
assert (!(sampling && (pidDataPointer >= PID_BUFFER_SIZE)));
checkDataDump();
}
// Called from dma completion - clears packet buffer so we can prepare the next packet
void pidPacketSent() {
digitalWrite(PID_DATA_READY_PIN, LOW);
if ((assert(pidPacketReady))) {
noInterrupts();
pidPacketChecksum = 0;
pidPacketBodyPointer = 0;
pidPacketReady = false;
pidSamplesSent += PID_DATA_DUMP_SIZE;
interrupts();
}
}
// Called from enterTracking
void enterPidData() {
noInterrupts();
pidPacketChecksum = 0;
pidPacketReady = false;
pidSentDataPointer = 0;
pidDataPointer = 0;
timeSinceLastRead = 0;
pidPacketBodyPointer = 0;
sampling = true;
digitalWriteFast(PID_DATA_READY_PIN, LOW);
interrupts();
}
// Called from leaveTracking
void leavePidData() {
digitalWriteFast(PID_DATA_READY_PIN, LOW);
noInterrupts();
pidPacketReady = false;
sampling = false;
pidDataPointer = 0;
interrupts();
}
void pidDataHeartbeat() {
Serial.printf("PID front of buffer %d, back of buffer %d, packet ready? %d, chksum %d, packet pointer %d, sampling %d, packet %d, sent %d\n", pidDataPointer, pidSentDataPointer, pidPacketReady, pidPacketChecksum, pidPacketBodyPointer, sampling, pidPacketBodyPointer, pidSamplesSent);
}
<commit_msg>Updated pidData.cpp to insert dummy sample at discontinuities in logging<commit_after>#include <main.h>
#include <pidData.h>
/* *** Circular buffer for PID samples queued for logging *** */
// Indexes into pidSamples; Marks index of next data point to transmit to audacy
volatile unsigned int pidSentDataPointer = 0;
// If sentDataPointer == dataPointer, buffer is empty
// If dataPointer == sentDataPointer - 1, buffer is full
volatile unsigned int pidDataPointer = 0; // Marks index of next place to read into
volatile unsigned int pidSamplesSent = 0;
volatile pidSample pidSamples[PID_BUFFER_SIZE + 10]; // Add some extra space on the end in case we overflow
volatile bool sampling = false;
elapsedMicros timeSinceLastRead;
volatile pidDumpPacket_t pidDumpPacket;
volatile uint32_t* pidDumpPacketUints = (uint32_t *) &(pidDumpPacket.header);
volatile uint16_t pidPacketChecksum = 0;
volatile unsigned int pidPacketBodyPointer = 0;
volatile bool pidPacketReady = false;
// Telemetry
volatile unsigned int pidSamplesRead = 0;
volatile unsigned int pidSamplesQueued = 0;
void write32WithChecksum(const uint16_t& in, volatile uint32_t& out, volatile uint16_t& pidBufferChecksum) {
pidBufferChecksum += in;
out = in;
}
// Checksum is updated as samples are pushed into this buffer
void writeExpandedPidSampleWithChecksum(const pidSample* in, volatile expandedPidSample* out, volatile uint16_t& pidBufferChecksum) {
assert(sizeof(pidSample) * 2 == sizeof(expandedPidSample));
assert(sizeof(pidSample) == 4 * 4 * 3);
unsigned int num_uint32 = sizeof(pidSample) / 4;
for (unsigned int i = 0; i < num_uint32; i++) {
uint32_t num = ((uint32_t *) in)[i];
((uint32_t *) out)[2 * i] = num >> 16; // msb
pidBufferChecksum += num >> 16;
((uint32_t *) out)[2 * i + 1] = num % (1 << 16); // lsb
pidBufferChecksum += num % (1 << 16);
}
}
void populateHeader() {
write32WithChecksum(0, pidDumpPacket.p_x, pidPacketChecksum);
write32WithChecksum(1, pidDumpPacket.i_x, pidPacketChecksum);
write32WithChecksum(2, pidDumpPacket.d_x, pidPacketChecksum);
write32WithChecksum(3, pidDumpPacket.p_y, pidPacketChecksum);
write32WithChecksum(4, pidDumpPacket.i_y, pidPacketChecksum);
write32WithChecksum(5, pidDumpPacket.d_y, pidPacketChecksum);
write32WithChecksum(6, pidDumpPacket.last_x, pidPacketChecksum);
write32WithChecksum(7, pidDumpPacket.last_y, pidPacketChecksum);
write32WithChecksum(8, pidDumpPacket.set_x, pidPacketChecksum);
write32WithChecksum(9, pidDumpPacket.set_y, pidPacketChecksum);
}
bool pidBufferEmpty() {
return (pidSentDataPointer % PID_BUFFER_SIZE) == (pidDataPointer % PID_BUFFER_SIZE);
}
bool pidBufferFull() {
return ((pidDataPointer + 1) % PID_BUFFER_SIZE) == (pidSentDataPointer % PID_BUFFER_SIZE);
}
// Runs in main's setup()
void pidDataSetup() {
(void) assert(((unsigned int) pidDumpPacket.body) % 4 == 0); // Check offset; Misaligned data may segfault at 0x20000000
(void) assert(((unsigned int) pidSamples) % 4 == 0);
debugPrintf("pidSamples location (we want this to be far from 0x2000000): %p to %p\n", pidSamples, pidSamples + PID_BUFFER_SIZE);
debugPrintf("pidDumpPacket location (we want this to be far from 0x2000000): memory begins %p, samples %p to %p\n", &pidDumpPacket, pidDumpPacket.body, pidDumpPacket.abcdFooter + SpiSlave::ABCD_BUFFER_SIZE);
pinMode(PID_DATA_READY_PIN, OUTPUT);
for (int i = 0; i < 10; i++) {
((uint16_t *) &pidSamples[PID_BUFFER_SIZE])[i] = 0xbeef;
((uint16_t *) pidDumpPacket.abcdFooter)[SpiSlave::ABCD_BUFFER_SIZE + i] = 0xbeef;
}
for (int i = 0; i < SpiSlave::ABCD_BUFFER_SIZE; i++) {
pidDumpPacket.abcdHeader[i] = 0xabcd;
pidDumpPacket.abcdFooter[i] = 0xabcd;
}
assert ((uint32_t) pidSamples[PID_BUFFER_SIZE].sample.c == 0xbeefbeef);
}
/*void restartSamplingIfApplicable() {
noInterrupts();
if (pidBufferEmpty() && !sampling && !tryingToRestartSampling && !pidPacketReady) {
// Start sampling again!
pidPacketBodyPointer = 0;
pidPacketChecksum = 0;
tryingToRestartSampling = true;
}
interrupts();
}
*/
//void sentTriggerPacket() {
//}
/* *** Dequeues from pidSamples and moves samples into next packet *** */
void checkDataDump() {
noInterrupts();
unsigned int pidPacketBodyPointerSave = pidPacketBodyPointer;
unsigned int pidPacketReadySave = pidPacketReady;
if(!assert((pidPacketBodyPointerSave == PID_DATA_DUMP_SIZE) == pidPacketReadySave)) {
// Likely a race condition
debugPrintf("packetBodyPointer %d, ready? %d\n", pidPacketBodyPointerSave, pidPacketReadySave);
}
if (pidPacketReady) {
interrupts();
return;
}
noInterrupts();
if ((pidPacketBodyPointer < PID_DATA_DUMP_SIZE) && !pidBufferEmpty()) {
// Move a sample from large buffer to packet buffer
if (pidPacketBodyPointer == 0) {
populateHeader();
}
pidSample sample = pidSamples[pidSentDataPointer];
writeExpandedPidSampleWithChecksum(&sample, &(pidDumpPacket.body[pidPacketBodyPointer]), pidPacketChecksum);
pidPacketBodyPointer++;
pidSentDataPointer++;
}
pidSentDataPointer = pidSentDataPointer % PID_BUFFER_SIZE;
assert(pidPacketBodyPointer <= PID_DATA_DUMP_SIZE);
if (pidPacketBodyPointer >= PID_DATA_DUMP_SIZE) {
// Packet is ready!
noInterrupts();
assert((sizeof(pidSample) * 8) % 16 == 0);
pidPacketReady = true;
digitalWriteFast(PID_DATA_READY_PIN, HIGH);
}
interrupts();
}
// Enqueue pid sample for logging
void recordPid(const volatile pidSample& s) {
if (pidBufferEmpty() && !sampling) {
//restart sampling once buffer has been cleared
sampling = true;
//insert a dummy sample into the stream to indicate the break in sampling
pidSample fakeSample;
fakeSample.sample.a = 0x10;
fakeSample.sample.b = 0x11;
fakeSample.sample.c = 0x12;
fakeSample.sample.d = 0x13;
fakeSample.incoherentOutput.a = 0x14;
fakeSample.incoherentOutput.b = 0x14;
fakeSample.incoherentOutput.c = 0x14;
fakeSample.incoherentOutput.d = 0x14;
fakeSample.out.x = 0x13;
fakeSample.out.y = 0x12;
fakeSample.out.useless1 = 0x11;
fakeSample.out.useless2 = 0x10;
((pidSample *) pidSamples)[pidDataPointer] = fakeSample;
pidDataPointer = (pidDataPointer + 1) % PID_BUFFER_SIZE;
assert(pidDataPointer <= PID_BUFFER_SIZE);
if (pidBufferFull()) {
//buffer is full after one sample
sampling = false;
}
}
if (!sampling) {
return;
}
((pidSample *) pidSamples)[pidDataPointer] = s;
pidDataPointer = (pidDataPointer + 1) % PID_BUFFER_SIZE;
pidSamplesRead++;
assert(pidDataPointer <= PID_BUFFER_SIZE);
if (pidBufferFull()) {
sampling = false;
}
}
// Runs in main loop
void taskPidData() {
if (!assert ((uint32_t) pidSamples[PID_BUFFER_SIZE].sample.c == 0xbeefbeef)) {
debugPrintf("End of buf is %x\n", pidSamples[PID_BUFFER_SIZE].sample.c);
}
assert (pidDataPointer <= PID_BUFFER_SIZE);
assert (!(sampling && (pidDataPointer >= PID_BUFFER_SIZE)));
checkDataDump();
}
// Called from dma completion - clears packet buffer so we can prepare the next packet
void pidPacketSent() {
digitalWrite(PID_DATA_READY_PIN, LOW);
if ((assert(pidPacketReady))) {
noInterrupts();
pidPacketChecksum = 0;
pidPacketBodyPointer = 0;
pidPacketReady = false;
pidSamplesSent += PID_DATA_DUMP_SIZE;
interrupts();
}
}
// Called from enterTracking
void enterPidData() {
noInterrupts();
pidPacketChecksum = 0;
pidPacketReady = false;
pidSentDataPointer = 0;
pidDataPointer = 0;
timeSinceLastRead = 0;
pidPacketBodyPointer = 0;
sampling = true;
digitalWriteFast(PID_DATA_READY_PIN, LOW);
interrupts();
}
// Called from leaveTracking
void leavePidData() {
digitalWriteFast(PID_DATA_READY_PIN, LOW);
noInterrupts();
pidPacketReady = false;
sampling = false;
pidDataPointer = 0;
interrupts();
}
void pidDataHeartbeat() {
Serial.printf("PID front of buffer %d, back of buffer %d, packet ready? %d, chksum %d, packet pointer %d, sampling %d, packet %d, sent %d\n", pidDataPointer, pidSentDataPointer, pidPacketReady, pidPacketChecksum, pidPacketBodyPointer, sampling, pidPacketBodyPointer, pidSamplesSent);
}
<|endoftext|>
|
<commit_before>////////////////////////////////////////////////////////////////////////////////
//
// main.cpp
// Sophia
// Blake Nelson
//
// Driver for the unit tests.
//
////////////////////////////////////////////////////////////////////////////////
#include <boost/test/unit_test.hpp>
#include <boost/test/test_tools.hpp>
#include <boost/test/included/unit_test_framework.hpp>
#include <boost/test/floating_point_comparison.hpp>
using boost::unit_test_framework::test_suite;
#include <iostream>
using namespace std;
#include <LibUtilities/BasicUtils/NekManager.hpp>
#include <LibUtilities/Foundations/Points.h>
#include <LibUtilities/Foundations/GaussPoints.h>
#include <LibUtilities/Foundations/PolyEPoints.h>
#include <LibUtilities/Foundations/Basis.h>
#include <LibUtilities/Foundations/NodalTriFekete.h>
#include <LibUtilities/Foundations/ManagerAccess.h>
using namespace Nektar;
using namespace Nektar::LibUtilities;
namespace Nektar
{
namespace MyNewUnitTests
{
void simpleTest();
void testPolyFunc();
}
}
// The boost unit test framework provides the main function for us.
// All we need to do is provide a test suite.
test_suite* init_unit_test_suite( int, char* [] )
{
test_suite* test= BOOST_TEST_SUITE( "Nektar++ Test Suite" );
test->add(BOOST_TEST_CASE(&Nektar::MyNewUnitTests::simpleTest), 0);
test->add(BOOST_TEST_CASE(&Nektar::MyNewUnitTests::testPolyFunc),0);
return test;
}
namespace Nektar
{
namespace MyNewUnitTests
{
void simpleTest()
{
int size = 10;
//PointsKey gaussKey(size, eGaussLobattoLegendre);
PointsKey gaussKey(size, eGaussGaussLegendre);
PointsKey polyKey(size, ePolyEvenlySpaced);
boost::shared_ptr<Points<double> > ptr = PointsManager()[gaussKey];
boost::shared_ptr<NekMatrix<double> > mat = ptr->GetI(gaussKey);
int m = mat->GetRows();
int n = mat->GetColumns();
cout << "(m, n) = (" << m << ", " << n << ")" << endl;
BOOST_CHECK(mat->GetRows() == size); // Fails here
BOOST_CHECK(mat->GetColumns() == size);
Points<double> & points = *ptr;
cout << "points.GetPointsDim() = " << points.GetPointsDim() << endl;
cout << "points.GetNumPoints() = " << points.GetNumPoints() << endl;
cout << "points.GetTotNumPoints() = " << points.GetTotNumPoints() << endl;
double *z = points.GetZ();
for( int i=0; i<size; ++i )
{
cout << "z[i] = " << z[i] << endl;
}
cout << endl;
double *w = points.GetW();
for( int i=0; i<size; ++i )
{
cout << "w[i] = " << w[i] << endl;
}
cout << "Happy Testing!" << endl;
}
}
namespace TestUtilities
{
vector<double> generatePolynomial(int degree) {
double a[] = {
-1.3, 1.4, -1.5, 1.2, -1.3, 1.5, -0.1, 1.4, -3.2, 2.4, -1.0, 1.6, -1.3, 4.5,
1.3, 1.9, 1.6, 1.3, 1.4, 1.7, 1.9, 0.3, 1.6, // 23
1.2, 0.5, 1.0, 0.3, 0.5, 0.7, 0.4, 0.6 }; // 31
// double a[] = {
// 1, 1, 3, 3, 5, 5, 7, 7, 9, 9,
// 11,11,13, 13,15,15, 17,17,19, 19,
// 21,21,23, 23,25,25, 27,27,29, 29,
// 31,31,33, 33,35,35, 37,37,39, 39,
// 41,41,43, 43,45,45, 47,47,49, 49,
// 51,51,53, 53,55,55, 57,57,59, 59,
// 61
// };
vector<double> coefficients(a, a + degree + 1);
return coefficients;
}
// Evaluates at x the polynomial that is given by the coefficents
double evaluatePolynomial(double x, const vector<double> & coefficients) {
int N = coefficients.size();
double y = coefficients[N-1];
for( int i = N-2; i >= 0; --i ) {
y = coefficients[i] + x*y;
}
return y;
}
// Integrates the polynomial from [-1,1]
double integrate(const vector<double> & coefficients) {
int M = coefficients.size(), N = M - 1;
double integral = 0;
for( int n = 0; n <= N/2; ++n ) {
integral += coefficients[2*n] / (2.0*n + 1.0);
// if( N == 4 ) {
// cout << "N/2 = " << N/2 << ", 2*n = " << 2*n << ", coefficients[2*n] = " << coefficients[2*n] << ", (2*n + 1) = " << (2*n + 1) << ", coefficients[2*n] / (2*n + 1) = " << coefficients[2*n] / (2*n + 1) << endl;
// }
}
return 2.0 * integral;
}
void printPolynomial(const vector<double> & a) {
cout << a[0];
if( a.size() > 1 ) {
cout << " + " << a[1] << "x";
}
for( int n = 2; n < a.size(); ++n ) {
cout << " + " << a[n] << "x^" << n;
}
}
}
namespace MyNewUnitTests
{
void testPolynomialOnWeights(const boost::shared_ptr<Points<double> > points, const vector<double> & polynomialCoefficients) {
const double *z, *w;
points->GetZW(z, w);
int numPoints = points->GetNumPoints();
for(int i = 0; i < polynomialCoefficients.size(); ++i) {
vector<double> a( polynomialCoefficients.begin(), polynomialCoefficients.begin() + i + 1 );
double analyticIntegral = TestUtilities::integrate(a);
double numericIntegral = 0;
for(int j = 0; j < numPoints; ++j) {
numericIntegral += w[j] * TestUtilities::evaluatePolynomial( z[j], a );
}
cout << "Points = " << numPoints << ", Polynomial degree = " << i << ", nCoef = " << a.size();
cout << ", Integral = " << analyticIntegral << ", Computed area = " << numericIntegral;
// cout << ", P_" << i << " = "; TestUtilities::printPolynomial(a);
cout << endl;
BOOST_CHECK_CLOSE( numericIntegral, analyticIntegral, 1e-12 );
}
}
const int MaxNumberOfPoints = 15;
// const int MaxNumberOfPoints = 31;
void testPolyFunc()
{
// int P[] = {2,4,8,12};
// int N[] = {2,3,5,7};
vector<double> coefficients;
PointsType type;
BOOST_CHECKPOINT("Testing eGaussGaussLegendre");
type = eGaussGaussLegendre;
for( int i = 1; i < MaxNumberOfPoints; ++i ) {
int nPts = i, degree = 2*i - 1;
coefficients = TestUtilities::generatePolynomial(degree);
testPolynomialOnWeights( PointsManager()[PointsKey(nPts, type)], coefficients );
}
BOOST_CHECKPOINT("Testing eGaussLobattoLegendre");
type = eGaussLobattoLegendre;
for( int i = 1; i < MaxNumberOfPoints; ++i ) {
int nPts = i, degree = 2*i - 3;
coefficients = TestUtilities::generatePolynomial(degree);
testPolynomialOnWeights( PointsManager()[PointsKey(nPts, type)], coefficients );
}
}
}
}
/**
$Log: main.cpp,v $
Revision 1.2 2007/03/01 14:09:14 ehan
*** empty log message ***
Revision 1.1 2007/03/01 04:36:20 ehan
Kdevelop for UnitTest
Revision 1.1 2007/2/26 04:05:23 ehan
Added the NewUnitTest project.
**/
<commit_msg>test passed eGaussRadauMLegendre, eGaussRadauPLegendre, eGaussGaussLegendre, eGaussLobattoLegendre<commit_after>////////////////////////////////////////////////////////////////////////////////
//
// main.cpp
// Sophia
// Blake Nelson
//
// Driver for the unit tests.
//
////////////////////////////////////////////////////////////////////////////////
#include <boost/test/unit_test.hpp>
#include <boost/test/test_tools.hpp>
#include <boost/test/included/unit_test_framework.hpp>
#include <boost/test/floating_point_comparison.hpp>
using boost::unit_test_framework::test_suite;
#include <iostream>
using namespace std;
#include <LibUtilities/BasicUtils/NekManager.hpp>
#include <LibUtilities/Foundations/Points.h>
#include <LibUtilities/Foundations/GaussPoints.h>
#include <LibUtilities/Foundations/PolyEPoints.h>
#include <LibUtilities/Foundations/Basis.h>
#include <LibUtilities/Foundations/NodalTriFekete.h>
#include <LibUtilities/Foundations/ManagerAccess.h>
using namespace Nektar;
using namespace Nektar::LibUtilities;
namespace Nektar
{
namespace MyNewUnitTests
{
void simpleTest();
void testPolyFunc();
}
}
// The boost unit test framework provides the main function for us.
// All we need to do is provide a test suite.
test_suite* init_unit_test_suite( int, char* [] )
{
test_suite* test= BOOST_TEST_SUITE( "Nektar++ Test Suite" );
test->add(BOOST_TEST_CASE(&Nektar::MyNewUnitTests::simpleTest), 0);
test->add(BOOST_TEST_CASE(&Nektar::MyNewUnitTests::testPolyFunc),0);
return test;
}
namespace Nektar
{
namespace MyNewUnitTests
{
void simpleTest()
{
int size = 10;
//PointsKey gaussKey(size, eGaussLobattoLegendre);
PointsKey gaussKey(size, eGaussGaussLegendre);
PointsKey polyKey(size, ePolyEvenlySpaced);
boost::shared_ptr<Points<double> > ptr = PointsManager()[gaussKey];
boost::shared_ptr<NekMatrix<double> > mat = ptr->GetI(gaussKey);
int m = mat->GetRows();
int n = mat->GetColumns();
cout << "(m, n) = (" << m << ", " << n << ")" << endl;
BOOST_CHECK(mat->GetRows() == size); // Fails here
BOOST_CHECK(mat->GetColumns() == size);
Points<double> & points = *ptr;
cout << "points.GetPointsDim() = " << points.GetPointsDim() << endl;
cout << "points.GetNumPoints() = " << points.GetNumPoints() << endl;
cout << "points.GetTotNumPoints() = " << points.GetTotNumPoints() << endl;
double *z = points.GetZ();
for( int i=0; i<size; ++i )
{
cout << "z[i] = " << z[i] << endl;
}
cout << endl;
double *w = points.GetW();
for( int i=0; i<size; ++i )
{
cout << "w[i] = " << w[i] << endl;
}
cout << "Happy Testing!" << endl;
}
}
namespace TestUtilities
{
vector<double> generatePolynomial(int degree) {
double a[] = {
-1.3, 1.4, -1.5, 1.2, -1.3, 1.5, -0.1, 1.4, -3.2, 2.4, -1.0, 1.6, -1.3, 4.5,
1.3, 1.9, 1.6, 1.3, 1.4, 1.7, 1.9, 0.3, 1.6, // 23
1.2, 0.5, 1.0, 0.3, 0.5, 0.7, 0.4, 0.6 }; // 31
// double a[] = {
// 1, 1, 3, 3, 5, 5, 7, 7, 9, 9,
// 11,11,13, 13,15,15, 17,17,19, 19,
// 21,21,23, 23,25,25, 27,27,29, 29,
// 31,31,33, 33,35,35, 37,37,39, 39,
// 41,41,43, 43,45,45, 47,47,49, 49,
// 51,51,53, 53,55,55, 57,57,59, 59,
// 61
// };
vector<double> coefficients(a, a + degree + 1);
return coefficients;
}
// Evaluates at x the polynomial that is given by the coefficents
double evaluatePolynomial(double x, const vector<double> & coefficients) {
int N = coefficients.size();
double y = coefficients[N-1];
for( int i = N-2; i >= 0; --i ) {
y = coefficients[i] + x*y;
}
return y;
}
// Integrates the polynomial from [-1,1]
double integrate(const vector<double> & coefficients) {
int M = coefficients.size(), N = M - 1;
double integral = 0;
for( int n = 0; n <= N/2; ++n ) {
integral += coefficients[2*n] / (2.0*n + 1.0);
// if( N == 4 ) {
// cout << "N/2 = " << N/2 << ", 2*n = " << 2*n << ", coefficients[2*n] = " << coefficients[2*n] << ", (2*n + 1) = " << (2*n + 1) << ", coefficients[2*n] / (2*n + 1) = " << coefficients[2*n] / (2*n + 1) << endl;
// }
}
return 2.0 * integral;
}
void printPolynomial(const vector<double> & a) {
cout << a[0];
if( a.size() > 1 ) {
cout << " + " << a[1] << "x";
}
for( int n = 2; n < a.size(); ++n ) {
cout << " + " << a[n] << "x^" << n;
}
}
}
namespace MyNewUnitTests
{
void testPolynomialOnWeights(const boost::shared_ptr<Points<double> > points, const vector<double> & polynomialCoefficients, bool isVerbose = false) {
//bool isVerbose = false;
const double *z, *w;
points->GetZW(z, w);
int numPoints = points->GetNumPoints();
for(int i = 0; i < polynomialCoefficients.size(); ++i) {
vector<double> a( polynomialCoefficients.begin(), polynomialCoefficients.begin() + i + 1 );
double analyticIntegral = TestUtilities::integrate(a);
double numericIntegral = 0;
for(int j = 0; j < numPoints; ++j) {
numericIntegral += w[j] * TestUtilities::evaluatePolynomial( z[j], a );
}
if( isVerbose ) {
cout << "Points = " << numPoints << ", Polynomial degree = " << i << ", nCoef = " << a.size();
cout << ", Integral = " << analyticIntegral << ", Computed area = " << numericIntegral;
// cout << ", P_" << i << " = "; TestUtilities::printPolynomial(a);
cout << ", z[0] = " << z[0] << ", w[0] = " << w[0] << ", z[n-1] = " << z[numPoints-1] << ", w[n-1] = " << w[numPoints-1];
cout << endl;
}
//BOOST_CHECK_CLOSE( numericIntegral, analyticIntegral, 1e-12 );
BOOST_CHECK_CLOSE( numericIntegral, analyticIntegral, 1e-11 );
}
if( isVerbose ) {
cout << " End of the polynomial Unit Test" << endl;
}
}
const int MaxNumberOfPoints = 15;
void testPolyFunc()
{
vector<double> coefficients;
PointsType type;
const char * cp = "";
type = eGaussGaussLegendre;
cp = "Testing eGaussGaussLegendre";
cout << cp << endl;
BOOST_CHECKPOINT(cp);
for( int i = 1; i < MaxNumberOfPoints; ++i ) {
int nPts = i, n = nPts - 1, degree = 2*n + 1;
coefficients = TestUtilities::generatePolynomial(degree);
testPolynomialOnWeights( PointsManager()[PointsKey(nPts, type)], coefficients );
}
type = eGaussLobattoLegendre;
cp = "Testing eGaussLobattoLegendre";
cout << cp << endl;
BOOST_CHECKPOINT(cp);
for( int i = 1; i < MaxNumberOfPoints; ++i ) {
int nPts = i, n = nPts - 1, degree = 2*n - 1;
coefficients = TestUtilities::generatePolynomial(degree);
testPolynomialOnWeights( PointsManager()[PointsKey(nPts, type)], coefficients );
}
type = eGaussRadauMLegendre;
cp = "Testing eGaussRadauMLegendre";
cout << cp << endl;
BOOST_CHECKPOINT(cp);
for( int i = 1; i< MaxNumberOfPoints; ++i) {
int nPts = i, n = nPts - 1, degree = 2*n - 1;
coefficients = TestUtilities::generatePolynomial(degree);
testPolynomialOnWeights( PointsManager()[PointsKey(nPts, type)], coefficients );
}
type = eGaussRadauPLegendre;
cp = "Testing eGaussRadauPLegendre";
cout << cp << endl;
BOOST_CHECKPOINT(cp);
for( int i=1; i<MaxNumberOfPoints; ++i){
int nPts = i, n = nPts - 1, degree = 2*n;
coefficients = TestUtilities::generatePolynomial(degree);
testPolynomialOnWeights( PointsManager()[PointsKey(nPts, type)], coefficients, true );
}
}
}
}
// enum PointsType
// 00075 {
// 00076 eNoPointsType,
// 00077 eGaussGaussLegendre,
// 00078 eGaussRadauMLegendre,
// 00079 eGaussRadauPLegendre,
// 00080 eGaussLobattoLegendre,
// 00081 eGaussGaussChebyshev,
// 00082 eGaussRadauMChebyshev,
// 00083 eGaussRadauPChebyshev,
// 00084 eGaussLobattoChebyshev,
// 00085 eGaussRadauMAlpha0Beta1,
// 00086 eGaussRadauMAlpha0Beta2,
// 00087 ePolyEvenlySpaced,
// 00088 eFourierEvenlySpaced,
// 00089 eNodalTriElec,
// 00090 eNodalTriFekete,
// 00091 eNodalTetElec,
// 00092 SIZE_PointsType
// 00093 };
/**
$Log: main.cpp,v $
Revision 1.4 2007/03/02 01:10:44 ehan
fixed some bugs
Revision 1.2 2007/03/01 14:09:14 ehan
*** empty log message ***
Revision 1.1 2007/03/01 04:36:20 ehan
Kdevelop for UnitTest
Revision 1.1 2007/2/26 04:05:23 ehan
Added the NewUnitTest project.
**/
<|endoftext|>
|
<commit_before>#ifdef HAVE_CONFIG_H
#include <config.h>
#endif
#include <asio.hpp>
#include <ctime>
#include <cstring>
#include <vector>
#include <functional>
#include "common.hxx"
#include "auth.hxx"
#include "service.hxx"
#include "realm.hxx"
#include "client.hxx"
#include "packets.hxx"
using namespace std;
Client::Client(const Realm* realm_,
const asio::ip::udp::endpoint& ep)
: realm(realm_),
endpoint(ep),
online(false),
lastContact(time(NULL)),
advert(realm, endpoint),
advertIterator(realm),
isIteratingAdverts(false),
advertIterationTimer(service)
{ }
Client::Client(const Client& that)
: realm(that.realm),
endpoint(that.endpoint),
online(that.online),
lastContact(that.lastContact),
advert(that.advert),
advertIterator(that.advertIterator),
isIteratingAdverts(that.isIteratingAdverts),
advertIterationTimer(service)
{ }
bool Client::isOnline() const {
return online && time(NULL) < lastContact + CONNECTION_TIMEOUT;
}
void Client::kill() {
online = false;
}
const asio::ip::udp::endpoint& Client::getEndpoint() const {
return endpoint;
}
void (Client::*const Client::messages[256])(const byte*, unsigned) = {
&Client::connect,
&Client::ping,
&Client::proxy,
&Client::post,
&Client::list,
&Client::sign,
&Client::bye,
//NULLs to end of array are implicit
};
#define READ(type,from) (*(reinterpret_cast<const type*>(from)))
#define WRITE(type,to) (*(reinterpret_cast<type*>(to)))
void Client::connect(const byte* dat, unsigned len) {
contact();
//Check length sanity
if (len < 2*4 + HMAC_SIZE + 2 ||
len > 2*4 + HMAC_SIZE + MAX_CLIENT_NAME_LENGTH + 1)
return;
//Ensure NUL-terminated
if (dat[len-1]) return;
unsigned id = READ(unsigned, dat);
unsigned timestamp = READ(unsigned, dat+4);
byte hmac[HMAC_SIZE];
memcpy(hmac, dat+8, HMAC_SIZE);
const char* name = (const char*)(dat+8+HMAC_SIZE);
if (!*name) return; //Empty name
if (authenticate(realm, id, timestamp, name, hmac)) {
online = true;
this->id = id;
this->name = name;
//Send response
byte dontKnowWhoIAm = 1;
ping(&dontKnowWhoIAm, 1);
}
}
void Client::ping(const byte* dat, unsigned len) {
contact();
if (len == 1 && dat[0]) {
//Client needs to know its external address/port
vector<byte> response(1 + realm->addressSize + 2);
response[0] = PAK_YOUARE;
realm->encodeAddress(&response[1], endpoint.address());
WRITE(unsigned short, &response[response.size()-2]) = endpoint.port();
sendPacket(endpoint, &response[0], response.size());
} else {
//Just respond for the sake of two-way traffic
byte response = PAK_PONG;
sendPacket(endpoint, &response, 1);
}
}
void Client::proxy(const byte* dat, unsigned len) {
contact();
//TODO
}
void Client::post(const byte* dat, unsigned len) {
contact();
if (len > MAX_ADVERTISEMENT_SIZE)
return;
advert.setData(dat, len);
}
void Client::list(const byte* dat, unsigned len) {
contact();
if (isIteratingAdverts) return;
isIteratingAdverts = true;
setIterationTimer();
}
void Client::sign(const byte* dat, unsigned len) {
contact();
//TODO
}
void Client::bye(const byte* dat, unsigned len) {
contact();
online = false;
}
void Client::contact() {
lastContact = time(NULL);
}
//G++'s bind1st seems to be broken, as it tries to overload its operator() in a
//forbidden manner.
struct ClientTHBind1st {
Client* that;
void (*f)(Client*, const asio::error_code&);
void operator()(const asio::error_code& code) {
f(that, code);
}
};
void Client::setIterationTimer() {
advertIterationTimer.expires_from_now(boost::posix_time::milliseconds(512));
ClientTHBind1st f;
f.that = this;
f.f = &Client::timerHandler_static;
advertIterationTimer.async_wait(f);
}
void Client::timerHandler_static(Client* c, const asio::error_code& code) {
c->timerHandler(code);
}
void Client::timerHandler(const asio::error_code&) {
asio::ip::udp::endpoint from;
vector<byte> pack(1 + realm->addressSize + 2);
if (advertIterator.next(from, pack)) {
pack[0] = PAK_FROMOTHER;
realm->encodeAddress(&pack[1], from.address());
WRITE(unsigned short, &pack[1+realm->addressSize]) = from.port();
setIterationTimer();
} else {
isIteratingAdverts = false;
}
}
<commit_msg>Fix Client::timerHandler() not actually sending the packet.<commit_after>#ifdef HAVE_CONFIG_H
#include <config.h>
#endif
#include <asio.hpp>
#include <ctime>
#include <cstring>
#include <vector>
#include <functional>
#include "common.hxx"
#include "auth.hxx"
#include "service.hxx"
#include "realm.hxx"
#include "client.hxx"
#include "packets.hxx"
using namespace std;
Client::Client(const Realm* realm_,
const asio::ip::udp::endpoint& ep)
: realm(realm_),
endpoint(ep),
online(false),
lastContact(time(NULL)),
advert(realm, endpoint),
advertIterator(realm),
isIteratingAdverts(false),
advertIterationTimer(service)
{ }
Client::Client(const Client& that)
: realm(that.realm),
endpoint(that.endpoint),
online(that.online),
lastContact(that.lastContact),
advert(that.advert),
advertIterator(that.advertIterator),
isIteratingAdverts(that.isIteratingAdverts),
advertIterationTimer(service)
{ }
bool Client::isOnline() const {
return online && time(NULL) < lastContact + CONNECTION_TIMEOUT;
}
void Client::kill() {
online = false;
}
const asio::ip::udp::endpoint& Client::getEndpoint() const {
return endpoint;
}
void (Client::*const Client::messages[256])(const byte*, unsigned) = {
&Client::connect,
&Client::ping,
&Client::proxy,
&Client::post,
&Client::list,
&Client::sign,
&Client::bye,
//NULLs to end of array are implicit
};
#define READ(type,from) (*(reinterpret_cast<const type*>(from)))
#define WRITE(type,to) (*(reinterpret_cast<type*>(to)))
void Client::connect(const byte* dat, unsigned len) {
contact();
//Check length sanity
if (len < 2*4 + HMAC_SIZE + 2 ||
len > 2*4 + HMAC_SIZE + MAX_CLIENT_NAME_LENGTH + 1)
return;
//Ensure NUL-terminated
if (dat[len-1]) return;
unsigned id = READ(unsigned, dat);
unsigned timestamp = READ(unsigned, dat+4);
byte hmac[HMAC_SIZE];
memcpy(hmac, dat+8, HMAC_SIZE);
const char* name = (const char*)(dat+8+HMAC_SIZE);
if (!*name) return; //Empty name
if (authenticate(realm, id, timestamp, name, hmac)) {
online = true;
this->id = id;
this->name = name;
//Send response
byte dontKnowWhoIAm = 1;
ping(&dontKnowWhoIAm, 1);
}
}
void Client::ping(const byte* dat, unsigned len) {
contact();
if (len == 1 && dat[0]) {
//Client needs to know its external address/port
vector<byte> response(1 + realm->addressSize + 2);
response[0] = PAK_YOUARE;
realm->encodeAddress(&response[1], endpoint.address());
WRITE(unsigned short, &response[response.size()-2]) = endpoint.port();
sendPacket(endpoint, &response[0], response.size());
} else {
//Just respond for the sake of two-way traffic
byte response = PAK_PONG;
sendPacket(endpoint, &response, 1);
}
}
void Client::proxy(const byte* dat, unsigned len) {
contact();
//TODO
}
void Client::post(const byte* dat, unsigned len) {
contact();
if (len > MAX_ADVERTISEMENT_SIZE)
return;
advert.setData(dat, len);
}
void Client::list(const byte* dat, unsigned len) {
contact();
if (isIteratingAdverts) return;
isIteratingAdverts = true;
setIterationTimer();
}
void Client::sign(const byte* dat, unsigned len) {
contact();
//TODO
}
void Client::bye(const byte* dat, unsigned len) {
contact();
online = false;
}
void Client::contact() {
lastContact = time(NULL);
}
//G++'s bind1st seems to be broken, as it tries to overload its operator() in a
//forbidden manner.
struct ClientTHBind1st {
Client* that;
void (*f)(Client*, const asio::error_code&);
void operator()(const asio::error_code& code) {
f(that, code);
}
};
void Client::setIterationTimer() {
advertIterationTimer.expires_from_now(boost::posix_time::milliseconds(512));
ClientTHBind1st f;
f.that = this;
f.f = &Client::timerHandler_static;
advertIterationTimer.async_wait(f);
}
void Client::timerHandler_static(Client* c, const asio::error_code& code) {
c->timerHandler(code);
}
void Client::timerHandler(const asio::error_code&) {
asio::ip::udp::endpoint from;
vector<byte> pack(1 + realm->addressSize + 2);
if (advertIterator.next(from, pack)) {
pack[0] = PAK_FROMOTHER;
realm->encodeAddress(&pack[1], from.address());
WRITE(unsigned short, &pack[1+realm->addressSize]) = from.port();
sendPacket(endpoint, &pack[0], pack.size());
setIterationTimer();
} else {
isIteratingAdverts = false;
}
}
<|endoftext|>
|
<commit_before>/*
* Code Copyright 2011 Robert Hodgin ( http://roberthodgin.com ) and Andrew Bell ( http://drawnline.net )
* Used with permission for the Cinder Project ( http://libcinder.org )
*/
#include "cinder/app/AppBasic.h"
#include "cinder/Rand.h"
#include "cinder/ImageIo.h"
#include "cinder/gl/gl.h"
#include "cinder/gl/Texture.h"
#include "cinder/gl/TextureFont.h"
#include <list>
#include <algorithm>
#include "Resources.h"
#include "WordNode.h"
#include "Dictionary.h"
#include "CenterState.h"
using namespace ci;
using namespace ci::app;
using namespace std;
class VisualDictionaryApp : public AppBasic {
public:
void prepareSettings( Settings *settings );
void layoutWords( vector<string> words, float radius );
void setup();
void initialize();
void enableSelections() { mEnableSelections = true; }
void mouseMove( MouseEvent event );
void mouseDown( MouseEvent event );
void keyDown( KeyEvent event );
float getLayoutRadius(){ return getWindowHeight() * 0.415f; }
void selectNode( list<WordNode>::iterator selectedWord );
void update();
void draw();
list<WordNode>::iterator getNodeAtPoint( const Vec2f &point );
shared_ptr<Dictionary> mDictionary;
list<WordNode> mNodes, mDyingNodes;
list<WordNode>::iterator mMouseOverNode;
CenterState mCenterState;
gl::Texture mBgTex;
gl::Texture mCircleTex;
gl::Texture mSmallCircleTex;
bool mEnableSelections;
WordNode mCurrentNode;
float mCurrentCircleRadius;
};
void VisualDictionaryApp::prepareSettings( Settings *settings )
{
settings->setWindowSize( 800, 800 );
}
void VisualDictionaryApp::layoutWords( vector<string> words, float radius )
{
int radiusDivisor = 26;//std::max<int>( 10, words.size() ); // don't let the circles get too small
mCurrentCircleRadius = radius / radiusDivisor * M_PI;
for( size_t w = 0; w < words.size(); ++w ) {
int wordLength = words[w].length();
string s = words[w];
int charIndex = (int)s[wordLength-1] - 97;
float charPer = charIndex/26.0f;
float angle = charPer * 2.0f * M_PI;
//float angle = w / (float)words.size() * 2 * M_PI;
Vec2f pos = getWindowCenter() + radius * Vec2f( cos( angle ), sin( angle ) );
Color col( CM_HSV, charPer, 0.875f, 1 );
mNodes.push_back( WordNode( words[w] ) );
mNodes.back().mPos = getWindowCenter() + radius * 0.5f * Vec2f( cos( angle ), sin( angle ) );
mNodes.back().mColor = ColorA( col, 0.0f );
mNodes.back().mRadiusDest = mCurrentCircleRadius;
mNodes.back().mRadius = 0;
timeline().apply( &mNodes.back().mRadius, mNodes.back().mRadiusDest, 0.4f, EaseOutAtan( 10 ) ).timelineEnd( -0.39f );
timeline().apply( &mNodes.back().mPos, pos, 0.4f, EaseOutAtan( 10 ) ).timelineEnd( -0.39f );
timeline().apply( &mNodes.back().mColor, ColorA( col, 1.0f ), 0.4f, EaseOutAtan( 10 ) ).timelineEnd( -0.39f );
}
}
void VisualDictionaryApp::setup()
{
mCenterState = CenterState( 140.0f );
// load textures
mBgTex = gl::Texture( loadImage( loadResource( RES_BACKGROUND_IMAGE ) ) );
gl::Texture::Format fmt;
fmt.enableMipmapping();
mCircleTex = gl::Texture( loadImage( loadResource( RES_CIRCLE_IMAGE ) ), fmt );
mSmallCircleTex = gl::Texture( loadImage( loadResource( RES_SMALL_CIRCLE_IMAGE ) ), fmt );
// load the dictionary
mDictionary = shared_ptr<Dictionary>( new Dictionary( loadResource( RES_DICTIONARY ) ) );
// give the WordNodes their font
WordNode::setFont( gl::TextureFont::create( Font( loadResource( RES_FONT ), 34 ), gl::TextureFont::Format().enableMipmapping( true ) ) );
// give CenterState its font
CenterState::setFont( gl::TextureFont::create( Font( loadResource( RES_FONT ), 150 ), gl::TextureFont::Format().enableMipmapping( true ) ) );
initialize();
}
void VisualDictionaryApp::initialize()
{
mNodes.clear();
// make the first 26 nodes, one for each letter
vector<string> initialWords;
for( char c = 0; c < 26; ++c )
initialWords.push_back( string( 1, (char)('a' + c) ) );
layoutWords( initialWords, getLayoutRadius() );
mCenterState.mCircles.clear();
mCenterState.setWord( "" );
// mark our currently highlighted node as "none"
mMouseOverNode = mNodes.end();
mEnableSelections = true;
}
list<WordNode>::iterator VisualDictionaryApp::getNodeAtPoint( const Vec2f &point )
{
for( list<WordNode>::iterator nodeIt = mNodes.begin(); nodeIt != mNodes.end(); ++nodeIt ) {
if( nodeIt->isPointInside( point ) )
return nodeIt;
}
return mNodes.end();
}
void VisualDictionaryApp::keyDown( KeyEvent event )
{
if( ! mEnableSelections )
return;
if( isalpha( event.getChar() ) ){
// see if we can find a word that ends with this letter
list<WordNode>::iterator foundWord = mNodes.end();
for( foundWord = mNodes.begin(); foundWord != mNodes.end(); ++foundWord ) {
if( foundWord->getWord()[foundWord->getWord().size()-1] == event.getChar() )
break;
}
if( foundWord != mNodes.end() )
selectNode( foundWord );
} else {
if( event.getCode() == KeyEvent::KEY_BACKSPACE ){
initialize();
}
}
}
void VisualDictionaryApp::mouseDown( MouseEvent event )
{
list<WordNode>::iterator clickedNode = getNodeAtPoint( event.getPos() );
if( clickedNode != mNodes.end() ){
selectNode( clickedNode );
} else {
if( ( event.getPos() - getWindowCenter() ).length() < 180.0f )
initialize();
}
}
void VisualDictionaryApp::mouseMove( MouseEvent event )
{
if( ! mEnableSelections )
return;
list<WordNode>::iterator currentMouseOver = getNodeAtPoint( event.getPos() );
if( currentMouseOver != mMouseOverNode ) {
mMouseOverNode = currentMouseOver;
// make all the circles not moused-over normal size, and the mouse-over big
for( list<WordNode>::iterator nodeIt = mNodes.begin(); nodeIt != mNodes.end(); ++nodeIt ) {
if( mMouseOverNode == nodeIt ){
timeline().apply( &nodeIt->mRadius, mCurrentCircleRadius * 1.35f, 0.25f, EaseOutElastic( 2.0f, 1.2f ) );
} else {
timeline().apply( &nodeIt->mRadius, mCurrentCircleRadius, 0.5f, EaseOutAtan( 10 ) );
}
}
}
}
void VisualDictionaryApp::selectNode( list<WordNode>::iterator selectedNode )
{
// have all the nodes but this one disappear
for( list<WordNode>::iterator nodeIt = mNodes.begin(); nodeIt != mNodes.end(); ++nodeIt ) {
if( nodeIt != selectedNode ) {
// copy this node to dying nodes and erase it from the current
mDyingNodes.push_back( *nodeIt );
timeline().apply( &mDyingNodes.back().mRadius, 0.0f, 0.5f, EaseInQuint() )
.finishFn( bind( &WordNode::setShouldBeDeleted, &(mDyingNodes.back()) ) ); // when you're done, mark yourself for deletion
}
}
mCurrentNode = *selectedNode;
mCurrentNode.setSelected();
mNodes.clear();
Color c = Color( mCurrentNode.mColor().r, mCurrentNode.mColor().g, mCurrentNode.mColor().b );
Vec2f dirToCenter = ( mCurrentNode.mPos() - getWindowCenter() ) * 0.5f;
timeline().add( bind( &CenterState::addCircle, &mCenterState, mCurrentNode.getWord(), c, dirToCenter * 0.2f ), timeline().getCurrentTime() + 0.25f );
// move the selected node towards the center
timeline().apply( &mCurrentNode.mPos, getWindowCenter() + dirToCenter, 0.3f, EaseInQuint() );
timeline().apply( &mCurrentNode.mColor, ColorA( mCurrentNode.mColor().r, mCurrentNode.mColor().g, mCurrentNode.mColor().b, 0.0f ), 0.3f, EaseInAtan( 10 ) );
// now add all the descendants of the clicked node
vector<string> children( mDictionary->getDescendants( mCurrentNode.getWord() ) );
layoutWords( children, getLayoutRadius() );
// mark our currently highlighted node as "none"
mMouseOverNode = mNodes.end();
// once everything is done animating, then we can allow selections, but for now, disable them
mEnableSelections = false;
std::function<void()> cueAction = bind( &VisualDictionaryApp::enableSelections, this );
timeline().add( cueAction, timeline().getEndTime() - 2.0f );
}
void VisualDictionaryApp::update()
{
if( mDictionary->isCompleteWord( mCurrentNode.getWord() ) ){
mCenterState.update( mCurrentNode );
}
// erase any nodes which have been marked as ready to be deleted
mDyingNodes.remove_if( bind( &WordNode::shouldBeDeleted, _1 ) );
}
void VisualDictionaryApp::draw()
{
gl::clear( Color( 0, 0, 0 ) );
gl::enableAlphaBlending();
// draw background image
gl::color( Color::white() );
mBgTex.enableAndBind();
gl::drawSolidRect( getWindowBounds() );
mCircleTex.bind();
// draw the center circles
mCenterState.draw();
// draw the dying nodes
mSmallCircleTex.bind();
for( list<WordNode>::const_iterator nodeIt = mDyingNodes.begin(); nodeIt != mDyingNodes.end(); ++nodeIt )
nodeIt->draw();
// draw all the non-mouseOver nodes
for( list<WordNode>::const_iterator nodeIt = mNodes.begin(); nodeIt != mNodes.end(); ++nodeIt ){
if( nodeIt != mMouseOverNode )
nodeIt->draw();
}
// if there is a mouseOverNode, draw it last so it is 'above' the non-mouseOver nodes
if( mMouseOverNode != mNodes.end() )
mMouseOverNode->draw();
// if there is a currentNode (previously selected), draw it
if( ! mCurrentNode.getWord().empty() )
mCurrentNode.draw();
mSmallCircleTex.disable();
}
CINDER_APP_BASIC( VisualDictionaryApp, RendererGl )
<commit_msg>Fixed an issue with the timeline VisualDictionary sample, which did not compile in vs2010. Please check if this fix is compatible with MacOSX before merging it.<commit_after>/*
* Code Copyright 2011 Robert Hodgin ( http://roberthodgin.com ) and Andrew Bell ( http://drawnline.net )
* Used with permission for the Cinder Project ( http://libcinder.org )
*/
#include "cinder/app/AppBasic.h"
#include "cinder/Rand.h"
#include "cinder/ImageIo.h"
#include "cinder/gl/gl.h"
#include "cinder/gl/Texture.h"
#include "cinder/gl/TextureFont.h"
#include <list>
#include <algorithm>
#include "Resources.h"
#include "WordNode.h"
#include "Dictionary.h"
#include "CenterState.h"
using namespace ci;
using namespace ci::app;
using namespace std;
class VisualDictionaryApp : public AppBasic {
public:
void prepareSettings( Settings *settings );
void layoutWords( vector<string> words, float radius );
void setup();
void initialize();
void enableSelections() { mEnableSelections = true; }
void mouseMove( MouseEvent event );
void mouseDown( MouseEvent event );
void keyDown( KeyEvent event );
float getLayoutRadius(){ return getWindowHeight() * 0.415f; }
void selectNode( list<WordNode>::iterator selectedWord );
void update();
void draw();
list<WordNode>::iterator getNodeAtPoint( const Vec2f &point );
shared_ptr<Dictionary> mDictionary;
list<WordNode> mNodes, mDyingNodes;
list<WordNode>::iterator mMouseOverNode;
CenterState mCenterState;
gl::Texture mBgTex;
gl::Texture mCircleTex;
gl::Texture mSmallCircleTex;
bool mEnableSelections;
WordNode mCurrentNode;
float mCurrentCircleRadius;
};
void VisualDictionaryApp::prepareSettings( Settings *settings )
{
settings->setWindowSize( 800, 800 );
}
void VisualDictionaryApp::layoutWords( vector<string> words, float radius )
{
int radiusDivisor = 26;//std::max<int>( 10, words.size() ); // don't let the circles get too small
mCurrentCircleRadius = radius / radiusDivisor * M_PI;
for( size_t w = 0; w < words.size(); ++w ) {
int wordLength = words[w].length();
string s = words[w];
int charIndex = (int)s[wordLength-1] - 97;
float charPer = charIndex/26.0f;
float angle = charPer * 2.0f * M_PI;
//float angle = w / (float)words.size() * 2 * M_PI;
Vec2f pos = getWindowCenter() + radius * Vec2f( cos( angle ), sin( angle ) );
Color col( CM_HSV, charPer, 0.875f, 1 );
mNodes.push_back( WordNode( words[w] ) );
mNodes.back().mPos = getWindowCenter() + radius * 0.5f * Vec2f( cos( angle ), sin( angle ) );
mNodes.back().mColor = ColorA( col, 0.0f );
mNodes.back().mRadiusDest = mCurrentCircleRadius;
mNodes.back().mRadius = 0;
timeline().apply( &mNodes.back().mRadius, mNodes.back().mRadiusDest, 0.4f, EaseOutAtan( 10 ) ).timelineEnd( -0.39f );
timeline().apply( &mNodes.back().mPos, pos, 0.4f, EaseOutAtan( 10 ) ).timelineEnd( -0.39f );
timeline().apply( &mNodes.back().mColor, ColorA( col, 1.0f ), 0.4f, EaseOutAtan( 10 ) ).timelineEnd( -0.39f );
}
}
void VisualDictionaryApp::setup()
{
mCenterState = CenterState( 140.0f );
// load textures
mBgTex = gl::Texture( loadImage( loadResource( RES_BACKGROUND_IMAGE ) ) );
gl::Texture::Format fmt;
fmt.enableMipmapping();
mCircleTex = gl::Texture( loadImage( loadResource( RES_CIRCLE_IMAGE ) ), fmt );
mSmallCircleTex = gl::Texture( loadImage( loadResource( RES_SMALL_CIRCLE_IMAGE ) ), fmt );
// load the dictionary
mDictionary = shared_ptr<Dictionary>( new Dictionary( loadResource( RES_DICTIONARY ) ) );
// give the WordNodes their font
WordNode::setFont( gl::TextureFont::create( Font( loadResource( RES_FONT ), 34 ), gl::TextureFont::Format().enableMipmapping( true ) ) );
// give CenterState its font
CenterState::setFont( gl::TextureFont::create( Font( loadResource( RES_FONT ), 150 ), gl::TextureFont::Format().enableMipmapping( true ) ) );
initialize();
}
void VisualDictionaryApp::initialize()
{
mNodes.clear();
// make the first 26 nodes, one for each letter
vector<string> initialWords;
for( char c = 0; c < 26; ++c )
initialWords.push_back( string( 1, (char)('a' + c) ) );
layoutWords( initialWords, getLayoutRadius() );
mCenterState.mCircles.clear();
mCenterState.setWord( "" );
// mark our currently highlighted node as "none"
mMouseOverNode = mNodes.end();
mEnableSelections = true;
}
list<WordNode>::iterator VisualDictionaryApp::getNodeAtPoint( const Vec2f &point )
{
for( list<WordNode>::iterator nodeIt = mNodes.begin(); nodeIt != mNodes.end(); ++nodeIt ) {
if( nodeIt->isPointInside( point ) )
return nodeIt;
}
return mNodes.end();
}
void VisualDictionaryApp::keyDown( KeyEvent event )
{
if( ! mEnableSelections )
return;
if( isalpha( event.getChar() ) ){
// see if we can find a word that ends with this letter
list<WordNode>::iterator foundWord = mNodes.end();
for( foundWord = mNodes.begin(); foundWord != mNodes.end(); ++foundWord ) {
if( foundWord->getWord()[foundWord->getWord().size()-1] == event.getChar() )
break;
}
if( foundWord != mNodes.end() )
selectNode( foundWord );
} else {
if( event.getCode() == KeyEvent::KEY_BACKSPACE ){
initialize();
}
}
}
void VisualDictionaryApp::mouseDown( MouseEvent event )
{
list<WordNode>::iterator clickedNode = getNodeAtPoint( event.getPos() );
if( clickedNode != mNodes.end() ){
selectNode( clickedNode );
} else {
if( ( event.getPos() - getWindowCenter() ).length() < 180.0f )
initialize();
}
}
void VisualDictionaryApp::mouseMove( MouseEvent event )
{
if( ! mEnableSelections )
return;
list<WordNode>::iterator currentMouseOver = getNodeAtPoint( event.getPos() );
if( currentMouseOver != mMouseOverNode ) {
mMouseOverNode = currentMouseOver;
// make all the circles not moused-over normal size, and the mouse-over big
for( list<WordNode>::iterator nodeIt = mNodes.begin(); nodeIt != mNodes.end(); ++nodeIt ) {
if( mMouseOverNode == nodeIt ){
timeline().apply( &nodeIt->mRadius, mCurrentCircleRadius * 1.35f, 0.25f, EaseOutElastic( 2.0f, 1.2f ) );
} else {
timeline().apply( &nodeIt->mRadius, mCurrentCircleRadius, 0.5f, EaseOutAtan( 10 ) );
}
}
}
}
void VisualDictionaryApp::selectNode( list<WordNode>::iterator selectedNode )
{
// have all the nodes but this one disappear
for( list<WordNode>::iterator nodeIt = mNodes.begin(); nodeIt != mNodes.end(); ++nodeIt ) {
if( nodeIt != selectedNode ) {
// copy this node to dying nodes and erase it from the current
mDyingNodes.push_back( *nodeIt );
timeline().apply( &mDyingNodes.back().mRadius, 0.0f, 0.5f, EaseInQuint() )
.finishFn( bind( &WordNode::setShouldBeDeleted, &(mDyingNodes.back()) ) ); // when you're done, mark yourself for deletion
}
}
mCurrentNode = *selectedNode;
mCurrentNode.setSelected();
mNodes.clear();
Color c = Color( mCurrentNode.mColor().r, mCurrentNode.mColor().g, mCurrentNode.mColor().b );
Vec2f dirToCenter = ( mCurrentNode.mPos() - getWindowCenter() ) * 0.5f;
timeline().add( bind( &CenterState::addCircle, &mCenterState, mCurrentNode.getWord(), c, dirToCenter * 0.2f ), timeline().getCurrentTime() + 0.25f );
// move the selected node towards the center
timeline().apply( &mCurrentNode.mPos, getWindowCenter() + dirToCenter, 0.3f, EaseInQuint() );
timeline().apply( &mCurrentNode.mColor, ColorA( mCurrentNode.mColor().r, mCurrentNode.mColor().g, mCurrentNode.mColor().b, 0.0f ), 0.3f, EaseInAtan( 10 ) );
// now add all the descendants of the clicked node
vector<string> children( mDictionary->getDescendants( mCurrentNode.getWord() ) );
layoutWords( children, getLayoutRadius() );
// mark our currently highlighted node as "none"
mMouseOverNode = mNodes.end();
// once everything is done animating, then we can allow selections, but for now, disable them
mEnableSelections = false;
std::function<void()> cueAction = bind( &VisualDictionaryApp::enableSelections, this );
timeline().add( cueAction, timeline().getEndTime() - 2.0f );
}
void VisualDictionaryApp::update()
{
if( mDictionary->isCompleteWord( mCurrentNode.getWord() ) ){
mCenterState.update( mCurrentNode );
}
// erase any nodes which have been marked as ready to be deleted
mDyingNodes.remove_if( bind( &WordNode::shouldBeDeleted, std::placeholders::_1 ) );
}
void VisualDictionaryApp::draw()
{
gl::clear( Color( 0, 0, 0 ) );
gl::enableAlphaBlending();
// draw background image
gl::color( Color::white() );
mBgTex.enableAndBind();
gl::drawSolidRect( getWindowBounds() );
mCircleTex.bind();
// draw the center circles
mCenterState.draw();
// draw the dying nodes
mSmallCircleTex.bind();
for( list<WordNode>::const_iterator nodeIt = mDyingNodes.begin(); nodeIt != mDyingNodes.end(); ++nodeIt )
nodeIt->draw();
// draw all the non-mouseOver nodes
for( list<WordNode>::const_iterator nodeIt = mNodes.begin(); nodeIt != mNodes.end(); ++nodeIt ){
if( nodeIt != mMouseOverNode )
nodeIt->draw();
}
// if there is a mouseOverNode, draw it last so it is 'above' the non-mouseOver nodes
if( mMouseOverNode != mNodes.end() )
mMouseOverNode->draw();
// if there is a currentNode (previously selected), draw it
if( ! mCurrentNode.getWord().empty() )
mCurrentNode.draw();
mSmallCircleTex.disable();
}
CINDER_APP_BASIC( VisualDictionaryApp, RendererGl )
<|endoftext|>
|
<commit_before>#include <iostream> /* allows to perform standard input and output operations */
#include <fstream>
#include <stdio.h> /* Standard input/output definitions */
#include <stdint.h> /* Standard input/output definitions */
#include <stdlib.h> /* defines several general purpose functions */
#include <unistd.h> /* UNIX standard function definitions */
#include <fcntl.h> /* File control definitions */
#include <errno.h> /* Error number definitions */
#include <termios.h> /* POSIX terminal control definitions */
#include <ctype.h> /* isxxx() */
const char* serialport="/dev/ttyAMA0"; /* defines used serialport */
int serialport_bps=B38400; /* defines baudrate od serialport */
int32_t EncoderL; /* stores encoder value left read from md49 */
int32_t EncoderR; /* stores encoder value right read from md49 */
unsigned char speed_l=128, speed_r=128; /* speed to set for MD49 */
int filedesc; // File descriptor of serial port we will talk to
int fd; /* serial port file descriptor */
unsigned char serialBuffer[16]; /* Serial buffer to store uart data */
struct termios orig; // Port options
using namespace std;
int openSerialPort(const char * device, int bps);
void writeBytes(int descriptor, int count);
void readBytes(int descriptor, int count);
void read_MD49_Data (void);
void set_MD49_speed (unsigned char speed_l, unsigned char speed_r);
char* itoa(int value, char* result, int base) {
// check that the base if valid
if (base < 2 || base > 36) { *result = '\0'; return result; }
char* ptr = result, *ptr1 = result, tmp_char;
int tmp_value;
do {
tmp_value = value;
value /= base;
*ptr++ = "zyxwvutsrqponmlkjihgfedcba9876543210123456789abcdefghijklmnopqrstuvwxyz" [35 + (tmp_value - value * base)];
} while ( value );
// Apply negative sign
if (tmp_value < 0) *ptr++ = '-';
*ptr-- = '\0';
while(ptr1 < ptr) {
tmp_char = *ptr;
*ptr--= *ptr1;
*ptr1++ = tmp_char;
}
return result;
}
int main( int argc, char* argv[] ){
// Open serial port
// ****************
filedesc = openSerialPort("/dev/ttyAMA0", serialport_bps);
if (filedesc == -1) exit(1);
usleep(10000); // Sleep for UART to power up and set options
while( 1 )
{
// Read encoder and other data from MD49
// and put into sqlite db
// *************************************
read_MD49_Data();
usleep(250000);
// Read commands from sqlite db and
// set speed and other commands to MD49
// ************************************
}// end.mainloop
return 1;
} // end.main
int openSerialPort(const char * device, int bps){
struct termios neu;
char buf[128];
//fd = open(device, O_RDWR | O_NOCTTY | O_NDELAY | O_NONBLOCK);
fd = open(device, O_RDWR | O_NOCTTY);
if (fd == -1)
{
sprintf(buf, "openSerialPort %s error", device);
perror(buf);
}
else
{
tcgetattr(fd, &orig); /* save current serial settings */
tcgetattr(fd, &neu);
cfmakeraw(&neu);
//fprintf(stderr, "speed=%d\n", bps);
cfsetispeed(&neu, bps);
cfsetospeed(&neu, bps);
tcflush(fd, TCIFLUSH);
tcsetattr(fd, TCSANOW, &neu); /* set new serial settings */
fcntl (fd, F_SETFL, O_RDWR);
}
return fd;
}
void writeBytes(int descriptor, int count) {
if ((write(descriptor, serialBuffer, count)) == -1) { // Send data out
perror("Error writing");
close(descriptor); // Close port if there is an error
exit(1);
}
}
void readBytes(int descriptor, int count) {
if (read(descriptor, serialBuffer, count) == -1) { // Read back data into buf[]
perror("Error reading ");
close(descriptor); // Close port if there is an error
exit(1);
}
}
void read_MD49_Data (void){
serialBuffer[0] = 82; // 82=R Steuerbyte um alle Daten vom MD49 zu lesen
writeBytes(fd, 1);
//Daten lesen und in Array schreiben
readBytes(fd, 18);
ofstream myfile;
myfile.open ("example.txt");
//myfile << "Writing this to a file.\n";
char buffer[33];
printf("\033[2J"); /* clear the screen */
printf("\033[H"); /* position cursor at top-left corner */
printf ("MD49-Data read from AVR-Master: \n");
printf("====================================================== \n");
printf("Encoder1 Byte1: %i ",serialBuffer[0]);
myfile << itoa(serialBuffer[0],buffer,10);
myfile << "\n";
printf("Byte2: %i ",serialBuffer[1]);
myfile << itoa(serialBuffer[1],buffer,10);
myfile << "\n";
printf("Byte3: % i ",serialBuffer[2]);
myfile << itoa(serialBuffer[2],buffer,10);
myfile << "\n";
printf("Byte4: %i \n",serialBuffer[3]);
myfile << itoa(serialBuffer[3],buffer,10);
myfile << "\n";
printf("Encoder2 Byte1: %i ",serialBuffer[4]);
myfile << itoa(serialBuffer[4],buffer,10);
myfile << "\n";
printf("Byte2: %i ",serialBuffer[5]);
myfile << itoa(serialBuffer[5],buffer,10);
myfile << "\n";
printf("Byte3: %i ",serialBuffer[6]);
myfile << itoa(serialBuffer[6],buffer,10);
myfile << "\n";
printf("Byte4: %i \n",serialBuffer[7]);
myfile << itoa(serialBuffer[7],buffer,10);
myfile << "\n";
printf("EncoderL: %i ",EncoderL);
myfile << itoa(EncoderL,buffer,10);
myfile << "\n";
printf("EncoderR: %i \n",EncoderR);
myfile << itoa(EncoderR,buffer,10);
myfile << "\n";
printf("====================================================== \n");
printf("Speed1: %i ",serialBuffer[8]);
myfile << itoa(serialBuffer[8],buffer,10);
myfile << "\n";
printf("Speed2: %i \n",serialBuffer[9]);
myfile << itoa(serialBuffer[9],buffer,10);
myfile << "\n";
printf("Volts: %i \n",serialBuffer[10]);
myfile << itoa(serialBuffer[10],buffer,10);
myfile << "\n";
printf("Current1: %i ",serialBuffer[11]);
myfile << itoa(serialBuffer[11],buffer,10);
myfile << "\n";
printf("Current2: %i \n",serialBuffer[12]);
myfile << itoa(serialBuffer[12],buffer,10);
myfile << "\n";
printf("Error: %i \n",serialBuffer[13]);
myfile << itoa(serialBuffer[13],buffer,10);
myfile << "\n";
printf("Acceleration: %i \n",serialBuffer[14]);
myfile << itoa(serialBuffer[14],buffer,10);
myfile << "\n";
printf("Mode: %i \n",serialBuffer[15]);
myfile << itoa(serialBuffer[15],buffer,10);
myfile << "\n";
printf("Regulator: %i \n",serialBuffer[16]);
myfile << itoa(serialBuffer[16],buffer,10);
myfile << "\n";
printf("Timeout: %i \n",serialBuffer[17]);
myfile << itoa(serialBuffer[17],buffer,10);
myfile << "\n";
EncoderL = serialBuffer[0] << 24; // Put together first encoder value
EncoderL |= (serialBuffer[1] << 16);
EncoderL |= (serialBuffer[2] << 8);
EncoderL |= (serialBuffer[3]);
EncoderR = serialBuffer[4] << 24; // Put together second encoder value
EncoderR |= (serialBuffer[5] << 16);
EncoderR |= (serialBuffer[6] << 8);
EncoderR |= (serialBuffer[7]);
myfile.close();
}
void set_MD49_speed (unsigned char speed_l, unsigned char speed_r){
serialBuffer[0] = 88; // 88 =X Steuerbyte um Commands an MD49 zu senden
serialBuffer[1] = 115; // 115=s Steuerbyte setSpeed
serialBuffer[2] = speed_l; // speed1
serialBuffer[3] = speed_r; // speed2
writeBytes(fd, 4);
}
<commit_msg>Update code<commit_after>#include <iostream> /* allows to perform standard input and output operations */
#include <fstream>
#include <stdio.h> /* Standard input/output definitions */
#include <stdint.h> /* Standard input/output definitions */
#include <stdlib.h> /* defines several general purpose functions */
#include <unistd.h> /* UNIX standard function definitions */
#include <fcntl.h> /* File control definitions */
#include <errno.h> /* Error number definitions */
#include <termios.h> /* POSIX terminal control definitions */
#include <ctype.h> /* isxxx() */
const char* serialport="/dev/ttyAMA0"; /* defines used serialport */
int serialport_bps=B38400; /* defines baudrate od serialport */
int32_t EncoderL; /* stores encoder value left read from md49 */
int32_t EncoderR; /* stores encoder value right read from md49 */
unsigned char speed_l=128, speed_r=128; /* speed to set for MD49 */
int filedesc; // File descriptor of serial port we will talk to
int fd; /* serial port file descriptor */
unsigned char serialBuffer[16]; /* Serial buffer to store uart data */
struct termios orig; // Port options
using namespace std;
int openSerialPort(const char * device, int bps);
void writeBytes(int descriptor, int count);
void readBytes(int descriptor, int count);
void read_MD49_Data (void);
void set_MD49_speed (unsigned char speed_l, unsigned char speed_r);
char* itoa(int value, char* result, int base) {
// check that the base if valid
if (base < 2 || base > 36) { *result = '\0'; return result; }
char* ptr = result, *ptr1 = result, tmp_char;
int tmp_value;
do {
tmp_value = value;
value /= base;
*ptr++ = "zyxwvutsrqponmlkjihgfedcba9876543210123456789abcdefghijklmnopqrstuvwxyz" [35 + (tmp_value - value * base)];
} while ( value );
// Apply negative sign
if (tmp_value < 0) *ptr++ = '-';
*ptr-- = '\0';
while(ptr1 < ptr) {
tmp_char = *ptr;
*ptr--= *ptr1;
*ptr1++ = tmp_char;
}
return result;
}
int main( int argc, char* argv[] ){
// Open serial port
// ****************
filedesc = openSerialPort("/dev/ttyAMA0", serialport_bps);
if (filedesc == -1) exit(1);
usleep(10000); // Sleep for UART to power up and set options
while( 1 )
{
// Read encoder and other data from MD49
// and put into sqlite db
// *************************************
read_MD49_Data();
usleep(250000);
// Read commands from sqlite db and
// set speed and other commands to MD49
// ************************************
}// end.mainloop
return 1;
} // end.main
int openSerialPort(const char * device, int bps){
struct termios neu;
char buf[128];
//fd = open(device, O_RDWR | O_NOCTTY | O_NDELAY | O_NONBLOCK);
fd = open(device, O_RDWR | O_NOCTTY);
if (fd == -1)
{
sprintf(buf, "openSerialPort %s error", device);
perror(buf);
}
else
{
tcgetattr(fd, &orig); /* save current serial settings */
tcgetattr(fd, &neu);
cfmakeraw(&neu);
//fprintf(stderr, "speed=%d\n", bps);
cfsetispeed(&neu, bps);
cfsetospeed(&neu, bps);
tcflush(fd, TCIFLUSH);
tcsetattr(fd, TCSANOW, &neu); /* set new serial settings */
fcntl (fd, F_SETFL, O_RDWR);
}
return fd;
}
void writeBytes(int descriptor, int count) {
if ((write(descriptor, serialBuffer, count)) == -1) { // Send data out
perror("Error writing");
close(descriptor); // Close port if there is an error
exit(1);
}
}
void readBytes(int descriptor, int count) {
if (read(descriptor, serialBuffer, count) == -1) { // Read back data into buf[]
perror("Error reading ");
close(descriptor); // Close port if there is an error
exit(1);
}
}
void read_MD49_Data (void){
serialBuffer[0] = 82; // 82=R Steuerbyte um alle Daten vom MD49 zu lesen
writeBytes(fd, 1);
//Daten lesen und in Array schreiben
readBytes(fd, 18);
ofstream myfile;
myfile.open ("md49_data.txt");
//myfile << "Writing this to a file.\n";
char buffer[33];
printf("\033[2J"); /* clear the screen */
printf("\033[H"); /* position cursor at top-left corner */
printf ("MD49-Data read from AVR-Master: \n");
printf("====================================================== \n");
printf("Encoder1 Byte1: %i ",serialBuffer[0]);
myfile << itoa(serialBuffer[0],buffer,10);
myfile << "\n";
printf("Byte2: %i ",serialBuffer[1]);
myfile << itoa(serialBuffer[1],buffer,10);
myfile << "\n";
printf("Byte3: % i ",serialBuffer[2]);
myfile << itoa(serialBuffer[2],buffer,10);
myfile << "\n";
printf("Byte4: %i \n",serialBuffer[3]);
myfile << itoa(serialBuffer[3],buffer,10);
myfile << "\n";
printf("Encoder2 Byte1: %i ",serialBuffer[4]);
myfile << itoa(serialBuffer[4],buffer,10);
myfile << "\n";
printf("Byte2: %i ",serialBuffer[5]);
myfile << itoa(serialBuffer[5],buffer,10);
myfile << "\n";
printf("Byte3: %i ",serialBuffer[6]);
myfile << itoa(serialBuffer[6],buffer,10);
myfile << "\n";
printf("Byte4: %i \n",serialBuffer[7]);
myfile << itoa(serialBuffer[7],buffer,10);
myfile << "\n";
printf("EncoderL: %i ",EncoderL);
myfile << itoa(EncoderL,buffer,10);
myfile << "\n";
printf("EncoderR: %i \n",EncoderR);
myfile << itoa(EncoderR,buffer,10);
myfile << "\n";
printf("====================================================== \n");
printf("Speed1: %i ",serialBuffer[8]);
myfile << itoa(serialBuffer[8],buffer,10);
myfile << "\n";
printf("Speed2: %i \n",serialBuffer[9]);
myfile << itoa(serialBuffer[9],buffer,10);
myfile << "\n";
printf("Volts: %i \n",serialBuffer[10]);
myfile << itoa(serialBuffer[10],buffer,10);
myfile << "\n";
printf("Current1: %i ",serialBuffer[11]);
myfile << itoa(serialBuffer[11],buffer,10);
myfile << "\n";
printf("Current2: %i \n",serialBuffer[12]);
myfile << itoa(serialBuffer[12],buffer,10);
myfile << "\n";
printf("Error: %i \n",serialBuffer[13]);
myfile << itoa(serialBuffer[13],buffer,10);
myfile << "\n";
printf("Acceleration: %i \n",serialBuffer[14]);
myfile << itoa(serialBuffer[14],buffer,10);
myfile << "\n";
printf("Mode: %i \n",serialBuffer[15]);
myfile << itoa(serialBuffer[15],buffer,10);
myfile << "\n";
printf("Regulator: %i \n",serialBuffer[16]);
myfile << itoa(serialBuffer[16],buffer,10);
myfile << "\n";
printf("Timeout: %i \n",serialBuffer[17]);
myfile << itoa(serialBuffer[17],buffer,10);
myfile << "\n";
EncoderL = serialBuffer[0] << 24; // Put together first encoder value
EncoderL |= (serialBuffer[1] << 16);
EncoderL |= (serialBuffer[2] << 8);
EncoderL |= (serialBuffer[3]);
EncoderR = serialBuffer[4] << 24; // Put together second encoder value
EncoderR |= (serialBuffer[5] << 16);
EncoderR |= (serialBuffer[6] << 8);
EncoderR |= (serialBuffer[7]);
myfile.close();
}
void set_MD49_speed (unsigned char speed_l, unsigned char speed_r){
serialBuffer[0] = 88; // 88 =X Steuerbyte um Commands an MD49 zu senden
serialBuffer[1] = 115; // 115=s Steuerbyte setSpeed
serialBuffer[2] = speed_l; // speed1
serialBuffer[3] = speed_r; // speed2
writeBytes(fd, 4);
}
<|endoftext|>
|
<commit_before>#include <common.hpp>
int debugCount=0;
pair<float,float> HotspotPos[] = {
// TOP_LEFT,
{0.0,0.0},
// TOP,
{0.5,0.0},
// TOP_RIGHT,
{1.0,0.0},
// LEFT,
{0.0,0.5},
// CENTER,
{0.5,0.5},
// RIGHT,
{1.0,0.5},
// BOTTOM_LEFT,
{0.0,1.0},
// BOTTOM,
{0.5,1.0},
// BOTTOM_RIGHT
{1.0,1.0}
};
SDL_Color MakeColor(int r,int g,int b,int a) {
SDL_Color color;
color.r=r;
color.g=g;
color.b=b;
color.a=a;
return color;
}
bool equals(const float &a,const float &b) {
return (std::fabs((a-b))<=PRECISION);
}
float closeDist(const float &from,const float &to,const float &change) {
if (abs(from-to)<change)return to;
if (from>to)return from - change;
return from + change;
}
string FloatToStr(float f) {
char s[15];
sprintf(s,"%.2f",f);
return s;
}
<commit_msg>Applies Comments Technique to file common.cpp<commit_after>/*
* File: common.cpp
*
* Description: Implements common functions
*/
#include <common.hpp>
// Global variable used as debug counter
int debugCount = 0;
// Hotspot screen positions to be used as shortcuts
// The number on the left is x axis and the right one is y axis
pair<float,float> HotspotPos[] = {
// TOP_LEFT
{0.0,0.0},
// TOP
{0.5,0.0},
// TOP_RIGHT
{1.0,0.0},
// LEFT
{0.0,0.5},
// CENTER
{0.5,0.5},
// RIGHT
{1.0,0.5},
// BOTTOM_LEFT
{0.0,1.0},
// BOTTOM
{0.5,1.0},
// BOTTOM_RIGHT
{1.0,1.0}
};
// Returns a color generated by the params
SDL_Color MakeColor(int r, // red value, range: 0 -> 255
int g, // green value, range: 0 -> 255
int b, // blue value, range: 0 -> 255
int a) { // alpha value, range: unknown
SDL_Color color;
color.r = r;
color.g = g;
color.b = b;
color.a = a;
return color;
}
// Function that compares two float constants
// Returns true if the difference between them is <= than 0.0001 (PRECISION)
bool equals(const float &a, const float &b) {
return (std::fabs((a-b)) <= PRECISION);
}
// TODO: refactorate for better understanding
// Function that cannot be comprehended by mere human beings
float closeDist(const float &from, const float &to, const float &change) {
if (abs(from - to) < change) {
return to;
}
if (from > to) {
return from - change;
}
return from + change;
}
// Converts a float number to a string and returns it
string FloatToStr(float f) {
char s[15];
sprintf(s,"%.2f",f);
return s;
}
<|endoftext|>
|
<commit_before>/* IBM_PROLOG_BEGIN_TAG */
/* This is an automatically generated prolog. */
/* */
/* $Source: src/import/chips/p9/procedures/hwp/memory/p9_mss_draminit_training.C $ */
/* */
/* OpenPOWER HostBoot Project */
/* */
/* Contributors Listed Below - COPYRIGHT 2015,2019 */
/* [+] International Business Machines Corp. */
/* */
/* */
/* Licensed under the Apache License, Version 2.0 (the "License"); */
/* you may not use this file except in compliance with the License. */
/* You may obtain a copy of the License at */
/* */
/* http://www.apache.org/licenses/LICENSE-2.0 */
/* */
/* Unless required by applicable law or agreed to in writing, software */
/* distributed under the License is distributed on an "AS IS" BASIS, */
/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or */
/* implied. See the License for the specific language governing */
/* permissions and limitations under the License. */
/* */
/* IBM_PROLOG_END_TAG */
///
/// @file p9_mss_draminit_training.C
/// @brief Train dram
///
// *HWP HWP Owner: Brian Silver <bsilver@us.ibm.com>
// *HWP HWP Backup: Andre Marin <aamarin@us.ibm.com>
// *HWP Team: Memory
// *HWP Level: 2
// *HWP Consumed by: FSP:HB
#include <fapi2.H>
#include <mss.H>
#include <p9_mss_draminit_training.H>
using fapi2::TARGET_TYPE_MCBIST;
using fapi2::TARGET_TYPE_MCA;
extern "C"
{
///
/// @brief Train dram
/// @param[in] i_target, the McBIST of the ports of the dram you're training
/// @param[in] i_special_training, optional CAL_STEP_ENABLE override. Used in sim, debug
/// @return FAPI2_RC_SUCCESS iff ok
///
fapi2::ReturnCode p9_mss_draminit_training( const fapi2::Target<TARGET_TYPE_MCBIST>& i_target,
const uint16_t i_special_training )
{
fapi2::buffer<uint16_t> l_cal_steps_enabled = i_special_training;
FAPI_INF("Start draminit training");
uint8_t l_reset_disable = 0;
FAPI_TRY( mss::draminit_reset_disable(l_reset_disable) );
// Configure the CCS engine.
{
fapi2::buffer<uint64_t> l_ccs_config;
FAPI_TRY( mss::ccs::read_mode(i_target, l_ccs_config) );
// It's unclear if we want to run with this true or false. Right now (10/15) this
// has to be false. Shelton was unclear if this should be on or off in general BRS
mss::ccs::stop_on_err(i_target, l_ccs_config, false);
mss::ccs::ue_disable(i_target, l_ccs_config, false);
mss::ccs::copy_cke_to_spare_cke(i_target, l_ccs_config, true);
// Hm. Centaur sets this up for the longest duration possible. Can we do better?
mss::ccs::cal_count(i_target, l_ccs_config, ~0, ~0);
#ifndef JIM_SAYS_TURN_OFF_ECC
mss::ccs::disable_ecc(i_target, l_ccs_config);
#endif
FAPI_TRY( mss::ccs::write_mode(i_target, l_ccs_config) );
}
// Clean out any previous calibration results, set bad-bits and configure the ranks.
FAPI_DBG("MCA's on this McBIST: %d", i_target.getChildren<TARGET_TYPE_MCA>().size());
for( auto p : i_target.getChildren<TARGET_TYPE_MCA>())
{
mss::ccs::program<TARGET_TYPE_MCBIST, TARGET_TYPE_MCA> l_program;
// Setup a series of register probes which we'll see during the polling loop
// Leaving these probes in here as we need them from time to time, but they
// take up a lot of sim time, so we like to remove them simply
#ifdef TRAINING_POLLING_PROBES
l_program.iv_probes =
{
// One block for each DP16
{p, "wr_cntr_status0 (dp16 0)", MCA_DDRPHY_DP16_WR_CNTR_STATUS0_P0_0},
{p, "wr_cntr_status1 (dp16 0)", MCA_DDRPHY_DP16_WR_CNTR_STATUS1_P0_0},
{p, "wr_cntr_status2 (dp16 0)", MCA_DDRPHY_DP16_WR_CNTR_STATUS2_P0_0},
{p, "wr_lvl_status (dp16 0)", MCA_DDRPHY_DP16_WR_LVL_STATUS0_P0_0},
{p, "wr_cntr_status0 (dp16 1)", MCA_DDRPHY_DP16_WR_CNTR_STATUS0_P0_1},
{p, "wr_cntr_status1 (dp16 1)", MCA_DDRPHY_DP16_WR_CNTR_STATUS1_P0_1},
{p, "wr_cntr_status2 (dp16 1)", MCA_DDRPHY_DP16_WR_CNTR_STATUS2_P0_1},
{p, "wr_lvl_status (dp16 1)", MCA_DDRPHY_DP16_WR_LVL_STATUS0_P0_1},
{p, "wr_cntr_status0 (dp16 2)", MCA_DDRPHY_DP16_WR_CNTR_STATUS0_P0_2},
{p, "wr_cntr_status1 (dp16 2)", MCA_DDRPHY_DP16_WR_CNTR_STATUS1_P0_2},
{p, "wr_cntr_status2 (dp16 2)", MCA_DDRPHY_DP16_WR_CNTR_STATUS2_P0_2},
{p, "wr_lvl_status (dp16 2)", MCA_DDRPHY_DP16_WR_LVL_STATUS0_P0_2},
{p, "wr_cntr_status0 (dp16 3)", MCA_DDRPHY_DP16_WR_CNTR_STATUS0_P0_3},
{p, "wr_cntr_status1 (dp16 3)", MCA_DDRPHY_DP16_WR_CNTR_STATUS1_P0_3},
{p, "wr_cntr_status2 (dp16 3)", MCA_DDRPHY_DP16_WR_CNTR_STATUS2_P0_3},
{p, "wr_lvl_status (dp16 3)", MCA_DDRPHY_DP16_WR_LVL_STATUS0_P0_3},
{p, "wr_cntr_status0 (dp16 4)", MCA_DDRPHY_DP16_WR_CNTR_STATUS0_P0_4},
{p, "wr_cntr_status1 (dp16 4)", MCA_DDRPHY_DP16_WR_CNTR_STATUS1_P0_4},
{p, "wr_cntr_status2 (dp16 4)", MCA_DDRPHY_DP16_WR_CNTR_STATUS2_P0_4},
{p, "wr_lvl_status (dp16 4)", MCA_DDRPHY_DP16_WR_LVL_STATUS0_P0_4},
};
#endif
// Delays in the CCS instruction ARR1 for training are supposed to be 0xFFFF,
// and we're supposed to poll for the done or timeout bit. But we don't want
// to wait 0xFFFF cycles before we start polling - that's too long. So we put
// in a best-guess of how long to wait. This, in a perfect world, would be the
// time it takes one rank to train one training algorithm times the number of
// ranks we're going to train. We fail-safe as worst-case we simply poll the
// register too much - so we can tune this as we learn more.
l_program.iv_poll.iv_initial_sim_delay = mss::DELAY_100US;
l_program.iv_poll.iv_initial_sim_delay = 200;
l_program.iv_poll.iv_poll_count = 0xFFFF;
// Returned from set_rank_pairs, it tells us how many rank pairs
// we configured on this port.
std::vector<uint64_t> l_pairs;
#ifdef CAL_STATUS_DOESNT_REPORT_COMPLETE
// This isn't correct - shouldn't be setting
static const uint64_t CLEAR_CAL_COMPLETE = 0x000000000000F000;
FAPI_TRY( mss::putScom(p, MCA_DDRPHY_PC_INIT_CAL_STATUS_P0, CLEAR_CAL_COMPLETE) );
#endif
FAPI_TRY( mss::putScom(p, MCA_DDRPHY_PC_INIT_CAL_ERROR_P0, 0) );
FAPI_TRY( mss::putScom(p, MCA_DDRPHY_PC_INIT_CAL_CONFIG0_P0, 0) );
// Disable port fails as it doesn't appear the MC handles initial cal timeouts
// correctly (cal_length.) BRS, see conversation with Brad Michael
FAPI_TRY( mss::change_port_fail_disable(p, mss::ON ) );
// The following registers must be configured to the correct operating environment:
// Unclear, can probably be 0's for sim BRS
// • Section 5.2.5.10 SEQ ODT Write Configuration {0-3} on page 422
FAPI_TRY( mss::reset_seq_config0(p) );
FAPI_TRY( mss::reset_seq_rd_wr_data(p) );
FAPI_TRY( mss::reset_odt_config(p) );
// These are reset in phy_scominit
// • Section 5.2.6.1 WC Configuration 0 Register on page 434
// • Section 5.2.6.2 WC Configuration 1 Register on page 436
// • Section 5.2.6.3 WC Configuration 2 Register on page 438
// Get our rank pairs.
FAPI_TRY( mss::get_rank_pairs(p, l_pairs) );
// Setup the config register
//
// Grab the attribute which contains the information on what cal steps we should run
// if the i_specal_training bits have not been specified.
if (i_special_training == 0)
{
FAPI_TRY( mss::cal_step_enable(p, l_cal_steps_enabled) );
}
FAPI_DBG("cal steps enabled: 0x%x special training: 0x%x", l_cal_steps_enabled, i_special_training);
// Check to see if we're supposed to reset the delay values before starting training
// don't reset if we're running special training - assumes there's a checkpoint which has valid state.
if ((l_reset_disable == fapi2::ENUM_ATTR_MSS_DRAMINIT_RESET_DISABLE_ENABLE) && (i_special_training == 0))
{
FAPI_TRY( mss::dp16<TARGET_TYPE_MCA>().reset_delay_values(p, l_pairs) );
}
FAPI_DBG("generating calibration CCS instructions: %d rank-pairs", l_pairs.size());
// For each rank pair we need to calibrate, pop a ccs instruction in an array and execute it.
// NOTE: IF YOU CALIBRATE MORE THAN ONE RANK PAIR PER CCS PROGRAM, MAKE SURE TO CHANGE
// THE PROCESSING OF THE ERRORS. (it's hard to figure out which DIMM failed, too) BRS.
for (auto rp : l_pairs)
{
auto l_inst = mss::ccs::initial_cal_command<TARGET_TYPE_MCBIST>(rp);
FAPI_DBG("exeecuting training CCS instruction: 0x%llx, 0x%llx", l_inst.arr0, l_inst.arr1);
l_program.iv_instructions.push_back(l_inst);
// We need to figure out how long to wait before we start polling. Each cal step has an expected
// duration, so for each cal step which was enabled, we update the CCS program.
FAPI_TRY( mss::cal_timer_setup(p, l_program.iv_poll, l_cal_steps_enabled) );
FAPI_TRY( mss::setup_cal_config(p, rp, l_cal_steps_enabled) );
// In the event of an init cal hang, CCS_STATQ(2) will assert and CCS_STATQ(3:5) = “001” to indicate a
// timeout. Otherwise, if calibration completes, FW should inspect DDRPHY_FIR_REG bits (50) and (58)
// for signs of a calibration error. If either bit is on, then the DDRPHY_PC_INIT_CAL_ERROR register
// should be polled to determine which calibration step failed.
// If we got a cal timeout, or another CCS error just leave now. If we got success, check the error
// bits for a cal failure. We'll return the proper ReturnCode so all we need to do is FAPI_TRY.
FAPI_TRY( mss::ccs::execute(i_target, l_program, p) );
FAPI_TRY( mss::process_initial_cal_errors(p) );
}
}
fapi_try_exit:
FAPI_INF("End draminit training");
return fapi2::current_err;
}
}
<commit_msg>Change PHY PC, RC and DP16 register blocks to functional API<commit_after>/* IBM_PROLOG_BEGIN_TAG */
/* This is an automatically generated prolog. */
/* */
/* $Source: src/import/chips/p9/procedures/hwp/memory/p9_mss_draminit_training.C $ */
/* */
/* OpenPOWER HostBoot Project */
/* */
/* Contributors Listed Below - COPYRIGHT 2015,2019 */
/* [+] International Business Machines Corp. */
/* */
/* */
/* Licensed under the Apache License, Version 2.0 (the "License"); */
/* you may not use this file except in compliance with the License. */
/* You may obtain a copy of the License at */
/* */
/* http://www.apache.org/licenses/LICENSE-2.0 */
/* */
/* Unless required by applicable law or agreed to in writing, software */
/* distributed under the License is distributed on an "AS IS" BASIS, */
/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or */
/* implied. See the License for the specific language governing */
/* permissions and limitations under the License. */
/* */
/* IBM_PROLOG_END_TAG */
///
/// @file p9_mss_draminit_training.C
/// @brief Train dram
///
// *HWP HWP Owner: Brian Silver <bsilver@us.ibm.com>
// *HWP HWP Backup: Andre Marin <aamarin@us.ibm.com>
// *HWP Team: Memory
// *HWP Level: 2
// *HWP Consumed by: FSP:HB
#include <fapi2.H>
#include <mss.H>
#include <p9_mss_draminit_training.H>
using fapi2::TARGET_TYPE_MCBIST;
using fapi2::TARGET_TYPE_MCA;
extern "C"
{
///
/// @brief Train dram
/// @param[in] i_target, the McBIST of the ports of the dram you're training
/// @param[in] i_special_training, optional CAL_STEP_ENABLE override. Used in sim, debug
/// @return FAPI2_RC_SUCCESS iff ok
///
fapi2::ReturnCode p9_mss_draminit_training( const fapi2::Target<TARGET_TYPE_MCBIST>& i_target,
const uint16_t i_special_training )
{
fapi2::buffer<uint16_t> l_cal_steps_enabled = i_special_training;
FAPI_INF("Start draminit training");
uint8_t l_reset_disable = 0;
FAPI_TRY( mss::draminit_reset_disable(l_reset_disable) );
// Configure the CCS engine.
{
fapi2::buffer<uint64_t> l_ccs_config;
FAPI_TRY( mss::ccs::read_mode(i_target, l_ccs_config) );
// It's unclear if we want to run with this true or false. Right now (10/15) this
// has to be false. Shelton was unclear if this should be on or off in general BRS
mss::ccs::stop_on_err(i_target, l_ccs_config, false);
mss::ccs::ue_disable(i_target, l_ccs_config, false);
mss::ccs::copy_cke_to_spare_cke(i_target, l_ccs_config, true);
// Hm. Centaur sets this up for the longest duration possible. Can we do better?
mss::ccs::cal_count(i_target, l_ccs_config, ~0, ~0);
#ifndef JIM_SAYS_TURN_OFF_ECC
mss::ccs::disable_ecc(i_target, l_ccs_config);
#endif
FAPI_TRY( mss::ccs::write_mode(i_target, l_ccs_config) );
}
// Clean out any previous calibration results, set bad-bits and configure the ranks.
FAPI_DBG("MCA's on this McBIST: %d", i_target.getChildren<TARGET_TYPE_MCA>().size());
for( auto p : i_target.getChildren<TARGET_TYPE_MCA>())
{
mss::ccs::program<TARGET_TYPE_MCBIST, TARGET_TYPE_MCA> l_program;
// Setup a series of register probes which we'll see during the polling loop
// Leaving these probes in here as we need them from time to time, but they
// take up a lot of sim time, so we like to remove them simply
#ifdef TRAINING_POLLING_PROBES
l_program.iv_probes =
{
// One block for each DP16
{p, "wr_cntr_status0 (dp16 0)", MCA_DDRPHY_DP16_WR_CNTR_STATUS0_P0_0},
{p, "wr_cntr_status1 (dp16 0)", MCA_DDRPHY_DP16_WR_CNTR_STATUS1_P0_0},
{p, "wr_cntr_status2 (dp16 0)", MCA_DDRPHY_DP16_WR_CNTR_STATUS2_P0_0},
{p, "wr_lvl_status (dp16 0)", MCA_DDRPHY_DP16_WR_LVL_STATUS0_P0_0},
{p, "wr_cntr_status0 (dp16 1)", MCA_DDRPHY_DP16_WR_CNTR_STATUS0_P0_1},
{p, "wr_cntr_status1 (dp16 1)", MCA_DDRPHY_DP16_WR_CNTR_STATUS1_P0_1},
{p, "wr_cntr_status2 (dp16 1)", MCA_DDRPHY_DP16_WR_CNTR_STATUS2_P0_1},
{p, "wr_lvl_status (dp16 1)", MCA_DDRPHY_DP16_WR_LVL_STATUS0_P0_1},
{p, "wr_cntr_status0 (dp16 2)", MCA_DDRPHY_DP16_WR_CNTR_STATUS0_P0_2},
{p, "wr_cntr_status1 (dp16 2)", MCA_DDRPHY_DP16_WR_CNTR_STATUS1_P0_2},
{p, "wr_cntr_status2 (dp16 2)", MCA_DDRPHY_DP16_WR_CNTR_STATUS2_P0_2},
{p, "wr_lvl_status (dp16 2)", MCA_DDRPHY_DP16_WR_LVL_STATUS0_P0_2},
{p, "wr_cntr_status0 (dp16 3)", MCA_DDRPHY_DP16_WR_CNTR_STATUS0_P0_3},
{p, "wr_cntr_status1 (dp16 3)", MCA_DDRPHY_DP16_WR_CNTR_STATUS1_P0_3},
{p, "wr_cntr_status2 (dp16 3)", MCA_DDRPHY_DP16_WR_CNTR_STATUS2_P0_3},
{p, "wr_lvl_status (dp16 3)", MCA_DDRPHY_DP16_WR_LVL_STATUS0_P0_3},
{p, "wr_cntr_status0 (dp16 4)", MCA_DDRPHY_DP16_WR_CNTR_STATUS0_P0_4},
{p, "wr_cntr_status1 (dp16 4)", MCA_DDRPHY_DP16_WR_CNTR_STATUS1_P0_4},
{p, "wr_cntr_status2 (dp16 4)", MCA_DDRPHY_DP16_WR_CNTR_STATUS2_P0_4},
{p, "wr_lvl_status (dp16 4)", MCA_DDRPHY_DP16_WR_LVL_STATUS0_P0_4},
};
#endif
// Delays in the CCS instruction ARR1 for training are supposed to be 0xFFFF,
// and we're supposed to poll for the done or timeout bit. But we don't want
// to wait 0xFFFF cycles before we start polling - that's too long. So we put
// in a best-guess of how long to wait. This, in a perfect world, would be the
// time it takes one rank to train one training algorithm times the number of
// ranks we're going to train. We fail-safe as worst-case we simply poll the
// register too much - so we can tune this as we learn more.
l_program.iv_poll.iv_initial_sim_delay = mss::DELAY_100US;
l_program.iv_poll.iv_initial_sim_delay = 200;
l_program.iv_poll.iv_poll_count = 0xFFFF;
// Returned from set_rank_pairs, it tells us how many rank pairs
// we configured on this port.
std::vector<uint64_t> l_pairs;
#ifdef CAL_STATUS_DOESNT_REPORT_COMPLETE
// This isn't correct - shouldn't be setting
static const uint64_t CLEAR_CAL_COMPLETE = 0x000000000000F000;
FAPI_TRY( mss::putScom(p, MCA_DDRPHY_PC_INIT_CAL_STATUS_P0, CLEAR_CAL_COMPLETE) );
#endif
FAPI_TRY( mss::putScom(p, MCA_DDRPHY_PC_INIT_CAL_ERROR_P0, 0) );
FAPI_TRY( mss::putScom(p, MCA_DDRPHY_PC_INIT_CAL_CONFIG0_P0, 0) );
// Disable port fails as it doesn't appear the MC handles initial cal timeouts
// correctly (cal_length.) BRS, see conversation with Brad Michael
FAPI_TRY( mss::change_port_fail_disable(p, mss::ON ) );
// The following registers must be configured to the correct operating environment:
// Unclear, can probably be 0's for sim BRS
// • Section 5.2.5.10 SEQ ODT Write Configuration {0-3} on page 422
FAPI_TRY( mss::reset_seq_config0(p) );
FAPI_TRY( mss::reset_seq_rd_wr_data(p) );
FAPI_TRY( mss::reset_odt_config(p) );
// These are reset in phy_scominit
// • Section 5.2.6.1 WC Configuration 0 Register on page 434
// • Section 5.2.6.2 WC Configuration 1 Register on page 436
// • Section 5.2.6.3 WC Configuration 2 Register on page 438
// Get our rank pairs.
FAPI_TRY( mss::get_rank_pairs(p, l_pairs) );
// Setup the config register
//
// Grab the attribute which contains the information on what cal steps we should run
// if the i_specal_training bits have not been specified.
if (i_special_training == 0)
{
FAPI_TRY( mss::cal_step_enable(p, l_cal_steps_enabled) );
}
FAPI_DBG("cal steps enabled: 0x%x special training: 0x%x", l_cal_steps_enabled, i_special_training);
// Check to see if we're supposed to reset the delay values before starting training
// don't reset if we're running special training - assumes there's a checkpoint which has valid state.
if ((l_reset_disable == fapi2::ENUM_ATTR_MSS_DRAMINIT_RESET_DISABLE_ENABLE) && (i_special_training == 0))
{
FAPI_TRY( mss::dp16::reset_delay_values(p, l_pairs) );
}
FAPI_DBG("generating calibration CCS instructions: %d rank-pairs", l_pairs.size());
// For each rank pair we need to calibrate, pop a ccs instruction in an array and execute it.
// NOTE: IF YOU CALIBRATE MORE THAN ONE RANK PAIR PER CCS PROGRAM, MAKE SURE TO CHANGE
// THE PROCESSING OF THE ERRORS. (it's hard to figure out which DIMM failed, too) BRS.
for (auto rp : l_pairs)
{
auto l_inst = mss::ccs::initial_cal_command<TARGET_TYPE_MCBIST>(rp);
FAPI_DBG("exeecuting training CCS instruction: 0x%llx, 0x%llx", l_inst.arr0, l_inst.arr1);
l_program.iv_instructions.push_back(l_inst);
// We need to figure out how long to wait before we start polling. Each cal step has an expected
// duration, so for each cal step which was enabled, we update the CCS program.
FAPI_TRY( mss::cal_timer_setup(p, l_program.iv_poll, l_cal_steps_enabled) );
FAPI_TRY( mss::setup_cal_config(p, rp, l_cal_steps_enabled) );
// In the event of an init cal hang, CCS_STATQ(2) will assert and CCS_STATQ(3:5) = “001” to indicate a
// timeout. Otherwise, if calibration completes, FW should inspect DDRPHY_FIR_REG bits (50) and (58)
// for signs of a calibration error. If either bit is on, then the DDRPHY_PC_INIT_CAL_ERROR register
// should be polled to determine which calibration step failed.
// If we got a cal timeout, or another CCS error just leave now. If we got success, check the error
// bits for a cal failure. We'll return the proper ReturnCode so all we need to do is FAPI_TRY.
FAPI_TRY( mss::ccs::execute(i_target, l_program, p) );
FAPI_TRY( mss::process_initial_cal_errors(p) );
}
}
fapi_try_exit:
FAPI_INF("End draminit training");
return fapi2::current_err;
}
}
<|endoftext|>
|
<commit_before>//------------------------------------------------------------------------------
// File: mframework.hpp
//
// Desc: Data Mining Framework.
//
// Copyright (c) 2014-2018. veyesys.com All rights reserved.
//------------------------------------------------------------------------------
#ifndef __M_FRAME_WORK_HPP__
#define __M_FRAME_WORK_HPP__
#include "utility.hpp"
#include "debug.hpp"
#include "videotype.hpp"
#include "miningtype.hpp"
#include "mmodule.hpp"
#include "factory.hpp"
#include <QThread>
#include <qdebug.h>
#include "cppkit/ck_string.h"
#include "cppkit/ck_memory.h"
#include "cppkit/ck_command_queue.h"
#include "cppkit/ck_dynamic_library.h"
#include "cppkit/ck_byte_ptr.h"
using namespace std;
using namespace cppkit;
/* All the mining data will be post a queue to here,
Then start a thread to peek the queue to post to each device in factory
*/
typedef command_queue<MiningRet> MModuleRetQueue;
typedef std::map<int, MiningModule *> MModuleMap;
class MFramework:public QThread
{
Q_OBJECT
public:
inline MFramework(Factory &pFactory);
inline ~MFramework();
public:
inline void run();
public:
inline static BOOL RetHandler(s32 id, MiningRet& ret, void * pParam);
inline BOOL RetHandler1(s32 id, MiningRet& ret);
private:
MModuleMap m_MModules;
MModuleRetQueue m_RetQueue;
BOOL m_bExit;
};
BOOL MFramework::RetHandler(s32 id, MiningRet& ret, void * pParam)
{
int dummy = errno;
MFramework *pMFramework = (MFramework)pParam;
if (pMFramework)
{
return pMFramework->RetHandler1(id, ret);
}
return TRUE;
}
BOOL MFramework::RetHandler1(s32 id, MiningRet& ret)
{
m_RetQueue.post(ret);
return TRUE;
}
void MFramework::run()
{
MiningRet ret;
while (m_bExit != TRUE)
{
if (m_RetQueue.size() > 0)
{
ret = m_RetQueue.pop();
//send the ret va data to factory for showing
continue;
}else
{
ve_sleep(1000);
}
}
return;
}
#endif /* __M_FRAME_WORK_HPP__ */
<commit_msg>add device change api<commit_after>//------------------------------------------------------------------------------
// File: mframework.hpp
//
// Desc: Data Mining Framework.
//
// Copyright (c) 2014-2018. veyesys.com All rights reserved.
//------------------------------------------------------------------------------
#ifndef __M_FRAME_WORK_HPP__
#define __M_FRAME_WORK_HPP__
#include "utility.hpp"
#include "debug.hpp"
#include "videotype.hpp"
#include "miningtype.hpp"
#include "mmodule.hpp"
#include "factory.hpp"
#include <QThread>
#include <qdebug.h>
#include "cppkit/ck_string.h"
#include "cppkit/ck_memory.h"
#include "cppkit/ck_command_queue.h"
#include "cppkit/ck_dynamic_library.h"
#include "cppkit/ck_byte_ptr.h"
using namespace std;
using namespace cppkit;
/* All the mining data will be post a queue to here,
Then start a thread to peek the queue to post to each device in factory
*/
typedef command_queue<MiningRet> MModuleRetQueue;
typedef std::map<int, MiningModule *> MModuleMap;
class MFramework:public QThread
{
Q_OBJECT
public:
inline MFramework(Factory &pFactory);
inline ~MFramework();
public:
inline void run();
public:
inline static BOOL RetHandler(s32 id, MiningRet& ret, void * pParam);
inline BOOL RetHandler1(s32 id, MiningRet& ret);
public:
static BOOL DeviceChangeCallbackFunc(void* pData, FactoryDeviceChangeData change);
BOOL DeviceChangeCallbackFunc1(FactoryDeviceChangeData change);
private:
MModuleMap m_MModules;
MModuleRetQueue m_RetQueue;
BOOL m_bExit;
};
BOOL MFramework::RetHandler(s32 id, MiningRet& ret, void * pParam)
{
int dummy = errno;
MFramework *pMFramework = (MFramework)pParam;
if (pMFramework)
{
return pMFramework->RetHandler1(id, ret);
}
return TRUE;
}
BOOL MFramework::RetHandler1(s32 id, MiningRet& ret)
{
m_RetQueue.post(ret);
return TRUE;
}
void MFramework::run()
{
MiningRet ret;
while (m_bExit != TRUE)
{
if (m_RetQueue.size() > 0)
{
ret = m_RetQueue.pop();
//send the ret va data to factory for showing
continue;
}else
{
ve_sleep(1000);
}
}
return;
}
bool MFramework::DeviceChangeCallbackFunc(void* pData,
FactoryDeviceChangeData change)
{
if (pData)
{
MFramework * pthread = (MFramework *)pData;
pthread->DeviceChangeCallbackFunc1(change);
}
return true;
}
bool MFramework::DeviceChangeCallbackFunc1(FactoryDeviceChangeData change)
{
VDC_DEBUG( "Event Device Change Callback %d type %d Begin\n", change.id, change.type);
if (change.type == FACTORY_DEVICE_OFFLINE)
{
}
if (change.type == FACTORY_DEVICE_ONLINE)
{
}
VDC_DEBUG( "Event Device Change Callback %d type %d End \n", change.id, change.type);
return TRUE;
}
#endif /* __M_FRAME_WORK_HPP__ */
<|endoftext|>
|
<commit_before>/************************************************************************************
**
* @copyright (c) 2013-2100, ChengDu Duyer Technology Co., LTD. All Right Reserved.
*
*************************************************************************************/
/**
* @GFile g_file.cpp
* @version
* @brief
* @author duye
* @date 2013-06-20
* @note
*
* 1. 2013-06-20 duye Created this GFile
*
*/
#include <stdarg.h>
#include <fcntl.h>
#include <unistd.h>
#include <string.h>
#include <g_file.h>
using namespace gsys;
// default create GFile permissions
static const GUint32 G_FILE_MASK = 0x775;
GResult FileUtil::createFile(const GInt8* filePath)
{
return createFile(filePath, 0);
}
GResult FileUtil::createFile(const GInt8* filePath, const GUint64& initSize)
{
GInt32 fd = ::creat(filePath, G_FILE_MASK);
if (fd == -1)
{
return G_NO;
}
if (ftruncate(fd, initSize) == -1)
{
::close(fd);
return G_NO;
}
::close(fd);
return G_YES;
}
bool FileUtil::isExist(const GInt8* filePath)
{
if (filePath == nullptr)
{
return false;
}
if (access(filePath, 0) < 0)
{
return false;
}
return true;
}
GResult FileUtil::removeFile(const GInt8* filePath)
{
if (filePath == nullptr)
{
return G_NO;
}
GInt8 cmd[128] = {0};
sprintf(cmd, "rm %s -f", filePath);
return System::shell(cmd);
}
File::File() : m_fd(-1), m_flags(0), m_pathLen(0)
{
m_error[0] = 0;
m_path[0] = 0;
}
File::File(const GInt8* filePath) : m_fd(-1), m_flags(0), m_pathLen(0)
{
GUint32 len = strlen(filePath);
if (len < G_PATH_MAX)
{
memcpy(m_path, filePath, len);
m_path[len] = 0;
m_pathLen = len;
}
m_error[0] = 0;
}
File::~File()
{
close();
}
GResult File::open(const FileOpenFlags fileOpenFlags)
{
return open(fileOpenFlags, G_FILE_MASK);
}
GResult File::open(const FileOpenFlags fileOpenFlags, const GInt32 mode)
{
GInt32 openFlags = 0;
if (fileOpenFlags | G_OPEN_READ)
{
openFlags = O_RDONLY;
}
else if (fileOpenFlags | G_OPEN_WRITE)
{
openFlags = O_WRONLY | O_CREAT;
}
else if (fileOpenFlags | G_OPEN_RDWR)
{
openFlags = O_RDWR | O_CREAT;
}
else if (fileOpenFlags | G_OPEN_APPEND)
{
if (openFlags == 0)
{
return G_NO;
}
openFlags |= O_APPEND;
}
if (openFlags == 0)
{
setError("input open mode error");
return G_NO;
}
return orgOpen(openFlags, mode);
}
GResult File::close()
{
if (m_fd < 0)
{
setError("file don't open");
return G_NO;
}
GResult ret = (::close(m_fd) != -1 ? G_YES : G_NO);
m_fd = -1;
m_path[0] = 0;
m_flags = 0;
return ret;
}
GInt64 File::getSize()
{
if (m_fd <= 0)
{
setError("file don't open");
return G_NO;
}
struct stat fileStat;
fstat(m_fd, &fileStat);
return (GInt64)(fileStat.st_size);
}
GInt64 File::seek(const GInt64 offset, const FileSeekFlags& flags)
{
if (m_fd <= 0)
{
setError("file don't open");
return G_NO;
}
GInt32 sysFlags = -1;
switch(flags)
{
case G_SEEK_BEG:
sysFlags = SEEK_SET;
break;
case G_SEEK_CUR:
sysFlags = SEEK_CUR;
break;
case G_SEEK_END:
sysFlags = SEEK_END;
break;
default:
return G_NO;
break;
}
return ::lseek(m_fd, offset, sysFlags);
}
GInt64 File::tell()
{
return seek(0, G_SEEK_CUR);
}
GInt64 File::read(GInt8* buffer, const GUint64 size)
{
if (buffer == NULL || size <= 0)
{
setError("input parameter is error");
return G_NO;
}
if (m_fd <= 0)
{
setError("file don't open");
return G_NO;
}
return ::read(m_fd, buffer, size);
}
GInt64 File::write(const GInt8* data, const GUint64 length)
{
if (data == NULL || length <= 0)
{
setError("input parameter is error");
return G_NO;
}
if (m_fd <= 0)
{
setError("file don't open");
return G_NO;
}
return ::write(m_fd, data, length);
}
GInt8* File::getError()
{
return m_error;
}
GResult File::orgOpen(const GInt32 flags, const GUint32 mode)
{
if (m_fd > 0)
{
setError("file had opened");
return G_NO;
}
if (m_pathLen == 0)
{
setError("hasn't set file path");
return G_NO;
}
m_fd = ::open(m_path, flags, mode);
if (m_fd > 0)
{
m_flags = flags;
}
else
{
setError("open file failed, check whether exist this file path");
}
return (m_fd != -1 ? true : false);
}
void File::setError(const GInt8* args, ...)
{
System::pformat(m_error, G_ERROR_BUF_SIZE, args);
}
<commit_msg>Update g_file.cpp<commit_after>/************************************************************************************
**
* @copyright (c) 2013-2100, ChengDu Duyer Technology Co., LTD. All Right Reserved.
*
*************************************************************************************/
/**
* @GFile g_file.cpp
* @version
* @brief
* @author duye
* @date 2013-06-20
* @note
*
* 1. 2013-06-20 duye Created this GFile
*
*/
#include <stdarg.h>
#include <fcntl.h>
#include <unistd.h>
#include <string.h>
#include <g_file.h>
namespace gsys {
// default create GFile permissions
static const GUint32 G_FILE_MASK = 0x775;
GResult FileUtil::createFile(const GInt8* filePath)
{
return createFile(filePath, 0);
}
GResult FileUtil::createFile(const GInt8* filePath, const GUint64& initSize)
{
GInt32 fd = ::creat(filePath, G_FILE_MASK);
if (fd == -1)
{
return G_NO;
}
if (ftruncate(fd, initSize) == -1)
{
::close(fd);
return G_NO;
}
::close(fd);
return G_YES;
}
bool FileUtil::isExist(const GInt8* filePath)
{
if (filePath == nullptr)
{
return false;
}
if (access(filePath, 0) < 0)
{
return false;
}
return true;
}
GResult FileUtil::removeFile(const GInt8* filePath)
{
if (filePath == nullptr)
{
return G_NO;
}
GInt8 cmd[128] = {0};
sprintf(cmd, "rm %s -f", filePath);
return System::shell(cmd);
}
File::File() : m_fd(-1), m_flags(0), m_pathLen(0)
{
m_error[0] = 0;
m_path[0] = 0;
}
File::File(const GInt8* filePath) : m_fd(-1), m_flags(0), m_pathLen(0)
{
GUint32 len = strlen(filePath);
if (len < G_PATH_MAX)
{
memcpy(m_path, filePath, len);
m_path[len] = 0;
m_pathLen = len;
}
m_error[0] = 0;
}
File::~File()
{
close();
}
GResult File::open(const FileOpenFlags fileOpenFlags)
{
return open(fileOpenFlags, G_FILE_MASK);
}
GResult File::open(const FileOpenFlags fileOpenFlags, const GInt32 mode)
{
GInt32 openFlags = 0;
if (fileOpenFlags | G_OPEN_READ)
{
openFlags = O_RDONLY;
}
else if (fileOpenFlags | G_OPEN_WRITE)
{
openFlags = O_WRONLY | O_CREAT;
}
else if (fileOpenFlags | G_OPEN_RDWR)
{
openFlags = O_RDWR | O_CREAT;
}
else if (fileOpenFlags | G_OPEN_APPEND)
{
if (openFlags == 0)
{
return G_NO;
}
openFlags |= O_APPEND;
}
if (openFlags == 0)
{
setError("input open mode error");
return G_NO;
}
return orgOpen(openFlags, mode);
}
GResult File::close()
{
if (m_fd < 0)
{
setError("file don't open");
return G_NO;
}
GResult ret = (::close(m_fd) != -1 ? G_YES : G_NO);
m_fd = -1;
m_path[0] = 0;
m_flags = 0;
return ret;
}
GInt64 File::getSize()
{
if (m_fd <= 0)
{
setError("file don't open");
return G_NO;
}
struct stat fileStat;
fstat(m_fd, &fileStat);
return (GInt64)(fileStat.st_size);
}
GInt64 File::seek(const GInt64 offset, const FileSeekFlags& flags)
{
if (m_fd <= 0)
{
setError("file don't open");
return G_NO;
}
GInt32 sysFlags = -1;
switch(flags)
{
case G_SEEK_BEG:
sysFlags = SEEK_SET;
break;
case G_SEEK_CUR:
sysFlags = SEEK_CUR;
break;
case G_SEEK_END:
sysFlags = SEEK_END;
break;
default:
return G_NO;
break;
}
return ::lseek(m_fd, offset, sysFlags);
}
GInt64 File::tell()
{
return seek(0, G_SEEK_CUR);
}
GInt64 File::read(GInt8* buffer, const GUint64 size)
{
if (buffer == NULL || size <= 0)
{
setError("input parameter is error");
return G_NO;
}
if (m_fd <= 0)
{
setError("file don't open");
return G_NO;
}
return ::read(m_fd, buffer, size);
}
GInt64 File::write(const GInt8* data, const GUint64 length)
{
if (data == NULL || length <= 0)
{
setError("input parameter is error");
return G_NO;
}
if (m_fd <= 0)
{
setError("file don't open");
return G_NO;
}
return ::write(m_fd, data, length);
}
GInt8* File::getError()
{
return m_error;
}
GResult File::orgOpen(const GInt32 flags, const GUint32 mode)
{
if (m_fd > 0)
{
setError("file had opened");
return G_NO;
}
if (m_pathLen == 0)
{
setError("hasn't set file path");
return G_NO;
}
m_fd = ::open(m_path, flags, mode);
if (m_fd > 0)
{
m_flags = flags;
}
else
{
setError("open file failed, check whether exist this file path");
}
return (m_fd != -1 ? true : false);
}
void File::setError(const GInt8* args, ...)
{
System::pformat(m_error, G_ERROR_BUF_SIZE, args);
}
<|endoftext|>
|
<commit_before>/*
* SPDX-FileCopyrightText: 2016-2016 CSSlayer <wengxt@gmail.com>
*
* SPDX-License-Identifier: LGPL-2.1-or-later
*
*/
#include "chttrans.h"
#include "config.h"
#include <fcitx-config/iniparser.h>
#include <fcitx-utils/i18n.h>
#include <fcitx-utils/standardpath.h>
#include <fcitx-utils/utf8.h>
#include <fcitx/addonfactory.h>
#include <fcitx/addonmanager.h>
#include <fcitx/inputmethodentry.h>
#include <fcntl.h>
#ifdef ENABLE_OPENCC
#include "chttrans-opencc.h"
#endif
#include "chttrans-native.h"
#include <fcitx/inputcontext.h>
#include <fcitx/userinterfacemanager.h>
using namespace fcitx;
static ChttransIMType inputMethodType(const InputMethodEntry &entry) {
if (entry.languageCode() == "zh_CN") {
return ChttransIMType::Simp;
}
if (entry.languageCode() == "zh_HK" || entry.languageCode() == "zh_TW") {
return ChttransIMType::Trad;
}
return ChttransIMType::Other;
}
Chttrans::Chttrans(fcitx::Instance *instance) : instance_(instance) {
instance_->userInterfaceManager().registerAction("chttrans",
&toggleAction_);
reloadConfig();
#ifdef ENABLE_OPENCC
backends_.emplace(ChttransEngine::OpenCC,
std::make_unique<OpenCCBackend>());
#endif
backends_.emplace(ChttransEngine::Native,
std::make_unique<NativeBackend>());
eventHandler_ = instance_->watchEvent(
EventType::InputContextKeyEvent, EventWatcherPhase::Default,
[this](Event &event) {
auto &keyEvent = static_cast<KeyEvent &>(event);
if (keyEvent.isRelease()) {
return;
}
auto *ic = keyEvent.inputContext();
auto *engine = instance_->inputMethodEngine(ic);
const auto *entry = instance_->inputMethodEntry(ic);
if (!engine || !entry ||
!toggleAction_.isParent(&ic->statusArea())) {
return;
}
auto type = inputMethodType(*entry);
if (type == ChttransIMType::Other) {
return;
}
if (keyEvent.key().checkKeyList(config_.hotkey.value())) {
toggle(ic);
bool tradEnabled = convertType(ic) == ChttransIMType::Trad;
if (notifications()) {
notifications()->call<INotifications::showTip>(
"fcitx-chttrans-toggle",
_("Simplified and Traditional Chinese Translation"),
tradEnabled ? "fcitx-chttrans-active"
: "fcitx-chttrans-inactive",
tradEnabled ? _("Switch to Simplified Chinese")
: _("Switch to Traditional Chinese"),
tradEnabled ? _("Traditional Chinese is enabled.")
: _("Simplified Chinese is enabled."),
-1);
}
keyEvent.filterAndAccept();
ic->updateUserInterface(UserInterfaceComponent::InputPanel);
}
});
outputFilterConn_ = instance_->connect<Instance::OutputFilter>(
[this](InputContext *inputContext, Text &text) {
if (!toggleAction_.isParent(&inputContext->statusArea()) ||
!needConvert(inputContext)) {
return;
}
auto type = convertType(inputContext);
auto oldString = text.toString();
auto oldLength = utf8::lengthValidated(oldString);
if (oldLength == utf8::INVALID_LENGTH) {
return;
}
auto newString = convert(type, oldString);
auto newLength = utf8::lengthValidated(newString);
if (newLength == utf8::INVALID_LENGTH) {
return;
}
Text newText;
size_t off = 0;
size_t remainLength = newLength;
for (size_t i = 0; i < text.size(); i++) {
auto segmentLength = utf8::length(text.stringAt(i));
if (remainLength < segmentLength) {
segmentLength = remainLength;
}
remainLength -= segmentLength;
size_t segmentByteLength = utf8::ncharByteLength(
newString.begin() + off, segmentLength);
newText.append(newString.substr(off, segmentByteLength),
text.formatAt(i));
off = off + segmentByteLength;
}
if (text.cursor() >= 0) {
auto length = utf8::length(oldString, 0, text.cursor());
if (length > newLength) {
length = newLength;
}
newText.setCursor(
utf8::ncharByteLength(newText.toString().begin(), length));
} else {
newText.setCursor(text.cursor());
}
text = std::move(newText);
});
commitFilterConn_ = instance_->connect<Instance::CommitFilter>(
[this](InputContext *inputContext, std::string &str) {
if (!toggleAction_.isParent(&inputContext->statusArea()) ||
!needConvert(inputContext)) {
return;
}
auto type = convertType(inputContext);
str = convert(type, str);
});
}
void Chttrans::toggle(InputContext *ic) {
auto *engine = instance_->inputMethodEngine(ic);
const auto *entry = instance_->inputMethodEntry(ic);
if (!engine || !entry || !toggleAction_.isParent(&ic->statusArea())) {
return;
}
auto type = inputMethodType(*entry);
if (type == ChttransIMType::Other) {
return;
}
if (enabledIM_.count(entry->uniqueName())) {
enabledIM_.erase(entry->uniqueName());
} else {
enabledIM_.insert(entry->uniqueName());
}
toggleAction_.update(ic);
}
void Chttrans::reloadConfig() {
readAsIni(config_, "conf/chttrans.conf");
populateConfig();
}
void Chttrans::populateConfig() {
enabledIM_.clear();
enabledIM_.insert(config_.enabledIM.value().begin(),
config_.enabledIM.value().end());
}
void Chttrans::save() {
std::vector<std::string> values_;
for (const auto &id : enabledIM_) {
values_.push_back(id);
}
config_.enabledIM.setValue(std::move(values_));
safeSaveAsIni(config_, "conf/chttrans.conf");
}
std::string Chttrans::convert(ChttransIMType type, const std::string &str) {
auto iter = backends_.find(config_.engine.value());
if (iter == backends_.end()) {
iter = backends_.find(ChttransEngine::Native);
}
if (iter == backends_.end() || !iter->second->load()) {
return str;
}
if (type == ChttransIMType::Trad) {
return iter->second->convertSimpToTrad(str);
}
return iter->second->convertTradToSimp(str);
}
bool Chttrans::needConvert(fcitx::InputContext *inputContext) {
auto *engine = instance_->inputMethodEngine(inputContext);
const auto *entry = instance_->inputMethodEntry(inputContext);
if (!engine || !entry) {
return false;
}
auto type = inputMethodType(*entry);
if (type == ChttransIMType::Other) {
return false;
}
return enabledIM_.count(entry->uniqueName());
}
ChttransIMType Chttrans::convertType(fcitx::InputContext *inputContext) {
auto *engine = instance_->inputMethodEngine(inputContext);
const auto *entry = instance_->inputMethodEntry(inputContext);
if (!engine || !entry) {
return ChttransIMType::Other;
}
auto type = inputMethodType(*entry);
if (type == ChttransIMType::Other) {
return ChttransIMType::Other;
}
if (!enabledIM_.count(entry->uniqueName())) {
return type;
}
return type == ChttransIMType::Simp ? ChttransIMType::Trad
: ChttransIMType::Simp;
}
class ChttransModuleFactory : public AddonFactory {
AddonInstance *create(AddonManager *manager) override {
return new Chttrans(manager->instance());
}
};
FCITX_ADDON_FACTORY(ChttransModuleFactory)
<commit_msg>Fix wrong string in chttrans notification<commit_after>/*
* SPDX-FileCopyrightText: 2016-2016 CSSlayer <wengxt@gmail.com>
*
* SPDX-License-Identifier: LGPL-2.1-or-later
*
*/
#include "chttrans.h"
#include "config.h"
#include <fcitx-config/iniparser.h>
#include <fcitx-utils/i18n.h>
#include <fcitx-utils/standardpath.h>
#include <fcitx-utils/utf8.h>
#include <fcitx/addonfactory.h>
#include <fcitx/addonmanager.h>
#include <fcitx/inputmethodentry.h>
#include <fcntl.h>
#ifdef ENABLE_OPENCC
#include "chttrans-opencc.h"
#endif
#include "chttrans-native.h"
#include <fcitx/inputcontext.h>
#include <fcitx/userinterfacemanager.h>
using namespace fcitx;
static ChttransIMType inputMethodType(const InputMethodEntry &entry) {
if (entry.languageCode() == "zh_CN") {
return ChttransIMType::Simp;
}
if (entry.languageCode() == "zh_HK" || entry.languageCode() == "zh_TW") {
return ChttransIMType::Trad;
}
return ChttransIMType::Other;
}
Chttrans::Chttrans(fcitx::Instance *instance) : instance_(instance) {
instance_->userInterfaceManager().registerAction("chttrans",
&toggleAction_);
reloadConfig();
#ifdef ENABLE_OPENCC
backends_.emplace(ChttransEngine::OpenCC,
std::make_unique<OpenCCBackend>());
#endif
backends_.emplace(ChttransEngine::Native,
std::make_unique<NativeBackend>());
eventHandler_ = instance_->watchEvent(
EventType::InputContextKeyEvent, EventWatcherPhase::Default,
[this](Event &event) {
auto &keyEvent = static_cast<KeyEvent &>(event);
if (keyEvent.isRelease()) {
return;
}
auto *ic = keyEvent.inputContext();
auto *engine = instance_->inputMethodEngine(ic);
const auto *entry = instance_->inputMethodEntry(ic);
if (!engine || !entry ||
!toggleAction_.isParent(&ic->statusArea())) {
return;
}
auto type = inputMethodType(*entry);
if (type == ChttransIMType::Other) {
return;
}
if (keyEvent.key().checkKeyList(config_.hotkey.value())) {
toggle(ic);
bool tradEnabled = convertType(ic) == ChttransIMType::Trad;
if (notifications()) {
notifications()->call<INotifications::showTip>(
"fcitx-chttrans-toggle",
_("Simplified and Traditional Chinese Translation"),
tradEnabled ? "fcitx-chttrans-active"
: "fcitx-chttrans-inactive",
tradEnabled ? _("Switch to Traditional Chinese")
: _("Switch to Simplified Chinese"),
tradEnabled ? _("Traditional Chinese is enabled.")
: _("Simplified Chinese is enabled."),
-1);
}
keyEvent.filterAndAccept();
ic->updateUserInterface(UserInterfaceComponent::InputPanel);
}
});
outputFilterConn_ = instance_->connect<Instance::OutputFilter>(
[this](InputContext *inputContext, Text &text) {
if (!toggleAction_.isParent(&inputContext->statusArea()) ||
!needConvert(inputContext)) {
return;
}
auto type = convertType(inputContext);
auto oldString = text.toString();
auto oldLength = utf8::lengthValidated(oldString);
if (oldLength == utf8::INVALID_LENGTH) {
return;
}
auto newString = convert(type, oldString);
auto newLength = utf8::lengthValidated(newString);
if (newLength == utf8::INVALID_LENGTH) {
return;
}
Text newText;
size_t off = 0;
size_t remainLength = newLength;
for (size_t i = 0; i < text.size(); i++) {
auto segmentLength = utf8::length(text.stringAt(i));
if (remainLength < segmentLength) {
segmentLength = remainLength;
}
remainLength -= segmentLength;
size_t segmentByteLength = utf8::ncharByteLength(
newString.begin() + off, segmentLength);
newText.append(newString.substr(off, segmentByteLength),
text.formatAt(i));
off = off + segmentByteLength;
}
if (text.cursor() >= 0) {
auto length = utf8::length(oldString, 0, text.cursor());
if (length > newLength) {
length = newLength;
}
newText.setCursor(
utf8::ncharByteLength(newText.toString().begin(), length));
} else {
newText.setCursor(text.cursor());
}
text = std::move(newText);
});
commitFilterConn_ = instance_->connect<Instance::CommitFilter>(
[this](InputContext *inputContext, std::string &str) {
if (!toggleAction_.isParent(&inputContext->statusArea()) ||
!needConvert(inputContext)) {
return;
}
auto type = convertType(inputContext);
str = convert(type, str);
});
}
void Chttrans::toggle(InputContext *ic) {
auto *engine = instance_->inputMethodEngine(ic);
const auto *entry = instance_->inputMethodEntry(ic);
if (!engine || !entry || !toggleAction_.isParent(&ic->statusArea())) {
return;
}
auto type = inputMethodType(*entry);
if (type == ChttransIMType::Other) {
return;
}
if (enabledIM_.count(entry->uniqueName())) {
enabledIM_.erase(entry->uniqueName());
} else {
enabledIM_.insert(entry->uniqueName());
}
toggleAction_.update(ic);
}
void Chttrans::reloadConfig() {
readAsIni(config_, "conf/chttrans.conf");
populateConfig();
}
void Chttrans::populateConfig() {
enabledIM_.clear();
enabledIM_.insert(config_.enabledIM.value().begin(),
config_.enabledIM.value().end());
}
void Chttrans::save() {
std::vector<std::string> values_;
for (const auto &id : enabledIM_) {
values_.push_back(id);
}
config_.enabledIM.setValue(std::move(values_));
safeSaveAsIni(config_, "conf/chttrans.conf");
}
std::string Chttrans::convert(ChttransIMType type, const std::string &str) {
auto iter = backends_.find(config_.engine.value());
if (iter == backends_.end()) {
iter = backends_.find(ChttransEngine::Native);
}
if (iter == backends_.end() || !iter->second->load()) {
return str;
}
if (type == ChttransIMType::Trad) {
return iter->second->convertSimpToTrad(str);
}
return iter->second->convertTradToSimp(str);
}
bool Chttrans::needConvert(fcitx::InputContext *inputContext) {
auto *engine = instance_->inputMethodEngine(inputContext);
const auto *entry = instance_->inputMethodEntry(inputContext);
if (!engine || !entry) {
return false;
}
auto type = inputMethodType(*entry);
if (type == ChttransIMType::Other) {
return false;
}
return enabledIM_.count(entry->uniqueName());
}
ChttransIMType Chttrans::convertType(fcitx::InputContext *inputContext) {
auto *engine = instance_->inputMethodEngine(inputContext);
const auto *entry = instance_->inputMethodEntry(inputContext);
if (!engine || !entry) {
return ChttransIMType::Other;
}
auto type = inputMethodType(*entry);
if (type == ChttransIMType::Other) {
return ChttransIMType::Other;
}
if (!enabledIM_.count(entry->uniqueName())) {
return type;
}
return type == ChttransIMType::Simp ? ChttransIMType::Trad
: ChttransIMType::Simp;
}
class ChttransModuleFactory : public AddonFactory {
AddonInstance *create(AddonManager *manager) override {
return new Chttrans(manager->instance());
}
};
FCITX_ADDON_FACTORY(ChttransModuleFactory)
<|endoftext|>
|
<commit_before>/* Copyright (C) 2003 MySQL AB
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */
/************************************************************************************************
Name: NdbRecAttr.C
Include:
Link:
Author: UABRONM Mikael Ronstrm UAB/B/SD
Date: 971206
Version: 0.1
Description: Interface between TIS and NDB
Documentation:
Adjust: 971206 UABRONM First version
************************************************************************************************/
#include <ndb_global.h>
#include <NdbOut.hpp>
#include <NdbRecAttr.hpp>
#include <NdbBlob.hpp>
#include "NdbDictionaryImpl.hpp"
#include <NdbTCP.h>
NdbRecAttr::NdbRecAttr()
{
init();
}
NdbRecAttr::~NdbRecAttr()
{
release();
}
int
NdbRecAttr::setup(const class NdbDictionary::Column* col, char* aValue)
{
return setup(&(col->m_impl), aValue);
}
int
NdbRecAttr::setup(const NdbColumnImpl* anAttrInfo, char* aValue)
{
Uint32 tAttrSize = anAttrInfo->m_attrSize;
Uint32 tArraySize = anAttrInfo->m_arraySize;
Uint32 tAttrByteSize = tAttrSize * tArraySize;
m_column = anAttrInfo;
theAttrId = anAttrInfo->m_attrId;
theAttrSize = tAttrSize;
theArraySize = tArraySize;
theValue = aValue;
theNULLind = 0;
m_nullable = anAttrInfo->m_nullable;
// check alignment to signal data
// a future version could check alignment per data type as well
if (aValue != NULL && (UintPtr(aValue)&3) == 0 && (tAttrByteSize&3) == 0) {
theStorageX = NULL;
theRef = aValue;
return 0;
}
if (tAttrByteSize <= 32) {
theStorageX = NULL;
theStorage[0] = 0;
theStorage[1] = 0;
theStorage[2] = 0;
theStorage[3] = 0;
theRef = theStorage;
return 0;
}
Uint32 tSize = (tAttrByteSize + 7) >> 3;
Uint64* tRef = new Uint64[tSize];
if (tRef != NULL) {
for (Uint32 i = 0; i < tSize; i++) {
tRef[i] = 0;
}
theStorageX = tRef;
theRef = tRef;
return 0;
}
return -1;
}
void
NdbRecAttr::copyout()
{
char* tRef = (char*)theRef;
char* tValue = theValue;
if (tRef != tValue && tRef != NULL && tValue != NULL) {
Uint32 n = theAttrSize * theArraySize;
while (n-- > 0) {
*tValue++ = *tRef++;
}
}
}
NdbRecAttr *
NdbRecAttr::clone() const {
NdbRecAttr * ret = new NdbRecAttr();
ret->theAttrId = theAttrId;
ret->theNULLind = theNULLind;
ret->theAttrSize = theAttrSize;
ret->theArraySize = theArraySize;
ret->m_column = m_column;
Uint32 n = theAttrSize * theArraySize;
if(n <= 32){
ret->theRef = (char*)&ret->theStorage[0];
ret->theStorageX = 0;
ret->theValue = 0;
} else {
ret->theStorageX = new Uint64[((n + 7) >> 3)];
ret->theRef = (char*)ret->theStorageX;
ret->theValue = 0;
}
memcpy(ret->theRef, theRef, n);
return ret;
}
bool
NdbRecAttr::receive_data(const Uint32 * data, Uint32 sz){
const Uint32 n = (theAttrSize * theArraySize + 3) >> 2;
if(n == sz){
theNULLind = 0;
if(!copyoutRequired())
memcpy(theRef, data, 4 * sz);
else
memcpy(theValue, data, theAttrSize * theArraySize);
return true;
} else if(sz == 0){
setNULL();
return true;
}
return false;
}
NdbOut& operator<<(NdbOut& out, const NdbRecAttr &r)
{
if (r.isNULL())
{
out << "[NULL]";
return out;
}
if (r.arraySize() > 1)
out << "[";
for (Uint32 j = 0; j < r.arraySize(); j++)
{
if (j > 0)
out << " ";
switch(r.getType())
{
case NdbDictionary::Column::Bigunsigned:
out << r.u_64_value();
break;
case NdbDictionary::Column::Bit:
out << hex << "H'" << r.u_32_value() << dec;
break;
case NdbDictionary::Column::Unsigned:
out << r.u_32_value();
break;
case NdbDictionary::Column::Smallunsigned:
out << r.u_short_value();
break;
case NdbDictionary::Column::Tinyunsigned:
out << (unsigned) r.u_char_value();
break;
case NdbDictionary::Column::Bigint:
out << r.int64_value();
break;
case NdbDictionary::Column::Int:
out << r.int32_value();
break;
case NdbDictionary::Column::Smallint:
out << r.short_value();
break;
case NdbDictionary::Column::Tinyint:
out << (int) r.char_value();
break;
case NdbDictionary::Column::Char:
out.print("%.*s", r.arraySize(), r.aRef());
j = r.arraySize();
break;
case NdbDictionary::Column::Varchar:
{
short len = ntohs(r.u_short_value());
out.print("%.*s", len, r.aRef()+2);
}
j = r.arraySize();
break;
case NdbDictionary::Column::Float:
out << r.float_value();
break;
case NdbDictionary::Column::Double:
out << r.double_value();
break;
case NdbDictionary::Column::Blob:
{
const NdbBlob::Head* h = (const NdbBlob::Head*)r.aRef();
out << h->length << ":";
const unsigned char* p = (const unsigned char*)(h + 1);
unsigned n = r.arraySize() - sizeof(*h);
for (unsigned k = 0; k < n && k < h->length; k++)
out.print("%02X", (int)p[k]);
j = r.arraySize();
}
break;
case NdbDictionary::Column::Text:
{
const NdbBlob::Head* h = (const NdbBlob::Head*)r.aRef();
out << h->length << ":";
const unsigned char* p = (const unsigned char*)(h + 1);
unsigned n = r.arraySize() - sizeof(*h);
for (unsigned k = 0; k < n && k < h->length; k++)
out.print("%c", (int)p[k]);
j = r.arraySize();
}
break;
default: /* no print functions for the rest, just print type */
out << (int) r.getType();
j = r.arraySize();
if (j > 1)
out << " " << j << " times";
break;
}
}
if (r.arraySize() > 1)
{
out << "]";
}
return out;
}
<commit_msg>improved print routine for NdbRecAttr<commit_after>/* Copyright (C) 2003 MySQL AB
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */
#include <ndb_global.h>
#include <NdbOut.hpp>
#include <NdbRecAttr.hpp>
#include <NdbBlob.hpp>
#include "NdbDictionaryImpl.hpp"
#include <NdbTCP.h>
NdbRecAttr::NdbRecAttr()
{
init();
}
NdbRecAttr::~NdbRecAttr()
{
release();
}
int
NdbRecAttr::setup(const class NdbDictionary::Column* col, char* aValue)
{
return setup(&(col->m_impl), aValue);
}
int
NdbRecAttr::setup(const NdbColumnImpl* anAttrInfo, char* aValue)
{
Uint32 tAttrSize = anAttrInfo->m_attrSize;
Uint32 tArraySize = anAttrInfo->m_arraySize;
Uint32 tAttrByteSize = tAttrSize * tArraySize;
m_column = anAttrInfo;
theAttrId = anAttrInfo->m_attrId;
theAttrSize = tAttrSize;
theArraySize = tArraySize;
theValue = aValue;
theNULLind = 0;
m_nullable = anAttrInfo->m_nullable;
// check alignment to signal data
// a future version could check alignment per data type as well
if (aValue != NULL && (UintPtr(aValue)&3) == 0 && (tAttrByteSize&3) == 0) {
theStorageX = NULL;
theRef = aValue;
return 0;
}
if (tAttrByteSize <= 32) {
theStorageX = NULL;
theStorage[0] = 0;
theStorage[1] = 0;
theStorage[2] = 0;
theStorage[3] = 0;
theRef = theStorage;
return 0;
}
Uint32 tSize = (tAttrByteSize + 7) >> 3;
Uint64* tRef = new Uint64[tSize];
if (tRef != NULL) {
for (Uint32 i = 0; i < tSize; i++) {
tRef[i] = 0;
}
theStorageX = tRef;
theRef = tRef;
return 0;
}
return -1;
}
void
NdbRecAttr::copyout()
{
char* tRef = (char*)theRef;
char* tValue = theValue;
if (tRef != tValue && tRef != NULL && tValue != NULL) {
Uint32 n = theAttrSize * theArraySize;
while (n-- > 0) {
*tValue++ = *tRef++;
}
}
}
NdbRecAttr *
NdbRecAttr::clone() const {
NdbRecAttr * ret = new NdbRecAttr();
ret->theAttrId = theAttrId;
ret->theNULLind = theNULLind;
ret->theAttrSize = theAttrSize;
ret->theArraySize = theArraySize;
ret->m_column = m_column;
Uint32 n = theAttrSize * theArraySize;
if(n <= 32){
ret->theRef = (char*)&ret->theStorage[0];
ret->theStorageX = 0;
ret->theValue = 0;
} else {
ret->theStorageX = new Uint64[((n + 7) >> 3)];
ret->theRef = (char*)ret->theStorageX;
ret->theValue = 0;
}
memcpy(ret->theRef, theRef, n);
return ret;
}
bool
NdbRecAttr::receive_data(const Uint32 * data, Uint32 sz){
const Uint32 n = (theAttrSize * theArraySize + 3) >> 2;
if(n == sz){
theNULLind = 0;
if(!copyoutRequired())
memcpy(theRef, data, 4 * sz);
else
memcpy(theValue, data, theAttrSize * theArraySize);
return true;
} else if(sz == 0){
setNULL();
return true;
}
return false;
}
static void
ndbrecattr_print_string(NdbOut& out, const char *type,
const char *ref, unsigned sz)
{
int i;
// trailing zeroes are not printed
for (i=sz-1; i >= 0; i--)
if (ref[i] == 0) sz--;
else break;
if (sz == 0) return; // empty
char *str= (char*)malloc(sz+1);
memcpy(str, ref, sz);
str[sz]= 0; // null terminate
int len= strlen(str);
int printable= 1;
for (i=0; i < len; i++)
{
if (str[i] < 32) {
printable= 0;
break;
}
}
if (printable)
out.print("%.*s", len, str);
else
{
for (i=0; i < len; i++)
out.print("%02X", (int)str[i]);
}
free(str);
if (len != (int)sz)
{
out.print("[");
for (i= len+1; ref[i] != 0; i++)
out.print("%u]",len-i);
assert(sz > i);
ndbrecattr_print_string(out,type,ref+i,sz-i);
}
}
NdbOut& operator<<(NdbOut& out, const NdbRecAttr &r)
{
if (r.isNULL())
{
out << "[NULL]";
return out;
}
if (r.arraySize() > 1)
out << "[";
for (Uint32 j = 0; j < r.arraySize(); j++)
{
if (j > 0)
out << " ";
switch(r.getType())
{
case NdbDictionary::Column::Bigunsigned:
out << r.u_64_value();
break;
case NdbDictionary::Column::Bit:
out << hex << "H'" << r.u_32_value() << dec;
break;
case NdbDictionary::Column::Unsigned:
out << r.u_32_value();
break;
case NdbDictionary::Column::Smallunsigned:
out << r.u_short_value();
break;
case NdbDictionary::Column::Tinyunsigned:
out << (unsigned) r.u_char_value();
break;
case NdbDictionary::Column::Bigint:
out << r.int64_value();
break;
case NdbDictionary::Column::Int:
out << r.int32_value();
break;
case NdbDictionary::Column::Smallint:
out << r.short_value();
break;
case NdbDictionary::Column::Tinyint:
out << (int) r.char_value();
break;
case NdbDictionary::Column::Binary:
ndbrecattr_print_string(out,"Binary",r.aRef(),r.arraySize());
j = r.arraySize();
break;
case NdbDictionary::Column::Char:
ndbrecattr_print_string(out,"Char",r.aRef(),r.arraySize());
j = r.arraySize();
break;
case NdbDictionary::Column::Varchar:
ndbrecattr_print_string(out,"Varchar", r.aRef()+ 2,
ntohs(r.u_short_value()));
j = r.arraySize();
break;
case NdbDictionary::Column::Float:
out << r.float_value();
break;
case NdbDictionary::Column::Double:
out << r.double_value();
break;
case NdbDictionary::Column::Blob:
{
const NdbBlob::Head* h = (const NdbBlob::Head*)r.aRef();
out << h->length << ":";
const unsigned char* p = (const unsigned char*)(h + 1);
unsigned n = r.arraySize() - sizeof(*h);
for (unsigned k = 0; k < n && k < h->length; k++)
out.print("%02X", (int)p[k]);
j = r.arraySize();
}
break;
case NdbDictionary::Column::Text:
{
const NdbBlob::Head* h = (const NdbBlob::Head*)r.aRef();
out << h->length << ":";
const unsigned char* p = (const unsigned char*)(h + 1);
unsigned n = r.arraySize() - sizeof(*h);
for (unsigned k = 0; k < n && k < h->length; k++)
out.print("%c", (int)p[k]);
j = r.arraySize();
}
break;
default: /* no print functions for the rest, just print type */
out << (int) r.getType();
j = r.arraySize();
if (j > 1)
out << " " << j << " times";
break;
}
}
if (r.arraySize() > 1)
{
out << "]";
}
return out;
}
<|endoftext|>
|
<commit_before>// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "base/basictypes.h"
#include "googleurl/src/gurl.h"
#include "net/base/data_url.h"
#include "testing/gtest/include/gtest/gtest.h"
namespace {
struct ParseTestData {
const char* url;
bool is_valid;
const char* mime_type;
const char* charset;
const char* data;
};
class DataURLTest : public testing::Test {
};
}
TEST(DataURLTest, Parse) {
const ParseTestData tests[] = {
{ "data:",
false,
"",
"",
"" },
{ "data:,",
true,
"text/plain",
"US-ASCII",
"" },
{ "data:;base64,",
true,
"text/plain",
"US-ASCII",
"" },
{ "data:;charset=,test",
true,
"text/plain",
"US-ASCII",
"test" },
{ "data:TeXt/HtMl,<b>x</b>",
true,
"text/html",
"US-ASCII",
"<b>x</b>" },
{ "data:,foo",
true,
"text/plain",
"US-ASCII",
"foo" },
{ "data:;base64,aGVsbG8gd29ybGQ=",
true,
"text/plain",
"US-ASCII",
"hello world" },
{ "data:foo/bar;baz=1;charset=kk,boo",
true,
"foo/bar",
"kk",
"boo" },
{ "data:text/html,%3Chtml%3E%3Cbody%3E%3Cb%3Ehello%20world"
"%3C%2Fb%3E%3C%2Fbody%3E%3C%2Fhtml%3E",
true,
"text/html",
"US-ASCII",
"<html><body><b>hello world</b></body></html>" },
{ "data:text/html,<html><body><b>hello world</b></body></html>",
true,
"text/html",
"US-ASCII",
"<html><body><b>hello world</b></body></html>" },
// the comma cannot be url-escaped!
{ "data:%2Cblah",
false,
"",
"",
"" },
// invalid base64 content
{ "data:;base64,aGVs_-_-",
false,
"",
"",
"" },
// Spaces should be removed from non-text data URLs (we already tested
// spaces above).
{ "data:image/fractal,a b c d e f g",
true,
"image/fractal",
"US-ASCII",
"abcdefg" },
// Spaces should also be removed from anything base-64 encoded
{ "data:;base64,aGVs bG8gd2 9ybGQ=",
true,
"text/plain",
"US-ASCII",
"hello world" },
// Other whitespace should also be removed from anything base-64 encoded.
{ "data:;base64,aGVs bG8gd2 \n9ybGQ=",
true,
"text/plain",
"US-ASCII",
"hello world" },
// In base64 encoding, escaped whitespace should be stripped.
// (This test was taken from acid3)
// http://b/1054495
{ "data:text/javascript;base64,%20ZD%20Qg%0D%0APS%20An%20Zm91cic%0D%0A%207"
"%20",
true,
"text/javascript",
"US-ASCII",
"d4 = 'four';" },
// Only unescaped whitespace should be stripped in non-base64.
// http://b/1157796
{ "data:img/png,A B %20 %0A C",
true,
"img/png",
"US-ASCII",
"AB \nC" },
// TODO(darin): add more interesting tests
};
for (size_t i = 0; i < arraysize(tests); ++i) {
std::string mime_type;
std::string charset;
std::string data;
bool ok =
net::DataURL::Parse(GURL(tests[i].url), &mime_type, &charset, &data);
EXPECT_EQ(ok, tests[i].is_valid);
if (tests[i].is_valid) {
EXPECT_EQ(tests[i].mime_type, mime_type);
EXPECT_EQ(tests[i].charset, charset);
EXPECT_EQ(tests[i].data, data);
}
}
}
<commit_msg>Fix indentation.<commit_after>// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "base/basictypes.h"
#include "googleurl/src/gurl.h"
#include "net/base/data_url.h"
#include "testing/gtest/include/gtest/gtest.h"
namespace {
struct ParseTestData {
const char* url;
bool is_valid;
const char* mime_type;
const char* charset;
const char* data;
};
class DataURLTest : public testing::Test {
};
}
TEST(DataURLTest, Parse) {
const ParseTestData tests[] = {
{ "data:",
false,
"",
"",
"" },
{ "data:,",
true,
"text/plain",
"US-ASCII",
"" },
{ "data:;base64,",
true,
"text/plain",
"US-ASCII",
"" },
{ "data:;charset=,test",
true,
"text/plain",
"US-ASCII",
"test" },
{ "data:TeXt/HtMl,<b>x</b>",
true,
"text/html",
"US-ASCII",
"<b>x</b>" },
{ "data:,foo",
true,
"text/plain",
"US-ASCII",
"foo" },
{ "data:;base64,aGVsbG8gd29ybGQ=",
true,
"text/plain",
"US-ASCII",
"hello world" },
{ "data:foo/bar;baz=1;charset=kk,boo",
true,
"foo/bar",
"kk",
"boo" },
{ "data:text/html,%3Chtml%3E%3Cbody%3E%3Cb%3Ehello%20world"
"%3C%2Fb%3E%3C%2Fbody%3E%3C%2Fhtml%3E",
true,
"text/html",
"US-ASCII",
"<html><body><b>hello world</b></body></html>" },
{ "data:text/html,<html><body><b>hello world</b></body></html>",
true,
"text/html",
"US-ASCII",
"<html><body><b>hello world</b></body></html>" },
// the comma cannot be url-escaped!
{ "data:%2Cblah",
false,
"",
"",
"" },
// invalid base64 content
{ "data:;base64,aGVs_-_-",
false,
"",
"",
"" },
// Spaces should be removed from non-text data URLs (we already tested
// spaces above).
{ "data:image/fractal,a b c d e f g",
true,
"image/fractal",
"US-ASCII",
"abcdefg" },
// Spaces should also be removed from anything base-64 encoded
{ "data:;base64,aGVs bG8gd2 9ybGQ=",
true,
"text/plain",
"US-ASCII",
"hello world" },
// Other whitespace should also be removed from anything base-64 encoded.
{ "data:;base64,aGVs bG8gd2 \n9ybGQ=",
true,
"text/plain",
"US-ASCII",
"hello world" },
// In base64 encoding, escaped whitespace should be stripped.
// (This test was taken from acid3)
// http://b/1054495
{ "data:text/javascript;base64,%20ZD%20Qg%0D%0APS%20An%20Zm91cic%0D%0A%207"
"%20",
true,
"text/javascript",
"US-ASCII",
"d4 = 'four';" },
// Only unescaped whitespace should be stripped in non-base64.
// http://b/1157796
{ "data:img/png,A B %20 %0A C",
true,
"img/png",
"US-ASCII",
"AB \nC" },
// TODO(darin): add more interesting tests
};
for (size_t i = 0; i < arraysize(tests); ++i) {
std::string mime_type;
std::string charset;
std::string data;
bool ok =
net::DataURL::Parse(GURL(tests[i].url), &mime_type, &charset, &data);
EXPECT_EQ(ok, tests[i].is_valid);
if (tests[i].is_valid) {
EXPECT_EQ(tests[i].mime_type, mime_type);
EXPECT_EQ(tests[i].charset, charset);
EXPECT_EQ(tests[i].data, data);
}
}
}
<|endoftext|>
|
<commit_before>// This file is part of OpenCV project.
// It is subject to the license terms in the LICENSE file found in the top-level directory
// of this distribution and at http://opencv.org/license.html.
//
// Copyright (C) 2019 Intel Corporation
#include "pattern_matching.hpp"
#include "ade/util/zip_range.hpp"
namespace cv { namespace gimpl {
namespace {
using Graph = GModel::Graph;
template<typename Iterator>
ade::NodeHandle getNh(Iterator it) { return *it; }
template<>
ade::NodeHandle getNh(SubgraphMatch::M::const_iterator it) { return it->second; }
template<typename Container>
void erase(Graph& g, const Container& c)
{
for (auto first = c.begin(); first != c.end(); ++first) {
ade::NodeHandle node = getNh(first);
if (node == nullptr) continue; // some nodes might already be erased
g.erase(node);
}
}
} // anonymous namespace
void performSubstitution(GModel::Graph& graph,
const Protocol& patternP,
const Protocol& substituteP,
const SubgraphMatch& patternToGraphMatch)
{
// 1. substitute input nodes
const auto& patternIns = patternP.in_nhs;
const auto& substituteIns = substituteP.in_nhs;
for (auto it : ade::util::zip(ade::util::toRange(patternIns),
ade::util::toRange(substituteIns))) {
// Note: we don't replace input DATA nodes here, only redirect their output edges
const auto& patternDataNode = std::get<0>(it);
const auto& substituteDataNode = std::get<1>(it);
const auto& graphDataNode = patternToGraphMatch.inputDataNodes.at(patternDataNode);
GModel::redirectReaders(graph, substituteDataNode, graphDataNode);
}
// 2. substitute output nodes
const auto& patternOuts = patternP.out_nhs;
const auto& substituteOuts = substituteP.out_nhs;
for (auto it : ade::util::zip(ade::util::toRange(patternOuts),
ade::util::toRange(substituteOuts))) {
// Note: we don't replace output DATA nodes here, only redirect their input edges
const auto& patternDataNode = std::get<0>(it);
const auto& substituteDataNode = std::get<1>(it);
const auto& graphDataNode = patternToGraphMatch.outputDataNodes.at(patternDataNode);
// delete existing edges (otherwise we cannot redirect)
for (auto e : graphDataNode->inEdges()) {
graph.erase(e);
}
GModel::redirectWriter(graph, substituteDataNode, graphDataNode);
}
// 3. erase redundant nodes:
// erase input data nodes of __substitute__
erase(graph, substituteIns);
// erase old start OP nodes of __main graph__
erase(graph, patternToGraphMatch.startOpNodes);
// erase old internal nodes of __main graph__
erase(graph, patternToGraphMatch.internalLayers);
// erase old finish OP nodes of __main graph__
erase(graph, patternToGraphMatch.finishOpNodes);
// erase output data nodes of __substitute__
erase(graph, substituteOuts);
}
} // namespace gimpl
} // namespace cv
<commit_msg>G-API: fix perform substitution UB/crash<commit_after>// This file is part of OpenCV project.
// It is subject to the license terms in the LICENSE file found in the top-level directory
// of this distribution and at http://opencv.org/license.html.
//
// Copyright (C) 2019 Intel Corporation
#include "pattern_matching.hpp"
#include "ade/util/zip_range.hpp"
namespace cv { namespace gimpl {
namespace {
using Graph = GModel::Graph;
template<typename Iterator>
ade::NodeHandle getNh(Iterator it) { return *it; }
template<>
ade::NodeHandle getNh(SubgraphMatch::M::const_iterator it) { return it->second; }
template<typename Container>
void erase(Graph& g, const Container& c)
{
for (auto first = c.begin(); first != c.end(); ++first) {
ade::NodeHandle node = getNh(first);
if (node == nullptr) continue; // some nodes might already be erased
g.erase(node);
}
}
} // anonymous namespace
void performSubstitution(GModel::Graph& graph,
const Protocol& patternP,
const Protocol& substituteP,
const SubgraphMatch& patternToGraphMatch)
{
// 1. substitute input nodes
const auto& patternIns = patternP.in_nhs;
const auto& substituteIns = substituteP.in_nhs;
for (auto it : ade::util::zip(ade::util::toRange(patternIns),
ade::util::toRange(substituteIns))) {
// Note: we don't replace input DATA nodes here, only redirect their output edges
const auto& patternDataNode = std::get<0>(it);
const auto& substituteDataNode = std::get<1>(it);
const auto& graphDataNode = patternToGraphMatch.inputDataNodes.at(patternDataNode);
GModel::redirectReaders(graph, substituteDataNode, graphDataNode);
}
// 2. substitute output nodes
const auto& patternOuts = patternP.out_nhs;
const auto& substituteOuts = substituteP.out_nhs;
for (auto it : ade::util::zip(ade::util::toRange(patternOuts),
ade::util::toRange(substituteOuts))) {
// Note: we don't replace output DATA nodes here, only redirect their input edges
const auto& patternDataNode = std::get<0>(it);
const auto& substituteDataNode = std::get<1>(it);
const auto& graphDataNode = patternToGraphMatch.outputDataNodes.at(patternDataNode);
// delete existing edges (otherwise we cannot redirect)
auto existingEdges = graphDataNode->inEdges();
// NB: we cannot iterate over node->inEdges() here directly because it gets modified when
// edges are erased. Erasing an edge supposes that src/dst nodes will remove
// (correspondingly) out/in edge (which is _our edge_). Now, this deleting means
// node->inEdges() will also get updated in the process: so, we'd iterate over a
// container which changes in this case. Using supplementary std::vector instead:
std::vector<ade::EdgeHandle> handles(existingEdges.begin(), existingEdges.end());
for (const auto& e : handles) {
graph.erase(e);
}
GModel::redirectWriter(graph, substituteDataNode, graphDataNode);
}
// 3. erase redundant nodes:
// erase input data nodes of __substitute__
erase(graph, substituteIns);
// erase old start OP nodes of __main graph__
erase(graph, patternToGraphMatch.startOpNodes);
// erase old internal nodes of __main graph__
erase(graph, patternToGraphMatch.internalLayers);
// erase old finish OP nodes of __main graph__
erase(graph, patternToGraphMatch.finishOpNodes);
// erase output data nodes of __substitute__
erase(graph, substituteOuts);
}
} // namespace gimpl
} // namespace cv
<|endoftext|>
|
<commit_before>#include "WallFrictionChurchillMaterial.h"
#include "WallFrictionModels.h"
#include "Numerics.h"
template <>
InputParameters
validParams<WallFrictionChurchillMaterial>()
{
InputParameters params = validParams<WallFriction3EqnBaseMaterial>();
params.addRequiredCoupledVar("rhoA", "Mass equation variable: rho*A");
params.addRequiredCoupledVar("rhouA", "Momentum equation variable: rho*u*A");
params.addRequiredCoupledVar("rhoEA", "Total energy equation variable: rho*E*A");
params.addRequiredCoupledVar("rho", "Density");
params.addRequiredCoupledVar("vel", "x-component of the velocity");
params.addRequiredCoupledVar("D_h", "hydraulic diameter");
params.addRequiredParam<MaterialPropertyName>("Cw", "Drag coefficient material property");
params.addRequiredParam<MaterialPropertyName>("mu", "Dynamic viscosity material property");
params.addRequiredParam<Real>("roughness", "Surface roughness");
params.declareControllable("roughness");
return params;
}
WallFrictionChurchillMaterial::WallFrictionChurchillMaterial(const InputParameters & parameters)
: WallFriction3EqnBaseMaterial(parameters)
{
}
void
WallFrictionChurchillMaterial::computeQpProperties()
{
Real Re = RELAP7::Reynolds(1, _rho[_qp], _vel[_qp], _D_h[_qp], _mu[_qp]);
_Cw[_qp] = WallFriction::Churchill(Re, _roughness, _D_h[_qp]) * 2. * _rho[_qp] / _D_h[_qp];
_dCw_drhoA[_qp] = 0;
_dCw_drhouA[_qp] = 0;
_dCw_drhoEA[_qp] = 0;
}
<commit_msg>Update to new register methods<commit_after>#include "WallFrictionChurchillMaterial.h"
#include "WallFrictionModels.h"
#include "Numerics.h"
registerMooseObject("RELAP7App", WallFrictionChurchillMaterial);
template <>
InputParameters
validParams<WallFrictionChurchillMaterial>()
{
InputParameters params = validParams<WallFriction3EqnBaseMaterial>();
params.addRequiredCoupledVar("rhoA", "Mass equation variable: rho*A");
params.addRequiredCoupledVar("rhouA", "Momentum equation variable: rho*u*A");
params.addRequiredCoupledVar("rhoEA", "Total energy equation variable: rho*E*A");
params.addRequiredCoupledVar("rho", "Density");
params.addRequiredCoupledVar("vel", "x-component of the velocity");
params.addRequiredCoupledVar("D_h", "hydraulic diameter");
params.addRequiredParam<MaterialPropertyName>("Cw", "Drag coefficient material property");
params.addRequiredParam<MaterialPropertyName>("mu", "Dynamic viscosity material property");
params.addRequiredParam<Real>("roughness", "Surface roughness");
params.declareControllable("roughness");
return params;
}
WallFrictionChurchillMaterial::WallFrictionChurchillMaterial(const InputParameters & parameters)
: WallFriction3EqnBaseMaterial(parameters)
{
}
void
WallFrictionChurchillMaterial::computeQpProperties()
{
Real Re = RELAP7::Reynolds(1, _rho[_qp], _vel[_qp], _D_h[_qp], _mu[_qp]);
_Cw[_qp] = WallFriction::Churchill(Re, _roughness, _D_h[_qp]) * 2. * _rho[_qp] / _D_h[_qp];
_dCw_drhoA[_qp] = 0;
_dCw_drhouA[_qp] = 0;
_dCw_drhoEA[_qp] = 0;
}
<|endoftext|>
|
<commit_before>//
// OCTrace.cpp
// IPAPatch
//
// Created by wadahana on 01/06/2017.
// Copyright © 2017. All rights reserved.
//
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <dlfcn.h>
#include <assert.h>
#include <string.h>
#include <pthread.h>
#include <uuid/uuid.h>
#include <objc/objc.h>
#include <objc/runtime.h>
#include <mach/mach.h>
#include <mach-o/dyld_images.h>
#include <mach/vm_map.h>
#include <mach-o/loader.h>
#include <mach-o/nlist.h>
#include <mach-o/fat.h>
#include <mach-o/loader.h>
#include <mach-o/dyld.h>
#import "fishhook.h"
#include "OCTrace.h"
#include "OCTraceImage.h"
#include "OCTraceLogger.h"
#include "OCTraceLocalLogger.h"
#include "OCTraceRemoteLogger.h"
#include <vector>
#include <string>
static OCTraceLogger * s_logger = NULL;
static const char * s_skip_image_names[] = {
"WeChat",
"demo",
"IPAPatch",
NULL,
};
static const char * s_skip_class_names[] = {
"NewStrategyItem",
"StrategyInterval",
NULL,
};
static std::vector<OCTraceImage> s_image_list;
typedef id (*fn_objc_msgSend)(id self, SEL op);
static fn_objc_msgSend s_origin_objc_msgSend = NULL;
static bool __skip_image_addr(intptr_t addr) {
bool retval = true;
if (addr != (intptr_t)NULL) {
for (std::vector<OCTraceImage>::iterator itor = s_image_list.begin();
itor != s_image_list.end(); itor += 1) {
OCTraceImage image = *itor;
if (addr >= image.start_addr && addr <= image.end_addr) {
retval = false;
break;
}
}
}
return retval;
}
static bool __skip_class_name(const char * name) {
bool retval = false;
if (name != NULL) {
for (int i = 0; s_skip_class_names[i] != NULL; i++) {
if (strcasecmp(name, s_skip_class_names[i]) == 0) {
retval = true;
}
}
}
return retval;
}
extern "C"
void * __hook_callback_pre(id self, SEL op, intptr_t arg0, intptr_t arg1) {
const char* class_name = (char*) object_getClassName( self );
Class clazz = objc_lookUpClass(class_name);
if (!__skip_image_addr((intptr_t)clazz) && !__skip_class_name(class_name)) {
#if 0
const char* op_name = (const char*) op;
op_name = !op_name ? "null" : op_name;
__uint64_t threadId = 0;
if (pthread_threadid_np(0, &threadId)) {
threadId = pthread_mach_thread_np(pthread_self());
}
fprintf(stderr, "[%ld:%llu] [%s %s] -> \n", (long)getpid(), threadId, class_name, op_name);
#endif
if (s_logger) {
s_logger->logBeforeCallee((intptr_t)self, (intptr_t)op);
}
}
return (void *)s_origin_objc_msgSend;
}
extern "C"
void __hook_callback_post(id self, SEL op) {
// fprintf(stderr, "post self :%p, op:%s\n", self, (const char *)op);
if (s_logger) {
s_logger->logAfterCallee((intptr_t)self, (intptr_t)op);
}
return;
}
#if __LP64__
__attribute__((naked))
static id new_objc_msgSend(id self, SEL op) {
__asm__
__volatile__ (
"stp fp, lr, [sp, #-16]!;\n"
"mov fp, sp;\n"
// store x10-x13,
"sub sp, sp, #(8*16+14*8);\n"
"stp x0, x1, [sp, #(0*8)];\n"
"stp x2, x3, [sp, #(2*8)];\n"
"stp x4, x5, [sp, #(4*8)];\n"
"stp x6, x7, [sp, #(6*8)];\n"
"stp x8, x9, [sp, #(8*8)];\n"
"stp x10, x11, [sp, #(10*8)];\n"
"stp x12, x13, [sp, #(12*8)];\n"
"stp q0, q1, [sp, #(14*8+0*16)];\n"
"stp q2, q3, [sp, #(14*8+2*16)];\n"
"stp q4, q5, [sp, #(14*8+4*16)];\n"
"stp q6, q7, [sp, #(14*8+6*16)];\n"
"ldr x9, [fp];\n"
"add x10, fp, #16;\n"
"adr lr, Llocal_return;\n"
"stp fp, lr, [sp, #-16]!;\n"
"mov fp, sp;\n"
// reconstruct arguments stack
"mov x11, x9;\n"
"mov x12, sp;\n"
"cmp x10, x11;\n"
"bhs Lskip_copy;\n"
"Lcopy_stack:\n"
"ldr x13, [x11,#-8]!;\n"
"str x13, [x12,#-8]!;\n"
"cmp x10, x11;\n"
"bne Lcopy_stack;\n"
"mov sp, x12;\n"
"Lskip_copy:\n"
"adr lr, Llocal_return;\n"
"BL ___hook_callback_pre;\n"
"mov x9, x0;\n"
"add x10, fp, #16;\n"
"ldp x0, x1, [x10, #(0*8)];\n"
"ldp x2, x3, [x10, #(2*8)];\n"
"ldp x4, x5, [x10, #(4*8)];\n"
"ldp x6, x7, [x10, #(6*8)];\n"
"ldr x8, [x10, #(8*8)];\n"
"ldp q0, q1, [x10, #(14*8+0*16)];\n"
"ldp q2, q3, [x10, #(14*8+2*16)];\n"
"ldp q4, q5, [x10, #(14*8+4*16)];\n"
"ldp q6, q7, [x10, #(14*8+6*16)];\n"
"BLR x9;\n"
"Llocal_return:\n"
// store x0-x8 / q0-q7 after call objc_sendMsg.
"add x9, fp, #16;\n"
"ldp x10, x11, [x9, #(0*8)];\n"
"stp x0, x1, [x9, #(0*8)];\n"
"stp x2, x3, [x9, #(2*8)];\n"
"stp x4, x5, [x9, #(4*8)];\n"
"stp x6, x7, [x9, #(6*8)];\n"
"str x8, [x9, #(8*8)];\n"
"stp q0, q1, [x9, #(14*8+0*16)];\n"
"stp q2, q3, [x9, #(14*8+2*16)];\n"
"stp q4, q5, [x9, #(14*8+4*16)];\n"
"stp q6, q7, [x9, #(14*8+6*16)];\n"
// restore self and op before call __hook_callback_post
"mov x0, x10;\n"
"mov x1, x11;\n"
"BL ___hook_callback_post;\n"
"mov sp, fp;\n"
"ldp fp, lr, [sp], #16;\n"
// restore x0-x13 and q0-q7 to objc_sendMsg's return values
"ldp x0, x1, [sp, #(0*8)];\n"
"ldp x2, x3, [sp, #(2*8)];\n"
"ldp x4, x5, [sp, #(4*8)];\n"
"ldp x6, x7, [sp, #(6*8)];\n"
"ldp x8, x9, [sp, #(8*8)];\n"
"ldp x10, x11, [sp, #(10*8)];\n"
"ldp x12, x13, [sp, #(12*8)];\n"
"ldp q0, q1, [sp, #(14*8+0*16)];\n"
"ldp q2, q3, [sp, #(14*8+2*16)];\n"
"ldp q4, q5, [sp, #(14*8+4*16)];\n"
"ldp q6, q7, [sp, #(14*8+6*16)];\n"
"mov sp, fp;\n"
"ldp fp, lr, [sp], #16;\n"
"ret;\n"
);
}
#else
__attribute__((naked))
static id new_objc_msgSend(id self, SEL op) {
}
#endif
int OCTraceInit(OCTraceLogger * logger) {
#if 1
OCTraceImageListInit();
s_image_list.clear();
for(int i = 0; s_skip_image_names[i] != NULL; i++) {
const char * image_name = s_skip_image_names[i];
OCTraceImage image = OCTraceGetImageWithName(image_name);
if (image.start_addr != (intptr_t)NULL) {
s_image_list.insert(s_image_list.end(), image);
}
}
#endif
//s_logger = new OCTraceLocalLogger();
s_logger = logger ;//new OCTraceRemoteLogger();
s_origin_objc_msgSend = (fn_objc_msgSend)dlsym(RTLD_DEFAULT, "objc_msgSend");
return rebind_symbols((struct rebinding[1]){{"objc_msgSend", (void *)new_objc_msgSend}}, 1);
}
<commit_msg>use imp addr to check image<commit_after>//
// OCTrace.cpp
// IPAPatch
//
// Created by wadahana on 01/06/2017.
// Copyright © 2017. All rights reserved.
//
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <dlfcn.h>
#include <assert.h>
#include <string.h>
#include <pthread.h>
#include <uuid/uuid.h>
#include <objc/objc.h>
#include <objc/runtime.h>
#include <mach/mach.h>
#include <mach-o/dyld_images.h>
#include <mach/vm_map.h>
#include <mach-o/loader.h>
#include <mach-o/nlist.h>
#include <mach-o/fat.h>
#include <mach-o/loader.h>
#include <mach-o/dyld.h>
#import "fishhook.h"
#include "OCTrace.h"
#include "OCTraceImage.h"
#include "OCTraceLogger.h"
#include "OCTraceLocalLogger.h"
#include "OCTraceRemoteLogger.h"
#include <vector>
#include <string>
static OCTraceLogger * s_logger = NULL;
static const char * s_skip_image_names[] = {
"WeChat",
"demo",
"IPAPatch",
NULL,
};
static const char * s_skip_class_names[] = {
"NewStrategyItem",
"StrategyInterval",
NULL,
};
static std::vector<OCTraceImage> s_image_list;
typedef id (*fn_objc_msgSend)(id self, SEL op);
static fn_objc_msgSend s_origin_objc_msgSend = NULL;
static bool __skip_image_addr(intptr_t addr) {
bool retval = true;
if (addr != (intptr_t)NULL) {
for (std::vector<OCTraceImage>::iterator itor = s_image_list.begin();
itor != s_image_list.end(); itor += 1) {
OCTraceImage image = *itor;
if (addr >= image.start_addr && addr <= image.end_addr) {
retval = false;
break;
}
}
}
return retval;
}
static bool __skip_class_name(const char * name) {
bool retval = false;
if (name != NULL) {
for (int i = 0; s_skip_class_names[i] != NULL; i++) {
if (strcasecmp(name, s_skip_class_names[i]) == 0) {
retval = true;
}
}
}
return retval;
}
extern "C"
void * __hook_callback_pre(id self, SEL op, intptr_t arg0, intptr_t arg1) {
const char* class_name = (char*) object_getClassName( self );
Class clazz = objc_lookUpClass(class_name);
IMP imp = method_getImplementation(class_getInstanceMethod(clazz, op));
if (!imp) {
imp = method_getImplementation(class_getClassMethod(clazz, op));
}
if (!__skip_image_addr((intptr_t)imp) && !__skip_class_name(class_name)) {
#if 0
const char* op_name = (const char*) op;
op_name = !op_name ? "null" : op_name;
__uint64_t threadId = 0;
if (pthread_threadid_np(0, &threadId)) {
threadId = pthread_mach_thread_np(pthread_self());
}
fprintf(stderr, "[%ld:%llu] [%s %s] -> \n", (long)getpid(), threadId, class_name, op_name);
#endif
if (s_logger) {
s_logger->logBeforeCallee((intptr_t)self, (intptr_t)op);
}
}
return (void *)s_origin_objc_msgSend;
}
extern "C"
void __hook_callback_post(id self, SEL op) {
// fprintf(stderr, "post self :%p, op:%s\n", self, (const char *)op);
if (s_logger) {
s_logger->logAfterCallee((intptr_t)self, (intptr_t)op);
}
return;
}
#if __LP64__
__attribute__((naked))
static id new_objc_msgSend(id self, SEL op) {
__asm__
__volatile__ (
"stp fp, lr, [sp, #-16]!;\n"
"mov fp, sp;\n"
// store x10-x13,
"sub sp, sp, #(8*16+14*8);\n"
"stp x0, x1, [sp, #(0*8)];\n"
"stp x2, x3, [sp, #(2*8)];\n"
"stp x4, x5, [sp, #(4*8)];\n"
"stp x6, x7, [sp, #(6*8)];\n"
"stp x8, x9, [sp, #(8*8)];\n"
"stp x10, x11, [sp, #(10*8)];\n"
"stp x12, x13, [sp, #(12*8)];\n"
"stp q0, q1, [sp, #(14*8+0*16)];\n"
"stp q2, q3, [sp, #(14*8+2*16)];\n"
"stp q4, q5, [sp, #(14*8+4*16)];\n"
"stp q6, q7, [sp, #(14*8+6*16)];\n"
"ldr x9, [fp];\n"
"add x10, fp, #16;\n"
"adr lr, Llocal_return;\n"
"stp fp, lr, [sp, #-16]!;\n"
"mov fp, sp;\n"
// reconstruct arguments stack
"mov x11, x9;\n"
"mov x12, sp;\n"
"cmp x10, x11;\n"
"bhs Lskip_copy;\n"
"Lcopy_stack:\n"
"ldr x13, [x11,#-8]!;\n"
"str x13, [x12,#-8]!;\n"
"cmp x10, x11;\n"
"bne Lcopy_stack;\n"
"mov sp, x12;\n"
"Lskip_copy:\n"
"adr lr, Llocal_return;\n"
"BL ___hook_callback_pre;\n"
"mov x9, x0;\n"
"add x10, fp, #16;\n"
"ldp x0, x1, [x10, #(0*8)];\n"
"ldp x2, x3, [x10, #(2*8)];\n"
"ldp x4, x5, [x10, #(4*8)];\n"
"ldp x6, x7, [x10, #(6*8)];\n"
"ldr x8, [x10, #(8*8)];\n"
"ldp q0, q1, [x10, #(14*8+0*16)];\n"
"ldp q2, q3, [x10, #(14*8+2*16)];\n"
"ldp q4, q5, [x10, #(14*8+4*16)];\n"
"ldp q6, q7, [x10, #(14*8+6*16)];\n"
"BLR x9;\n"
"Llocal_return:\n"
// store x0-x8 / q0-q7 after call objc_sendMsg.
"add x9, fp, #16;\n"
"ldp x10, x11, [x9, #(0*8)];\n"
"stp x0, x1, [x9, #(0*8)];\n"
"stp x2, x3, [x9, #(2*8)];\n"
"stp x4, x5, [x9, #(4*8)];\n"
"stp x6, x7, [x9, #(6*8)];\n"
"str x8, [x9, #(8*8)];\n"
"stp q0, q1, [x9, #(14*8+0*16)];\n"
"stp q2, q3, [x9, #(14*8+2*16)];\n"
"stp q4, q5, [x9, #(14*8+4*16)];\n"
"stp q6, q7, [x9, #(14*8+6*16)];\n"
// restore self and op before call __hook_callback_post
"mov x0, x10;\n"
"mov x1, x11;\n"
"BL ___hook_callback_post;\n"
"mov sp, fp;\n"
"ldp fp, lr, [sp], #16;\n"
// restore x0-x13 and q0-q7 to objc_sendMsg's return values
"ldp x0, x1, [sp, #(0*8)];\n"
"ldp x2, x3, [sp, #(2*8)];\n"
"ldp x4, x5, [sp, #(4*8)];\n"
"ldp x6, x7, [sp, #(6*8)];\n"
"ldp x8, x9, [sp, #(8*8)];\n"
"ldp x10, x11, [sp, #(10*8)];\n"
"ldp x12, x13, [sp, #(12*8)];\n"
"ldp q0, q1, [sp, #(14*8+0*16)];\n"
"ldp q2, q3, [sp, #(14*8+2*16)];\n"
"ldp q4, q5, [sp, #(14*8+4*16)];\n"
"ldp q6, q7, [sp, #(14*8+6*16)];\n"
"mov sp, fp;\n"
"ldp fp, lr, [sp], #16;\n"
"ret;\n"
);
}
#else
__attribute__((naked))
static id new_objc_msgSend(id self, SEL op) {
}
#endif
int OCTraceInit(OCTraceLogger * logger) {
#if 1
OCTraceImageListInit();
s_image_list.clear();
for(int i = 0; s_skip_image_names[i] != NULL; i++) {
const char * image_name = s_skip_image_names[i];
OCTraceImage image = OCTraceGetImageWithName(image_name);
if (image.start_addr != (intptr_t)NULL) {
s_image_list.insert(s_image_list.end(), image);
}
}
#endif
s_logger = new OCTraceLocalLogger();
//s_logger = logger ;//new OCTraceRemoteLogger();
s_origin_objc_msgSend = (fn_objc_msgSend)dlsym(RTLD_DEFAULT, "objc_msgSend");
return rebind_symbols((struct rebinding[1]){{"objc_msgSend", (void *)new_objc_msgSend}}, 1);
}
<|endoftext|>
|
<commit_before>//----------------------------------------------------------------------------
//
// "Copyright Centre National d'Etudes Spatiales"
//
// License: LGPL
//
// See LICENSE.txt file in the top level directory for more details.
//
//----------------------------------------------------------------------------
// $Id$
#include <otb/HermiteInterpolator.h>
#include <string>
#include <cassert>
namespace ossimplugins
{
HermiteInterpolator::HermiteInterpolator():
theNPointsAvailable(0),
theXValues(NULL),
theYValues(NULL),
thedYValues(NULL),
prodC(NULL),
sumC(NULL),
isComputed(false)
{
}
HermiteInterpolator::HermiteInterpolator(int nbrPoints, double* x, double* y, double* dy):
theNPointsAvailable(nbrPoints),
isComputed(false)
{
if(x != NULL)
{
theXValues = new double[theNPointsAvailable];
for (int i=0;i<theNPointsAvailable;i++)
{
theXValues[i] = x[i];
}
}
else
{
theXValues = NULL;
}
if(y != NULL)
{
theYValues = new double[theNPointsAvailable];
for (int i=0;i<theNPointsAvailable;i++)
{
theYValues[i] = y[i];
}
}
else
{
theYValues = NULL;
}
if(dy != NULL)
{
thedYValues = new double[theNPointsAvailable];
for (int i=0;i<theNPointsAvailable;i++)
{
thedYValues[i] = dy[i];
}
}
else
{
thedYValues = NULL;
}
for (int i = 1 ; i < theNPointsAvailable ; i++)
{
/**
* @todo Verifier que l'interpolateur n'ai pas besoin ques les abscisses soitent strictement croissantes
*/
/*
* Les abscisses ne sont pas croissantes
*/
// if (theXValues[i] <= theXValues[i-1])
// std::cerr << "WARNING: Hermite interpolation assumes increasing x values" << std::endl;
assert(theXValues[i] > theXValues[i-1]);
}
}
HermiteInterpolator::~HermiteInterpolator()
{
Clear();
}
HermiteInterpolator::HermiteInterpolator(const HermiteInterpolator& rhs):
theNPointsAvailable(rhs.theNPointsAvailable),
isComputed(false)
{
if(rhs.theXValues != NULL)
{
theXValues = new double[theNPointsAvailable];
for (int i=0;i<theNPointsAvailable;i++)
{
theXValues[i] = rhs.theXValues[i];
}
}
else
{
theXValues = NULL;
}
if(rhs.theYValues != NULL)
{
theYValues = new double[theNPointsAvailable];
for (int i=0;i<theNPointsAvailable;i++)
{
theYValues[i] = rhs.theYValues[i];
}
}
else
{
theYValues = NULL;
}
if(rhs.thedYValues != NULL)
{
thedYValues = new double[theNPointsAvailable];
for (int i=0;i<theNPointsAvailable;i++)
{
thedYValues[i] = rhs.thedYValues[i];
}
}
else
{
thedYValues = NULL;
}
}
HermiteInterpolator& HermiteInterpolator::operator =(const HermiteInterpolator& rhs)
{
Clear();
theNPointsAvailable = rhs.theNPointsAvailable;
isComputed = false;
if(rhs.theXValues != NULL)
{
theXValues = new double[theNPointsAvailable];
for (int i=0;i<theNPointsAvailable;i++)
{
theXValues[i] = rhs.theXValues[i];
}
}
else
{
theXValues = NULL;
}
if(rhs.theYValues != NULL)
{
theYValues = new double[theNPointsAvailable];
for (int i=0;i<theNPointsAvailable;i++)
{
theYValues[i] = rhs.theYValues[i];
}
}
else
{
theYValues = NULL;
}
if(rhs.thedYValues != NULL)
{
thedYValues = new double[theNPointsAvailable];
for (int i=0;i<theNPointsAvailable;i++)
{
thedYValues[i] = rhs.thedYValues[i];
}
}
else
{
thedYValues = NULL;
}
return *this;
}
// Interpolation method for the value and the derivative
int HermiteInterpolator::Interpolate(double x, double& y, double& dy) const
{
//NOTE assume that x is increasing
// Not enough points to interpolate
if (theNPointsAvailable < 2) return -1;
y = 0.0;
dy = 0.0;
//Precompute useful value if they are not available
if (!isComputed)
{
Precompute();
}
for (int i = 0; i < theNPointsAvailable; i++)
{
double si = 0.0;
double hi = 1.0;
double ui = 0; //derivative computation
double r = x - theXValues[i];
for (int j = 0; j < theNPointsAvailable; j++)
{
if (j != i)
{
hi = hi * (x - theXValues[j]);
ui = ui + 1 / (x - theXValues[j]);//derivative computation
}
}
hi *= prodC[i];
si = sumC[i];
double f = 1.0 - 2.0 * r * si;
y += (theYValues[i] * f + thedYValues[i] * r) * hi * hi;
ui *= hi;//derivative computation
double fp = 2.0 * hi * (ui * (1.0 - 2.0 * si * r) - hi * si);//derivative computation
double d = hi * (hi + 2.0 * r * ui);//derivative computation
dy += fp * theYValues[i] + d * thedYValues[i];//derivative computation
}
return 0;
}
// Interpolation method for the value only
// this is about 5 times faster and should be used when time
// is a constraint.
int HermiteInterpolator::Interpolate(double x, double& y) const
{
//NOTE assume that x is increasing
// Not enough points to interpolate
if (theNPointsAvailable < 2) return -1;
y = 0.0;
//Precompute useful value if they are not available
if (!isComputed)
{
Precompute();
}
for (int i = 0; i < theNPointsAvailable; i++)
{
double si = 0.0;
double hi = 1.0;
double r = x - theXValues[i];
for (int j = 0; j < theNPointsAvailable; j++)
{
if (j != i)
{
hi = hi * (x - theXValues[j]);
}
}
hi *= prodC[i];
si = sumC[i];
double f = 1.0 - 2.0 * r * si;
y += (theYValues[i] * f + thedYValues[i] * r) * hi * hi;
}
return 0;
}
int HermiteInterpolator::Precompute() const
{
prodC = new double[theNPointsAvailable];
sumC= new double[theNPointsAvailable];
for (int i = 0; i < theNPointsAvailable; i++)
{
prodC[i] = 1;
sumC[i] = 0;
for (int j = 0; j < theNPointsAvailable; j++)
{
if (j != i)
{
double v = 1.0 / (theXValues[i] - theXValues[j]);
prodC[i] *= v;
sumC[i] += v;
}
}
}
isComputed = true;
}
void HermiteInterpolator::Clear()
{
if (theXValues != NULL)
{
delete[] theXValues;
theXValues = NULL;
}
if (theYValues != NULL)
{
delete[] theYValues;
theYValues = NULL;
}
if (thedYValues != NULL)
{
delete[] thedYValues;
thedYValues = NULL;
}
if (prodC != NULL)
{
delete[] prodC;
prodC = NULL;
}
if (sumC != NULL)
{
delete[] sumC;
prodC = NULL;
}
isComputed = false;
theNPointsAvailable = 0;
}
}
<commit_msg>WRG: fix warning<commit_after>//----------------------------------------------------------------------------
//
// "Copyright Centre National d'Etudes Spatiales"
//
// License: LGPL
//
// See LICENSE.txt file in the top level directory for more details.
//
//----------------------------------------------------------------------------
// $Id$
#include <otb/HermiteInterpolator.h>
#include <string>
#include <cassert>
namespace ossimplugins
{
HermiteInterpolator::HermiteInterpolator():
theNPointsAvailable(0),
theXValues(NULL),
theYValues(NULL),
thedYValues(NULL),
prodC(NULL),
sumC(NULL),
isComputed(false)
{
}
HermiteInterpolator::HermiteInterpolator(int nbrPoints, double* x, double* y, double* dy):
theNPointsAvailable(nbrPoints),
isComputed(false)
{
if(x != NULL)
{
theXValues = new double[theNPointsAvailable];
for (int i=0;i<theNPointsAvailable;i++)
{
theXValues[i] = x[i];
}
}
else
{
theXValues = NULL;
}
if(y != NULL)
{
theYValues = new double[theNPointsAvailable];
for (int i=0;i<theNPointsAvailable;i++)
{
theYValues[i] = y[i];
}
}
else
{
theYValues = NULL;
}
if(dy != NULL)
{
thedYValues = new double[theNPointsAvailable];
for (int i=0;i<theNPointsAvailable;i++)
{
thedYValues[i] = dy[i];
}
}
else
{
thedYValues = NULL;
}
for (int i = 1 ; i < theNPointsAvailable ; i++)
{
/**
* @todo Verifier que l'interpolateur n'ai pas besoin ques les abscisses soitent strictement croissantes
*/
/*
* Les abscisses ne sont pas croissantes
*/
// if (theXValues[i] <= theXValues[i-1])
// std::cerr << "WARNING: Hermite interpolation assumes increasing x values" << std::endl;
assert(theXValues[i] > theXValues[i-1]);
}
}
HermiteInterpolator::~HermiteInterpolator()
{
Clear();
}
HermiteInterpolator::HermiteInterpolator(const HermiteInterpolator& rhs):
theNPointsAvailable(rhs.theNPointsAvailable),
isComputed(false)
{
if(rhs.theXValues != NULL)
{
theXValues = new double[theNPointsAvailable];
for (int i=0;i<theNPointsAvailable;i++)
{
theXValues[i] = rhs.theXValues[i];
}
}
else
{
theXValues = NULL;
}
if(rhs.theYValues != NULL)
{
theYValues = new double[theNPointsAvailable];
for (int i=0;i<theNPointsAvailable;i++)
{
theYValues[i] = rhs.theYValues[i];
}
}
else
{
theYValues = NULL;
}
if(rhs.thedYValues != NULL)
{
thedYValues = new double[theNPointsAvailable];
for (int i=0;i<theNPointsAvailable;i++)
{
thedYValues[i] = rhs.thedYValues[i];
}
}
else
{
thedYValues = NULL;
}
}
HermiteInterpolator& HermiteInterpolator::operator =(const HermiteInterpolator& rhs)
{
Clear();
theNPointsAvailable = rhs.theNPointsAvailable;
isComputed = false;
if(rhs.theXValues != NULL)
{
theXValues = new double[theNPointsAvailable];
for (int i=0;i<theNPointsAvailable;i++)
{
theXValues[i] = rhs.theXValues[i];
}
}
else
{
theXValues = NULL;
}
if(rhs.theYValues != NULL)
{
theYValues = new double[theNPointsAvailable];
for (int i=0;i<theNPointsAvailable;i++)
{
theYValues[i] = rhs.theYValues[i];
}
}
else
{
theYValues = NULL;
}
if(rhs.thedYValues != NULL)
{
thedYValues = new double[theNPointsAvailable];
for (int i=0;i<theNPointsAvailable;i++)
{
thedYValues[i] = rhs.thedYValues[i];
}
}
else
{
thedYValues = NULL;
}
return *this;
}
// Interpolation method for the value and the derivative
int HermiteInterpolator::Interpolate(double x, double& y, double& dy) const
{
//NOTE assume that x is increasing
// Not enough points to interpolate
if (theNPointsAvailable < 2) return -1;
y = 0.0;
dy = 0.0;
//Precompute useful value if they are not available
if (!isComputed)
{
Precompute();
}
for (int i = 0; i < theNPointsAvailable; i++)
{
double si = 0.0;
double hi = 1.0;
double ui = 0; //derivative computation
double r = x - theXValues[i];
for (int j = 0; j < theNPointsAvailable; j++)
{
if (j != i)
{
hi = hi * (x - theXValues[j]);
ui = ui + 1 / (x - theXValues[j]);//derivative computation
}
}
hi *= prodC[i];
si = sumC[i];
double f = 1.0 - 2.0 * r * si;
y += (theYValues[i] * f + thedYValues[i] * r) * hi * hi;
ui *= hi;//derivative computation
double fp = 2.0 * hi * (ui * (1.0 - 2.0 * si * r) - hi * si);//derivative computation
double d = hi * (hi + 2.0 * r * ui);//derivative computation
dy += fp * theYValues[i] + d * thedYValues[i];//derivative computation
}
return 0;
}
// Interpolation method for the value only
// this is about 5 times faster and should be used when time
// is a constraint.
int HermiteInterpolator::Interpolate(double x, double& y) const
{
//NOTE assume that x is increasing
// Not enough points to interpolate
if (theNPointsAvailable < 2) return -1;
y = 0.0;
//Precompute useful value if they are not available
if (!isComputed)
{
Precompute();
}
for (int i = 0; i < theNPointsAvailable; i++)
{
double si = 0.0;
double hi = 1.0;
double r = x - theXValues[i];
for (int j = 0; j < theNPointsAvailable; j++)
{
if (j != i)
{
hi = hi * (x - theXValues[j]);
}
}
hi *= prodC[i];
si = sumC[i];
double f = 1.0 - 2.0 * r * si;
y += (theYValues[i] * f + thedYValues[i] * r) * hi * hi;
}
return 0;
}
int HermiteInterpolator::Precompute() const
{
prodC = new double[theNPointsAvailable];
sumC= new double[theNPointsAvailable];
for (int i = 0; i < theNPointsAvailable; i++)
{
prodC[i] = 1;
sumC[i] = 0;
for (int j = 0; j < theNPointsAvailable; j++)
{
if (j != i)
{
double v = 1.0 / (theXValues[i] - theXValues[j]);
prodC[i] *= v;
sumC[i] += v;
}
}
}
isComputed = true;
return 0;
}
void HermiteInterpolator::Clear()
{
if (theXValues != NULL)
{
delete[] theXValues;
theXValues = NULL;
}
if (theYValues != NULL)
{
delete[] theYValues;
theYValues = NULL;
}
if (thedYValues != NULL)
{
delete[] thedYValues;
thedYValues = NULL;
}
if (prodC != NULL)
{
delete[] prodC;
prodC = NULL;
}
if (sumC != NULL)
{
delete[] sumC;
prodC = NULL;
}
isComputed = false;
theNPointsAvailable = 0;
}
}
<|endoftext|>
|
<commit_before>#include <rclcpp/rclcpp.hpp>
#include <std_msgs/String.h>
#include "std_msgs/dds_impl/String_convert.h"
#include <std_msgs/Int32.h>
#include <rclcpp_examples/AddTwoIntsRequest.h>
#include <rclcpp_examples/AddTwoIntsResponse.h>
#include "std_msgs/dds_impl/Int32_convert.h"
#include "rclcpp_examples/dds_impl/AddTwoIntsRequest_convert.h"
#include "rclcpp_examples/dds_impl/AddTwoIntsResponse_convert.h"
#include <iostream>
int main(int argc, char** argv)
{
rclcpp::init(argc, argv);
rclcpp::Node::Ptr node = rclcpp::create_node("add_two_ints_server");
auto client = node->create_client<rclcpp_examples::AddTwoIntsRequest, rclcpp_examples::AddTwoIntsResponse>("add_two_ints");
rclcpp_examples::AddTwoIntsRequest req;
req.a = 2;
req.b = 3;
auto response = client->async_call(req);
//std::cout << "Sum: " << response->sum << std::endl;
node->spin();
return 0;
}
<commit_msg>Use sync call<commit_after>#include <rclcpp/rclcpp.hpp>
#include <std_msgs/String.h>
#include "std_msgs/dds_impl/String_convert.h"
#include <std_msgs/Int32.h>
#include <rclcpp_examples/AddTwoIntsRequest.h>
#include <rclcpp_examples/AddTwoIntsResponse.h>
#include "std_msgs/dds_impl/Int32_convert.h"
#include "rclcpp_examples/dds_impl/AddTwoIntsRequest_convert.h"
#include "rclcpp_examples/dds_impl/AddTwoIntsResponse_convert.h"
#include <iostream>
int main(int argc, char** argv)
{
rclcpp::init(argc, argv);
rclcpp::Node::Ptr node = rclcpp::create_node("add_two_ints_server");
auto client = node->create_client<rclcpp_examples::AddTwoIntsRequest, rclcpp_examples::AddTwoIntsResponse>("add_two_ints");
rclcpp_examples::AddTwoIntsRequest req;
req.a = 2;
req.b = 3;
auto response = client->call(req);
std::cout << "Sum: " << response->sum << std::endl;
return 0;
}
<|endoftext|>
|
<commit_before>/**
This file contains a sequence of tests to perform for different instances of a templatized fixture.
It is thus inlined several times in the .cpp test file.
*/
// ==============================
// Set/get value tests
TEST_F(TestMatrix, set_fullMat ) { ASSERT_TRUE( matrixMaxDiff(mat,fullMat) < 100*epsilon() ); }
TEST_F(TestMatrix, set_crs1 ) { ASSERT_TRUE( matrixMaxDiff( fullMat,crs1 ) < 100*epsilon() ); }
TEST_F(TestMatrix, set_crs2 ) { ASSERT_TRUE( matrixMaxDiff(fullMat,crs2) < 100*epsilon() ); }
TEST_F(TestMatrix, set_mapMat ) { ASSERT_TRUE( matrixMaxDiff(fullMat,mapMat) < 100*epsilon() ); }
TEST_F(TestMatrix, set_eiBlock1 ) { ASSERT_TRUE( matrixMaxDiff(fullMat,eiBlock1) < 100*epsilon() ); }
TEST_F(TestMatrix, set_eiBlock2 ) { ASSERT_TRUE( matrixMaxDiff(fullMat,eiBlock2) < 100*epsilon() ); }
TEST_F(TestMatrix, set_eiBase ) { ASSERT_TRUE( matrixMaxDiff(fullMat,eiBase) < 100*epsilon() ); }
TEST_F(TestMatrix, eigenMatrix_update ) { ASSERT_TRUE( checkEigenMatrixUpdate() ); }
TEST_F(TestMatrix, eigenMatrix_block_row_filling ) { ASSERT_TRUE( checkEigenMatrixBlockRowFilling() ); }
TEST_F(TestMatrix, eigenMatrixBlockFromCompressedRowSparseMatrix ) { ASSERT_TRUE( checkEigenMatrixBlockFromCompressedRowSparseMatrix() ); }
TEST_F(TestMatrix, eigenMapToDenseMatrix ) { ASSERT_TRUE( checkEigenDenseMatrix() ); }
// ==============================
// Matrix-Vector product tests
TEST_F(TestMatrix, set_fullVec_nrows_reference )
{
ASSERT_TRUE(vectorMaxDiff(vecM,fullVec_nrows_reference) < epsilon() );
}
TEST_F(TestMatrix, fullMat_vector_product )
{
// fullMat.opMulV(&fullVec_nrows_result,&fullVec_ncols);
fullVec_nrows_result = fullMat * fullVec_ncols;
ASSERT_TRUE(vectorMaxDiff(fullVec_nrows_reference,fullVec_nrows_result) < epsilon() );
}
TEST_F(TestMatrix, mapMat_vector_product )
{
// mapMat.opMulV(&fullVec_nrows_result,&fullVec_ncols);
fullVec_nrows_result = mapMat * fullVec_ncols;
ASSERT_TRUE(vectorMaxDiff(fullVec_nrows_reference,fullVec_nrows_result) < epsilon() );
}
TEST_F(TestMatrix, eiBlock1_vector_product )
{
// eiBlock1.opMulV(&fullVec_nrows_result,&fullVec_ncols);
// eiBlock1.multVector(fullVec_nrows_result,fullVec_ncols);
fullVec_nrows_result = eiBlock1 * fullVec_ncols;
ASSERT_TRUE(vectorMaxDiff(fullVec_nrows_reference,fullVec_nrows_result) < epsilon() );
}
TEST_F(TestMatrix, crs1_vector_product )
{
// EXPECT_TRUE(NROWS%BROWS==0 && NCOLS%BCOLS==0) << "Error: CompressedRowSparseMatrix * Vector crashes when the size of the matrix is not a multiple of the size of the matrix blocks. Aborting this test, and reporting a failure."; // otherwise the product crashes
// crs1.opMulV(&fullVec_nrows_result,&fullVec_ncols);
fullVec_nrows_result = crs1 * fullVec_ncols;
ASSERT_TRUE(vectorMaxDiff(fullVec_nrows_reference,fullVec_nrows_result) < epsilon() );
}
// ==============================
// Matrix product tests
TEST_F(TestMatrix, full_matrix_product ) { ASSERT_TRUE( matrixMaxDiff(matMultiplication,fullMultiplication) < 100*epsilon() ); }
TEST_F(TestMatrix, crs_matrix_product ) { ASSERT_TRUE( matrixMaxDiff(fullMultiplication,crsMultiplication) < 100*epsilon() ); }
TEST_F(TestMatrix, EigenBase_matrix_product ) { ASSERT_TRUE( matrixMaxDiff(fullMultiplication,eiBaseMultiplication) < 100*epsilon() ); }
TEST_F(TestMatrix, EigenSparseDense_matrix_product ) { ASSERT_TRUE( EigenDenseMatrix(eiBaseMultiplication.compressedMatrix) == eiDenseMultiplication ); }
TEST_F(TestMatrix, full_matrix_transposeproduct ) { ASSERT_TRUE( matrixMaxDiff(matTransposeMultiplication,fullTransposeMultiplication) < 100*epsilon() ); }
TEST_F(TestMatrix, crs_matrix_transposeproduct ) { ASSERT_TRUE( matrixMaxDiff(fullTransposeMultiplication,crsTransposeMultiplication) < 100*epsilon() ); }
// Matrix addition
TEST_F(TestMatrix, crs_matrix_addition )
{
crs2 = crs1 + crs1;
ASSERT_TRUE( matrixMaxDiff(mat*2,crs2) < 100*epsilon() );
crs2 += crs1;
ASSERT_TRUE( matrixMaxDiff(mat*3,crs2) < 100*epsilon() );
crs2 -= crs1;
ASSERT_FALSE( matrixMaxDiff(mat*2,crs2) < 100*epsilon() ); // create an error to check if I get a message from Jenkins
// ASSERT_TRUE( matrixMaxDiff(mat*2,crs2) < 100*epsilon() );
}
<commit_msg>META-TEST adding a failure<commit_after>/**
This file contains a sequence of tests to perform for different instances of a templatized fixture.
It is thus inlined several times in the .cpp test file.
*/
// ==============================
// Set/get value tests
TEST_F(TestMatrix, set_fullMat ) { ASSERT_TRUE( matrixMaxDiff(mat,fullMat) < 100*epsilon() ); }
TEST_F(TestMatrix, set_crs1 ) { ASSERT_TRUE( matrixMaxDiff( fullMat,crs1 ) < 100*epsilon() ); }
TEST_F(TestMatrix, set_crs2 ) { ASSERT_TRUE( matrixMaxDiff(fullMat,crs2) < 100*epsilon() ); }
TEST_F(TestMatrix, set_mapMat ) { ASSERT_TRUE( matrixMaxDiff(fullMat,mapMat) < 100*epsilon() ); }
TEST_F(TestMatrix, set_eiBlock1 ) { ASSERT_TRUE( matrixMaxDiff(fullMat,eiBlock1) < 100*epsilon() ); }
TEST_F(TestMatrix, set_eiBlock2 ) { ASSERT_TRUE( matrixMaxDiff(fullMat,eiBlock2) < 100*epsilon() ); }
TEST_F(TestMatrix, set_eiBase ) { ASSERT_TRUE( matrixMaxDiff(fullMat,eiBase) < 100*epsilon() ); }
TEST_F(TestMatrix, eigenMatrix_update ) { ASSERT_TRUE( checkEigenMatrixUpdate() ); }
TEST_F(TestMatrix, eigenMatrix_block_row_filling ) { ASSERT_TRUE( checkEigenMatrixBlockRowFilling() ); }
TEST_F(TestMatrix, eigenMatrixBlockFromCompressedRowSparseMatrix ) { ASSERT_TRUE( checkEigenMatrixBlockFromCompressedRowSparseMatrix() ); }
TEST_F(TestMatrix, eigenMapToDenseMatrix ) { ASSERT_TRUE( checkEigenDenseMatrix() ); }
// ==============================
// Matrix-Vector product tests
TEST_F(TestMatrix, set_fullVec_nrows_reference )
{
ASSERT_TRUE(vectorMaxDiff(vecM,fullVec_nrows_reference) < epsilon() );
}
TEST_F(TestMatrix, fullMat_vector_product )
{
// fullMat.opMulV(&fullVec_nrows_result,&fullVec_ncols);
fullVec_nrows_result = fullMat * fullVec_ncols;
ASSERT_TRUE(vectorMaxDiff(fullVec_nrows_reference,fullVec_nrows_result) < epsilon() );
}
TEST_F(TestMatrix, mapMat_vector_product )
{
// mapMat.opMulV(&fullVec_nrows_result,&fullVec_ncols);
fullVec_nrows_result = mapMat * fullVec_ncols;
ASSERT_TRUE(vectorMaxDiff(fullVec_nrows_reference,fullVec_nrows_result) < epsilon() );
}
TEST_F(TestMatrix, eiBlock1_vector_product )
{
// eiBlock1.opMulV(&fullVec_nrows_result,&fullVec_ncols);
// eiBlock1.multVector(fullVec_nrows_result,fullVec_ncols);
fullVec_nrows_result = eiBlock1 * fullVec_ncols;
ASSERT_TRUE(vectorMaxDiff(fullVec_nrows_reference,fullVec_nrows_result) < epsilon() );
}
TEST_F(TestMatrix, crs1_vector_product )
{
// EXPECT_TRUE(NROWS%BROWS==0 && NCOLS%BCOLS==0) << "Error: CompressedRowSparseMatrix * Vector crashes when the size of the matrix is not a multiple of the size of the matrix blocks. Aborting this test, and reporting a failure."; // otherwise the product crashes
// crs1.opMulV(&fullVec_nrows_result,&fullVec_ncols);
fullVec_nrows_result = crs1 * fullVec_ncols;
ASSERT_FALSE(vectorMaxDiff(fullVec_nrows_reference,fullVec_nrows_result) < epsilon() ); // create an error to check if I get a message from Jenkins
// ASSERT_TRUE(vectorMaxDiff(fullVec_nrows_reference,fullVec_nrows_result) < epsilon() );
}
// ==============================
// Matrix product tests
TEST_F(TestMatrix, full_matrix_product ) { ASSERT_TRUE( matrixMaxDiff(matMultiplication,fullMultiplication) < 100*epsilon() ); }
TEST_F(TestMatrix, crs_matrix_product ) { ASSERT_TRUE( matrixMaxDiff(fullMultiplication,crsMultiplication) < 100*epsilon() ); }
TEST_F(TestMatrix, EigenBase_matrix_product ) { ASSERT_TRUE( matrixMaxDiff(fullMultiplication,eiBaseMultiplication) < 100*epsilon() ); }
TEST_F(TestMatrix, EigenSparseDense_matrix_product ) { ASSERT_TRUE( EigenDenseMatrix(eiBaseMultiplication.compressedMatrix) == eiDenseMultiplication ); }
TEST_F(TestMatrix, full_matrix_transposeproduct ) { ASSERT_TRUE( matrixMaxDiff(matTransposeMultiplication,fullTransposeMultiplication) < 100*epsilon() ); }
TEST_F(TestMatrix, crs_matrix_transposeproduct ) { ASSERT_TRUE( matrixMaxDiff(fullTransposeMultiplication,crsTransposeMultiplication) < 100*epsilon() ); }
// Matrix addition
TEST_F(TestMatrix, crs_matrix_addition )
{
crs2 = crs1 + crs1;
ASSERT_TRUE( matrixMaxDiff(mat*2,crs2) < 100*epsilon() );
crs2 += crs1;
ASSERT_TRUE( matrixMaxDiff(mat*3,crs2) < 100*epsilon() );
crs2 -= crs1;
ASSERT_FALSE( matrixMaxDiff(mat*2,crs2) < 100*epsilon() ); // create an error to check if I get a message from Jenkins
// ASSERT_TRUE( matrixMaxDiff(mat*2,crs2) < 100*epsilon() );
}
<|endoftext|>
|
<commit_before>//===-- SymbolVendorMacOSX.cpp ----------------------------------*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "SymbolVendorMacOSX.h"
#include <string.h>
#include "lldb/Core/Module.h"
#include "lldb/Core/ModuleSpec.h"
#include "lldb/Core/PluginManager.h"
#include "lldb/Core/Section.h"
#include "lldb/Core/StreamString.h"
#include "lldb/Core/Timer.h"
#include "lldb/Host/Host.h"
#include "lldb/Host/Symbols.h"
#include "lldb/Host/XML.h"
#include "lldb/Symbol/ObjectFile.h"
using namespace lldb;
using namespace lldb_private;
//----------------------------------------------------------------------
// SymbolVendorMacOSX constructor
//----------------------------------------------------------------------
SymbolVendorMacOSX::SymbolVendorMacOSX(const lldb::ModuleSP &module_sp) :
SymbolVendor (module_sp)
{
}
//----------------------------------------------------------------------
// Destructor
//----------------------------------------------------------------------
SymbolVendorMacOSX::~SymbolVendorMacOSX()
{
}
static bool
UUIDsMatch(Module *module, ObjectFile *ofile, lldb_private::Stream *feedback_strm)
{
if (module && ofile)
{
// Make sure the UUIDs match
lldb_private::UUID dsym_uuid;
if (!ofile->GetUUID(&dsym_uuid))
{
if (feedback_strm)
{
feedback_strm->PutCString("warning: failed to get the uuid for object file: '");
ofile->GetFileSpec().Dump(feedback_strm);
feedback_strm->PutCString("\n");
}
return false;
}
if (dsym_uuid == module->GetUUID())
return true;
// Emit some warning messages since the UUIDs do not match!
if (feedback_strm)
{
feedback_strm->PutCString("warning: UUID mismatch detected between modules:\n ");
module->GetUUID().Dump(feedback_strm);
feedback_strm->PutChar(' ');
module->GetFileSpec().Dump(feedback_strm);
feedback_strm->PutCString("\n ");
dsym_uuid.Dump(feedback_strm);
feedback_strm->PutChar(' ');
ofile->GetFileSpec().Dump(feedback_strm);
feedback_strm->EOL();
}
}
return false;
}
void
SymbolVendorMacOSX::Initialize()
{
PluginManager::RegisterPlugin (GetPluginNameStatic(),
GetPluginDescriptionStatic(),
CreateInstance);
}
void
SymbolVendorMacOSX::Terminate()
{
PluginManager::UnregisterPlugin (CreateInstance);
}
lldb_private::ConstString
SymbolVendorMacOSX::GetPluginNameStatic()
{
static ConstString g_name("macosx");
return g_name;
}
const char *
SymbolVendorMacOSX::GetPluginDescriptionStatic()
{
return "Symbol vendor for MacOSX that looks for dSYM files that match executables.";
}
//----------------------------------------------------------------------
// CreateInstance
//
// Platforms can register a callback to use when creating symbol
// vendors to allow for complex debug information file setups, and to
// also allow for finding separate debug information files.
//----------------------------------------------------------------------
SymbolVendor*
SymbolVendorMacOSX::CreateInstance (const lldb::ModuleSP &module_sp, lldb_private::Stream *feedback_strm)
{
if (!module_sp)
return NULL;
ObjectFile * obj_file = module_sp->GetObjectFile();
if (!obj_file)
return NULL;
static ConstString obj_file_macho("mach-o");
ConstString obj_name = obj_file->GetPluginName();
if (obj_name != obj_file_macho)
return NULL;
Timer scoped_timer (__PRETTY_FUNCTION__,
"SymbolVendorMacOSX::CreateInstance (module = %s)",
module_sp->GetFileSpec().GetPath().c_str());
SymbolVendorMacOSX* symbol_vendor = new SymbolVendorMacOSX(module_sp);
if (symbol_vendor)
{
char path[PATH_MAX];
path[0] = '\0';
// Try and locate the dSYM file on Mac OS X
Timer scoped_timer2 ("SymbolVendorMacOSX::CreateInstance () locate dSYM",
"SymbolVendorMacOSX::CreateInstance (module = %s) locate dSYM",
module_sp->GetFileSpec().GetPath().c_str());
// First check to see if the module has a symbol file in mind already.
// If it does, then we MUST use that.
FileSpec dsym_fspec (module_sp->GetSymbolFileFileSpec());
ObjectFileSP dsym_objfile_sp;
if (!dsym_fspec)
{
// No symbol file was specified in the module, lets try and find
// one ourselves.
FileSpec file_spec = obj_file->GetFileSpec();
if (!file_spec)
file_spec = module_sp->GetFileSpec();
ModuleSpec module_spec(file_spec, module_sp->GetArchitecture());
module_spec.GetUUID() = module_sp->GetUUID();
dsym_fspec = Symbols::LocateExecutableSymbolFile (module_spec);
if (module_spec.GetSourceMappingList().GetSize())
module_sp->GetSourceMappingList().Append (module_spec.GetSourceMappingList (), true);
}
if (dsym_fspec)
{
DataBufferSP dsym_file_data_sp;
lldb::offset_t dsym_file_data_offset = 0;
dsym_objfile_sp = ObjectFile::FindPlugin(module_sp, &dsym_fspec, 0, dsym_fspec.GetByteSize(), dsym_file_data_sp, dsym_file_data_offset);
if (UUIDsMatch(module_sp.get(), dsym_objfile_sp.get(), feedback_strm))
{
// We need a XML parser if we hope to parse a plist...
if (XMLDocument::XMLEnabled())
{
char dsym_path[PATH_MAX];
if (module_sp->GetSourceMappingList().IsEmpty() && dsym_fspec.GetPath(dsym_path, sizeof(dsym_path)))
{
lldb_private::UUID dsym_uuid;
if (dsym_objfile_sp->GetUUID(&dsym_uuid))
{
std::string uuid_str = dsym_uuid.GetAsString ();
if (!uuid_str.empty())
{
char *resources = strstr (dsym_path, "/Contents/Resources/");
if (resources)
{
char dsym_uuid_plist_path[PATH_MAX];
resources[strlen("/Contents/Resources/")] = '\0';
snprintf(dsym_uuid_plist_path, sizeof(dsym_uuid_plist_path), "%s%s.plist", dsym_path, uuid_str.c_str());
FileSpec dsym_uuid_plist_spec(dsym_uuid_plist_path, false);
if (dsym_uuid_plist_spec.Exists())
{
ApplePropertyList plist(dsym_uuid_plist_path);
if (plist)
{
std::string DBGBuildSourcePath;
std::string DBGSourcePath;
plist.GetValueAsString("DBGBuildSourcePath", DBGBuildSourcePath);
plist.GetValueAsString("DBGSourcePath", DBGSourcePath);
if (DBGBuildSourcePath[0] && DBGSourcePath[0])
{
module_sp->GetSourceMappingList().Append (ConstString(DBGBuildSourcePath), ConstString(DBGSourcePath), true);
}
}
}
}
}
}
}
}
symbol_vendor->AddSymbolFileRepresentation(dsym_objfile_sp);
return symbol_vendor;
}
}
// Just create our symbol vendor using the current objfile as this is either
// an executable with no dSYM (that we could locate), an executable with
// a dSYM that has a UUID that doesn't match.
symbol_vendor->AddSymbolFileRepresentation(obj_file->shared_from_this());
}
return symbol_vendor;
}
//------------------------------------------------------------------
// PluginInterface protocol
//------------------------------------------------------------------
ConstString
SymbolVendorMacOSX::GetPluginName()
{
return GetPluginNameStatic();
}
uint32_t
SymbolVendorMacOSX::GetPluginVersion()
{
return 1;
}
<commit_msg>Fix some logic where we used to have char arrays, but we now use std::string. Use the correctly API to detect if they are not empty.<commit_after>//===-- SymbolVendorMacOSX.cpp ----------------------------------*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "SymbolVendorMacOSX.h"
#include <string.h>
#include "lldb/Core/Module.h"
#include "lldb/Core/ModuleSpec.h"
#include "lldb/Core/PluginManager.h"
#include "lldb/Core/Section.h"
#include "lldb/Core/StreamString.h"
#include "lldb/Core/Timer.h"
#include "lldb/Host/Host.h"
#include "lldb/Host/Symbols.h"
#include "lldb/Host/XML.h"
#include "lldb/Symbol/ObjectFile.h"
using namespace lldb;
using namespace lldb_private;
//----------------------------------------------------------------------
// SymbolVendorMacOSX constructor
//----------------------------------------------------------------------
SymbolVendorMacOSX::SymbolVendorMacOSX(const lldb::ModuleSP &module_sp) :
SymbolVendor (module_sp)
{
}
//----------------------------------------------------------------------
// Destructor
//----------------------------------------------------------------------
SymbolVendorMacOSX::~SymbolVendorMacOSX()
{
}
static bool
UUIDsMatch(Module *module, ObjectFile *ofile, lldb_private::Stream *feedback_strm)
{
if (module && ofile)
{
// Make sure the UUIDs match
lldb_private::UUID dsym_uuid;
if (!ofile->GetUUID(&dsym_uuid))
{
if (feedback_strm)
{
feedback_strm->PutCString("warning: failed to get the uuid for object file: '");
ofile->GetFileSpec().Dump(feedback_strm);
feedback_strm->PutCString("\n");
}
return false;
}
if (dsym_uuid == module->GetUUID())
return true;
// Emit some warning messages since the UUIDs do not match!
if (feedback_strm)
{
feedback_strm->PutCString("warning: UUID mismatch detected between modules:\n ");
module->GetUUID().Dump(feedback_strm);
feedback_strm->PutChar(' ');
module->GetFileSpec().Dump(feedback_strm);
feedback_strm->PutCString("\n ");
dsym_uuid.Dump(feedback_strm);
feedback_strm->PutChar(' ');
ofile->GetFileSpec().Dump(feedback_strm);
feedback_strm->EOL();
}
}
return false;
}
void
SymbolVendorMacOSX::Initialize()
{
PluginManager::RegisterPlugin (GetPluginNameStatic(),
GetPluginDescriptionStatic(),
CreateInstance);
}
void
SymbolVendorMacOSX::Terminate()
{
PluginManager::UnregisterPlugin (CreateInstance);
}
lldb_private::ConstString
SymbolVendorMacOSX::GetPluginNameStatic()
{
static ConstString g_name("macosx");
return g_name;
}
const char *
SymbolVendorMacOSX::GetPluginDescriptionStatic()
{
return "Symbol vendor for MacOSX that looks for dSYM files that match executables.";
}
//----------------------------------------------------------------------
// CreateInstance
//
// Platforms can register a callback to use when creating symbol
// vendors to allow for complex debug information file setups, and to
// also allow for finding separate debug information files.
//----------------------------------------------------------------------
SymbolVendor*
SymbolVendorMacOSX::CreateInstance (const lldb::ModuleSP &module_sp, lldb_private::Stream *feedback_strm)
{
if (!module_sp)
return NULL;
ObjectFile * obj_file = module_sp->GetObjectFile();
if (!obj_file)
return NULL;
static ConstString obj_file_macho("mach-o");
ConstString obj_name = obj_file->GetPluginName();
if (obj_name != obj_file_macho)
return NULL;
Timer scoped_timer (__PRETTY_FUNCTION__,
"SymbolVendorMacOSX::CreateInstance (module = %s)",
module_sp->GetFileSpec().GetPath().c_str());
SymbolVendorMacOSX* symbol_vendor = new SymbolVendorMacOSX(module_sp);
if (symbol_vendor)
{
char path[PATH_MAX];
path[0] = '\0';
// Try and locate the dSYM file on Mac OS X
Timer scoped_timer2 ("SymbolVendorMacOSX::CreateInstance () locate dSYM",
"SymbolVendorMacOSX::CreateInstance (module = %s) locate dSYM",
module_sp->GetFileSpec().GetPath().c_str());
// First check to see if the module has a symbol file in mind already.
// If it does, then we MUST use that.
FileSpec dsym_fspec (module_sp->GetSymbolFileFileSpec());
ObjectFileSP dsym_objfile_sp;
if (!dsym_fspec)
{
// No symbol file was specified in the module, lets try and find
// one ourselves.
FileSpec file_spec = obj_file->GetFileSpec();
if (!file_spec)
file_spec = module_sp->GetFileSpec();
ModuleSpec module_spec(file_spec, module_sp->GetArchitecture());
module_spec.GetUUID() = module_sp->GetUUID();
dsym_fspec = Symbols::LocateExecutableSymbolFile (module_spec);
if (module_spec.GetSourceMappingList().GetSize())
module_sp->GetSourceMappingList().Append (module_spec.GetSourceMappingList (), true);
}
if (dsym_fspec)
{
DataBufferSP dsym_file_data_sp;
lldb::offset_t dsym_file_data_offset = 0;
dsym_objfile_sp = ObjectFile::FindPlugin(module_sp, &dsym_fspec, 0, dsym_fspec.GetByteSize(), dsym_file_data_sp, dsym_file_data_offset);
if (UUIDsMatch(module_sp.get(), dsym_objfile_sp.get(), feedback_strm))
{
// We need a XML parser if we hope to parse a plist...
if (XMLDocument::XMLEnabled())
{
char dsym_path[PATH_MAX];
if (module_sp->GetSourceMappingList().IsEmpty() && dsym_fspec.GetPath(dsym_path, sizeof(dsym_path)))
{
lldb_private::UUID dsym_uuid;
if (dsym_objfile_sp->GetUUID(&dsym_uuid))
{
std::string uuid_str = dsym_uuid.GetAsString ();
if (!uuid_str.empty())
{
char *resources = strstr (dsym_path, "/Contents/Resources/");
if (resources)
{
char dsym_uuid_plist_path[PATH_MAX];
resources[strlen("/Contents/Resources/")] = '\0';
snprintf(dsym_uuid_plist_path, sizeof(dsym_uuid_plist_path), "%s%s.plist", dsym_path, uuid_str.c_str());
FileSpec dsym_uuid_plist_spec(dsym_uuid_plist_path, false);
if (dsym_uuid_plist_spec.Exists())
{
ApplePropertyList plist(dsym_uuid_plist_path);
if (plist)
{
std::string DBGBuildSourcePath;
std::string DBGSourcePath;
plist.GetValueAsString("DBGBuildSourcePath", DBGBuildSourcePath);
plist.GetValueAsString("DBGSourcePath", DBGSourcePath);
if (!DBGBuildSourcePath.empty() && !DBGSourcePath.empty())
{
module_sp->GetSourceMappingList().Append (ConstString(DBGBuildSourcePath), ConstString(DBGSourcePath), true);
}
}
}
}
}
}
}
}
symbol_vendor->AddSymbolFileRepresentation(dsym_objfile_sp);
return symbol_vendor;
}
}
// Just create our symbol vendor using the current objfile as this is either
// an executable with no dSYM (that we could locate), an executable with
// a dSYM that has a UUID that doesn't match.
symbol_vendor->AddSymbolFileRepresentation(obj_file->shared_from_this());
}
return symbol_vendor;
}
//------------------------------------------------------------------
// PluginInterface protocol
//------------------------------------------------------------------
ConstString
SymbolVendorMacOSX::GetPluginName()
{
return GetPluginNameStatic();
}
uint32_t
SymbolVendorMacOSX::GetPluginVersion()
{
return 1;
}
<|endoftext|>
|
<commit_before>#ifndef MJOLNIR_CORE_OBSERVER_CONTAINER_HPP
#define MJOLNIR_CORE_OBSERVER_CONTAINER_HPP
#include <mjolnir/util/io.hpp>
#include <mjolnir/util/progress_bar.hpp>
#include <mjolnir/core/ObserverBase.hpp>
#include <vector>
// This class manages several different XXXObservers to output
// positions, energies, topologies, and others.
//
// Also, this class outputs progress bar into stdout if the flag is on.
namespace mjolnir
{
template<typename traitsT>
class ObserverContainer
{
public:
using observer_base_type = ObserverBase<traitsT>;
using observer_base_ptr = std::unique_ptr<observer_base_type>;
using real_type = typename observer_base_type::real_type;
using coordinate_type = typename observer_base_type::coordinate_type;
using system_type = typename observer_base_type::system_type;
using forcefield_type = typename observer_base_type::forcefield_type;
using progress_bar_type = progress_bar</*width of bar = */50>;
public:
explicit ObserverContainer(bool output_progress = false)
: output_progress_(output_progress && io::detail::isatty(std::cerr))
{}
~ObserverContainer() = default;
ObserverContainer(const ObserverContainer&) = default;
ObserverContainer(ObserverContainer&&) = default;
ObserverContainer& operator=(const ObserverContainer&) = default;
ObserverContainer& operator=(ObserverContainer&&) = default;
// open files, write header and so on.
void initialize(const std::size_t total_step, const real_type dt,
const system_type& sys, const forcefield_type& ff)
{
for(const auto& obs : observers_)
{
obs->initialize(total_step, dt, sys, ff);
}
this->progress_bar_.reset(total_step); // set total_step as 100%.
}
// call if system or forcefield is changed.
void update(const std::size_t step, const real_type dt,
const system_type& sys, const forcefield_type& ff)
{
for(const auto& obs : this->observers_)
{
obs->update(step, dt, sys, ff);
}
}
// output the current state.
void output(const std::size_t step, const real_type dt,
const system_type& sys, const forcefield_type& ff)
{
for(const auto& obs : this->observers_)
{
obs->output(step, dt, sys, ff);
}
// this branching might be wiped out by introducing another parameter
// to SimulatorTraits, but I don't think the cost of the implementation
// is larger than the benefit on the runtime efficiency.
if(this->output_progress_)
{
this->progress_bar_.format(step, std::cerr);
}
}
// update header, or something that required to be finalized
void finalize(const std::size_t total_step, const real_type dt,
const system_type& sys, const forcefield_type& ff)
{
for(const auto& obs : this->observers_)
{
obs->finalize(total_step, dt, sys, ff);
}
if(this->output_progress_)
{
// In order to re-write progress bar in each step, it does not print
// end-line after the progress bar. But if finalize is called, we
// can `finalize` the progress bar.
std::cerr << std::endl;
}
}
// assign one another XXXObserver
void push_back(observer_base_ptr&& obs)
{
this->observers_.push_back(std::move(obs));
}
// mainly for testing purpose.
std::vector<observer_base_ptr> const& observers() const noexcept
{
return this->observers_;
}
private:
std::vector<observer_base_ptr> observers_;
progress_bar_type progress_bar_;
bool output_progress_;
};
#ifdef MJOLNIR_SEPARATE_BUILD
extern template class ObserverContainer<SimulatorTraits<double, UnlimitedBoundary> >;
extern template class ObserverContainer<SimulatorTraits<float, UnlimitedBoundary> >;
extern template class ObserverContainer<SimulatorTraits<double, CuboidalPeriodicBoundary>>;
extern template class ObserverContainer<SimulatorTraits<float, CuboidalPeriodicBoundary>>;
#endif
} // mjolnir
#endif// MJOLNIR_CORE_OBSERVER_HPP
<commit_msg>feat: add prefix() to ObserverContainer<commit_after>#ifndef MJOLNIR_CORE_OBSERVER_CONTAINER_HPP
#define MJOLNIR_CORE_OBSERVER_CONTAINER_HPP
#include <mjolnir/util/io.hpp>
#include <mjolnir/util/progress_bar.hpp>
#include <mjolnir/core/ObserverBase.hpp>
#include <vector>
// This class manages several different XXXObservers to output
// positions, energies, topologies, and others.
//
// Also, this class outputs progress bar into stdout if the flag is on.
namespace mjolnir
{
template<typename traitsT>
class ObserverContainer
{
public:
using observer_base_type = ObserverBase<traitsT>;
using observer_base_ptr = std::unique_ptr<observer_base_type>;
using real_type = typename observer_base_type::real_type;
using coordinate_type = typename observer_base_type::coordinate_type;
using system_type = typename observer_base_type::system_type;
using forcefield_type = typename observer_base_type::forcefield_type;
using progress_bar_type = progress_bar</*width of bar = */50>;
public:
explicit ObserverContainer(bool output_progress = false)
: output_progress_(output_progress && io::detail::isatty(std::cerr))
{}
~ObserverContainer() = default;
ObserverContainer(const ObserverContainer&) = default;
ObserverContainer(ObserverContainer&&) = default;
ObserverContainer& operator=(const ObserverContainer&) = default;
ObserverContainer& operator=(ObserverContainer&&) = default;
// open files, write header and so on.
void initialize(const std::size_t total_step, const real_type dt,
const system_type& sys, const forcefield_type& ff)
{
for(const auto& obs : observers_)
{
obs->initialize(total_step, dt, sys, ff);
}
this->progress_bar_.reset(total_step); // set total_step as 100%.
}
// call if system or forcefield is changed.
void update(const std::size_t step, const real_type dt,
const system_type& sys, const forcefield_type& ff)
{
for(const auto& obs : this->observers_)
{
obs->update(step, dt, sys, ff);
}
}
// output the current state.
void output(const std::size_t step, const real_type dt,
const system_type& sys, const forcefield_type& ff)
{
for(const auto& obs : this->observers_)
{
obs->output(step, dt, sys, ff);
}
// this branching might be wiped out by introducing another parameter
// to SimulatorTraits, but I don't think the cost of the implementation
// is larger than the benefit on the runtime efficiency.
if(this->output_progress_)
{
this->progress_bar_.format(step, std::cerr);
}
}
// update header, or something that required to be finalized
void finalize(const std::size_t total_step, const real_type dt,
const system_type& sys, const forcefield_type& ff)
{
for(const auto& obs : this->observers_)
{
obs->finalize(total_step, dt, sys, ff);
}
if(this->output_progress_)
{
// In order to re-write progress bar in each step, it does not print
// end-line after the progress bar. But if finalize is called, we
// can `finalize` the progress bar.
std::cerr << std::endl;
}
}
std::string prefix() const
{
return observers_.front()->prefix();
}
// assign one another XXXObserver
void push_back(observer_base_ptr&& obs)
{
this->observers_.push_back(std::move(obs));
}
// mainly for testing purpose.
std::vector<observer_base_ptr> const& observers() const noexcept
{
return this->observers_;
}
private:
std::vector<observer_base_ptr> observers_;
progress_bar_type progress_bar_;
bool output_progress_;
};
#ifdef MJOLNIR_SEPARATE_BUILD
extern template class ObserverContainer<SimulatorTraits<double, UnlimitedBoundary> >;
extern template class ObserverContainer<SimulatorTraits<float, UnlimitedBoundary> >;
extern template class ObserverContainer<SimulatorTraits<double, CuboidalPeriodicBoundary>>;
extern template class ObserverContainer<SimulatorTraits<float, CuboidalPeriodicBoundary>>;
#endif
} // mjolnir
#endif// MJOLNIR_CORE_OBSERVER_HPP
<|endoftext|>
|
<commit_before>#ifndef MJOLNIR_READ_INTERACTION
#define MJOLNIR_READ_INTERACTION
#include <extlib/toml/toml.hpp>
#include <mjolnir/core/LocalInteractionBase.hpp>
#include <mjolnir/core/BondLengthInteraction.hpp>
#include <mjolnir/core/BondAngleInteraction.hpp>
#include <mjolnir/core/DihedralAngleInteraction.hpp>
#include <mjolnir/core/GlobalInteractionBase.hpp>
#include <mjolnir/core/GlobalDistanceInteraction.hpp>
#include <mjolnir/core/ZaxisExternalForceInteraction.hpp>
#include <mjolnir/util/make_unique.hpp>
#include <mjolnir/util/throw_exception.hpp>
#include <mjolnir/input/get_toml_value.hpp>
#include <mjolnir/input/read_potential.hpp>
#include <mjolnir/input/read_spatial_partition.hpp>
#include <memory>
namespace mjolnir
{
// ----------------------------------------------------------------------------
// local interaction
// ----------------------------------------------------------------------------
template<typename traitsT>
std::unique_ptr<LocalInteractionBase<traitsT>>
read_bond_length_interaction(
const typename LocalInteractionBase<traitsT>::connection_kind_type kind,
const toml::Table& local)
{
const auto potential = toml::get<std::string>(
toml_value_at(local, "potential", "[forcefield.local]"));
if(potential == "Harmonic")
{
using potential_t = HarmonicPotential<traitsT>;
return make_unique<BondLengthInteraction<traitsT, potential_t>>(
kind, read_harmonic_potential<traitsT, 2>(local));
}
else if(potential == "Go1012Contact")
{
using potential_t = Go1012ContactPotential<traitsT>;
return make_unique<BondLengthInteraction<traitsT, potential_t>>(
kind, read_go1012_contact_potential<traitsT, 2>(local));
}
else if(potential == "AICG2PlusAngle")
{
using potential_t = GaussianPotential<traitsT>;
return make_unique<BondLengthInteraction<traitsT, potential_t>>(
kind, read_gaussian_potential<traitsT, 2>(local));
}
else
{
throw_exception<std::runtime_error>(
"invalid potential as BondLengthInteraction: ", potential);
}
}
template<typename traitsT>
std::unique_ptr<LocalInteractionBase<traitsT>>
read_bond_angle_interaction(
const typename LocalInteractionBase<traitsT>::connection_kind_type kind,
const toml::Table& local)
{
const auto potential = toml::get<std::string>(
toml_value_at(local, "potential", "[[forcefield.local]]"));
if(potential == "Harmonic")
{
using potential_t = HarmonicPotential<traitsT>;
return make_unique<BondAngleInteraction<traitsT, potential_t>>(
kind, read_harmonic_potential<traitsT, 3>(local));
}
else if(potential == "FlexibleLocalAngle")
{
using potential_t = FlexibleLocalAnglePotential<traitsT>;
return make_unique<BondAngleInteraction<traitsT, potential_t>>(
kind, read_flexible_local_angle_potential<traitsT, 3>(local));
}
else
{
throw_exception<std::runtime_error>(
"invalid potential as BondAngleInteraction: " + potential);
}
}
template<typename traitsT>
std::unique_ptr<LocalInteractionBase<traitsT>>
read_dihedral_angle_interaction(
const typename LocalInteractionBase<traitsT>::connection_kind_type kind,
const toml::Table& local)
{
const auto potential = toml::get<std::string>(
toml_value_at(local, "potential", "[forcefield.local]"));
if(potential == "Harmonic")
{
using potential_t = HarmonicPotential<traitsT>;
return make_unique<DihedralAngleInteraction<traitsT, potential_t>>(
kind, read_harmonic_potential<traitsT, 4>(local));
}
else if(potential == "ClementiDihedral")
{
using potential_t = ClementiDihedralPotential<traitsT>;
return make_unique<DihedralAngleInteraction<traitsT, potential_t>>(
kind, read_clementi_dihedral_potential<traitsT, 4>(local));
}
else if(potential == "AICG2PlusDihedral")
{
using potential_t = GaussianPotential<traitsT>;
return make_unique<DihedralAngleInteraction<traitsT, potential_t>>(
kind, read_gaussian_potential<traitsT, 4>(local));
}
else if(potential == "FlexibleLocalDihedral")
{
using potential_t = FlexibleLocalDihedralPotential<traitsT>;
return make_unique<DihedralAngleInteraction<traitsT, potential_t>>(
kind, read_flexible_local_dihedral_potential<traitsT, 4>(local));
}
else
{
throw_exception<std::runtime_error>(
"invalid potential as DihedralAngleInteraction: " + potential);
}
}
// ----------------------------------------------------------------------------
// global interaction
// ----------------------------------------------------------------------------
template<typename traitsT, typename ignoreT>
std::unique_ptr<GlobalInteractionBase<traitsT>>
read_global_distance_interaction(const toml::Table& global)
{
const auto potential = toml::get<std::string>(
toml_value_at(global, "potential", "[forcefield.local]"));
if(potential == "ExcludedVolume")
{
using potential_t = ExcludedVolumePotential<traitsT, ignoreT>;
return read_spatial_partition_for_distance<traitsT, potential_t>(
global, read_excluded_volume_potential<traitsT, ignoreT>(global));
}
else if(potential == "DebyeHuckel")
{
using potential_t = DebyeHuckelPotential<traitsT, ignoreT>;
return read_spatial_partition_for_distance<traitsT, potential_t>(
global, read_debye_huckel_potential<traitsT, ignoreT>(global));
}
else if(potential == "LennardJones")
{
using potential_t = LennardJonesPotential<traitsT, ignoreT>;
return read_spatial_partition_for_distance<traitsT, potential_t>(
global, read_lennard_jones_potential<traitsT, ignoreT>(global));
}
else
{
throw_exception<std::runtime_error>(
"invalid potential as GlobalDistanceInteraction: " + potential);
}
}
template<typename traitsT>
std::unique_ptr<GlobalInteractionBase<traitsT>>
read_zaxis_external_force_interaction(const toml::Table& global)
{
const auto potential = toml::get<std::string>(
toml_value_at(global, "potential", "[forcefield.local]"));
if(potential == "ImplicitMembrane")
{
return read_spatial_partition_for_implicit_membrane<
traitsT, ImplicitMembranePotential<traitsT>>(
global, read_implicit_membrane_potential<traitsT>(global));
}
else
{
throw std::runtime_error("invalid distance potential: " + potential);
}
}
// ----------------------------------------------------------------------------
// general read_(local|global)_interaction function
// ----------------------------------------------------------------------------
template<typename traitsT>
std::unique_ptr<LocalInteractionBase<traitsT>>
read_local_interaction(const toml::Table& local)
{
const auto interaction = toml::get<std::string>(
toml_value_at(local, "interaction", "[forcefields.local]"));
// topology stuff
using connection_kind_type =
typename LocalInteractionBase<traitsT>::connection_kind_type;
const auto connection = toml::get<std::string>(
toml_value_at(local, "topology", "[forcefield.local]"));
connection_kind_type kind;
if (connection == "bond") {kind = connection_kind_type::bond;}
else if(connection == "contact") {kind = connection_kind_type::contact;}
else if(connection == "none") {kind = connection_kind_type::none;}
else {throw std::runtime_error("invalid connection type: " + connection);}
if(interaction == "BondLength")
{
return read_bond_length_interaction<traitsT>(kind, local);
}
else if(interaction == "BondAngle")
{
return read_bond_angle_interaction<traitsT>(kind, local);
}
else if(interaction == "DihedralAngle")
{
return read_dihedral_angle_interaction<traitsT>(kind, local);
}
else
{
throw std::runtime_error(
"invalid local interaction type: " + interaction);
}
}
template<typename traitsT>
std::unique_ptr<GlobalInteractionBase<traitsT>>
read_global_interaction(const toml::Table& global)
{
const auto interaction = toml::get<std::string>(
toml_value_at(global, "interaction", "[forcefields.global]"));
const auto ignored_chain = toml::get<std::string>(
toml_value_at(global, "ignored_chain", "[forcefields.global]"));
if(interaction == "Distance")
{
if(ignored_chain == "Nothing")
{
return read_global_distance_interaction<traitsT, IgnoreNothing>(global);
}
else if(ignored_chain == "Self")
{
return read_global_distance_interaction<traitsT, IgnoreSelf>(global);
}
else if(ignored_chain == "Others")
{
return read_global_distance_interaction<traitsT, IgnoreOthers>(global);
}
else
{
throw std::runtime_error("invalid `ignored_chain`: " + ignored_chain);
}
}
else if(interaction == "External")
{
return read_zaxis_external_force_interaction<traitsT>(global);
}
else
{
throw std::runtime_error(
"invalid global interaction type: " + interaction);
}
}
} // mjolnir
#endif// MJOLNIR_READ_INTERACTION
<commit_msg>add read_external interaction and shape<commit_after>#ifndef MJOLNIR_READ_INTERACTION
#define MJOLNIR_READ_INTERACTION
#include <extlib/toml/toml.hpp>
#include <mjolnir/core/BondLengthInteraction.hpp>
#include <mjolnir/core/BondAngleInteraction.hpp>
#include <mjolnir/core/DihedralAngleInteraction.hpp>
#include <mjolnir/core/GlobalDistanceInteraction.hpp>
#include <mjolnir/core/AxisAlignedPlane.hpp>
#include <mjolnir/core/ExternalDistanceInteraction.hpp>
#include <mjolnir/util/make_unique.hpp>
#include <mjolnir/util/throw_exception.hpp>
#include <mjolnir/input/get_toml_value.hpp>
#include <mjolnir/input/read_potential.hpp>
#include <mjolnir/input/read_spatial_partition.hpp>
#include <memory>
namespace mjolnir
{
// ----------------------------------------------------------------------------
// local interaction
// ----------------------------------------------------------------------------
template<typename traitsT>
std::unique_ptr<LocalInteractionBase<traitsT>>
read_bond_length_interaction(
const typename LocalInteractionBase<traitsT>::connection_kind_type kind,
const toml::Table& local)
{
const auto potential = toml::get<std::string>(
toml_value_at(local, "potential", "[forcefield.local]"));
if(potential == "Harmonic")
{
using potential_t = HarmonicPotential<traitsT>;
return make_unique<BondLengthInteraction<traitsT, potential_t>>(
kind, read_harmonic_potential<traitsT, 2>(local));
}
else if(potential == "Go1012Contact")
{
using potential_t = Go1012ContactPotential<traitsT>;
return make_unique<BondLengthInteraction<traitsT, potential_t>>(
kind, read_go1012_contact_potential<traitsT, 2>(local));
}
else if(potential == "AICG2PlusAngle")
{
using potential_t = GaussianPotential<traitsT>;
return make_unique<BondLengthInteraction<traitsT, potential_t>>(
kind, read_gaussian_potential<traitsT, 2>(local));
}
else
{
throw_exception<std::runtime_error>(
"invalid potential as BondLengthInteraction: ", potential);
}
}
template<typename traitsT>
std::unique_ptr<LocalInteractionBase<traitsT>>
read_bond_angle_interaction(
const typename LocalInteractionBase<traitsT>::connection_kind_type kind,
const toml::Table& local)
{
const auto potential = toml::get<std::string>(
toml_value_at(local, "potential", "[[forcefield.local]]"));
if(potential == "Harmonic")
{
using potential_t = HarmonicPotential<traitsT>;
return make_unique<BondAngleInteraction<traitsT, potential_t>>(
kind, read_harmonic_potential<traitsT, 3>(local));
}
else if(potential == "FlexibleLocalAngle")
{
using potential_t = FlexibleLocalAnglePotential<traitsT>;
return make_unique<BondAngleInteraction<traitsT, potential_t>>(
kind, read_flexible_local_angle_potential<traitsT, 3>(local));
}
else
{
throw_exception<std::runtime_error>(
"invalid potential as BondAngleInteraction: " + potential);
}
}
template<typename traitsT>
std::unique_ptr<LocalInteractionBase<traitsT>>
read_dihedral_angle_interaction(
const typename LocalInteractionBase<traitsT>::connection_kind_type kind,
const toml::Table& local)
{
const auto potential = toml::get<std::string>(
toml_value_at(local, "potential", "[forcefield.local]"));
if(potential == "Harmonic")
{
using potential_t = HarmonicPotential<traitsT>;
return make_unique<DihedralAngleInteraction<traitsT, potential_t>>(
kind, read_harmonic_potential<traitsT, 4>(local));
}
else if(potential == "ClementiDihedral")
{
using potential_t = ClementiDihedralPotential<traitsT>;
return make_unique<DihedralAngleInteraction<traitsT, potential_t>>(
kind, read_clementi_dihedral_potential<traitsT, 4>(local));
}
else if(potential == "AICG2PlusDihedral")
{
using potential_t = GaussianPotential<traitsT>;
return make_unique<DihedralAngleInteraction<traitsT, potential_t>>(
kind, read_gaussian_potential<traitsT, 4>(local));
}
else if(potential == "FlexibleLocalDihedral")
{
using potential_t = FlexibleLocalDihedralPotential<traitsT>;
return make_unique<DihedralAngleInteraction<traitsT, potential_t>>(
kind, read_flexible_local_dihedral_potential<traitsT, 4>(local));
}
else
{
throw_exception<std::runtime_error>(
"invalid potential as DihedralAngleInteraction: " + potential);
}
}
// ----------------------------------------------------------------------------
// global interaction
// ----------------------------------------------------------------------------
template<typename traitsT, typename ignoreT>
std::unique_ptr<GlobalInteractionBase<traitsT>>
read_global_distance_interaction(const toml::Table& global)
{
const auto potential = toml::get<std::string>(
toml_value_at(global, "potential", "[forcefield.global]"));
if(potential == "ExcludedVolume")
{
using potential_t = ExcludedVolumePotential<traitsT, ignoreT>;
return read_spatial_partition_for_distance<traitsT, potential_t>(
global, read_excluded_volume_potential<traitsT, ignoreT>(global));
}
else if(potential == "DebyeHuckel")
{
using potential_t = DebyeHuckelPotential<traitsT, ignoreT>;
return read_spatial_partition_for_distance<traitsT, potential_t>(
global, read_debye_huckel_potential<traitsT, ignoreT>(global));
}
else if(potential == "LennardJones")
{
using potential_t = LennardJonesPotential<traitsT, ignoreT>;
return read_spatial_partition_for_distance<traitsT, potential_t>(
global, read_lennard_jones_potential<traitsT, ignoreT>(global));
}
else
{
throw_exception<std::runtime_error>(
"invalid potential as GlobalDistanceInteraction: ", potential);
}
}
// ----------------------------------------------------------------------------
// external interaction
// ----------------------------------------------------------------------------
template<typename traitsT, typename shapeT>
std::unique_ptr<ExternalForceInteractionBase<traitsT>>
read_external_distance_interaction(const toml::Table& external, shapeT&& shape)
{
using real_type = typename traitsT::real_type;
const auto potential = toml::get<std::string>(toml_value_at(external,
"potential", "[forcefield.external]"));
if(potential == "ImplicitMembrane")
{
using potential_t = ImplicitMembranePotential<traitsT>;
using interaction_t = ExternalDistanceInteraction<
traitsT, potential_t, shapeT>;
return make_unique<interaction_t>(std::move(shape),
read_implicit_membrane_potential<traitsT>(external));
}
else
{
throw_exception<std::runtime_error>(
"invalid potential as ExternalDistanceInteraction: ", potential);
}
}
template<typename traitsT>
std::unique_ptr<ExternalForceInteractionBase<traitsT>>
read_external_distance_interaction_shape(const toml::Table& external)
{
using real_type = typename traitsT::real_type;
const auto shape = toml::get<toml::Table>(toml_value_at(external, "shape",
"[forcefield.external] for ExternalDistance"));
const auto name = toml::get<std::string>(toml_value_at(shape, "name",
"[forcefield.external.shape] for ExternalDistance"));
if(name == "AxisAlignedPlane")
{
const auto pos = toml::get<real_type>(toml_value_at(shape, "position",
"[forcefield.external.shape] for ExternalDistance"));
const auto mergin = toml::get<real_type>(toml_value_at(shape, "mergin",
"[forcefield.external.shape] for ExternalDistance"));
const auto axis = toml::get<std::string>(toml_value_at(shape, "axis",
"[forcefield.external.shape] for ExternalDistance"));
if(axis == "X")
{
using shape_t = AxisAlignedPlane<traitsT, 0>;
return read_external_distance_interaction<traitsT, shape_t>(
external, shape_t(pos, mergin));
}
else if(axis == "Y")
{
using shape_t = AxisAlignedPlane<traitsT, 1>;
return read_external_distance_interaction<traitsT, shape_t>(
external, shape_t(pos, mergin));
}
else if(axis == "Z")
{
using shape_t = AxisAlignedPlane<traitsT, 2>;
return read_external_distance_interaction<traitsT, shape_t>(
external, shape_t(pos, mergin));
}
else
{
throw std::runtime_error("invalid axis name: " + axis);
}
}
else
{
throw std::runtime_error("invalid external forcefield shape: " + name);
}
}
// ----------------------------------------------------------------------------
// general read_(local|global|external)_interaction function
// ----------------------------------------------------------------------------
template<typename traitsT>
std::unique_ptr<LocalInteractionBase<traitsT>>
read_local_interaction(const toml::Table& local)
{
const auto interaction = toml::get<std::string>(
toml_value_at(local, "interaction", "[forcefields.local]"));
// topology stuff
using connection_kind_type =
typename LocalInteractionBase<traitsT>::connection_kind_type;
const auto connection = toml::get<std::string>(
toml_value_at(local, "topology", "[forcefield.local]"));
connection_kind_type kind;
if (connection == "bond") {kind = connection_kind_type::bond;}
else if(connection == "contact") {kind = connection_kind_type::contact;}
else if(connection == "none") {kind = connection_kind_type::none;}
else {throw std::runtime_error("invalid connection type: " + connection);}
if(interaction == "BondLength")
{
return read_bond_length_interaction<traitsT>(kind, local);
}
else if(interaction == "BondAngle")
{
return read_bond_angle_interaction<traitsT>(kind, local);
}
else if(interaction == "DihedralAngle")
{
return read_dihedral_angle_interaction<traitsT>(kind, local);
}
else
{
throw std::runtime_error(
"invalid local interaction type: " + interaction);
}
}
template<typename traitsT>
std::unique_ptr<GlobalInteractionBase<traitsT>>
read_global_interaction(const toml::Table& global)
{
const auto interaction = toml::get<std::string>(
toml_value_at(global, "interaction", "[forcefields.global]"));
const auto ignored_chain = toml::get<std::string>(
toml_value_at(global, "ignored_chain", "[forcefields.global]"));
if(interaction == "Distance")
{
if(ignored_chain == "Nothing")
{
return read_global_distance_interaction<traitsT, IgnoreNothing>(global);
}
else if(ignored_chain == "Self")
{
return read_global_distance_interaction<traitsT, IgnoreSelf>(global);
}
else if(ignored_chain == "Others")
{
return read_global_distance_interaction<traitsT, IgnoreOthers>(global);
}
else
{
throw std::runtime_error("invalid `ignored_chain`: " + ignored_chain);
}
}
else
{
throw std::runtime_error(
"invalid global interaction type: " + interaction);
}
}
template<typename traitsT>
std::unique_ptr<ExternalForceInteractionBase<traitsT>>
read_external_interaction(const toml::Table& external)
{
const auto interaction = toml::get<std::string>(
toml_value_at(external, "interaction", "[forcefields.external]"));
if(interaction == "Distance")
{
return read_external_distance_interaction_shape<traitsT>(external);
}
else
{
throw std::runtime_error(
"invalid global interaction type: " + interaction);
}
}
} // mjolnir
#endif// MJOLNIR_READ_INTERACTION
<|endoftext|>
|
<commit_before>/*
TLD's work well w/ features (keypts) low-level features
- DoT works well with textureless objects (contoures)
- Use both to bootstrap a contour and features based reconstruction
- Does going to 3D from contour make tracking possible ??
*/
#define WINDOW_NAME "TLD Segmenter"
#include <set>
#include <bot_core/bot_core.h>
#include <bot_frames/bot_frames.h>
#include <bot_param/param_client.h>
#include <opencv2/opencv.hpp>
#include <image_io_utils/image_io_utils.hpp> // to simplify jpeg/zlib compression and decompression
#include <lcmtypes/perception_image_roi_t.h>
#include <ConciseArgs>
const int WINDOW_WIDTH = 800;
const int WINDOW_HEIGHT = 800;
int MAX_IMAGE_WIDTH = 0;
int MAX_IMAGE_HEIGHT = 0;
int32_t OBJECT_ID = 1;
int32_t FEATURE_ID = 1; // 1 for object (reference), -1 for virtual heading object
using namespace cv;
struct state_t {
lcm_t *lcm;
GMainLoop *mainloop;
BotParam *param;
BotFrames *frames;
int counter;
// Img
cv::Mat img;
// utimes for image
int64_t img_utime;
// UI selection of desired object
Rect selection, selection_virtual;
Point origin, origin_virtual;
bool selectObject, selectObject_virtual;
state_t () {
// LCM, BotFrames, BotParam inits
lcm = bot_lcm_get_global(NULL);
param = bot_param_new_from_server(lcm, 1);
frames = bot_frames_get_global (lcm, param);
// Counter for debug prints
counter = 0;
selectObject = false;
selectObject_virtual = false;
}
~state_t () {
lcm_destroy(lcm);
}
};
state_t * state = NULL;
struct MouseEvent {
MouseEvent() { event = -1; buttonState = 0; }
Point pt;
int event;
int buttonState;
};
MouseEvent mouse;
static void onMouse(int event, int x, int y, int flags, void* userdata) {
MouseEvent* data = (MouseEvent*)userdata;
float sx = 1.f / WINDOW_WIDTH ;
float sy = 1.f / WINDOW_HEIGHT;
if (state->selectObject) {
state->selection.x = MIN(x, state->origin.x);
state->selection.y = MIN(y, state->origin.y);
state->selection.width = std::abs(x - state->origin.x);
state->selection.height = std::abs(y - state->origin.y);
state->selection &= Rect(0, 0, WINDOW_WIDTH, WINDOW_HEIGHT);
}
if (state->selectObject_virtual) {
state->selection_virtual.x = MIN(x, state->origin_virtual.x);
state->selection_virtual.y = MIN(y, state->origin_virtual.y);
state->selection_virtual.width = std::abs(x - state->origin_virtual.x);
state->selection_virtual.height = std::abs(y - state->origin_virtual.y);
state->selection &= Rect(0, 0, WINDOW_WIDTH, WINDOW_HEIGHT);
}
switch (event) {
case CV_EVENT_RBUTTONDOWN:
state->origin_virtual = Point(x, y);
state->selection_virtual = Rect(x, y, 0, 0);
state->selectObject_virtual = true;
break;
case CV_EVENT_RBUTTONUP:
state->selectObject_virtual = false;
std::cerr << "SEND virtual selection: " << state->img_utime << " - " <<
state->selection_virtual.x << " " << state->selection_virtual.y << " " <<
state->selection_virtual.width << " " << state->selection_virtual.height << std::endl;
perception_image_roi_t img_vselection;
img_vselection.utime = state->img_utime;
img_vselection.object_id = OBJECT_ID;
img_vselection.feature_id = -1; // FEATURE_ID;
img_vselection.roi.x = state->selection_virtual.x * sx;
img_vselection.roi.y = state->selection_virtual.y * sy;
img_vselection.roi.width = state->selection_virtual.width * sx;
img_vselection.roi.height = state->selection_virtual.height * sy;
perception_image_roi_t_publish(state->lcm, "TLD_OBJECT_ROI", &img_vselection);
// destroyWindow(WINDOW_NAME);
// state->img = cv::Mat();
break;
case CV_EVENT_LBUTTONDOWN:
state->origin = Point(x, y);
state->selection = Rect(x, y, 0, 0);
state->selectObject = true;
// reset virtual feature
state->selection_virtual = Rect(0,0,0,0);
break;
case CV_EVENT_LBUTTONUP:
state->selectObject = false;
std::cerr << "SEND selection: " << state->img_utime << " - " <<
state->selection.x << " " << state->selection.y << " " <<
state->selection.width << " " << state->selection.height << std::endl;
perception_image_roi_t img_selection;
img_selection.utime = state->img_utime;
img_selection.object_id = OBJECT_ID;
img_selection.feature_id = 1; // FEATURE_ID;
img_selection.roi.x = state->selection.x * sx;
img_selection.roi.y = state->selection.y * sy;
img_selection.roi.width = state->selection.width * sx;
img_selection.roi.height = state->selection.height * sy;
perception_image_roi_t_publish(state->lcm, "TLD_OBJECT_ROI", &img_selection);
// destroyWindow(WINDOW_NAME);
// state->img = cv::Mat();
break;
}
return;
}
void INThandler(int sig)
{
printf("Exiting\n");
if (state) delete state;
exit(0);
}
void
decode_image(const bot_core_image_t * msg, cv::Mat& img)
{
int ch = msg->row_stride / (msg->width);
if (img.empty() || img.rows != msg->height || img.cols != msg->width)
if (ch == 3)
img.create(msg->height, msg->width, CV_8UC3);
else
img.create(msg->height, msg->width, CV_8UC1);
std::cerr << "msg: " << ch << " " << msg->row_stride << " " << msg->width << "x" << msg->height << std::endl;
// extract image data
switch (msg->pixelformat) {
case BOT_CORE_IMAGE_T_PIXEL_FORMAT_RGB:
memcpy(img.data, msg->data, sizeof(uint8_t) * msg->width * msg->height * 3);
cv::cvtColor(img, img, CV_RGB2BGR);
break;
case BOT_CORE_IMAGE_T_PIXEL_FORMAT_MJPEG:
// for some reason msg->row_stride is 0, so we use msg->width instead.
if (ch == 3) {
jpeg_decompress_8u_rgb(msg->data,
msg->size,
img.data,
msg->width,
msg->height,
msg->width * ch);
cv::cvtColor(img, img, CV_RGB2BGR);
} else {
jpeg_decompress_8u_gray(msg->data,
msg->size,
img.data,
msg->width,
msg->height,
msg->width);
}
break;
case BOT_CORE_IMAGE_T_PIXEL_FORMAT_GRAY:
memcpy(img.data, msg->data, sizeof(uint8_t) * msg->width * msg->height);
break;
default:
fprintf(stderr, "Unrecognized image format\n");
break;
}
return;
}
static void on_image_frame (const lcm_recv_buf_t *rbuf, const char *channel,
const bot_core_image_t *msg,
void *user_data ) {
if (!msg->width || !msg->height) return;
if (!MAX_IMAGE_WIDTH || !MAX_IMAGE_HEIGHT) {
MAX_IMAGE_WIDTH = msg->width;
MAX_IMAGE_HEIGHT = msg->height;
}
state_t* state = (state_t*) user_data;
if (state->img.empty() || state->img.rows != msg->height || state->img.cols != msg->width) {
if (msg->pixelformat == BOT_CORE_IMAGE_T_PIXEL_FORMAT_GRAY) {
std::cerr << "ERROR: Incoming image is grayscale!! Cannot perform color tracking!!!" << std::endl;
assert(0);
} else {
std::cerr << "One time creation of image" << std::endl;
state->img.create(msg->height, msg->width, CV_8UC3);
}
}
decode_image(msg, state->img);
state->img_utime = msg->utime;
return;
}
struct TLDSegmenterOptions {
bool vDEBUG;
std::string vCHANNEL;
TLDSegmenterOptions () :
vCHANNEL(std::string("CAMERALEFT")), vDEBUG(false) {}
};
TLDSegmenterOptions options;
int main(int argc, char** argv)
{
std::cout << "============= QUICK MODES ===================\n";
std::cout << "drc-tld-segmenter -c CAMERALEFT\n";
std::cout << "=============================================\n";
ConciseArgs opt(argc, (char**)argv);
opt.add(options.vCHANNEL, "c", "camera-channel","Camera Channel [CAMERALEFT]");
opt.add(options.vDEBUG, "d", "debug","Debug mode");
opt.parse();
std::cerr << "=========== TLD Tracker ============" << std::endl;
std::cerr << "=> CAMERA CHANNEL : " << options.vCHANNEL << std::endl;
std::cerr << "=> DEBUG : " << options.vDEBUG << std::endl;
std::cerr << "===============================================" << std::endl;
// Install signal handler to free data.
signal(SIGINT, INThandler);
// Param server, botframes
state = new state_t();
cv::namedWindow( WINDOW_NAME );
cv::setMouseCallback( WINDOW_NAME, onMouse, &mouse);
// Subscriptions
bot_core_image_t_subscribe(state->lcm, options.vCHANNEL.c_str(), on_image_frame, (void*)state);
// Install signal handler to free data.
signal(SIGINT, INThandler);
while(1) {
unsigned char c = cv::waitKey(1) & 0xff;
lcm_handle(state->lcm);
if (c == 'q') {
break;
// } else if (c == 'd') {
// FEATURE_ID++;
// } else if (c == 'a') {
// FEATURE_ID--;
} else if (c == 'w') {
OBJECT_ID++;
} else if (c == 's') {
OBJECT_ID--;
}
// UI handling
if (!state->img.empty()) {
cv::Mat display;
cv::resize(state->img.clone(), display, cv::Size(WINDOW_WIDTH,WINDOW_HEIGHT));
if (state->selection.width > 0 && state->selection.height > 0) {
cv::Mat roi(display, state->selection);
rectangle(display, state->selection, cv::Scalar(0,255,255), 2);
// bitwise_not(roi, roi);
}
if (state->selection_virtual.width > 0 && state->selection_virtual.height > 0) {
cv::Mat roi(display, state->selection_virtual);
rectangle(display, state->selection_virtual, cv::Scalar(0,255,0), 2);
// bitwise_not(roi, roi);
}
// Show OBJECT_ID, FEATURE_ID
cv::putText(display, cv::format("OBJ: %ld", OBJECT_ID),
Point(20,20), 0, .5, cv::Scalar(0,200,0), 2);
imshow(WINDOW_NAME, display);
}
}
if (state) delete state;
return 0;
}
<commit_msg>tld-segmenter: moved lcm handle to separate thread<commit_after>/*
TLD's work well w/ features (keypts) low-level features
- DoT works well with textureless objects (contoures)
- Use both to bootstrap a contour and features based reconstruction
- Does going to 3D from contour make tracking possible ??
*/
#define WINDOW_NAME "TLD Segmenter"
#include <set>
#include <bot_core/bot_core.h>
#include <bot_frames/bot_frames.h>
#include <bot_param/param_client.h>
#include <opencv2/opencv.hpp>
#include <image_io_utils/image_io_utils.hpp> // to simplify jpeg/zlib compression and decompression
#include <lcmtypes/perception_image_roi_t.h>
#include <ConciseArgs>
const int WINDOW_WIDTH = 800;
const int WINDOW_HEIGHT = 800;
int MAX_IMAGE_WIDTH = 0;
int MAX_IMAGE_HEIGHT = 0;
int32_t OBJECT_ID = 1;
int32_t FEATURE_ID = 1; // 1 for object (reference), -1 for virtual heading object
using namespace cv;
struct state_t {
lcm_t *lcm;
pthread_t lcm_thread;
pthread_mutex_t img_mutex;
GMainLoop *mainloop;
BotParam *param;
BotFrames *frames;
int counter;
// Img
cv::Mat img;
// utimes for image
int64_t img_utime;
// UI selection of desired object
Rect selection, selection_virtual;
Point origin, origin_virtual;
bool selectObject, selectObject_virtual;
state_t () {
// LCM, BotFrames, BotParam inits
lcm = bot_lcm_get_global(NULL);
param = bot_param_new_from_server(lcm, 1);
frames = bot_frames_get_global (lcm, param);
img_mutex = PTHREAD_MUTEX_INITIALIZER;
// Counter for debug prints
counter = 0;
selectObject = false;
selectObject_virtual = false;
}
~state_t () {
}
};
state_t * state = NULL;
void* lcm_thread_handler(void *l) {
state_t* state = (state_t*)l;
while(1)
lcm_handle(state->lcm);
}
struct MouseEvent {
MouseEvent() { event = -1; buttonState = 0; }
Point pt;
int event;
int buttonState;
};
MouseEvent mouse;
static void onMouse(int event, int x, int y, int flags, void* userdata) {
MouseEvent* data = (MouseEvent*)userdata;
float sx = 1.f / WINDOW_WIDTH ;
float sy = 1.f / WINDOW_HEIGHT;
if (state->selectObject) {
state->selection.x = MIN(x, state->origin.x);
state->selection.y = MIN(y, state->origin.y);
state->selection.width = std::abs(x - state->origin.x);
state->selection.height = std::abs(y - state->origin.y);
state->selection &= Rect(0, 0, WINDOW_WIDTH, WINDOW_HEIGHT);
}
if (state->selectObject_virtual) {
state->selection_virtual.x = MIN(x, state->origin_virtual.x);
state->selection_virtual.y = MIN(y, state->origin_virtual.y);
state->selection_virtual.width = std::abs(x - state->origin_virtual.x);
state->selection_virtual.height = std::abs(y - state->origin_virtual.y);
state->selection &= Rect(0, 0, WINDOW_WIDTH, WINDOW_HEIGHT);
}
switch (event) {
case CV_EVENT_RBUTTONDOWN:
state->origin_virtual = Point(x, y);
state->selection_virtual = Rect(x, y, 0, 0);
state->selectObject_virtual = true;
break;
case CV_EVENT_RBUTTONUP:
state->selectObject_virtual = false;
std::cerr << "SEND virtual selection: " << state->img_utime << " - " <<
state->selection_virtual.x << " " << state->selection_virtual.y << " " <<
state->selection_virtual.width << " " << state->selection_virtual.height << std::endl;
perception_image_roi_t img_vselection;
img_vselection.utime = state->img_utime;
img_vselection.object_id = OBJECT_ID;
img_vselection.feature_id = -1; // FEATURE_ID;
img_vselection.roi.x = state->selection_virtual.x * sx;
img_vselection.roi.y = state->selection_virtual.y * sy;
img_vselection.roi.width = state->selection_virtual.width * sx;
img_vselection.roi.height = state->selection_virtual.height * sy;
perception_image_roi_t_publish(state->lcm, "TLD_OBJECT_ROI", &img_vselection);
// destroyWindow(WINDOW_NAME);
// state->img = cv::Mat();
break;
case CV_EVENT_LBUTTONDOWN:
state->origin = Point(x, y);
state->selection = Rect(x, y, 0, 0);
state->selectObject = true;
// reset virtual feature
state->selection_virtual = Rect(0,0,0,0);
break;
case CV_EVENT_LBUTTONUP:
state->selectObject = false;
std::cerr << "SEND selection: " << state->img_utime << " - " <<
state->selection.x << " " << state->selection.y << " " <<
state->selection.width << " " << state->selection.height << std::endl;
perception_image_roi_t img_selection;
img_selection.utime = state->img_utime;
img_selection.object_id = OBJECT_ID;
img_selection.feature_id = 1; // FEATURE_ID;
img_selection.roi.x = state->selection.x * sx;
img_selection.roi.y = state->selection.y * sy;
img_selection.roi.width = state->selection.width * sx;
img_selection.roi.height = state->selection.height * sy;
perception_image_roi_t_publish(state->lcm, "TLD_OBJECT_ROI", &img_selection);
// destroyWindow(WINDOW_NAME);
// state->img = cv::Mat();
break;
}
return;
}
void INThandler(int sig)
{
printf("Exiting\n");
if (state) delete state;
exit(0);
}
void
decode_image(const bot_core_image_t * msg, cv::Mat& img)
{
int ch = msg->row_stride / (msg->width);
if (img.empty() || img.rows != msg->height || img.cols != msg->width)
if (ch == 3)
img.create(msg->height, msg->width, CV_8UC3);
else
img.create(msg->height, msg->width, CV_8UC1);
std::cerr << "msg: " << ch << " " << msg->row_stride << " " << msg->width << "x" << msg->height << std::endl;
// extract image data
switch (msg->pixelformat) {
case BOT_CORE_IMAGE_T_PIXEL_FORMAT_RGB:
memcpy(img.data, msg->data, sizeof(uint8_t) * msg->width * msg->height * 3);
cv::cvtColor(img, img, CV_RGB2BGR);
break;
case BOT_CORE_IMAGE_T_PIXEL_FORMAT_MJPEG:
// for some reason msg->row_stride is 0, so we use msg->width instead.
if (ch == 3) {
jpeg_decompress_8u_rgb(msg->data,
msg->size,
img.data,
msg->width,
msg->height,
msg->width * ch);
cv::cvtColor(img, img, CV_RGB2BGR);
} else {
jpeg_decompress_8u_gray(msg->data,
msg->size,
img.data,
msg->width,
msg->height,
msg->width);
}
break;
case BOT_CORE_IMAGE_T_PIXEL_FORMAT_GRAY:
memcpy(img.data, msg->data, sizeof(uint8_t) * msg->width * msg->height);
break;
default:
fprintf(stderr, "Unrecognized image format\n");
break;
}
return;
}
static void on_image_frame (const lcm_recv_buf_t *rbuf, const char *channel,
const bot_core_image_t *msg,
void *user_data ) {
if (!msg->width || !msg->height) return;
if (!MAX_IMAGE_WIDTH || !MAX_IMAGE_HEIGHT) {
MAX_IMAGE_WIDTH = msg->width;
MAX_IMAGE_HEIGHT = msg->height;
}
pthread_mutex_lock(&state->img_mutex);
state_t* state = (state_t*) user_data;
if (state->img.empty() || state->img.rows != msg->height || state->img.cols != msg->width) {
if (msg->pixelformat == BOT_CORE_IMAGE_T_PIXEL_FORMAT_GRAY) {
std::cerr << "ERROR: Incoming image is grayscale!! Cannot perform color tracking!!!" << std::endl;
assert(0);
} else {
std::cerr << "One time creation of image" << std::endl;
state->img.create(msg->height, msg->width, CV_8UC3);
}
}
decode_image(msg, state->img);
state->img_utime = msg->utime;
pthread_mutex_unlock(&state->img_mutex);
return;
}
struct TLDSegmenterOptions {
bool vDEBUG;
std::string vCHANNEL;
TLDSegmenterOptions () :
vCHANNEL(std::string("CAMERALEFT")), vDEBUG(false) {}
};
TLDSegmenterOptions options;
int main(int argc, char** argv)
{
std::cout << "============= QUICK MODES ===================\n";
std::cout << "drc-tld-segmenter -c CAMERALEFT\n";
std::cout << "=============================================\n";
ConciseArgs opt(argc, (char**)argv);
opt.add(options.vCHANNEL, "c", "camera-channel","Camera Channel [CAMERALEFT]");
opt.add(options.vDEBUG, "d", "debug","Debug mode");
opt.parse();
std::cerr << "=========== TLD Tracker ============" << std::endl;
std::cerr << "=> CAMERA CHANNEL : " << options.vCHANNEL << std::endl;
std::cerr << "=> DEBUG : " << options.vDEBUG << std::endl;
std::cerr << "===============================================" << std::endl;
// Install signal handler to free data.
signal(SIGINT, INThandler);
// Param server, botframes
state = new state_t();
printf("starting lcm thread\n");
pthread_create(&(state->lcm_thread), NULL, lcm_thread_handler, state);
cv::namedWindow( WINDOW_NAME );
cv::setMouseCallback( WINDOW_NAME, onMouse, &mouse);
// Subscriptions
bot_core_image_t_subscribe(state->lcm, options.vCHANNEL.c_str(), on_image_frame, (void*)state);
// Install signal handler to free data.
signal(SIGINT, INThandler);
while(1) {
unsigned char c = cv::waitKey(1) & 0xff;
// lcm_handle(state->lcm);
if (c == 'q') {
break;
// } else if (c == 'd') {
// FEATURE_ID++;
// } else if (c == 'a') {
// FEATURE_ID--;
} else if (c == 'w') {
OBJECT_ID++;
} else if (c == 's') {
OBJECT_ID--;
}
pthread_mutex_lock(&state->img_mutex);
// UI handling
if (!state->img.empty()) {
cv::Mat display;
cv::resize(state->img.clone(), display, cv::Size(WINDOW_WIDTH,WINDOW_HEIGHT));
if (state->selection.width > 0 && state->selection.height > 0) {
cv::Mat roi(display, state->selection);
rectangle(display, state->selection, cv::Scalar(0,255,255), 2);
// bitwise_not(roi, roi);
}
if (state->selection_virtual.width > 0 && state->selection_virtual.height > 0) {
cv::Mat roi(display, state->selection_virtual);
rectangle(display, state->selection_virtual, cv::Scalar(0,255,0), 2);
// bitwise_not(roi, roi);
}
// Show OBJECT_ID, FEATURE_ID
cv::putText(display, cv::format("OBJ: %ld", OBJECT_ID),
Point(20,20), 0, .5, cv::Scalar(0,200,0), 2);
imshow(WINDOW_NAME, display);
}
pthread_mutex_unlock(&state->img_mutex);
}
// if (state) delete state;
return 0;
}
<|endoftext|>
|
<commit_before>/***************************************************************************
irccontact.cpp - description
-------------------
begin : Wed Mar 6 2002
copyright : (C) 2002 by nbetcher
email : nbetcher@usinternet.com
***************************************************************************/
/***************************************************************************
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation; either version 2 of the License, or *
* (at your option) any later version. *
* *
***************************************************************************/
#include "irccontact.h"
#include <kmessagebox.h>
#include <qlayout.h>
#include <kdialog.h>
#include <kdebug.h>
#include <kconfig.h>
#include <ktabctl.h>
#include <kstddirs.h>
#include <ircchatwindow.h>
IRCContact::IRCContact(QListViewItem *parent, const QString &server, const QString &target, unsigned int port, bool joinOnConnect, IRCServerContact *contact)
: IMContact(parent)
{
engine = contact->engine;
requestedQuit = false;
KGlobal::config()->setGroup("IRC");
QString newServer;
if (server.isEmpty() == true)
{
newServer = KGlobal::config()->readEntry("Server", "irc.openprojects.net");
mServer = newServer;
} else {
mServer = server;
}
if (port == 0)
{
unsigned int port = KGlobal::config()->readEntry("Port", "6667").toUInt();
}
QString user = "kopeteuser";
QString nick = KGlobal::config()->readEntry("Nickname", "KopeteUser");
mContact = contact;
mTarget = target;
mPort = port;
mUsername = user;
mNickname = nick;
mJoinOnConnect = joinOnConnect;
if (target[0] == '#' || target[0] == '!' || target[0] == '&')
{
setPixmap(0, locate("data", "kopete/pics/irc_privmsg.xpm"));
QString oldTarget = mTarget;
mTarget = mTarget.remove(0,1);
setText(0, mTarget);
mTarget = oldTarget;
} else {
setText(0, mTarget);
}
connect(mContact, SIGNAL(quittingServer()), this, SLOT(slotServerIsQuitting()));
connect(mContact, SIGNAL(serverQuit()), this, SLOT(slotServerHasQuit()));
connect(mContact->engine, SIGNAL(incomingPartedChannel(const QString &, const QString &, const QString &)), this, SLOT(slotPartedChannel(const QString &, const QString &, const QString &)));
if (joinOnConnect == true)
{
if (mContact->engine->isLoggedIn() == true)
{
joinNow();
} else {
QObject::connect(mContact->engine, SIGNAL(connectedToServer()), this, SLOT(joinNow()));
}
}
}
void IRCContact::slotServerHasQuit()
{
delete this;
}
void IRCContact::slotServerIsQuitting()
{
if (requestedQuit == false)
{
QColor color(175, 8, 8);
QString partWarning = "<font color=";
partWarning.append(color.name());
partWarning.append(">Attempting to quit server. If this takes an unusual amount of time, please right click on one of the channels or server in Kopete contact list and click \"Quit IRC Server\" again.</font><br>");
chatView->chatView->append(partWarning);
chatView->chatView->scrollToBottom();
}
}
void IRCContact::rightButtonPressed(const QPoint &point)
{
popup = new KPopupMenu();
popup->insertTitle(mTarget);
popup->insertItem("Part", this, SLOT(slotPart()));
// TODO: popup->insertItem("Hop (Part and Re-join)", this, SLOT(slotHop()));
// TODO: popup->insertItem("Remove", this, SLOT(slotRemoveThis()));
popup->insertTitle(((QListViewItem *)mContact)->text(0));
popup->insertItem("Quit IRC Server", this, SLOT(slotQuitServer()));
popup->popup(point);
}
void IRCContact::slotQuitServer()
{
requestedQuit = true;
mContact->slotQuitServer();
}
void IRCContact::leftButtonDoubleClicked()
{
if (chatView != 0)
{
if (mContact->mWindow->isVisible() == true)
{
mContact->mWindow->raise();
chatView->setFocus();
chatView->messageBox->setFocus();
}
}
}
void IRCContact::slotPart()
{
if (chatView != 0)
{
QColor color(175, 8, 8);
QString partWarning = "<font color=";
partWarning.append(color.name());
partWarning.append(">Attempting to part channel. If this takes an unusual amount of time, please click the close button on this window again, or right click on the contact in the Kopete window and click \"Part\" again.</font><br>");
chatView->chatView->append(partWarning);
chatView->chatView->scrollToBottom();
}
waitingPart = true;
mContact->engine->partChannel(QCString(mTarget.local8Bit()) ,QString("Using Kopete IRC Plugin"));
}
void IRCContact::slotPartedChannel(const QString &originating, const QString &channel, const QString &reason)
{
if (mTarget.lower() == channel.lower() && originating.left(originating.find("!")).lower() == mContact->mNickname.lower())
{
unloading();
}
}
void IRCContact::unloading()
{
if (chatView != 0)
{
delete chatView;
}
mContact->unloading();
delete this;
}
void IRCContact::slotIncomingMotd(const QString &motd)
{
}
void IRCContact::joinNow()
{
mChatViewContainer = new QFrame(mContact->mWindow->mChannelsTabCtl);
mChatViewContainer->resize(300,300);
kdDebug() << "FUCK PART 1" << endl;
(new QVBoxLayout(mChatViewContainer, KDialog::marginHint(), KDialog::spacingHint()))->setAutoAdd(true);
(void)new QLabel(i18n("<b>Test :-):</b>"),mChatViewContainer );
kdDebug() << "FUCK PART 2" << endl;
chatView = new IRCChatView(mServer, mTarget, this, mChatViewContainer);
kdDebug() << "FUCK PART 3" << endl;
mContact->mWindow->mChannelsTabCtl->addTab(mChatViewContainer, mTarget);
mContact->mWindow->adjustSize();
mContact->mWindow->show();
mChatViewContainer->show();
chatView->show();
kdDebug() << "FUCK PART 4" << endl;
QObject::connect(mContact->engine, SIGNAL(userJoinedChannel(const QString &, const QString &)), chatView, SLOT(userJoinedChannel(const QString &, const QString &)));
QObject::connect(mContact->engine, SIGNAL(incomingMessage(const QString &, const QString &, const QString &)), chatView, SLOT(incomingMessage(const QString &, const QString &, const QString &)));
QObject::connect(mContact->engine, SIGNAL(incomingPartedChannel(const QString &, const QString &, const QString &)), chatView, SLOT(userPartedChannel(const QString &, const QString &, const QString &)));
QObject::connect(mContact->engine, SIGNAL(incomingNamesList(const QString &, const QString &, const int)), chatView, SLOT(incomingNamesList(const QString &, const QString &, const int)));
QObject::connect(mContact->engine, SIGNAL(incomingAction(const QString &, const QString &, const QString &)), chatView, SLOT(incomingAction(const QString &, const QString &, const QString &)));
QObject::connect(mContact->engine, SIGNAL(incomingQuitIRC(const QString &, const QString &)), chatView, SLOT(userQuitIRC(const QString &, const QString &)));
QObject::connect(mContact->engine, SIGNAL(incomingNickChange(const QString &, const QString &)), chatView, SLOT(nickNameChanged(const QString &, const QString &)));
QObject::connect(mContact->engine, SIGNAL(incomingTopicChange(const QString &, const QString &, const QString &)), chatView, SLOT(incomingNewTopic(const QString &, const QString &, const QString &)));
QObject::connect(mContact->engine, SIGNAL(incomingExistingTopic(const QString &, const QString &)), chatView, SLOT(receivedExistingTopic(const QString &, const QString &)));
}
<commit_msg><commit_after>/***************************************************************************
irccontact.cpp - description
-------------------
begin : Wed Mar 6 2002
copyright : (C) 2002 by nbetcher
email : nbetcher@usinternet.com
***************************************************************************/
/***************************************************************************
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation; either version 2 of the License, or *
* (at your option) any later version. *
* *
***************************************************************************/
#include "irccontact.h"
#include <kmessagebox.h>
#include <qlayout.h>
#include <kdialog.h>
#include <kdebug.h>
#include <kconfig.h>
#include <ktabctl.h>
#include <kstddirs.h>
#include <ircchatwindow.h>
IRCContact::IRCContact(QListViewItem *parent, const QString &server, const QString &target, unsigned int port, bool joinOnConnect, IRCServerContact *contact)
: IMContact(parent)
{
engine = contact->engine;
requestedQuit = false;
KGlobal::config()->setGroup("IRC");
QString newServer;
if (server.isEmpty() == true)
{
newServer = KGlobal::config()->readEntry("Server", "irc.openprojects.net");
mServer = newServer;
} else {
mServer = server;
}
if (port == 0)
{
unsigned int port = KGlobal::config()->readEntry("Port", "6667").toUInt();
}
QString user = "kopeteuser";
QString nick = KGlobal::config()->readEntry("Nickname", "KopeteUser");
mContact = contact;
mTarget = target;
mPort = port;
mUsername = user;
mNickname = nick;
mJoinOnConnect = joinOnConnect;
if (target[0] == '#' || target[0] == '!' || target[0] == '&')
{
setPixmap(0, locate("data", "kopete/pics/irc_privmsg.xpm"));
QString oldTarget = mTarget;
mTarget = mTarget.remove(0,1);
setText(0, mTarget);
mTarget = oldTarget;
} else {
setText(0, mTarget);
}
connect(mContact, SIGNAL(quittingServer()), this, SLOT(slotServerIsQuitting()));
connect(mContact, SIGNAL(serverQuit()), this, SLOT(slotServerHasQuit()));
connect(mContact->engine, SIGNAL(incomingPartedChannel(const QString &, const QString &, const QString &)), this, SLOT(slotPartedChannel(const QString &, const QString &, const QString &)));
if (joinOnConnect == true)
{
if (mContact->engine->isLoggedIn() == true)
{
joinNow();
} else {
QObject::connect(mContact->engine, SIGNAL(connectedToServer()), this, SLOT(joinNow()));
}
}
}
void IRCContact::slotServerHasQuit()
{
delete this;
}
void IRCContact::slotServerIsQuitting()
{
if (requestedQuit == false)
{
QColor color(175, 8, 8);
QString partWarning = "<font color=";
partWarning.append(color.name());
partWarning.append(">Attempting to quit server. If this takes an unusual amount of time, please right click on one of the channels or server in Kopete contact list and click \"Quit IRC Server\" again.</font><br>");
chatView->chatView->append(partWarning);
chatView->chatView->scrollToBottom();
}
}
void IRCContact::rightButtonPressed(const QPoint &point)
{
popup = new KPopupMenu();
popup->insertTitle(mTarget);
popup->insertItem("Part", this, SLOT(slotPart()));
// TODO: popup->insertItem("Hop (Part and Re-join)", this, SLOT(slotHop()));
// TODO: popup->insertItem("Remove", this, SLOT(slotRemoveThis()));
popup->insertTitle(((QListViewItem *)mContact)->text(0));
popup->insertItem("Quit IRC Server", this, SLOT(slotQuitServer()));
popup->popup(point);
}
void IRCContact::slotQuitServer()
{
requestedQuit = true;
mContact->slotQuitServer();
}
void IRCContact::leftButtonDoubleClicked()
{
if (chatView != 0)
{
if (mContact->mWindow->isVisible() == true)
{
mContact->mWindow->raise();
chatView->setFocus();
chatView->messageBox->setFocus();
}
}
}
void IRCContact::slotPart()
{
if (chatView != 0)
{
QColor color(175, 8, 8);
QString partWarning = "<font color=";
partWarning.append(color.name());
partWarning.append(">Attempting to part channel. If this takes an unusual amount of time, please click the close button on this window again, or right click on the contact in the Kopete window and click \"Part\" again.</font><br>");
chatView->chatView->append(partWarning);
chatView->chatView->scrollToBottom();
}
waitingPart = true;
mContact->engine->partChannel(QCString(mTarget.local8Bit()) ,QString("Using Kopete IRC Plugin"));
}
void IRCContact::slotPartedChannel(const QString &originating, const QString &channel, const QString &reason)
{
if (mTarget.lower() == channel.lower() && originating.left(originating.find("!")).lower() == mContact->mNickname.lower())
{
unloading();
}
}
void IRCContact::unloading()
{
if (chatView != 0)
{
delete chatView;
}
mContact->unloading();
delete this;
}
void IRCContact::slotIncomingMotd(const QString &motd)
{
}
void IRCContact::joinNow()
{
/* This is a frame inside the tab, where we put the widgets in */
mChatViewContainer = new QFrame(mContact->mWindow->mChannelsTabCtl);
mChatViewContainer->resize(640,480);
kdDebug() << "FUCK PART 1" << endl;
QVBoxLayout *containerLayout;
containerLayout = new QVBoxLayout(mChatViewContainer);
//(void)new QLabel(i18n("<b>Test :-):</b>"),mChatViewContainer );
//(void)new QLabel(i18n("<b>Test :-):</b>"), mContact->mWindow->mChannelsTabCtl);
kdDebug() << "FUCK PART 2" << endl;
chatView = new IRCChatView(mServer, mTarget, this, mChatViewContainer);
containerLayout->addWidget(chatView);
//chatView = new IRCChatView(mServer, mTarget, this, mContact->mWindow->mChannelsTabCtl );
kdDebug() << "FUCK PART 3" << endl;
mContact->mWindow->mChannelsTabCtl->addTab(mChatViewContainer, mTarget);
//mContact->mWindow->mChannelsTabCtl->addTab(mContact->mWindow->mChannelsTabCtl, mTarget);
//mContact->mWindow->adjustSize();
mContact->mWindow->show();
mChatViewContainer->show();
chatView->show();
kdDebug() << "FUCK PART 4" << endl;
QObject::connect(mContact->engine, SIGNAL(userJoinedChannel(const QString &, const QString &)), chatView, SLOT(userJoinedChannel(const QString &, const QString &)));
QObject::connect(mContact->engine, SIGNAL(incomingMessage(const QString &, const QString &, const QString &)), chatView, SLOT(incomingMessage(const QString &, const QString &, const QString &)));
QObject::connect(mContact->engine, SIGNAL(incomingPartedChannel(const QString &, const QString &, const QString &)), chatView, SLOT(userPartedChannel(const QString &, const QString &, const QString &)));
QObject::connect(mContact->engine, SIGNAL(incomingNamesList(const QString &, const QString &, const int)), chatView, SLOT(incomingNamesList(const QString &, const QString &, const int)));
QObject::connect(mContact->engine, SIGNAL(incomingAction(const QString &, const QString &, const QString &)), chatView, SLOT(incomingAction(const QString &, const QString &, const QString &)));
QObject::connect(mContact->engine, SIGNAL(incomingQuitIRC(const QString &, const QString &)), chatView, SLOT(userQuitIRC(const QString &, const QString &)));
QObject::connect(mContact->engine, SIGNAL(incomingNickChange(const QString &, const QString &)), chatView, SLOT(nickNameChanged(const QString &, const QString &)));
QObject::connect(mContact->engine, SIGNAL(incomingTopicChange(const QString &, const QString &, const QString &)), chatView, SLOT(incomingNewTopic(const QString &, const QString &, const QString &)));
QObject::connect(mContact->engine, SIGNAL(incomingExistingTopic(const QString &, const QString &)), chatView, SLOT(receivedExistingTopic(const QString &, const QString &)));
}
<|endoftext|>
|
<commit_before>//
// Copyright (c) 2018 Rokas Kupstys
//
// 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 "Widgets.h"
#include <ImGui/imgui_internal.h>
#include <Urho3D/Core/Context.h>
#include <Urho3D/Input/Input.h>
#include <SDL/SDL_scancode.h>
#include <Urho3D/SystemUI/SystemUI.h>
using namespace Urho3D;
using namespace ui::litterals;
namespace ImGui
{
const unsigned UISTATE_EXPIRATION_MS = 30000;
struct UIStateWrapper
{
void Set(void* state, void(*deleter)(void*)=nullptr)
{
state_ = state;
deleter_ = deleter;
}
void Unset()
{
if (deleter_ && state_)
deleter_(state_);
state_ = nullptr;
deleter_ = nullptr;
}
void* Get(bool keepAlive=true)
{
if (keepAlive)
timer_.Reset();
return state_;
}
bool IsExpired()
{
return timer_.GetMSec(false) >= UISTATE_EXPIRATION_MS;
}
protected:
/// User state pointer.
void* state_ = nullptr;
/// Function that handles deleting state object when it becomes unused.
void(*deleter_)(void* state) = nullptr;
/// Timer which determines when state expires.
Timer timer_;
};
HashMap<ImGuiID, UIStateWrapper> uiState_;
void SetUIStateP(void* state, void(*deleter)(void*))
{
auto id = ui::GetCurrentWindow()->IDStack.back();
uiState_[id].Set(state, deleter);
}
void* GetUIStateP()
{
void* result = nullptr;
auto id = ui::GetCurrentWindow()->IDStack.back();
auto it = uiState_.Find(id);
if (it != uiState_.End())
result = it->second_.Get();
// Every 30s check all saved states and remove expired ones.
static Timer gcTimer;
if (gcTimer.GetMSec(false) > UISTATE_EXPIRATION_MS)
{
gcTimer.Reset();
for (auto jt = uiState_.Begin(); jt != uiState_.End();)
{
if (jt->second_.IsExpired())
{
jt->second_.Unset();
jt = uiState_.Erase(jt);
}
else
++jt;
}
}
return result;
}
void ExpireUIStateP()
{
auto it = uiState_.Find(ui::GetCurrentWindow()->IDStack.back());
if (it != uiState_.End())
{
it->second_.Unset();
uiState_.Erase(it);
}
}
int DoubleClickSelectable(const char* label, bool* p_selected, ImGuiSelectableFlags flags, const ImVec2& size)
{
bool wasSelected = p_selected && *p_selected;
if (ui::Selectable(label, p_selected, flags | ImGuiSelectableFlags_AllowDoubleClick, size))
{
if (wasSelected && ui::IsMouseDoubleClicked(MOUSEB_LEFT))
return 2;
else
return 1;
}
if (ui::IsItemHovered() && ui::IsMouseClicked(MOUSEB_RIGHT))
{
*p_selected = true;
return 1;
}
return 0;
}
int DoubleClickSelectable(const char* label, bool selected, ImGuiSelectableFlags flags, const ImVec2& size)
{
return DoubleClickSelectable(label, &selected, flags, size);
}
bool CollapsingHeaderSimple(const char* label, ImGuiTreeNodeFlags flags)
{
ImGuiWindow* window = ui::GetCurrentWindow();
if (window->SkipItems)
return false;
ui::PushStyleColor(ImGuiCol_HeaderActive, 0);
ui::PushStyleColor(ImGuiCol_HeaderHovered, 0);
ui::PushStyleColor(ImGuiCol_Header, 0);
bool open = ui::TreeNodeBehavior(window->GetID(label), flags | ImGuiTreeNodeFlags_NoAutoOpenOnLog | ImGuiTreeNodeFlags_NoTreePushOnOpen, label);
ui::PopStyleColor(3);
return open;
}
bool ToolbarButton(const char* label)
{
auto& g = *ui::GetCurrentContext();
float dimension = g.FontBaseSize + g.Style.FramePadding.y * 2.0f;
return ui::ButtonEx(label, {0, dimension}, ImGuiButtonFlags_PressedOnClick);
}
void SetHelpTooltip(const char* text, Key requireKey)
{
unsigned scancode = requireKey & (~SDLK_SCANCODE_MASK);
if (ui::IsItemHovered() && (requireKey == KEY_UNKNOWN || ui::IsKeyDown(scancode)))
ui::SetTooltip("%s", text);
}
bool IconButton(const char* label)
{
float size = ui::GetItemRectSize().y;
return ui::Button(label, {size, size});
}
bool MaskSelector(unsigned int* mask)
{
bool modified = false;
auto style = ui::GetStyle();
auto pos = ui::GetCursorPos();
for (auto row = 0; row < 2; row++)
{
for (auto col = 0; col < 16; col++)
{
auto bitPosition = row * 16 + col;
int bitMask = 1 << bitPosition;
bool selected = (*mask & bitMask) != 0;
if (selected)
{
ui::PushStyleColor(ImGuiCol_Button, style.Colors[ImGuiCol_ButtonActive]);
ui::PushStyleColor(ImGuiCol_ButtonHovered, style.Colors[ImGuiCol_ButtonActive]);
}
else
{
ui::PushStyleColor(ImGuiCol_Button, style.Colors[ImGuiCol_Button]);
ui::PushStyleColor(ImGuiCol_ButtonHovered, style.Colors[ImGuiCol_Button]);
}
ui::PushID(bitMask);
if (ui::Button("", {8_dpx, 9_dpy}))
{
modified = true;
*mask ^= bitMask;
}
if (ui::IsItemHovered())
ui::SetTooltip("%d", bitPosition);
ui::PopID();
ui::SameLine(0, 0);
ui::PopStyleColor(2);
}
ui::NewLine();
if (row < 1)
ui::SetCursorPos({pos.x, pos.y + 9_dpy});
}
return modified;
}
enum TransformResizeType
{
RESIZE_NONE = 0,
RESIZE_LEFT = 1,
RESIZE_RIGHT = 2,
RESIZE_TOP = 4,
RESIZE_BOTTOM = 8,
RESIZE_MOVE = 15,
};
}
/// Flag manipuation operators.
URHO3D_FLAGSET_EX(ImGui, TransformResizeType, TransformResizeTypeFlags);
namespace ImGui
{
/// Hashing function which enables use of enum type as a HashMap key.
inline unsigned MakeHash(const TransformResizeType& value) { return value; }
bool TransformRect(IntRect& inOut, TransformSelectorFlags flags)
{
IntRect delta;
return TransformRect(inOut, delta, flags);
}
bool TransformRect(Urho3D::IntRect& inOut, Urho3D::IntRect& delta, TransformSelectorFlags flags)
{
struct State
{
/// A flag indicating type of resize action currently in progress
TransformResizeTypeFlags resizing_ = RESIZE_NONE;
/// A cache of system cursors
HashMap<TransformResizeTypeFlags, SDL_Cursor*> cursors_;
/// Default cursor shape
SDL_Cursor* cursorArrow_;
/// Flag indicating that this selector set cursor handle
bool ownsCursor_ = false;
State()
{
cursors_[RESIZE_MOVE] = SDL_CreateSystemCursor(SDL_SYSTEM_CURSOR_SIZEALL);
cursors_[RESIZE_LEFT] = cursors_[RESIZE_RIGHT] = SDL_CreateSystemCursor(SDL_SYSTEM_CURSOR_SIZEWE);
cursors_[RESIZE_BOTTOM] = cursors_[RESIZE_TOP] = SDL_CreateSystemCursor(SDL_SYSTEM_CURSOR_SIZENS);
cursors_[RESIZE_TOP | RESIZE_LEFT] = cursors_[RESIZE_BOTTOM | RESIZE_RIGHT] = SDL_CreateSystemCursor(
SDL_SYSTEM_CURSOR_SIZENWSE);
cursors_[RESIZE_TOP | RESIZE_RIGHT] = cursors_[RESIZE_BOTTOM | RESIZE_LEFT] = SDL_CreateSystemCursor(
SDL_SYSTEM_CURSOR_SIZENESW);
cursorArrow_ = SDL_CreateSystemCursor(SDL_SYSTEM_CURSOR_ARROW);
}
~State()
{
SDL_FreeCursor(cursorArrow_);
for (const auto& it : cursors_)
SDL_FreeCursor(it.second_);
}
};
Input* input = ui::GetSystemUI()->GetSubsystem<Input>();
auto renderHandle = [&](IntVector2 screenPos, int wh) -> bool {
IntRect rect(
screenPos.x_ - wh / 2,
screenPos.y_ - wh / 2,
screenPos.x_ + wh / 2,
screenPos.y_ + wh / 2
);
if (!(flags & TSF_HIDEHANDLES))
{
ui::GetWindowDrawList()->AddRectFilled(ToImGui(rect.Min()), ToImGui(rect.Max()),
ui::GetColorU32(ToImGui(Color::RED)));
}
return rect.IsInside(input->GetMousePosition()) == INSIDE;
};
auto size = inOut.Size();
auto handleSize = Max(Min(Min(size.x_ / 4, size.y_ / 4), 8), 2);
bool modified = false;
auto* s = ui::GetUIState<State>();
auto id = ui::GetID(s);
// Extend rect to cover resize handles that are sticking out of ui element boundaries.
auto extendedRect = inOut + IntRect(-handleSize / 2, -handleSize / 2, handleSize / 2, handleSize / 2);
ui::ItemSize(ToImGui(inOut));
if (ui::ItemAdd(ToImGui(extendedRect), id))
{
TransformResizeTypeFlags resizing = RESIZE_NONE;
if (renderHandle(inOut.Min() + size / 2, handleSize))
resizing = RESIZE_MOVE;
bool canResizeHorizontal = !(flags & TSF_NOHORIZONTAL);
bool canResizeVertical = !(flags & TSF_NOVERTICAL);
if (canResizeHorizontal && canResizeVertical)
{
if (renderHandle(inOut.Min(), handleSize))
resizing = RESIZE_LEFT | RESIZE_TOP;
if (renderHandle(inOut.Min() + IntVector2(0, size.y_), handleSize))
resizing = RESIZE_LEFT | RESIZE_BOTTOM;
if (renderHandle(inOut.Min() + IntVector2(size.x_, 0), handleSize))
resizing = RESIZE_TOP | RESIZE_RIGHT;
if (renderHandle(inOut.Max(), handleSize))
resizing = RESIZE_BOTTOM | RESIZE_RIGHT;
}
if (canResizeHorizontal)
{
if (renderHandle(inOut.Min() + IntVector2(0, size.y_ / 2), handleSize))
resizing = RESIZE_LEFT;
if (renderHandle(inOut.Min() + IntVector2(size.x_, size.y_ / 2), handleSize))
resizing = RESIZE_RIGHT;
}
if (canResizeVertical)
{
if (renderHandle(inOut.Min() + IntVector2(size.x_ / 2, 0), handleSize))
resizing = RESIZE_TOP;
if (renderHandle(inOut.Min() + IntVector2(size.x_ / 2, size.y_), handleSize))
resizing = RESIZE_BOTTOM;
}
// Draw rect around selected element
ui::GetWindowDrawList()->AddRect(ToImGui(inOut.Min()), ToImGui(inOut.Max()),
ui::GetColorU32(ToImGui(Color::RED)));
// Reset mouse cursor if we are not hovering any handle and are not resizing
if (resizing == RESIZE_NONE && s->resizing_ == RESIZE_NONE && s->ownsCursor_)
{
SDL_SetCursor(s->cursorArrow_);
s->ownsCursor_ = false;
}
// Prevent interaction when something else blocks inactive transform.
if (s->resizing_ != RESIZE_NONE || (ui::IsItemHovered(ImGuiHoveredFlags_RectOnly) &&
(!ui::IsWindowHovered(ImGuiHoveredFlags_AnyWindow) || ui::IsWindowHovered())))
{
// Set mouse cursor if handle is hovered or if we are resizing
if (resizing != RESIZE_NONE && !s->ownsCursor_)
{
SDL_SetCursor(s->cursors_[resizing]);
s->ownsCursor_ = true;
}
// Begin resizing
if (ui::IsMouseClicked(0))
s->resizing_ = resizing;
IntVector2 d = ToIntVector2(ui::GetIO().MouseDelta);
if (s->resizing_ != RESIZE_NONE)
{
ui::SetActiveID(id, ui::GetCurrentWindow());
if (!ui::IsMouseDown(0))
s->resizing_ = RESIZE_NONE;
else if (d != IntVector2::ZERO)
{
delta = IntRect::ZERO;
if (s->resizing_ == RESIZE_MOVE)
{
delta.left_ += d.x_;
delta.right_ += d.x_;
delta.top_ += d.y_;
delta.bottom_ += d.y_;
modified = true;
}
else
{
if (s->resizing_ & RESIZE_LEFT)
{
delta.left_ += d.x_;
modified = true;
}
else if (s->resizing_ & RESIZE_RIGHT)
{
delta.right_ += d.x_;
modified = true;
}
if (s->resizing_ & RESIZE_TOP)
{
delta.top_ += d.y_;
modified = true;
}
else if (s->resizing_ & RESIZE_BOTTOM)
{
delta.bottom_ += d.y_;
modified = true;
}
}
}
}
else if (ui::IsItemActive())
ui::SetActiveID(0, ui::GetCurrentWindow());
if (modified)
inOut += delta;
}
else if (ui::IsItemActive())
ui::SetActiveID(0, ui::GetCurrentWindow());
}
return modified;
}
SystemUI* GetSystemUI()
{
return static_cast<SystemUI*>(ui::GetIO().UserData);
}
bool EditorToolbarButton(const char* text, const char* tooltip, bool active)
{
const auto& style = ui::GetStyle();
if (active)
ui::PushStyleColor(ImGuiCol_Button, style.Colors[ImGuiCol_ButtonActive]);
else
ui::PushStyleColor(ImGuiCol_Button, style.Colors[ImGuiCol_Button]);
bool result = ui::ToolbarButton(text);
ui::PopStyleColor();
ui::SameLine(0, 0);
if (ui::IsItemHovered() && tooltip)
ui::SetTooltip("%s", tooltip);
return result;
}
void OpenTreeNode(ImGuiID id)
{
auto& storage = ui::GetCurrentWindow()->DC.StateStorage;
if (!storage->GetInt(id))
{
storage->SetInt(id, true);
ui::TreePushRawID(id);
}
}
}
<commit_msg>Toolbox/SystemUI: Replace timer-based ui state expiration with frame-based expiration. Items unused for two frames in a row are deleted.<commit_after>//
// Copyright (c) 2018 Rokas Kupstys
//
// 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 "Widgets.h"
#include <ImGui/imgui_internal.h>
#include <Urho3D/Core/Context.h>
#include <Urho3D/Input/Input.h>
#include <SDL/SDL_scancode.h>
#include <Urho3D/SystemUI/SystemUI.h>
using namespace Urho3D;
using namespace ui::litterals;
namespace ImGui
{
struct UIStateWrapper
{
void Set(void* state, void(*deleter)(void*)=nullptr)
{
lastUse_ = ui::GetCurrentContext()->FrameCount;
state_ = state;
deleter_ = deleter;
}
void Unset()
{
if (deleter_ && state_)
deleter_(state_);
state_ = nullptr;
deleter_ = nullptr;
}
void* Get()
{
lastUse_ = ui::GetCurrentContext()->FrameCount;
return state_;
}
bool IsExpired()
{
return (ui::GetCurrentContext()->FrameCount - lastUse_) > 1;
}
protected:
/// User state pointer.
void* state_ = nullptr;
/// Function that handles deleting state object when it becomes unused.
void(*deleter_)(void* state) = nullptr;
/// Frame when value was last used.
int lastUse_ = 0;
};
static HashMap<ImGuiID, UIStateWrapper> uiState_;
static int uiStateLastGcFrame_ = 0;
void SetUIStateP(void* state, void(*deleter)(void*))
{
auto id = ui::GetCurrentWindow()->IDStack.back();
uiState_[id].Set(state, deleter);
}
void* GetUIStateP()
{
void* result = nullptr;
auto id = ui::GetCurrentWindow()->IDStack.back();
auto it = uiState_.Find(id);
if (it != uiState_.End())
result = it->second_.Get();
int currentFrame = ui::GetCurrentContext()->FrameCount;
if (uiStateLastGcFrame_ != currentFrame)
{
uiStateLastGcFrame_ = currentFrame;
for (auto jt = uiState_.Begin(); jt != uiState_.End();)
{
if (jt->second_.IsExpired())
{
jt->second_.Unset();
jt = uiState_.Erase(jt);
}
else
++jt;
}
}
return result;
}
void ExpireUIStateP()
{
auto it = uiState_.Find(ui::GetCurrentWindow()->IDStack.back());
if (it != uiState_.End())
{
it->second_.Unset();
uiState_.Erase(it);
}
}
int DoubleClickSelectable(const char* label, bool* p_selected, ImGuiSelectableFlags flags, const ImVec2& size)
{
bool wasSelected = p_selected && *p_selected;
if (ui::Selectable(label, p_selected, flags | ImGuiSelectableFlags_AllowDoubleClick, size))
{
if (wasSelected && ui::IsMouseDoubleClicked(MOUSEB_LEFT))
return 2;
else
return 1;
}
if (ui::IsItemHovered() && ui::IsMouseClicked(MOUSEB_RIGHT))
{
*p_selected = true;
return 1;
}
return 0;
}
int DoubleClickSelectable(const char* label, bool selected, ImGuiSelectableFlags flags, const ImVec2& size)
{
return DoubleClickSelectable(label, &selected, flags, size);
}
bool CollapsingHeaderSimple(const char* label, ImGuiTreeNodeFlags flags)
{
ImGuiWindow* window = ui::GetCurrentWindow();
if (window->SkipItems)
return false;
ui::PushStyleColor(ImGuiCol_HeaderActive, 0);
ui::PushStyleColor(ImGuiCol_HeaderHovered, 0);
ui::PushStyleColor(ImGuiCol_Header, 0);
bool open = ui::TreeNodeBehavior(window->GetID(label), flags | ImGuiTreeNodeFlags_NoAutoOpenOnLog | ImGuiTreeNodeFlags_NoTreePushOnOpen, label);
ui::PopStyleColor(3);
return open;
}
bool ToolbarButton(const char* label)
{
auto& g = *ui::GetCurrentContext();
float dimension = g.FontBaseSize + g.Style.FramePadding.y * 2.0f;
return ui::ButtonEx(label, {0, dimension}, ImGuiButtonFlags_PressedOnClick);
}
void SetHelpTooltip(const char* text, Key requireKey)
{
unsigned scancode = requireKey & (~SDLK_SCANCODE_MASK);
if (ui::IsItemHovered() && (requireKey == KEY_UNKNOWN || ui::IsKeyDown(scancode)))
ui::SetTooltip("%s", text);
}
bool IconButton(const char* label)
{
float size = ui::GetItemRectSize().y;
return ui::Button(label, {size, size});
}
bool MaskSelector(unsigned int* mask)
{
bool modified = false;
auto style = ui::GetStyle();
auto pos = ui::GetCursorPos();
for (auto row = 0; row < 2; row++)
{
for (auto col = 0; col < 16; col++)
{
auto bitPosition = row * 16 + col;
int bitMask = 1 << bitPosition;
bool selected = (*mask & bitMask) != 0;
if (selected)
{
ui::PushStyleColor(ImGuiCol_Button, style.Colors[ImGuiCol_ButtonActive]);
ui::PushStyleColor(ImGuiCol_ButtonHovered, style.Colors[ImGuiCol_ButtonActive]);
}
else
{
ui::PushStyleColor(ImGuiCol_Button, style.Colors[ImGuiCol_Button]);
ui::PushStyleColor(ImGuiCol_ButtonHovered, style.Colors[ImGuiCol_Button]);
}
ui::PushID(bitMask);
if (ui::Button("", {8_dpx, 9_dpy}))
{
modified = true;
*mask ^= bitMask;
}
if (ui::IsItemHovered())
ui::SetTooltip("%d", bitPosition);
ui::PopID();
ui::SameLine(0, 0);
ui::PopStyleColor(2);
}
ui::NewLine();
if (row < 1)
ui::SetCursorPos({pos.x, pos.y + 9_dpy});
}
return modified;
}
enum TransformResizeType
{
RESIZE_NONE = 0,
RESIZE_LEFT = 1,
RESIZE_RIGHT = 2,
RESIZE_TOP = 4,
RESIZE_BOTTOM = 8,
RESIZE_MOVE = 15,
};
}
/// Flag manipuation operators.
URHO3D_FLAGSET_EX(ImGui, TransformResizeType, TransformResizeTypeFlags);
namespace ImGui
{
/// Hashing function which enables use of enum type as a HashMap key.
inline unsigned MakeHash(const TransformResizeType& value) { return value; }
bool TransformRect(IntRect& inOut, TransformSelectorFlags flags)
{
IntRect delta;
return TransformRect(inOut, delta, flags);
}
bool TransformRect(Urho3D::IntRect& inOut, Urho3D::IntRect& delta, TransformSelectorFlags flags)
{
struct State
{
/// A flag indicating type of resize action currently in progress
TransformResizeTypeFlags resizing_ = RESIZE_NONE;
/// A cache of system cursors
HashMap<TransformResizeTypeFlags, SDL_Cursor*> cursors_;
/// Default cursor shape
SDL_Cursor* cursorArrow_;
/// Flag indicating that this selector set cursor handle
bool ownsCursor_ = false;
State()
{
cursors_[RESIZE_MOVE] = SDL_CreateSystemCursor(SDL_SYSTEM_CURSOR_SIZEALL);
cursors_[RESIZE_LEFT] = cursors_[RESIZE_RIGHT] = SDL_CreateSystemCursor(SDL_SYSTEM_CURSOR_SIZEWE);
cursors_[RESIZE_BOTTOM] = cursors_[RESIZE_TOP] = SDL_CreateSystemCursor(SDL_SYSTEM_CURSOR_SIZENS);
cursors_[RESIZE_TOP | RESIZE_LEFT] = cursors_[RESIZE_BOTTOM | RESIZE_RIGHT] = SDL_CreateSystemCursor(
SDL_SYSTEM_CURSOR_SIZENWSE);
cursors_[RESIZE_TOP | RESIZE_RIGHT] = cursors_[RESIZE_BOTTOM | RESIZE_LEFT] = SDL_CreateSystemCursor(
SDL_SYSTEM_CURSOR_SIZENESW);
cursorArrow_ = SDL_CreateSystemCursor(SDL_SYSTEM_CURSOR_ARROW);
}
~State()
{
SDL_FreeCursor(cursorArrow_);
for (const auto& it : cursors_)
SDL_FreeCursor(it.second_);
}
};
Input* input = ui::GetSystemUI()->GetSubsystem<Input>();
auto renderHandle = [&](IntVector2 screenPos, int wh) -> bool {
IntRect rect(
screenPos.x_ - wh / 2,
screenPos.y_ - wh / 2,
screenPos.x_ + wh / 2,
screenPos.y_ + wh / 2
);
if (!(flags & TSF_HIDEHANDLES))
{
ui::GetWindowDrawList()->AddRectFilled(ToImGui(rect.Min()), ToImGui(rect.Max()),
ui::GetColorU32(ToImGui(Color::RED)));
}
return rect.IsInside(input->GetMousePosition()) == INSIDE;
};
auto size = inOut.Size();
auto handleSize = Max(Min(Min(size.x_ / 4, size.y_ / 4), 8), 2);
bool modified = false;
auto* s = ui::GetUIState<State>();
auto id = ui::GetID(s);
// Extend rect to cover resize handles that are sticking out of ui element boundaries.
auto extendedRect = inOut + IntRect(-handleSize / 2, -handleSize / 2, handleSize / 2, handleSize / 2);
ui::ItemSize(ToImGui(inOut));
if (ui::ItemAdd(ToImGui(extendedRect), id))
{
TransformResizeTypeFlags resizing = RESIZE_NONE;
if (renderHandle(inOut.Min() + size / 2, handleSize))
resizing = RESIZE_MOVE;
bool canResizeHorizontal = !(flags & TSF_NOHORIZONTAL);
bool canResizeVertical = !(flags & TSF_NOVERTICAL);
if (canResizeHorizontal && canResizeVertical)
{
if (renderHandle(inOut.Min(), handleSize))
resizing = RESIZE_LEFT | RESIZE_TOP;
if (renderHandle(inOut.Min() + IntVector2(0, size.y_), handleSize))
resizing = RESIZE_LEFT | RESIZE_BOTTOM;
if (renderHandle(inOut.Min() + IntVector2(size.x_, 0), handleSize))
resizing = RESIZE_TOP | RESIZE_RIGHT;
if (renderHandle(inOut.Max(), handleSize))
resizing = RESIZE_BOTTOM | RESIZE_RIGHT;
}
if (canResizeHorizontal)
{
if (renderHandle(inOut.Min() + IntVector2(0, size.y_ / 2), handleSize))
resizing = RESIZE_LEFT;
if (renderHandle(inOut.Min() + IntVector2(size.x_, size.y_ / 2), handleSize))
resizing = RESIZE_RIGHT;
}
if (canResizeVertical)
{
if (renderHandle(inOut.Min() + IntVector2(size.x_ / 2, 0), handleSize))
resizing = RESIZE_TOP;
if (renderHandle(inOut.Min() + IntVector2(size.x_ / 2, size.y_), handleSize))
resizing = RESIZE_BOTTOM;
}
// Draw rect around selected element
ui::GetWindowDrawList()->AddRect(ToImGui(inOut.Min()), ToImGui(inOut.Max()),
ui::GetColorU32(ToImGui(Color::RED)));
// Reset mouse cursor if we are not hovering any handle and are not resizing
if (resizing == RESIZE_NONE && s->resizing_ == RESIZE_NONE && s->ownsCursor_)
{
SDL_SetCursor(s->cursorArrow_);
s->ownsCursor_ = false;
}
// Prevent interaction when something else blocks inactive transform.
if (s->resizing_ != RESIZE_NONE || (ui::IsItemHovered(ImGuiHoveredFlags_RectOnly) &&
(!ui::IsWindowHovered(ImGuiHoveredFlags_AnyWindow) || ui::IsWindowHovered())))
{
// Set mouse cursor if handle is hovered or if we are resizing
if (resizing != RESIZE_NONE && !s->ownsCursor_)
{
SDL_SetCursor(s->cursors_[resizing]);
s->ownsCursor_ = true;
}
// Begin resizing
if (ui::IsMouseClicked(0))
s->resizing_ = resizing;
IntVector2 d = ToIntVector2(ui::GetIO().MouseDelta);
if (s->resizing_ != RESIZE_NONE)
{
ui::SetActiveID(id, ui::GetCurrentWindow());
if (!ui::IsMouseDown(0))
s->resizing_ = RESIZE_NONE;
else if (d != IntVector2::ZERO)
{
delta = IntRect::ZERO;
if (s->resizing_ == RESIZE_MOVE)
{
delta.left_ += d.x_;
delta.right_ += d.x_;
delta.top_ += d.y_;
delta.bottom_ += d.y_;
modified = true;
}
else
{
if (s->resizing_ & RESIZE_LEFT)
{
delta.left_ += d.x_;
modified = true;
}
else if (s->resizing_ & RESIZE_RIGHT)
{
delta.right_ += d.x_;
modified = true;
}
if (s->resizing_ & RESIZE_TOP)
{
delta.top_ += d.y_;
modified = true;
}
else if (s->resizing_ & RESIZE_BOTTOM)
{
delta.bottom_ += d.y_;
modified = true;
}
}
}
}
else if (ui::IsItemActive())
ui::SetActiveID(0, ui::GetCurrentWindow());
if (modified)
inOut += delta;
}
else if (ui::IsItemActive())
ui::SetActiveID(0, ui::GetCurrentWindow());
}
return modified;
}
SystemUI* GetSystemUI()
{
return static_cast<SystemUI*>(ui::GetIO().UserData);
}
bool EditorToolbarButton(const char* text, const char* tooltip, bool active)
{
const auto& style = ui::GetStyle();
if (active)
ui::PushStyleColor(ImGuiCol_Button, style.Colors[ImGuiCol_ButtonActive]);
else
ui::PushStyleColor(ImGuiCol_Button, style.Colors[ImGuiCol_Button]);
bool result = ui::ToolbarButton(text);
ui::PopStyleColor();
ui::SameLine(0, 0);
if (ui::IsItemHovered() && tooltip)
ui::SetTooltip("%s", tooltip);
return result;
}
void OpenTreeNode(ImGuiID id)
{
auto& storage = ui::GetCurrentWindow()->DC.StateStorage;
if (!storage->GetInt(id))
{
storage->SetInt(id, true);
ui::TreePushRawID(id);
}
}
}
<|endoftext|>
|
<commit_before>/*
* Copyright (C) 2005, 2008 Apple Inc. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
* OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "config.h"
#include "core/editing/RemoveNodeCommand.h"
#include "bindings/v8/ExceptionStatePlaceholder.h"
#include "core/dom/Node.h"
#include "wtf/Assertions.h"
namespace WebCore {
RemoveNodeCommand::RemoveNodeCommand(PassRefPtr<Node> node, ShouldAssumeContentIsAlwaysEditable shouldAssumeContentIsAlwaysEditable)
: SimpleEditCommand(node->document())
, m_node(node)
, m_shouldAssumeContentIsAlwaysEditable(shouldAssumeContentIsAlwaysEditable)
{
ASSERT(m_node);
ASSERT(m_node->parentNode());
}
void RemoveNodeCommand::doApply()
{
ContainerNode* parent = m_node->parentNode();
if (!parent || (m_shouldAssumeContentIsAlwaysEditable == DoNotAssumeContentIsAlwaysEditable
&& !parent->isContentEditable(Node::UserSelectAllIsAlwaysNonEditable) && parent->attached()))
return;
ASSERT(parent->isContentEditable(Node::UserSelectAllIsAlwaysNonEditable) || !parent->attached());
m_parent = parent;
m_refChild = m_node->nextSibling();
m_node->remove(IGNORE_EXCEPTION);
}
void RemoveNodeCommand::doUnapply()
{
RefPtr<ContainerNode> parent = m_parent.release();
RefPtr<Node> refChild = m_refChild.release();
if (!parent || !parent->rendererIsEditable())
return;
parent->insertBefore(m_node.get(), refChild.get(), IGNORE_EXCEPTION, DeprecatedAttachNow);
}
#ifndef NDEBUG
void RemoveNodeCommand::getNodesInCommand(HashSet<Node*>& nodes)
{
addNodeAndDescendants(m_parent.get(), nodes);
addNodeAndDescendants(m_refChild.get(), nodes);
addNodeAndDescendants(m_node.get(), nodes);
}
#endif
}
<commit_msg>RemoveNodeCommand should attach lazily.<commit_after>/*
* Copyright (C) 2005, 2008 Apple Inc. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
* OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "config.h"
#include "core/editing/RemoveNodeCommand.h"
#include "bindings/v8/ExceptionStatePlaceholder.h"
#include "core/dom/Node.h"
#include "wtf/Assertions.h"
namespace WebCore {
RemoveNodeCommand::RemoveNodeCommand(PassRefPtr<Node> node, ShouldAssumeContentIsAlwaysEditable shouldAssumeContentIsAlwaysEditable)
: SimpleEditCommand(node->document())
, m_node(node)
, m_shouldAssumeContentIsAlwaysEditable(shouldAssumeContentIsAlwaysEditable)
{
ASSERT(m_node);
ASSERT(m_node->parentNode());
}
void RemoveNodeCommand::doApply()
{
ContainerNode* parent = m_node->parentNode();
if (!parent || (m_shouldAssumeContentIsAlwaysEditable == DoNotAssumeContentIsAlwaysEditable
&& !parent->isContentEditable(Node::UserSelectAllIsAlwaysNonEditable) && parent->attached()))
return;
ASSERT(parent->isContentEditable(Node::UserSelectAllIsAlwaysNonEditable) || !parent->attached());
m_parent = parent;
m_refChild = m_node->nextSibling();
m_node->remove(IGNORE_EXCEPTION);
}
void RemoveNodeCommand::doUnapply()
{
RefPtr<ContainerNode> parent = m_parent.release();
RefPtr<Node> refChild = m_refChild.release();
if (!parent || !parent->rendererIsEditable())
return;
parent->insertBefore(m_node.get(), refChild.get(), IGNORE_EXCEPTION);
}
#ifndef NDEBUG
void RemoveNodeCommand::getNodesInCommand(HashSet<Node*>& nodes)
{
addNodeAndDescendants(m_parent.get(), nodes);
addNodeAndDescendants(m_refChild.get(), nodes);
addNodeAndDescendants(m_node.get(), nodes);
}
#endif
}
<|endoftext|>
|
<commit_before>//===----------------------------------------------------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is dual licensed under the MIT and the University of Illinois Open
// Source Licenses. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
// REQUIRES: diagnose-if-support
// UNSUPPORTED: c++98, c++03
// Libc++ only provides a defined primary template for std::hash in C++14 and
// newer.
// UNSUPPORTED: c++11
// <unordered_set>
// Test that we generate a reasonable diagnostic when the specified hash is
// not enabled.
#include <unordered_set>
#include <utility>
using VT = std::pair<int, int>;
struct BadHashNoCopy {
BadHashNoCopy() = default;
BadHashNoCopy(BadHashNoCopy const&) = delete;
template <class T>
size_t operator()(T const&) const { return 0; }
};
struct BadHashNoCall {
};
struct GoodHashNoDefault {
explicit GoodHashNoDefault(void*) {}
template <class T>
size_t operator()(T const&) const { return 0; }
};
int main() {
{
using Set = std::unordered_set<VT>;
Set s; // expected-error@__hash_table:* {{the specified hash does not meet the Hash requirements}}
// FIXME: It would be great to suppress the below diagnostic all together.
// but for now it's sufficient that it appears last. However there is
// currently no way to test the order diagnostics are issued.
// expected-error@memory:* {{call to implicitly-deleted default constructor of 'std::__1::hash<std::__1::pair<int, int> >'}}
}
{
using Set = std::unordered_set<int, BadHashNoCopy>;
Set s; // expected-error@__hash_table:* {{the specified hash does not meet the Hash requirements}}
}
{
using Set = std::unordered_set<int, BadHashNoCall>;
Set s; // expected-error@__hash_table:* {{the specified hash does not meet the Hash requirements}}
}
{
using Set = std::unordered_set<int, GoodHashNoDefault>;
Set s(/*bucketcount*/42, GoodHashNoDefault(nullptr));
}
}
<commit_msg>Update tests -verify error messages after r300140.<commit_after>//===----------------------------------------------------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is dual licensed under the MIT and the University of Illinois Open
// Source Licenses. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
// REQUIRES: diagnose-if-support
// UNSUPPORTED: c++98, c++03
// Libc++ only provides a defined primary template for std::hash in C++14 and
// newer.
// UNSUPPORTED: c++11
// <unordered_set>
// Test that we generate a reasonable diagnostic when the specified hash is
// not enabled.
#include <unordered_set>
#include <utility>
using VT = std::pair<int, int>;
struct BadHashNoCopy {
BadHashNoCopy() = default;
BadHashNoCopy(BadHashNoCopy const&) = delete;
template <class T>
size_t operator()(T const&) const { return 0; }
};
struct BadHashNoCall {
};
struct GoodHashNoDefault {
explicit GoodHashNoDefault(void*) {}
template <class T>
size_t operator()(T const&) const { return 0; }
};
int main() {
{
using Set = std::unordered_set<VT>;
Set s; // expected-error@__hash_table:* {{the specified hash does not meet the Hash requirements}}
// FIXME: It would be great to suppress the below diagnostic all together.
// but for now it's sufficient that it appears last. However there is
// currently no way to test the order diagnostics are issued.
// expected-error@memory:* {{call to implicitly-deleted default constructor of '__compressed_pair_elem}}
}
{
using Set = std::unordered_set<int, BadHashNoCopy>;
Set s; // expected-error@__hash_table:* {{the specified hash does not meet the Hash requirements}}
}
{
using Set = std::unordered_set<int, BadHashNoCall>;
Set s; // expected-error@__hash_table:* {{the specified hash does not meet the Hash requirements}}
}
{
using Set = std::unordered_set<int, GoodHashNoDefault>;
Set s(/*bucketcount*/42, GoodHashNoDefault(nullptr));
}
}
<|endoftext|>
|
<commit_before>//===----------------------------------------------------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is dual licensed under the MIT and the University of Illinois Open
// Source Licenses. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
// <istream>
// streamsize readsome(char_type* s, streamsize n);
#include <istream>
#include <cassert>
template <class CharT>
struct testbuf
: public std::basic_streambuf<CharT>
{
typedef std::basic_string<CharT> string_type;
typedef std::basic_streambuf<CharT> base;
private:
string_type str_;
public:
testbuf() {}
testbuf(const string_type& str)
: str_(str)
{
base::setg(const_cast<CharT*>(str_.data()),
const_cast<CharT*>(str_.data()),
const_cast<CharT*>(str_.data()) + str_.size());
}
CharT* eback() const {return base::eback();}
CharT* gptr() const {return base::gptr();}
CharT* egptr() const {return base::egptr();}
};
int main()
{
{
testbuf<char> sb(" 1234567890");
std::istream is(&sb);
char s[5];
assert(is.readsome(s, 5) == 5);
assert(!is.eof());
assert(!is.fail());
assert(std::string(s, 5) == " 1234");
assert(is.gcount() == 5);
is.readsome(s, 5);
assert(!is.eof());
assert(!is.fail());
assert(std::string(s, 5) == "56789");
assert(is.gcount() == 5);
is.readsome(s, 5);
assert(!is.eof());
assert(!is.fail());
assert(is.gcount() == 1);
assert(std::string(s, 1) == "0");
}
{
testbuf<wchar_t> sb(L" 1234567890");
std::wistream is(&sb);
wchar_t s[5];
assert(is.readsome(s, 5) == 5);
assert(!is.eof());
assert(!is.fail());
assert(std::wstring(s, 5) == L" 1234");
assert(is.gcount() == 5);
is.readsome(s, 5);
assert(!is.eof());
assert(!is.fail());
assert(std::wstring(s, 5) == L"56789");
assert(is.gcount() == 5);
is.readsome(s, 5);
assert(!is.eof());
assert(!is.fail());
assert(is.gcount() == 1);
assert(std::wstring(s, 1) == L"0");
}
}
<commit_msg>Test case for http://llvm.org/bugs/show_bug.cgi?id=14670.<commit_after>//===----------------------------------------------------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is dual licensed under the MIT and the University of Illinois Open
// Source Licenses. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
// <istream>
// streamsize readsome(char_type* s, streamsize n);
#include <istream>
#include <cassert>
template <class CharT>
struct testbuf
: public std::basic_streambuf<CharT>
{
typedef std::basic_string<CharT> string_type;
typedef std::basic_streambuf<CharT> base;
private:
string_type str_;
public:
testbuf() {}
testbuf(const string_type& str)
: str_(str)
{
base::setg(const_cast<CharT*>(str_.data()),
const_cast<CharT*>(str_.data()),
const_cast<CharT*>(str_.data()) + str_.size());
}
CharT* eback() const {return base::eback();}
CharT* gptr() const {return base::gptr();}
CharT* egptr() const {return base::egptr();}
};
int main()
{
{
testbuf<char> sb(" 1234567890");
std::istream is(&sb);
char s[5];
assert(is.readsome(s, 5) == 5);
assert(!is.eof());
assert(!is.fail());
assert(std::string(s, 5) == " 1234");
assert(is.gcount() == 5);
is.readsome(s, 5);
assert(!is.eof());
assert(!is.fail());
assert(std::string(s, 5) == "56789");
assert(is.gcount() == 5);
is.readsome(s, 5);
assert(!is.eof());
assert(!is.fail());
assert(is.gcount() == 1);
assert(std::string(s, 1) == "0");
assert(is.readsome(s, 5) == 0);
}
{
testbuf<wchar_t> sb(L" 1234567890");
std::wistream is(&sb);
wchar_t s[5];
assert(is.readsome(s, 5) == 5);
assert(!is.eof());
assert(!is.fail());
assert(std::wstring(s, 5) == L" 1234");
assert(is.gcount() == 5);
is.readsome(s, 5);
assert(!is.eof());
assert(!is.fail());
assert(std::wstring(s, 5) == L"56789");
assert(is.gcount() == 5);
is.readsome(s, 5);
assert(!is.eof());
assert(!is.fail());
assert(is.gcount() == 1);
assert(std::wstring(s, 1) == L"0");
assert(is.readsome(s, 5) == 0);
}
}
<|endoftext|>
|
<commit_before>// Copyright 2016 Alessio Sclocco <a.sclocco@vu.nl>
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#ifndef CONFIGURATION_TUNEBENCH_HPP
#define CONFIGURATION_TUNEBENCH_HPP
// Define the data types
typedef float inputDataType;
std::string inputDataName("float");
typedef float outputDataType;
std::string outputDataName("float");
// Magic value
const unsigned int magicValue = 42;
// MD
const float LJ1 = 1.5f;
const float LJ2 = 2.0f;
// Correlator
const unsigned int nrPolarizations = 2;
#endif // CONFIGURATION_TUNEBENCH_HPP
<commit_msg>Forgot to move one constant.<commit_after>// Copyright 2016 Alessio Sclocco <a.sclocco@vu.nl>
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#ifndef CONFIGURATION_TUNEBENCH_HPP
#define CONFIGURATION_TUNEBENCH_HPP
// Define the data types
typedef float inputDataType;
std::string inputDataName("float");
typedef float outputDataType;
std::string outputDataName("float");
// Magic value
const unsigned int magicValue = 42;
// Triad
const unsigned int factor = 42;
// MD
const float LJ1 = 1.5f;
const float LJ2 = 2.0f;
// Correlator
const unsigned int nrPolarizations = 2;
#endif // CONFIGURATION_TUNEBENCH_HPP
<|endoftext|>
|
<commit_before>/*
* Copyright (c) 2011, Willow Garage, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the Willow Garage, Inc. nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
#pragma once
#include <ecto/tendril.hpp>
#include <ecto/spore.hpp>
#include <boost/thread.hpp>
#include <string>
#include <sstream>
#include <cstring>
#include <map>
#include <stdexcept>
namespace ecto
{
/**
* \brief The tendrils are a collection for the ecto::tendril class, addressable by a string key.
*/
class ECTO_EXPORT tendrils : boost::noncopyable
{
public:
typedef std::map<std::string, tendril::ptr> storage_type;
typedef storage_type::iterator iterator;
typedef storage_type::const_iterator const_iterator;
typedef storage_type::value_type value_type;
typedef storage_type::key_type key_type;
typedef storage_type::size_type size_type;
typedef storage_type::difference_type difference_type;
typedef storage_type::key_compare key_compare;
tendrils();
iterator begin() { return storage.begin(); }
const_iterator begin() const { return storage.begin(); }
iterator end() { return storage.end(); }
const_iterator end() const { return storage.end(); }
iterator find(const std::string& name) { return storage.find(name); }
const_iterator find(const std::string& name) const { return storage.find(name); }
void clear() { storage.clear(); }
size_type size() const { return storage.size(); }
void erase(iterator pos) { storage.erase(pos); }
void erase(const key_type& k) { storage.erase(k); }
template <typename InputIterator>
void
insert(InputIterator first, InputIterator last)
{
storage.insert(first, last);
}
std::pair<iterator, bool> insert(const value_type &v)
{
return storage.insert(v);
}
key_compare key_comp() const { return storage.key_comp(); }
/**
* \brief Declare a tendril of a certain type, with only a name, no doc, or default values.
* @tparam T the type of tendril to declare.
* @param name The key for the tendril. Must be unique.
* @return A typed holder for the tendril.
*/
template<typename T>
spore<T>
declare(const std::string& name)
{
tendril::ptr t(make_tendril<T>());
return declare(name, t);
}
/**
* @see tendrils::declare
* @param name @see tendrils::declare
* @param doc The doc string for the tendril.
* @return @see tendrils::declare
*/
template<typename T>
spore<T>
declare(const std::string& name, const std::string& doc)
{
return declare<T>(name).set_doc(doc);
}
/**
* @see tendrils::declare
* @param name @see tendrils::declare
* @param doc @see tendrils::declare
* @param default_val A default value for the tendril.
* @return @see tendrils::declare
*/
template<typename T>
spore<T>
declare(const std::string& name, const std::string& doc, const T& default_val)
{
return declare<T>(name, doc).set_default_val(default_val);
}
/**
* Runtime declare function.
* @param name
* @param t
* @return
*/
tendril::ptr
declare(const std::string& name, tendril::ptr t);
/**
* \brief get the given type that is stored at the given key. Will throw if there is a type mismatch.
* @tparam T The compile time type to attempt to get from the tendrils.
* @param name The key value
* @return A const reference to the value, no copy is done.
*/
/*
template <typename T>
const T&
get(const std::string& name) const
{
try
{
const_iterator iter = storage.find(name);
if (iter == end())
doesnt_exist(name);
return iter->second->get<T>();
}catch(except::TypeMismatch& e)
{
e << std::string(" Hint : " ) + "'"+name+"' is of type: " + storage.at(name)->type_name();
throw e;
}
}
*/
/**
* \brief get the given type that is stored at the given key. Will throw if there is a type mismatch.
* @tparam T The compile time type to attempt to get from the tendrils.
* @param name The key value
* @return A reference to the value, no copy is done.
*/
template<typename T>
T&
get(const std::string& name) const
{
try
{
const_iterator iter = storage.find(name);
if (iter == end())
doesnt_exist(name);
return iter->second->get<T>();
} catch (except::TypeMismatch& e)
{
e << std::string(" Hint : ") + "'" + name + "' is of type: " + storage.at(name)->type_name();
throw e;
}
}
/**
* \brief Grabs the tendril at the key.
* @param name The key for the desired tendril.
* @return A shared pointer to the tendril.
* this throws if the key is not in the tendrils object
*/
const tendril::ptr& operator[](const std::string& name) const;
tendril::ptr& operator[](const std::string& name);
/**
* \brief Print the tendrils documentation string, in rst format.
* @param out The stream to print to.
* @param tendrils_name The name used as a label, for the tendrils.
*/
void
print_doc(std::ostream& out, const std::string& tendrils_name) const;
typedef boost::shared_ptr<tendrils> ptr;
typedef boost::shared_ptr<const tendrils> const_ptr;
private:
void doesnt_exist(const std::string& name) const;
storage_type storage;
mutable boost::mutex mtx;
tendrils(const tendrils&);
};
}
<commit_msg>Remove cruft from tendrils.hpp.<commit_after>/*
* Copyright (c) 2011, Willow Garage, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the Willow Garage, Inc. nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
#pragma once
#include <ecto/tendril.hpp>
#include <ecto/spore.hpp>
#include <boost/thread.hpp>
#include <string>
#include <sstream>
#include <cstring>
#include <map>
#include <stdexcept>
namespace ecto
{
/**
* \brief The tendrils are a collection for the ecto::tendril class, addressable by a string key.
*/
class ECTO_EXPORT tendrils : boost::noncopyable
{
public:
typedef std::map<std::string, tendril::ptr> storage_type;
typedef storage_type::iterator iterator;
typedef storage_type::const_iterator const_iterator;
typedef storage_type::value_type value_type;
typedef storage_type::key_type key_type;
typedef storage_type::size_type size_type;
typedef storage_type::difference_type difference_type;
typedef storage_type::key_compare key_compare;
tendrils();
iterator begin() { return storage.begin(); }
const_iterator begin() const { return storage.begin(); }
iterator end() { return storage.end(); }
const_iterator end() const { return storage.end(); }
iterator find(const std::string& name) { return storage.find(name); }
const_iterator find(const std::string& name) const { return storage.find(name); }
void clear() { storage.clear(); }
size_type size() const { return storage.size(); }
void erase(iterator pos) { storage.erase(pos); }
void erase(const key_type& k) { storage.erase(k); }
template <typename InputIterator>
void
insert(InputIterator first, InputIterator last)
{
storage.insert(first, last);
}
std::pair<iterator, bool> insert(const value_type &v)
{
return storage.insert(v);
}
key_compare key_comp() const { return storage.key_comp(); }
/**
* \brief Declare a tendril of a certain type, with only a name, no doc, or default values.
* @tparam T the type of tendril to declare.
* @param name The key for the tendril. Must be unique.
* @return A typed holder for the tendril.
*/
template<typename T>
spore<T>
declare(const std::string& name)
{
tendril::ptr t(make_tendril<T>());
return declare(name, t);
}
/**
* @see tendrils::declare
* @param name @see tendrils::declare
* @param doc The doc string for the tendril.
* @return @see tendrils::declare
*/
template<typename T>
spore<T>
declare(const std::string& name, const std::string& doc)
{
return declare<T>(name).set_doc(doc);
}
/**
* @see tendrils::declare
* @param name @see tendrils::declare
* @param doc @see tendrils::declare
* @param default_val A default value for the tendril.
* @return @see tendrils::declare
*/
template<typename T>
spore<T>
declare(const std::string& name, const std::string& doc, const T& default_val)
{
return declare<T>(name, doc).set_default_val(default_val);
}
/**
* Runtime declare function.
* @param name
* @param t
* @return
*/
tendril::ptr
declare(const std::string& name, tendril::ptr t);
/**
* \brief get the given type that is stored at the given key. Will throw if there is a type mismatch.
* @tparam T The compile time type to attempt to get from the tendrils.
* @param name The key value
* @return A reference to the value, no copy is done.
*/
template<typename T>
T&
get(const std::string& name) const
{
try
{
const_iterator iter = storage.find(name);
if (iter == end())
doesnt_exist(name);
return iter->second->get<T>();
} catch (except::TypeMismatch& e)
{
e << std::string(" Hint : ") + "'" + name + "' is of type: " + storage.at(name)->type_name();
throw e;
}
}
/**
* \brief Grabs the tendril at the key.
* @param name The key for the desired tendril.
* @return A shared pointer to the tendril.
* this throws if the key is not in the tendrils object
*/
const tendril::ptr& operator[](const std::string& name) const;
tendril::ptr& operator[](const std::string& name);
/**
* \brief Print the tendrils documentation string, in rst format.
* @param out The stream to print to.
* @param tendrils_name The name used as a label, for the tendrils.
*/
void
print_doc(std::ostream& out, const std::string& tendrils_name) const;
typedef boost::shared_ptr<tendrils> ptr;
typedef boost::shared_ptr<const tendrils> const_ptr;
private:
void doesnt_exist(const std::string& name) const;
storage_type storage;
mutable boost::mutex mtx;
tendrils(const tendrils&);
};
}
<|endoftext|>
|
<commit_before>#include "ImageWriter.h"
uint32 ImageWriter::GetChannelForPixel(uint32 x, uint32 y, uint32 ch) {
uint32 bytesPerRow = GetWidth() * 4;
uint32 byteLocation = y * bytesPerRow + x*4 + ch;
return m_PixelData[byteLocation];
}
<commit_msg>Make sure that we assume pixels are in block stream order when accessing.<commit_after>#include "ImageWriter.h"
uint32 ImageWriter::GetChannelForPixel(uint32 x, uint32 y, uint32 ch) {
// Assume pixels are in block stream order, hence we would need to first find
// the block that contains pixel (x, y) and then find the byte location for it.
const uint32 blocksPerRow = GetWidth() / 4;
const uint32 blockIdxX = x / 4;
const uint32 blockIdxY = y / 4;
const uint32 blockIdx = blockIdxY * blocksPerRow + blockIdxX;
// Now we find the offset in the block
const uint32 blockOffsetX = x % 4;
const uint32 blockOffsetY = y % 4;
const uint32 pixelOffset = blockOffsetY * 4 + blockOffsetX;
// There are 16 pixels per block and bytes per pixel...
uint32 dataOffset = blockIdx * 4 * 16;
dataOffset += 4 * pixelOffset;
dataOffset += ch;
return m_PixelData[dataOffset];
}
<|endoftext|>
|
<commit_before>//=======================================================================
// Copyright (c) 2014-2015 Baptiste Wicht
// Distributed under the terms of the MIT License.
// (See accompanying file LICENSE or copy at
// http://opensource.org/licenses/MIT)
//=======================================================================
#pragma once
#include <algorithm>
//Include the implementations
#include "etl/impl/std/conv.hpp"
#include "etl/impl/sse/conv.hpp"
#include "etl/impl/avx/conv.hpp"
#include "etl/impl/reduc/conv_mmul.hpp"
namespace etl {
enum class conv_type {
VALID,
SAME,
FULL
};
namespace detail {
enum class conv_impl {
STD,
SSE,
AVX
};
template<bool DMA, typename T>
inline cpp14_constexpr conv_impl select_conv_impl(){
//Only std implementation is able to handle non-dma expressions
if(!DMA){
return conv_impl::STD;
}
//Note since these boolean will be known at compile time, the conditions will be a lot simplified
auto sse = vectorize_impl && vector_mode == vector_mode_t::SSE3;
auto avx = vectorize_impl && vector_mode == vector_mode_t::AVX;
if(avx){
return conv_impl::AVX;
} else if(sse){
return conv_impl::SSE;
} else {
return conv_impl::STD;
}
}
template<typename I, typename K, typename C>
struct conv1_full_impl {
static void apply(const I& input, const K& kernel, C&& conv){
auto impl = select_conv_impl<all_dma<I,K,C>::value, value_t<I>>();
if(impl == conv_impl::AVX){
impl::avx::conv1_full(input, kernel, conv);
} else if(impl == conv_impl::SSE){
impl::sse::conv1_full(input, kernel, conv);
} else if(impl == conv_impl::STD){
impl::standard::conv1_full(input, kernel, conv);
}
}
};
template<typename I, typename K, typename C>
struct conv1_same_impl {
static void apply(const I& input, const K& kernel, C&& conv){
auto impl = select_conv_impl<all_dma<I,K,C>::value, value_t<I>>();
if(impl == conv_impl::AVX){
impl::avx::conv1_same(input, kernel, conv);
} else if(impl == conv_impl::SSE){
impl::sse::conv1_same(input, kernel, conv);
} else if(impl == conv_impl::STD){
impl::standard::conv1_same(input, kernel, conv);
}
}
};
template<typename I, typename K, typename C>
struct conv1_valid_impl {
static void apply(const I& input, const K& kernel, C&& conv){
auto impl = select_conv_impl<all_dma<I,K,C>::value, value_t<I>>();
if(impl == conv_impl::AVX){
impl::avx::conv1_valid(input, kernel, conv);
} else if(impl == conv_impl::SSE){
impl::sse::conv1_valid(input, kernel, conv);
} else if(impl == conv_impl::STD){
impl::standard::conv1_valid(input, kernel, conv);
}
}
};
template<typename I, typename K, typename C>
struct conv2_full_impl {
static void apply(const I& input, const K& kernel, C&& conv){
auto impl = select_conv_impl<all_dma<I,K,C>::value, value_t<I>>();
if(impl == conv_impl::AVX){
impl::avx::conv2_full(input, kernel, conv);
} else if(impl == conv_impl::SSE){
impl::sse::conv2_full(input, kernel, conv);
} else if(impl == conv_impl::STD){
impl::standard::conv2_full(input, kernel, conv);
}
}
};
template<typename I, typename K, typename C>
struct conv2_same_impl {
static void apply(const I& input, const K& kernel, C&& conv){
auto impl = select_conv_impl<all_dma<I,K,C>::value, value_t<I>>();
if(impl == conv_impl::AVX){
impl::avx::conv2_same(input, kernel, conv);
} else if(impl == conv_impl::SSE){
impl::sse::conv2_same(input, kernel, conv);
} else if(impl == conv_impl::STD){
impl::standard::conv2_same(input, kernel, conv);
}
}
};
template<typename I, typename K, typename C>
struct conv2_valid_impl {
static void apply(const I& input, const K& kernel, C&& conv){
auto impl = select_conv_impl<all_dma<I,K,C>::value, value_t<I>>();
if(impl == conv_impl::AVX){
impl::avx::conv2_valid(input, kernel, conv);
} else if(impl == conv_impl::SSE){
impl::sse::conv2_valid(input, kernel, conv);
} else if(impl == conv_impl::STD){
impl::standard::conv2_valid(input, kernel, conv);
}
}
};
template<conv_type TT, typename I, typename K, typename C>
struct conv_deep_impl {
template<conv_type TT2 = TT, typename I2 = I, cpp_enable_if(decay_traits<I2>::dimensions() == 3 && TT2 == conv_type::FULL)>
static void apply(const I& input, const K& kernel, C&& conv){
for(std::size_t i = 0; i < dim<0>(input); ++i){
conv(i) = conv_2d_full(input(i), kernel(i));
}
}
template<conv_type TT2 = TT, typename I2 = I, cpp_enable_if(decay_traits<I2>::dimensions() == 3 && TT2 == conv_type::SAME)>
static void apply(const I& input, const K& kernel, C&& conv){
for(std::size_t i = 0; i < dim<0>(input); ++i){
conv(i) = conv_2d_same(input(i), kernel(i));
}
}
template<conv_type TT2 = TT, typename I2 = I, cpp_enable_if(decay_traits<I2>::dimensions() == 3 && TT2 == conv_type::VALID)>
static void apply(const I& input, const K& kernel, C&& conv){
for(std::size_t i = 0; i < dim<0>(input); ++i){
conv(i) = conv_2d_valid(input(i), kernel(i));
}
}
template<typename I2 = I, cpp_enable_if((decay_traits<I2>::dimensions() > 3))>
static void apply(const I& input, const K& kernel, C&& conv){
for(std::size_t i = 0; i < dim<0>(input); ++i){
conv_deep_impl<TT, decltype(input(i)), decltype(kernel(i)), decltype(conv(i))>::apply(input(i), kernel(i), conv(i));
}
}
};
template<typename I, typename K, typename C>
using conv_deep_valid_impl = conv_deep_impl<conv_type::VALID, I, K, C>;
template<typename I, typename K, typename C>
using conv_deep_same_impl = conv_deep_impl<conv_type::SAME, I, K, C>;
template<typename I, typename K, typename C>
using conv_deep_full_impl = conv_deep_impl<conv_type::FULL, I, K, C>;
} //end of namespace detail
} //end of namespace etl
<commit_msg>Review DMA for conv<commit_after>//=======================================================================
// Copyright (c) 2014-2015 Baptiste Wicht
// Distributed under the terms of the MIT License.
// (See accompanying file LICENSE or copy at
// http://opensource.org/licenses/MIT)
//=======================================================================
#pragma once
#include <algorithm>
//Include the implementations
#include "etl/impl/std/conv.hpp"
#include "etl/impl/sse/conv.hpp"
#include "etl/impl/avx/conv.hpp"
#include "etl/impl/reduc/conv_mmul.hpp"
namespace etl {
enum class conv_type {
VALID,
SAME,
FULL
};
namespace detail {
enum class conv_impl {
STD,
SSE,
AVX
};
template<typename T>
inline cpp14_constexpr conv_impl select_conv_impl(){
//Note since these boolean will be known at compile time, the conditions will be a lot simplified
constexpr const bool sse = vectorize_impl && vector_mode == vector_mode_t::SSE3;
constexpr const bool avx = vectorize_impl && vector_mode == vector_mode_t::AVX;
if(avx){
return conv_impl::AVX;
} else if(sse){
return conv_impl::SSE;
} else {
return conv_impl::STD;
}
}
template<typename I, typename K, typename C, typename Enable = void>
struct conv1_full_impl {
static void apply(const I& input, const K& kernel, C&& conv){
auto impl = select_conv_impl<value_t<I>>();
if(impl == conv_impl::AVX){
impl::avx::conv1_full(input, kernel, conv);
} else if(impl == conv_impl::SSE){
impl::sse::conv1_full(input, kernel, conv);
} else if(impl == conv_impl::STD){
impl::standard::conv1_full(input, kernel, conv);
}
}
};
template<typename I, typename K, typename C, typename Enable = void>
struct conv1_same_impl {
static void apply(const I& input, const K& kernel, C&& conv){
auto impl = select_conv_impl<value_t<I>>();
if(impl == conv_impl::AVX){
impl::avx::conv1_same(input, kernel, conv);
} else if(impl == conv_impl::SSE){
impl::sse::conv1_same(input, kernel, conv);
} else if(impl == conv_impl::STD){
impl::standard::conv1_same(input, kernel, conv);
}
}
};
template<typename I, typename K, typename C, typename Enable = void>
struct conv1_valid_impl {
static void apply(const I& input, const K& kernel, C&& conv){
auto impl = select_conv_impl<value_t<I>>();
if(impl == conv_impl::AVX){
impl::avx::conv1_valid(input, kernel, conv);
} else if(impl == conv_impl::SSE){
impl::sse::conv1_valid(input, kernel, conv);
} else if(impl == conv_impl::STD){
impl::standard::conv1_valid(input, kernel, conv);
}
}
};
template<typename I, typename K, typename C, typename Enable = void>
struct conv2_full_impl {
static void apply(const I& input, const K& kernel, C&& conv){
auto impl = select_conv_impl<value_t<I>>();
if(impl == conv_impl::AVX){
impl::avx::conv2_full(input, kernel, conv);
} else if(impl == conv_impl::SSE){
impl::sse::conv2_full(input, kernel, conv);
} else if(impl == conv_impl::STD){
impl::standard::conv2_full(input, kernel, conv);
}
}
};
template<typename I, typename K, typename C, typename Enable = void>
struct conv2_same_impl {
static void apply(const I& input, const K& kernel, C&& conv){
auto impl = select_conv_impl<value_t<I>>();
if(impl == conv_impl::AVX){
impl::avx::conv2_same(input, kernel, conv);
} else if(impl == conv_impl::SSE){
impl::sse::conv2_same(input, kernel, conv);
} else if(impl == conv_impl::STD){
impl::standard::conv2_same(input, kernel, conv);
}
}
};
template<typename I, typename K, typename C, typename Enable = void>
struct conv2_valid_impl {
static void apply(const I& input, const K& kernel, C&& conv){
auto impl = select_conv_impl<value_t<I>>();
if(impl == conv_impl::AVX){
impl::avx::conv2_valid(input, kernel, conv);
} else if(impl == conv_impl::SSE){
impl::sse::conv2_valid(input, kernel, conv);
} else if(impl == conv_impl::STD){
impl::standard::conv2_valid(input, kernel, conv);
}
}
};
template<conv_type TT, typename I, typename K, typename C, typename Enable = void>
struct conv_deep_impl {
template<conv_type TT2 = TT, typename I2 = I, cpp_enable_if(decay_traits<I2>::dimensions() == 3 && TT2 == conv_type::FULL)>
static void apply(const I& input, const K& kernel, C&& conv){
for(std::size_t i = 0; i < dim<0>(input); ++i){
conv(i) = conv_2d_full(input(i), kernel(i));
}
}
template<conv_type TT2 = TT, typename I2 = I, cpp_enable_if(decay_traits<I2>::dimensions() == 3 && TT2 == conv_type::SAME)>
static void apply(const I& input, const K& kernel, C&& conv){
for(std::size_t i = 0; i < dim<0>(input); ++i){
conv(i) = conv_2d_same(input(i), kernel(i));
}
}
template<conv_type TT2 = TT, typename I2 = I, cpp_enable_if(decay_traits<I2>::dimensions() == 3 && TT2 == conv_type::VALID)>
static void apply(const I& input, const K& kernel, C&& conv){
for(std::size_t i = 0; i < dim<0>(input); ++i){
conv(i) = conv_2d_valid(input(i), kernel(i));
}
}
template<typename I2 = I, cpp_enable_if((decay_traits<I2>::dimensions() > 3))>
static void apply(const I& input, const K& kernel, C&& conv){
for(std::size_t i = 0; i < dim<0>(input); ++i){
conv_deep_impl<TT, decltype(input(i)), decltype(kernel(i)), decltype(conv(i))>::apply(input(i), kernel(i), conv(i));
}
}
};
template<typename I, typename K, typename C>
using conv_deep_valid_impl = conv_deep_impl<conv_type::VALID, I, K, C>;
template<typename I, typename K, typename C>
using conv_deep_same_impl = conv_deep_impl<conv_type::SAME, I, K, C>;
template<typename I, typename K, typename C>
using conv_deep_full_impl = conv_deep_impl<conv_type::FULL, I, K, C>;
//The following partial specializations are here to ensure compilation
//(and avoid using static_if/SFINAE at higher level)
template<typename I, typename K, typename C>
struct conv1_full_impl<I, K, C, std::enable_if_t<!all_dma<I,K,C>::value>> {
static void apply(const I& /*input*/, const K& /*kernel*/, C&& /*conv*/){
cpp_unreachable("Should never be reached");
}
};
template<typename I, typename K, typename C>
struct conv1_valid_impl<I, K, C, std::enable_if_t<!all_dma<I,K,C>::value>> {
static void apply(const I& /*input*/, const K& /*kernel*/, C&& /*conv*/){
cpp_unreachable("Should never be reached");
}
};
template<typename I, typename K, typename C>
struct conv1_same_impl<I, K, C, std::enable_if_t<!all_dma<I,K,C>::value>> {
static void apply(const I& /*input*/, const K& /*kernel*/, C&& /*conv*/){
cpp_unreachable("Should never be reached");
}
};
template<typename I, typename K, typename C>
struct conv2_full_impl<I, K, C, std::enable_if_t<!all_dma<I,K,C>::value>> {
static void apply(const I& /*input*/, const K& /*kernel*/, C&& /*conv*/){
cpp_unreachable("Should never be reached");
}
};
template<typename I, typename K, typename C>
struct conv2_valid_impl<I, K, C, std::enable_if_t<!all_dma<I,K,C>::value>> {
static void apply(const I& /*input*/, const K& /*kernel*/, C&& /*conv*/){
cpp_unreachable("Should never be reached");
}
};
template<typename I, typename K, typename C>
struct conv2_same_impl<I, K, C, std::enable_if_t<!all_dma<I,K,C>::value>> {
static void apply(const I& /*input*/, const K& /*kernel*/, C&& /*conv*/){
cpp_unreachable("Should never be reached");
}
};
template<conv_type TT, typename I, typename K, typename C>
struct conv_deep_impl<TT, I, K, C, std::enable_if_t<!all_dma<I,K,C>::value>> {
static void apply(const I& /*input*/, const K& /*kernel*/, C&& /*conv*/){
cpp_unreachable("Should never be reached");
}
};
} //end of namespace detail
} //end of namespace etl
<|endoftext|>
|
<commit_before>/*********************************************************************************
*
* Inviwo - Interactive Visualization Workshop
*
* Copyright (c) 2012-2019 Inviwo Foundation
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*********************************************************************************/
#include <modules/basegl/viewmanager.h>
#include <inviwo/core/interaction/events/mouseevent.h>
#include <inviwo/core/interaction/events/gestureevent.h>
#include <inviwo/core/interaction/events/touchevent.h>
#include <inviwo/core/interaction/events/wheelevent.h>
#include <inviwo/core/interaction/events/pickingevent.h>
#include <inviwo/core/util/exception.h>
namespace inviwo {
ViewManager::ViewManager() = default;
bool ViewManager::propagatePickingEvent(PickingEvent* pe, Propagator propagator) {
auto prop = [&](Event* newEvent, size_t ind) {
if (newEvent) {
auto pressPos = pe->getPressedPosition();
auto previousPos = pe->getPreviousPosition();
auto offset = dvec2(views_[ind].pos) / dvec2(pe->getCanvasSize() - uvec2(1));
auto scale = dvec2(pe->getCanvasSize() - uvec2(1)) / dvec2(views_[ind].size - ivec2(1));
auto pressNDC = dvec3(2.0 * scale * (pressPos - offset) - 1.0, pe->getPressedDepth());
auto previousNDC =
dvec3(2.0 * scale * (previousPos - offset) - 1.0, pe->getPreviousDepth());
PickingEvent newPe(pe->getPickingAction(), static_cast<InteractionEvent*>(newEvent),
pe->getState(), pe->getPressState(), pe->getPressItem(),
pe->getHoverState(), pe->getPressItems(), pe->getGlobalPickingId(),
pe->getCurrentGlobalPickingId(), pe->getPressedGlobalPickingId(),
pe->getPreviousGlobalPickingId(), pressNDC, previousNDC);
propagator(&newPe, ind);
if (newPe.hasBeenUsed()) newEvent->markAsUsed();
for (auto p : newPe.getVisitedProcessors()) newEvent->markAsVisited(p);
}
};
auto e = pe->getEvent();
bool propagated = false;
switch (e->hash()) {
case MouseEvent::chash():
propagated = propagateMouseEvent(static_cast<MouseEvent*>(e), prop);
break;
case WheelEvent::chash():
propagated = propagateWheelEvent(static_cast<WheelEvent*>(e), prop);
break;
case GestureEvent::chash():
propagated = propagateGestureEvent(static_cast<GestureEvent*>(e), prop);
break;
case TouchEvent::chash():
propagated = propagateTouchEvent(static_cast<TouchEvent*>(e), prop);
break;
default:
propagated = false;
break;
}
if (e->hasBeenUsed()) pe->markAsUsed();
for (auto p : e->getVisitedProcessors()) pe->markAsVisited(p);
return propagated;
}
bool ViewManager::propagateMouseEvent(MouseEvent* me, Propagator propagator) {
selectedView_ = eventState_.getView(*this, me);
if (selectedView_.first && selectedView_.second < views_.size()) {
MouseEvent newEvent(*me);
newEvent.setCanvasSize(uvec2(views_[selectedView_.second].size));
auto offset = dvec2(views_[selectedView_.second].pos) / dvec2(me->canvasSize() - uvec2(1));
auto scale = dvec2(me->canvasSize() - uvec2(1)) /
dvec2(views_[selectedView_.second].size - ivec2(1));
newEvent.setPosNormalized(scale * (newEvent.posNormalized() - offset));
propagator(&newEvent, selectedView_.second);
if (newEvent.hasBeenUsed()) me->markAsUsed();
for (auto p : newEvent.getVisitedProcessors()) me->markAsVisited(p);
return true;
} else {
return false;
}
}
bool ViewManager::propagateWheelEvent(WheelEvent* we, Propagator propagator) {
selectedView_ = findView(we->pos());
if (selectedView_.first && selectedView_.second < views_.size()) {
WheelEvent newEvent(*we);
newEvent.setCanvasSize(uvec2(views_[selectedView_.second].size));
auto offset = dvec2(views_[selectedView_.second].pos) / dvec2(we->canvasSize() - uvec2(1));
auto scale = dvec2(we->canvasSize() - uvec2(1)) /
dvec2(views_[selectedView_.second].size - ivec2(1));
newEvent.setPosNormalized(scale * (newEvent.posNormalized() - offset));
propagator(&newEvent, selectedView_.second);
if (newEvent.hasBeenUsed()) we->markAsUsed();
for (auto p : newEvent.getVisitedProcessors()) we->markAsVisited(p);
return true;
} else {
return false;
}
}
bool ViewManager::propagateGestureEvent(GestureEvent* ge, Propagator propagator) {
selectedView_ = eventState_.getView(*this, ge);
if (selectedView_.first && selectedView_.second < views_.size()) {
GestureEvent newEvent(*ge);
newEvent.setCanvasSize(uvec2(views_[selectedView_.second].size));
auto offset = dvec2(views_[selectedView_.second].pos) / dvec2(ge->canvasSize() - uvec2(1));
auto scale = dvec2(ge->canvasSize() - uvec2(1)) /
dvec2(views_[selectedView_.second].size - ivec2(1));
newEvent.setScreenPosNormalized(scale * (newEvent.screenPosNormalized() - offset));
propagator(&newEvent, selectedView_.second);
if (newEvent.hasBeenUsed()) ge->markAsUsed();
for (auto p : newEvent.getVisitedProcessors()) ge->markAsVisited(p);
return true;
} else {
return false;
}
}
bool ViewManager::propagateTouchEvent(TouchEvent* te, Propagator propagator) {
auto& touchPoints = te->touchPoints();
std::unordered_map<size_t, std::vector<TouchPoint>> viewIdToTouchPoints;
std::vector<int> propagatedPointIds;
auto idToView = eventState_.getView(*this, te);
for (auto& point : touchPoints) {
auto it = idToView.find(point.id());
if (it != idToView.end()) {
viewIdToTouchPoints[it->second].push_back(point);
}
}
for (auto& item : viewIdToTouchPoints) {
const auto& viewId = item.first;
auto points = item.second;
const auto canvasSize = uvec2(views_[viewId].size);
const auto offset = dvec2(views_[viewId].pos) / dvec2(te->canvasSize() - uvec2(1));
const auto scale =
dvec2(te->canvasSize() - uvec2(1)) / dvec2(views_[viewId].size - ivec2(1));
for (auto& p : points) {
p.setCanvasSize(canvasSize);
p.setPosNormalized(scale * (p.posNormalized() - offset));
p.setPrevPosNormalized(scale * (p.prevPosNormalized() - offset));
p.setPressedPosNormalized(scale * (p.pressedPosNormalized() - offset));
}
TouchEvent newEvent(points, te->getDevice(), te->modifiers());
propagator(&newEvent, viewId);
for (auto p : newEvent.getVisitedProcessors()) te->markAsVisited(p);
for (const auto& p : points) propagatedPointIds.push_back(p.id());
}
// remove the "used" points from the event
util::erase_remove_if(
touchPoints, [&](const auto& p) { return util::contains(propagatedPointIds, p.id()); });
if (touchPoints.empty()) te->markAsUsed();
return touchPoints.empty();
}
bool ViewManager::propagateEvent(Event* event, Propagator propagator) {
switch (event->hash()) {
case PickingEvent::chash(): {
return propagatePickingEvent(static_cast<PickingEvent*>(event), propagator);
}
case MouseEvent::chash(): {
return propagateMouseEvent(static_cast<MouseEvent*>(event), propagator);
}
case WheelEvent::chash(): {
return propagateWheelEvent(static_cast<WheelEvent*>(event), propagator);
}
case GestureEvent::chash(): {
return propagateGestureEvent(static_cast<GestureEvent*>(event), propagator);
}
case TouchEvent::chash(): {
return propagateTouchEvent(static_cast<TouchEvent*>(event), propagator);
}
default:
return false;
}
}
std::pair<bool, ViewManager::ViewId> ViewManager::getSelectedView() const { return selectedView_; }
const ViewManager::ViewList& ViewManager::getViews() const { return views_; }
void ViewManager::push_back(View view) { views_.push_back(view); }
void ViewManager::erase(View view) {
util::erase_remove_if(views_,
[&](const auto& v) { return view.pos == v.pos && view.size == v.size; });
}
void ViewManager::erase(ViewId ind) {
if (ind < views_.size()) {
views_.erase(views_.begin() + ind);
}
}
void ViewManager::replace(ViewId ind, View view) {
if (ind < views_.size()) {
views_[ind] = view;
} else {
throw Exception("Out of range", IVW_CONTEXT);
}
}
ViewManager::View& ViewManager::operator[](ViewId ind) { return views_[ind]; }
size_t ViewManager::size() const { return views_.size(); }
void ViewManager::clear() { views_.clear(); }
std::pair<bool, ViewManager::ViewId> ViewManager::findView(ivec2 pos) const {
auto it = util::find_if(views_, [&](const auto& view) { return inView(view, pos); });
if (it != views_.end()) {
return {true, std::distance(views_.begin(), it)};
} else {
return {false, 0};
}
}
bool ViewManager::inView(const View& view, const ivec2& pos) {
return glm::all(glm::greaterThanEqual(pos, view.pos)) &&
glm::all(glm::lessThan(pos, view.pos + view.size));
}
std::pair<bool, ViewManager::ViewId> ViewManager::EventState::getView(ViewManager& m,
const MouseEvent* me) {
if (!pressing_ && me->buttonState() != MouseButton::None) { // Start Pressing
pressing_ = true;
pressedView_ = m.findView(static_cast<ivec2>(me->pos()));
} else if (pressing_ && me->buttonState() == MouseButton::None) { // Stop Pressing
pressing_ = false;
pressedView_ = {false, 0};
}
return pressing_ ? pressedView_ : m.findView(static_cast<ivec2>(me->pos()));
}
std::pair<bool, ViewManager::ViewId> ViewManager::EventState::getView(ViewManager& m,
const GestureEvent* ge) {
if (!pressing_ && ge->state() == GestureState::Started) { // Start Pressing
pressing_ = true;
pressedView_ =
m.findView(static_cast<ivec2>(dvec2(ge->canvasSize()) * ge->screenPosNormalized()));
} else if (pressing_ && ge->state() == GestureState::Finished) { // Stop Pressing
pressing_ = false;
auto tmp = pressedView_;
pressedView_ = {false, 0};
return tmp;
}
return pressedView_;
}
std::unordered_map<int, ViewManager::ViewId> ViewManager::EventState::getView(
ViewManager& m, const TouchEvent* te) {
std::unordered_map<int, ViewId> newTouchpointIdToViewID;
std::vector<std::pair<bool, ViewManager::ViewId>> foundViews;
for (const auto& tp : te->touchPoints()) {
switch (tp.state()) {
case TouchState::Started: {
auto res = m.findView(static_cast<ivec2>(tp.pos()));
if (res.first) {
touchpointIdToViewId_[tp.id()] = res.second;
newTouchpointIdToViewID[tp.id()] = res.second;
}
break;
}
case TouchState::Finished: {
auto it = touchpointIdToViewId_.find(tp.id());
if (it != touchpointIdToViewId_.end()) {
newTouchpointIdToViewID[tp.id()] = it->second;
}
touchpointIdToViewId_.erase(tp.id());
break;
}
case TouchState::Stationary:
case TouchState::Updated:
case TouchState::None:
default: {
auto it = touchpointIdToViewId_.find(tp.id());
if (it != touchpointIdToViewId_.end()) {
newTouchpointIdToViewID[tp.id()] = it->second;
}
break;
}
}
}
return newTouchpointIdToViewID;
}
} // namespace inviwo
<commit_msg>BaseGL: ViewManager: Only check agains points of used events to determine wether the event was used or not.<commit_after>/*********************************************************************************
*
* Inviwo - Interactive Visualization Workshop
*
* Copyright (c) 2012-2019 Inviwo Foundation
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*********************************************************************************/
#include <modules/basegl/viewmanager.h>
#include <inviwo/core/interaction/events/mouseevent.h>
#include <inviwo/core/interaction/events/gestureevent.h>
#include <inviwo/core/interaction/events/touchevent.h>
#include <inviwo/core/interaction/events/wheelevent.h>
#include <inviwo/core/interaction/events/pickingevent.h>
#include <inviwo/core/util/exception.h>
namespace inviwo {
ViewManager::ViewManager() = default;
bool ViewManager::propagatePickingEvent(PickingEvent* pe, Propagator propagator) {
auto prop = [&](Event* newEvent, size_t ind) {
if (newEvent) {
auto pressPos = pe->getPressedPosition();
auto previousPos = pe->getPreviousPosition();
auto offset = dvec2(views_[ind].pos) / dvec2(pe->getCanvasSize() - uvec2(1));
auto scale = dvec2(pe->getCanvasSize() - uvec2(1)) / dvec2(views_[ind].size - ivec2(1));
auto pressNDC = dvec3(2.0 * scale * (pressPos - offset) - 1.0, pe->getPressedDepth());
auto previousNDC =
dvec3(2.0 * scale * (previousPos - offset) - 1.0, pe->getPreviousDepth());
PickingEvent newPe(pe->getPickingAction(), static_cast<InteractionEvent*>(newEvent),
pe->getState(), pe->getPressState(), pe->getPressItem(),
pe->getHoverState(), pe->getPressItems(), pe->getGlobalPickingId(),
pe->getCurrentGlobalPickingId(), pe->getPressedGlobalPickingId(),
pe->getPreviousGlobalPickingId(), pressNDC, previousNDC);
propagator(&newPe, ind);
if (newPe.hasBeenUsed()) newEvent->markAsUsed();
for (auto p : newPe.getVisitedProcessors()) newEvent->markAsVisited(p);
}
};
auto e = pe->getEvent();
bool propagated = false;
switch (e->hash()) {
case MouseEvent::chash():
propagated = propagateMouseEvent(static_cast<MouseEvent*>(e), prop);
break;
case WheelEvent::chash():
propagated = propagateWheelEvent(static_cast<WheelEvent*>(e), prop);
break;
case GestureEvent::chash():
propagated = propagateGestureEvent(static_cast<GestureEvent*>(e), prop);
break;
case TouchEvent::chash():
propagated = propagateTouchEvent(static_cast<TouchEvent*>(e), prop);
break;
default:
propagated = false;
break;
}
if (e->hasBeenUsed()) pe->markAsUsed();
for (auto p : e->getVisitedProcessors()) pe->markAsVisited(p);
return propagated;
}
bool ViewManager::propagateMouseEvent(MouseEvent* me, Propagator propagator) {
selectedView_ = eventState_.getView(*this, me);
if (selectedView_.first && selectedView_.second < views_.size()) {
MouseEvent newEvent(*me);
newEvent.setCanvasSize(uvec2(views_[selectedView_.second].size));
auto offset = dvec2(views_[selectedView_.second].pos) / dvec2(me->canvasSize() - uvec2(1));
auto scale = dvec2(me->canvasSize() - uvec2(1)) /
dvec2(views_[selectedView_.second].size - ivec2(1));
newEvent.setPosNormalized(scale * (newEvent.posNormalized() - offset));
propagator(&newEvent, selectedView_.second);
if (newEvent.hasBeenUsed()) me->markAsUsed();
for (auto p : newEvent.getVisitedProcessors()) me->markAsVisited(p);
return true;
} else {
return false;
}
}
bool ViewManager::propagateWheelEvent(WheelEvent* we, Propagator propagator) {
selectedView_ = findView(we->pos());
if (selectedView_.first && selectedView_.second < views_.size()) {
WheelEvent newEvent(*we);
newEvent.setCanvasSize(uvec2(views_[selectedView_.second].size));
auto offset = dvec2(views_[selectedView_.second].pos) / dvec2(we->canvasSize() - uvec2(1));
auto scale = dvec2(we->canvasSize() - uvec2(1)) /
dvec2(views_[selectedView_.second].size - ivec2(1));
newEvent.setPosNormalized(scale * (newEvent.posNormalized() - offset));
propagator(&newEvent, selectedView_.second);
if (newEvent.hasBeenUsed()) we->markAsUsed();
for (auto p : newEvent.getVisitedProcessors()) we->markAsVisited(p);
return true;
} else {
return false;
}
}
bool ViewManager::propagateGestureEvent(GestureEvent* ge, Propagator propagator) {
selectedView_ = eventState_.getView(*this, ge);
if (selectedView_.first && selectedView_.second < views_.size()) {
GestureEvent newEvent(*ge);
newEvent.setCanvasSize(uvec2(views_[selectedView_.second].size));
auto offset = dvec2(views_[selectedView_.second].pos) / dvec2(ge->canvasSize() - uvec2(1));
auto scale = dvec2(ge->canvasSize() - uvec2(1)) /
dvec2(views_[selectedView_.second].size - ivec2(1));
newEvent.setScreenPosNormalized(scale * (newEvent.screenPosNormalized() - offset));
propagator(&newEvent, selectedView_.second);
if (newEvent.hasBeenUsed()) ge->markAsUsed();
for (auto p : newEvent.getVisitedProcessors()) ge->markAsVisited(p);
return true;
} else {
return false;
}
}
bool ViewManager::propagateTouchEvent(TouchEvent* te, Propagator propagator) {
auto& touchPoints = te->touchPoints();
std::unordered_map<size_t, std::vector<TouchPoint>> viewIdToTouchPoints;
std::vector<int> usedPointIds;
auto idToView = eventState_.getView(*this, te);
for (auto& point : touchPoints) {
auto it = idToView.find(point.id());
if (it != idToView.end()) {
viewIdToTouchPoints[it->second].push_back(point);
}
}
for (auto& item : viewIdToTouchPoints) {
const auto& viewId = item.first;
auto points = item.second;
const auto canvasSize = uvec2(views_[viewId].size);
const auto offset = dvec2(views_[viewId].pos) / dvec2(te->canvasSize() - uvec2(1));
const auto scale =
dvec2(te->canvasSize() - uvec2(1)) / dvec2(views_[viewId].size - ivec2(1));
for (auto& p : points) {
p.setCanvasSize(canvasSize);
p.setPosNormalized(scale * (p.posNormalized() - offset));
p.setPrevPosNormalized(scale * (p.prevPosNormalized() - offset));
p.setPressedPosNormalized(scale * (p.pressedPosNormalized() - offset));
}
TouchEvent newEvent(points, te->getDevice(), te->modifiers());
propagator(&newEvent, viewId);
for (auto p : newEvent.getVisitedProcessors()) te->markAsVisited(p);
if (newEvent.hasBeenUsed()) {
for (const auto& p : points) {
usedPointIds.push_back(p.id());
}
}
}
// remove the "used" points from the event
util::erase_remove_if(touchPoints,
[&](const auto& p) { return util::contains(usedPointIds, p.id()); });
if (touchPoints.empty()) {
te->markAsUsed();
}
return touchPoints.empty();
}
bool ViewManager::propagateEvent(Event* event, Propagator propagator) {
switch (event->hash()) {
case PickingEvent::chash(): {
return propagatePickingEvent(static_cast<PickingEvent*>(event), propagator);
}
case MouseEvent::chash(): {
return propagateMouseEvent(static_cast<MouseEvent*>(event), propagator);
}
case WheelEvent::chash(): {
return propagateWheelEvent(static_cast<WheelEvent*>(event), propagator);
}
case GestureEvent::chash(): {
return propagateGestureEvent(static_cast<GestureEvent*>(event), propagator);
}
case TouchEvent::chash(): {
return propagateTouchEvent(static_cast<TouchEvent*>(event), propagator);
}
default:
return false;
}
}
std::pair<bool, ViewManager::ViewId> ViewManager::getSelectedView() const { return selectedView_; }
const ViewManager::ViewList& ViewManager::getViews() const { return views_; }
void ViewManager::push_back(View view) { views_.push_back(view); }
void ViewManager::erase(View view) {
util::erase_remove_if(views_,
[&](const auto& v) { return view.pos == v.pos && view.size == v.size; });
}
void ViewManager::erase(ViewId ind) {
if (ind < views_.size()) {
views_.erase(views_.begin() + ind);
}
}
void ViewManager::replace(ViewId ind, View view) {
if (ind < views_.size()) {
views_[ind] = view;
} else {
throw Exception("Out of range", IVW_CONTEXT);
}
}
ViewManager::View& ViewManager::operator[](ViewId ind) { return views_[ind]; }
size_t ViewManager::size() const { return views_.size(); }
void ViewManager::clear() { views_.clear(); }
std::pair<bool, ViewManager::ViewId> ViewManager::findView(ivec2 pos) const {
auto it = util::find_if(views_, [&](const auto& view) { return inView(view, pos); });
if (it != views_.end()) {
return {true, std::distance(views_.begin(), it)};
} else {
return {false, 0};
}
}
bool ViewManager::inView(const View& view, const ivec2& pos) {
return glm::all(glm::greaterThanEqual(pos, view.pos)) &&
glm::all(glm::lessThan(pos, view.pos + view.size));
}
std::pair<bool, ViewManager::ViewId> ViewManager::EventState::getView(ViewManager& m,
const MouseEvent* me) {
if (!pressing_ && me->buttonState() != MouseButton::None) { // Start Pressing
pressing_ = true;
pressedView_ = m.findView(static_cast<ivec2>(me->pos()));
} else if (pressing_ && me->buttonState() == MouseButton::None) { // Stop Pressing
pressing_ = false;
pressedView_ = {false, 0};
}
return pressing_ ? pressedView_ : m.findView(static_cast<ivec2>(me->pos()));
}
std::pair<bool, ViewManager::ViewId> ViewManager::EventState::getView(ViewManager& m,
const GestureEvent* ge) {
if (!pressing_ && ge->state() == GestureState::Started) { // Start Pressing
pressing_ = true;
pressedView_ =
m.findView(static_cast<ivec2>(dvec2(ge->canvasSize()) * ge->screenPosNormalized()));
} else if (pressing_ && ge->state() == GestureState::Finished) { // Stop Pressing
pressing_ = false;
auto tmp = pressedView_;
pressedView_ = {false, 0};
return tmp;
}
return pressedView_;
}
std::unordered_map<int, ViewManager::ViewId> ViewManager::EventState::getView(
ViewManager& m, const TouchEvent* te) {
std::unordered_map<int, ViewId> newTouchpointIdToViewID;
std::vector<std::pair<bool, ViewManager::ViewId>> foundViews;
for (const auto& tp : te->touchPoints()) {
switch (tp.state()) {
case TouchState::Started: {
auto res = m.findView(static_cast<ivec2>(tp.pos()));
if (res.first) {
touchpointIdToViewId_[tp.id()] = res.second;
newTouchpointIdToViewID[tp.id()] = res.second;
}
break;
}
case TouchState::Finished: {
auto it = touchpointIdToViewId_.find(tp.id());
if (it != touchpointIdToViewId_.end()) {
newTouchpointIdToViewID[tp.id()] = it->second;
}
touchpointIdToViewId_.erase(tp.id());
break;
}
case TouchState::Stationary:
case TouchState::Updated:
case TouchState::None:
default: {
auto it = touchpointIdToViewId_.find(tp.id());
if (it != touchpointIdToViewId_.end()) {
newTouchpointIdToViewID[tp.id()] = it->second;
}
break;
}
}
}
return newTouchpointIdToViewID;
}
} // namespace inviwo
<|endoftext|>
|
<commit_before>//=======================================================================
// Copyright (c) 2014-2016 Baptiste Wicht
// Distributed under the terms of the MIT License.
// (See accompanying file LICENSE or copy at
// http://opensource.org/licenses/MIT)
//=======================================================================
#pragma once
//The implementations
#include "etl/impl/std/mmul.hpp"
#include "etl/impl/std/strassen_mmul.hpp"
#include "etl/impl/blas/gemm.hpp"
#include "etl/impl/vec/gemm.hpp"
#include "etl/impl/cublas/gemm.hpp"
namespace etl {
namespace detail {
/*!
* \brief Select an implementation of GEMM, not considering local context
* \param n1 The left dimension of the multiplication
* \param n2 The inner dimension of the multiplication
* \param n3 The right dimension of the multiplication
* \return The implementation to use
*/
template <typename A, typename B, typename C>
inline cpp14_constexpr gemm_impl select_default_gemm_impl(const std::size_t n1, const std::size_t n2, const std::size_t n3) {
cpp_unused(n2);
constexpr bool DMA = all_dma<A, B, C>::value;
//Note since these boolean will be known at compile time, the conditions will be a lot simplified
constexpr bool blas = is_cblas_enabled;
constexpr bool cublas = is_cublas_enabled;
if (cublas && DMA) {
if (n1 * n3 < gemm_cublas_min) {
if (blas) {
return gemm_impl::BLAS;
}
if (n1 * n3 < gemm_std_max) {
return gemm_impl::STD;
}
}
return gemm_impl::CUBLAS;
} else if (blas && DMA) {
return gemm_impl::BLAS;
}
if(vec_enabled && all_vectorizable<vector_mode, A, B, C>::value){
return gemm_impl::VEC;
}
return gemm_impl::STD;
}
/*!
* \brief Select an implementation of GEMM
* \param n1 The left dimension of the multiplication
* \param n2 The inner dimension of the multiplication
* \param n3 The right dimension of the multiplication
* \return The implementation to use
*/
template <typename A, typename B, typename C>
inline gemm_impl select_gemm_impl(const std::size_t n1, const std::size_t n2, const std::size_t n3) {
constexpr bool DMA = all_dma<A, B, C>::value;
auto def = select_default_gemm_impl<A, B, C>(n1, n2, n3);
if (local_context().gemm_selector.forced) {
auto forced = local_context().gemm_selector.impl;
switch (forced) {
//CUBLAS cannot always be used
case gemm_impl::CUBLAS:
if (!is_cublas_enabled || !DMA) { //COVERAGE_EXCLUDE_LINE
std::cerr << "Forced selection to CUBLAS gemm implementation, but not possible for this expression" << std::endl; //COVERAGE_EXCLUDE_LINE
return def; //COVERAGE_EXCLUDE_LINE
} //COVERAGE_EXCLUDE_LINE
return forced;
//BLAS cannot always be used
case gemm_impl::BLAS:
if (!is_cblas_enabled || !DMA) { //COVERAGE_EXCLUDE_LINE
std::cerr << "Forced selection to BLAS gemm implementation, but not possible for this expression" << std::endl; //COVERAGE_EXCLUDE_LINE
return def; //COVERAGE_EXCLUDE_LINE
} //COVERAGE_EXCLUDE_LINE
return forced;
//VEC cannot always be used
case gemm_impl::VEC:
if (!vec_enabled || !all_vectorizable<vector_mode, A, B, C>::value) { //COVERAGE_EXCLUDE_LINE
std::cerr << "Forced selection to VEC gemv implementation, but not possible for this expression" << std::endl; //COVERAGE_EXCLUDE_LINE
return def; //COVERAGE_EXCLUDE_LINE
} //COVERAGE_EXCLUDE_LINE
return forced;
//In other cases, simply use the forced impl
default:
return forced;
}
}
return def;
}
/*!
* \brief Select an implementation of GEMV, not considering local context
* \param n1 The left dimension of the multiplication
* \param n2 The right dimension of the multiplication
* \return The implementation to use
*/
template <typename A, typename B, typename C>
inline cpp14_constexpr gemm_impl select_default_gemv_impl(const std::size_t n1, const std::size_t n2) {
constexpr bool DMA = all_dma<A, B, C>::value;
using T = value_t<A>;
if(DMA && is_cblas_enabled){
return gemm_impl::BLAS;
}
if(all_vectorizable<vector_mode, A, B, C>::value && vec_enabled){
return gemm_impl::VEC;
}
if (is_cublas_enabled) {
if (is_complex_single_t<T>::value && n1 * n2 > 1000 * 1000) {
return gemm_impl::CUBLAS;
}
}
return gemm_impl::STD;
}
/*!
* \brief Select an implementation of GEMV
* \param n1 The left dimension of the multiplication
* \param n2 The right dimension of the multiplication
* \return The implementation to use
*/
template <typename A, typename B, typename C>
inline gemm_impl select_gemv_impl(const std::size_t n1, const std::size_t n2) {
static constexpr bool DMA = all_dma<A, B, C>::value;
if (local_context().gemm_selector.forced) {
auto forced = local_context().gemm_selector.impl;
switch (forced) {
//CUBLAS cannot always be used
case gemm_impl::CUBLAS:
if (!is_cublas_enabled || !DMA) { //COVERAGE_EXCLUDE_LINE
std::cerr << "Forced selection to CUBLAS gemv implementation, but not possible for this expression" << std::endl; //COVERAGE_EXCLUDE_LINE
return select_default_gemv_impl<A, B, C>(n1, n2); //COVERAGE_EXCLUDE_LINE
} //COVERAGE_EXCLUDE_LINE
return forced;
//BLAS cannot always be used
case gemm_impl::BLAS:
if (!is_cblas_enabled || !DMA) { //COVERAGE_EXCLUDE_LINE
std::cerr << "Forced selection to BLAS gemv implementation, but not possible for this expression" << std::endl; //COVERAGE_EXCLUDE_LINE
return select_default_gemv_impl<A, B, C>(n1, n2); //COVERAGE_EXCLUDE_LINE
} //COVERAGE_EXCLUDE_LINE
return forced;
//VEC cannot always be used
case gemm_impl::VEC:
if (!vec_enabled || !all_vectorizable<vector_mode, A, B, C>::value) { //COVERAGE_EXCLUDE_LINE
std::cerr << "Forced selection to VEC gemv implementation, but not possible for this expression" << std::endl; //COVERAGE_EXCLUDE_LINE
return select_default_gemv_impl<A, B, C>(n1, n2); //COVERAGE_EXCLUDE_LINE
} //COVERAGE_EXCLUDE_LINE
return forced;
//In other cases, simply use the forced impl
default:
return forced;
}
}
return select_default_gemv_impl<A, B, C>(n1, n2);
}
/*!
* \brief Select an implementation of GEVM, not considering local context
* \param n1 The left dimension of the multiplication
* \param n2 The right dimension of the multiplication
* \return The implementation to use
*/
template <typename A, typename B, typename C>
inline cpp14_constexpr gemm_impl select_default_gevm_impl(const std::size_t n1, const std::size_t n2) {
constexpr bool DMA = all_dma<A, B, C>::value;
using T = value_t<A>;
if(DMA && is_cblas_enabled){
return gemm_impl::BLAS;
}
if(all_vectorizable<vector_mode, A, B, C>::value && vec_enabled){
return gemm_impl::VEC;
}
if (is_cublas_enabled) {
if (is_complex_single_t<T>::value && n1 * n2 > 1000 * 1000) {
return gemm_impl::CUBLAS;
}
}
return gemm_impl::STD;
}
/*!
* \brief Select an implementation of GEVM
* \param n1 The left dimension of the multiplication
* \param n2 The right dimension of the multiplication
* \return The implementation to use
*/
template <typename A, typename B, typename C>
inline gemm_impl select_gevm_impl(const std::size_t n1, const std::size_t n2) {
static constexpr bool DMA = all_dma<A, B, C>::value;
if (local_context().gemm_selector.forced) {
auto forced = local_context().gemm_selector.impl;
switch (forced) {
//CUBLAS cannot always be used
case gemm_impl::CUBLAS:
if (!is_cublas_enabled || !DMA) { //COVERAGE_EXCLUDE_LINE
std::cerr << "Forced selection to CUBLAS gevm implementation, but not possible for this expression" << std::endl; //COVERAGE_EXCLUDE_LINE
return select_default_gevm_impl<A, B, C>(n1, n2); //COVERAGE_EXCLUDE_LINE
} //COVERAGE_EXCLUDE_LINE
return forced;
//BLAS cannot always be used
case gemm_impl::BLAS:
if (!is_cblas_enabled || !DMA) { //COVERAGE_EXCLUDE_LINE
std::cerr << "Forced selection to BLAS gevm implementation, but not possible for this expression" << std::endl; //COVERAGE_EXCLUDE_LINE
return select_default_gevm_impl<A, B, C>(n1, n2); //COVERAGE_EXCLUDE_LINE
} //COVERAGE_EXCLUDE_LINE
return forced;
//VEC cannot always be used
case gemm_impl::VEC:
if (!vec_enabled || !all_vectorizable<vector_mode, A, B, C>::value) { //COVERAGE_EXCLUDE_LINE
std::cerr << "Forced selection to VEC gemv implementation, but not possible for this expression" << std::endl; //COVERAGE_EXCLUDE_LINE
return select_default_gemv_impl<A, B, C>(n1, n2); //COVERAGE_EXCLUDE_LINE
} //COVERAGE_EXCLUDE_LINE
return forced;
//In other cases, simply use the forced impl
default:
return forced;
}
}
return select_default_gevm_impl<A, B, C>(n1, n2);
}
/*!
* \brief Functor for matrix-matrix multiplication
*/
struct mm_mul_impl {
/*!
* \brief Apply the function C = A * B
* \param a The lhs of the multiplication
* \param b The rhs of the multiplication
* \param c The target of the multiplication
*/
template <typename A, typename B, typename C>
static void apply(A&& a, B&& b, C&& c) {
gemm_impl impl = select_gemm_impl<A, B, C>(etl::dim<0>(a), etl::dim<1>(a), etl::dim<1>(c));
if (impl == gemm_impl::STD) {
etl::impl::standard::mm_mul(a, b, c);
} else if (impl == gemm_impl::VEC) {
etl::impl::vec::gemm(a, b, c);
} else if (impl == gemm_impl::BLAS) {
etl::impl::blas::gemm(a, b, c);
} else if (impl == gemm_impl::CUBLAS) {
etl::impl::cublas::gemm(a, b, c);
}
}
};
/*!
* \brief Functor for vector-matrix multiplication
*/
struct vm_mul_impl {
/*!
* \brief Apply the function C = A * B
* \param a The lhs of the multiplication
* \param b The rhs of the multiplication
* \param c The target of the multiplication
*/
template <typename A, typename B, typename C>
static void apply(A&& a, B&& b, C&& c) {
gemm_impl impl = select_gevm_impl<A, B, C>(etl::dim<0>(b), etl::dim<1>(b));
if (impl == gemm_impl::STD) {
etl::impl::standard::vm_mul(a, b, c);
} else if (impl == gemm_impl::BLAS) {
etl::impl::blas::gevm(a, b, c);
} else if (impl == gemm_impl::VEC) {
etl::impl::vec::gevm(a, b, c);
} else if (impl == gemm_impl::CUBLAS) {
etl::impl::cublas::gevm(a, b, c);
}
}
};
/*!
* \brief Functor for matrix-vector multiplication
*/
struct mv_mul_impl {
/*!
* \brief Apply the function C = A * B
* \param a The lhs of the multiplication
* \param b The rhs of the multiplication
* \param c The target of the multiplication
*/
template <typename A, typename B, typename C>
static void apply(A&& a, B&& b, C&& c) {
gemm_impl impl = select_gemv_impl<A, B, C>(etl::dim<0>(a), etl::dim<1>(a));
if (impl == gemm_impl::STD) {
etl::impl::standard::mv_mul(a, b, c);
} else if (impl == gemm_impl::BLAS) {
etl::impl::blas::gemv(a, b, c);
} else if (impl == gemm_impl::VEC) {
etl::impl::vec::gemv(a, b, c);
} else if (impl == gemm_impl::CUBLAS) {
etl::impl::cublas::gemv(a, b, c);
}
}
};
/*!
* \brief Functor for Strassen matrix-matrix multiplication
*/
struct strassen_mm_mul_impl {
/*!
* \brief Apply the function C = A * B
* \param a The lhs of the multiplication
* \param b The rhs of the multiplication
* \param c The target of the multiplication
*/
template <typename A, typename B, typename C>
static void apply(A&& a, B&& b, C&& c) {
etl::impl::standard::strassen_mm_mul(a, b, c);
}
};
} //end of namespace detail
} //end of namespace etl
<commit_msg>Cleanup<commit_after>//=======================================================================
// Copyright (c) 2014-2016 Baptiste Wicht
// Distributed under the terms of the MIT License.
// (See accompanying file LICENSE or copy at
// http://opensource.org/licenses/MIT)
//=======================================================================
#pragma once
//The implementations
#include "etl/impl/std/mmul.hpp"
#include "etl/impl/std/strassen_mmul.hpp"
#include "etl/impl/blas/gemm.hpp"
#include "etl/impl/vec/gemm.hpp"
#include "etl/impl/cublas/gemm.hpp"
namespace etl {
namespace detail {
/*!
* \brief Select an implementation of GEMM, not considering local context
* \param n1 The left dimension of the multiplication
* \param n2 The inner dimension of the multiplication
* \param n3 The right dimension of the multiplication
* \return The implementation to use
*/
template <typename A, typename B, typename C>
inline cpp14_constexpr gemm_impl select_default_gemm_impl(const std::size_t n1, const std::size_t n2, const std::size_t n3) {
cpp_unused(n2);
constexpr bool DMA = all_dma<A, B, C>::value;
//Note since these boolean will be known at compile time, the conditions will be a lot simplified
constexpr bool blas = is_cblas_enabled;
constexpr bool cublas = is_cublas_enabled;
if (cublas && DMA) {
if (n1 * n3 < gemm_cublas_min) {
if (blas) {
return gemm_impl::BLAS;
}
if (n1 * n3 < gemm_std_max) {
return gemm_impl::STD;
}
}
return gemm_impl::CUBLAS;
} else if (blas && DMA) {
return gemm_impl::BLAS;
}
if(vec_enabled && all_vectorizable<vector_mode, A, B, C>::value){
return gemm_impl::VEC;
}
return gemm_impl::STD;
}
/*!
* \brief Select an implementation of GEMM
* \param n1 The left dimension of the multiplication
* \param n2 The inner dimension of the multiplication
* \param n3 The right dimension of the multiplication
* \return The implementation to use
*/
template <typename A, typename B, typename C>
inline gemm_impl select_gemm_impl(const std::size_t n1, const std::size_t n2, const std::size_t n3) {
constexpr bool DMA = all_dma<A, B, C>::value;
auto def = select_default_gemm_impl<A, B, C>(n1, n2, n3);
if (local_context().gemm_selector.forced) {
auto forced = local_context().gemm_selector.impl;
switch (forced) {
//CUBLAS cannot always be used
case gemm_impl::CUBLAS:
if (!is_cublas_enabled || !DMA) { //COVERAGE_EXCLUDE_LINE
std::cerr << "Forced selection to CUBLAS gemm implementation, but not possible for this expression" << std::endl; //COVERAGE_EXCLUDE_LINE
return def; //COVERAGE_EXCLUDE_LINE
} //COVERAGE_EXCLUDE_LINE
return forced;
//BLAS cannot always be used
case gemm_impl::BLAS:
if (!is_cblas_enabled || !DMA) { //COVERAGE_EXCLUDE_LINE
std::cerr << "Forced selection to BLAS gemm implementation, but not possible for this expression" << std::endl; //COVERAGE_EXCLUDE_LINE
return def; //COVERAGE_EXCLUDE_LINE
} //COVERAGE_EXCLUDE_LINE
return forced;
//VEC cannot always be used
case gemm_impl::VEC:
if (!vec_enabled || !all_vectorizable<vector_mode, A, B, C>::value) { //COVERAGE_EXCLUDE_LINE
std::cerr << "Forced selection to VEC gemv implementation, but not possible for this expression" << std::endl; //COVERAGE_EXCLUDE_LINE
return def; //COVERAGE_EXCLUDE_LINE
} //COVERAGE_EXCLUDE_LINE
return forced;
//In other cases, simply use the forced impl
default:
return forced;
}
}
return def;
}
/*!
* \brief Select an implementation of GEMV, not considering local context
* \param n1 The left dimension of the multiplication
* \param n2 The right dimension of the multiplication
* \return The implementation to use
*/
template <typename A, typename B, typename C>
inline cpp14_constexpr gemm_impl select_default_gemv_impl(const std::size_t n1, const std::size_t n2) {
constexpr bool DMA = all_dma<A, B, C>::value;
using T = value_t<A>;
if(DMA && is_cblas_enabled){
return gemm_impl::BLAS;
}
if(all_vectorizable<vector_mode, A, B, C>::value && vec_enabled){
return gemm_impl::VEC;
}
if (is_cublas_enabled && is_complex_single_t<T>::value && n1 * n2 > 1000 * 1000) {
return gemm_impl::CUBLAS;
}
return gemm_impl::STD;
}
/*!
* \brief Select an implementation of GEMV
* \param n1 The left dimension of the multiplication
* \param n2 The right dimension of the multiplication
* \return The implementation to use
*/
template <typename A, typename B, typename C>
inline gemm_impl select_gemv_impl(const std::size_t n1, const std::size_t n2) {
static constexpr bool DMA = all_dma<A, B, C>::value;
if (local_context().gemm_selector.forced) {
auto forced = local_context().gemm_selector.impl;
switch (forced) {
//CUBLAS cannot always be used
case gemm_impl::CUBLAS:
if (!is_cublas_enabled || !DMA) { //COVERAGE_EXCLUDE_LINE
std::cerr << "Forced selection to CUBLAS gemv implementation, but not possible for this expression" << std::endl; //COVERAGE_EXCLUDE_LINE
return select_default_gemv_impl<A, B, C>(n1, n2); //COVERAGE_EXCLUDE_LINE
} //COVERAGE_EXCLUDE_LINE
return forced;
//BLAS cannot always be used
case gemm_impl::BLAS:
if (!is_cblas_enabled || !DMA) { //COVERAGE_EXCLUDE_LINE
std::cerr << "Forced selection to BLAS gemv implementation, but not possible for this expression" << std::endl; //COVERAGE_EXCLUDE_LINE
return select_default_gemv_impl<A, B, C>(n1, n2); //COVERAGE_EXCLUDE_LINE
} //COVERAGE_EXCLUDE_LINE
return forced;
//VEC cannot always be used
case gemm_impl::VEC:
if (!vec_enabled || !all_vectorizable<vector_mode, A, B, C>::value) { //COVERAGE_EXCLUDE_LINE
std::cerr << "Forced selection to VEC gemv implementation, but not possible for this expression" << std::endl; //COVERAGE_EXCLUDE_LINE
return select_default_gemv_impl<A, B, C>(n1, n2); //COVERAGE_EXCLUDE_LINE
} //COVERAGE_EXCLUDE_LINE
return forced;
//In other cases, simply use the forced impl
default:
return forced;
}
}
return select_default_gemv_impl<A, B, C>(n1, n2);
}
/*!
* \brief Select an implementation of GEVM, not considering local context
* \param n1 The left dimension of the multiplication
* \param n2 The right dimension of the multiplication
* \return The implementation to use
*/
template <typename A, typename B, typename C>
inline cpp14_constexpr gemm_impl select_default_gevm_impl(const std::size_t n1, const std::size_t n2) {
constexpr bool DMA = all_dma<A, B, C>::value;
using T = value_t<A>;
if(DMA && is_cblas_enabled){
return gemm_impl::BLAS;
}
if(all_vectorizable<vector_mode, A, B, C>::value && vec_enabled){
return gemm_impl::VEC;
}
if (is_cublas_enabled && is_complex_single_t<T>::value && n1 * n2 > 1000 * 1000) {
return gemm_impl::CUBLAS;
}
return gemm_impl::STD;
}
/*!
* \brief Select an implementation of GEVM
* \param n1 The left dimension of the multiplication
* \param n2 The right dimension of the multiplication
* \return The implementation to use
*/
template <typename A, typename B, typename C>
inline gemm_impl select_gevm_impl(const std::size_t n1, const std::size_t n2) {
static constexpr bool DMA = all_dma<A, B, C>::value;
if (local_context().gemm_selector.forced) {
auto forced = local_context().gemm_selector.impl;
switch (forced) {
//CUBLAS cannot always be used
case gemm_impl::CUBLAS:
if (!is_cublas_enabled || !DMA) { //COVERAGE_EXCLUDE_LINE
std::cerr << "Forced selection to CUBLAS gevm implementation, but not possible for this expression" << std::endl; //COVERAGE_EXCLUDE_LINE
return select_default_gevm_impl<A, B, C>(n1, n2); //COVERAGE_EXCLUDE_LINE
} //COVERAGE_EXCLUDE_LINE
return forced;
//BLAS cannot always be used
case gemm_impl::BLAS:
if (!is_cblas_enabled || !DMA) { //COVERAGE_EXCLUDE_LINE
std::cerr << "Forced selection to BLAS gevm implementation, but not possible for this expression" << std::endl; //COVERAGE_EXCLUDE_LINE
return select_default_gevm_impl<A, B, C>(n1, n2); //COVERAGE_EXCLUDE_LINE
} //COVERAGE_EXCLUDE_LINE
return forced;
//VEC cannot always be used
case gemm_impl::VEC:
if (!vec_enabled || !all_vectorizable<vector_mode, A, B, C>::value) { //COVERAGE_EXCLUDE_LINE
std::cerr << "Forced selection to VEC gemv implementation, but not possible for this expression" << std::endl; //COVERAGE_EXCLUDE_LINE
return select_default_gemv_impl<A, B, C>(n1, n2); //COVERAGE_EXCLUDE_LINE
} //COVERAGE_EXCLUDE_LINE
return forced;
//In other cases, simply use the forced impl
default:
return forced;
}
}
return select_default_gevm_impl<A, B, C>(n1, n2);
}
/*!
* \brief Functor for matrix-matrix multiplication
*/
struct mm_mul_impl {
/*!
* \brief Apply the function C = A * B
* \param a The lhs of the multiplication
* \param b The rhs of the multiplication
* \param c The target of the multiplication
*/
template <typename A, typename B, typename C>
static void apply(A&& a, B&& b, C&& c) {
gemm_impl impl = select_gemm_impl<A, B, C>(etl::dim<0>(a), etl::dim<1>(a), etl::dim<1>(c));
if (impl == gemm_impl::STD) {
etl::impl::standard::mm_mul(a, b, c);
} else if (impl == gemm_impl::VEC) {
etl::impl::vec::gemm(a, b, c);
} else if (impl == gemm_impl::BLAS) {
etl::impl::blas::gemm(a, b, c);
} else if (impl == gemm_impl::CUBLAS) {
etl::impl::cublas::gemm(a, b, c);
}
}
};
/*!
* \brief Functor for vector-matrix multiplication
*/
struct vm_mul_impl {
/*!
* \brief Apply the function C = A * B
* \param a The lhs of the multiplication
* \param b The rhs of the multiplication
* \param c The target of the multiplication
*/
template <typename A, typename B, typename C>
static void apply(A&& a, B&& b, C&& c) {
gemm_impl impl = select_gevm_impl<A, B, C>(etl::dim<0>(b), etl::dim<1>(b));
if (impl == gemm_impl::STD) {
etl::impl::standard::vm_mul(a, b, c);
} else if (impl == gemm_impl::BLAS) {
etl::impl::blas::gevm(a, b, c);
} else if (impl == gemm_impl::VEC) {
etl::impl::vec::gevm(a, b, c);
} else if (impl == gemm_impl::CUBLAS) {
etl::impl::cublas::gevm(a, b, c);
}
}
};
/*!
* \brief Functor for matrix-vector multiplication
*/
struct mv_mul_impl {
/*!
* \brief Apply the function C = A * B
* \param a The lhs of the multiplication
* \param b The rhs of the multiplication
* \param c The target of the multiplication
*/
template <typename A, typename B, typename C>
static void apply(A&& a, B&& b, C&& c) {
gemm_impl impl = select_gemv_impl<A, B, C>(etl::dim<0>(a), etl::dim<1>(a));
if (impl == gemm_impl::STD) {
etl::impl::standard::mv_mul(a, b, c);
} else if (impl == gemm_impl::BLAS) {
etl::impl::blas::gemv(a, b, c);
} else if (impl == gemm_impl::VEC) {
etl::impl::vec::gemv(a, b, c);
} else if (impl == gemm_impl::CUBLAS) {
etl::impl::cublas::gemv(a, b, c);
}
}
};
/*!
* \brief Functor for Strassen matrix-matrix multiplication
*/
struct strassen_mm_mul_impl {
/*!
* \brief Apply the function C = A * B
* \param a The lhs of the multiplication
* \param b The rhs of the multiplication
* \param c The target of the multiplication
*/
template <typename A, typename B, typename C>
static void apply(A&& a, B&& b, C&& c) {
etl::impl::standard::strassen_mm_mul(a, b, c);
}
};
} //end of namespace detail
} //end of namespace etl
<|endoftext|>
|
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: register.cxx,v $
*
* $Revision: 1.5 $
*
* last change: $Author: vg $ $Date: 2006-09-25 13:06:05 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#ifndef _REGISTER_HXX_
#include "register.hxx"
#endif
#ifndef _REGISTRYEXCEPTION_HXX_
#include "registryexception.hxx"
#endif
#ifndef _REGISTRATIONCONTEXTINFORMATION_HXX_
#include "registrationcontextinformation.hxx"
#endif
#ifndef _USERREGISTRAR_HXX_
#include "userregistrar.hxx"
#endif
#ifndef _WINDOWSREGISTRY_HXX_
#include "windowsregistry.hxx"
#endif
#ifndef _STRINGCONVERTER_HXX_
#include "stringconverter.hxx"
#endif
#ifndef INCLUDED_MSIHELPER_HXX
#include "msihelper.hxx"
#endif
#pragma warning(push, 1) /* disable warnings within system headers */
#pragma warning(disable: 4917)
#include <shlobj.h>
#pragma warning(pop)
#include <assert.h>
#pragma warning(disable: 4350)
typedef std::auto_ptr<Registrar> RegistrarPtr;
namespace /* private */
{
RegistrarPtr CreateRegistrar(bool InstallForAllUser, const RegistrationContextInformation& RegCtx)
{
RegistrarPtr RegPtr;
if (InstallForAllUser)
RegPtr = RegistrarPtr(new Registrar(RegCtx));
else
RegPtr = RegistrarPtr(new UserRegistrar(RegCtx));
return RegPtr;
}
} // namespace private
bool query_preselect_registration_for_ms_application(MSIHANDLE handle, int Register)
{
bool preselect = false;
try
{
RegistrationContextInformation RegContext(handle, GetOfficeExecutablePath(handle));
RegistrarPtr CurrentRegistrar = CreateRegistrar(IsAllUserInstallation(handle), RegContext);
if (Register & MSWORD)
preselect = CurrentRegistrar->QueryPreselectMsWordRegistration();
else if (Register & MSEXCEL)
preselect = CurrentRegistrar->QueryPreselectMsExcelRegistration();
else if (Register & MSPOWERPOINT)
preselect = CurrentRegistrar->QueryPreselectMsPowerPointRegistration();
}
catch(RegistryException&)
{
assert(false);
}
return preselect;
}
//-----------------------------------------
// registers StarOffice for MS document
// types and as default HTML editor if
// specified
//-----------------------------------------
void Register4MsDoc(MSIHANDLE handle, int Register)
{
try
{
RegistrationContextInformation RegContext(handle, GetOfficeExecutablePath(handle));
RegistrarPtr CurrentRegistrar = CreateRegistrar(IsAllUserInstallation(handle), RegContext);
if ((Register & MSWORD))
CurrentRegistrar->RegisterForMsWord();
if ((Register & MSEXCEL))
CurrentRegistrar->RegisterForMsExcel();
if ((Register & MSPOWERPOINT))
CurrentRegistrar->RegisterForMsPowerPoint();
if ((Register & HTML_EDITOR))
CurrentRegistrar->RegisterAsHtmlEditorForInternetExplorer();
if ((Register & DEFAULT_SHELL_HTML_EDITOR))
{
CurrentRegistrar->RegisterAsDefaultHtmlEditorForInternetExplorer();
CurrentRegistrar->RegisterAsDefaultShellHtmlEditor();
}
}
catch(RegistryException&)
{
assert(false);
}
if (Register)
SHChangeNotify(SHCNE_ASSOCCHANGED, SHCNF_IDLIST, 0, 0);
}
void Unregister4MsDoc(MSIHANDLE handle, int Unregister)
{
try
{
RegistrationContextInformation RegContext(handle, GetOfficeExecutablePath(handle));
RegistrarPtr CurrentRegistrar = CreateRegistrar(IsAllUserInstallation(handle), RegContext);
if ((Unregister & MSWORD) && CurrentRegistrar->IsRegisteredFor(MSWORD))
CurrentRegistrar->UnregisterForMsWord();
if ((Unregister & HTML_EDITOR) && CurrentRegistrar->IsRegisteredFor(HTML_EDITOR))
CurrentRegistrar->UnregisterAsHtmlEditorForInternetExplorer();
if ((Unregister & MSEXCEL) && CurrentRegistrar->IsRegisteredFor(MSEXCEL))
CurrentRegistrar->UnregisterForMsExcel();
if ((Unregister & MSPOWERPOINT) && CurrentRegistrar->IsRegisteredFor(MSPOWERPOINT))
CurrentRegistrar->UnregisterForMsPowerPoint();
if ((Unregister & DEFAULT_HTML_EDITOR_FOR_IE) && CurrentRegistrar->IsRegisteredFor(DEFAULT_HTML_EDITOR_FOR_IE))
CurrentRegistrar->UnregisterAsDefaultHtmlEditorForInternetExplorer();
if ((Unregister & DEFAULT_SHELL_HTML_EDITOR) && CurrentRegistrar->IsRegisteredFor(DEFAULT_SHELL_HTML_EDITOR))
CurrentRegistrar->UnregisterAsDefaultShellHtmlEditor();
}
catch(RegistryException&)
{
assert(false);
}
if (Unregister)
SHChangeNotify(SHCNE_ASSOCCHANGED, SHCNF_IDLIST, 0, 0);
}
//-----------------------------------------
// restores the entries for the selected
// registry entries
// Algorithm:
//
// 1.
// Target key exist (e.g. '.doc')
// Default value == soffice.?
// Backup key != empty
// Action: Replace Default value with backup
// key
//
// 2.
// Target key exist
// Default value == soffice.?
// Backup key == empty
// Action: delete default value
//
// 3.
// Target key exist
// Default value != soffice.?
// Action: nop
//
// 4.
// Target key does not exist
// Action: nop
//-----------------------------------------
void Unregister4MsDocAll(MSIHANDLE handle)
{
try
{
RegistrationContextInformation RegContext(handle, GetOfficeExecutablePath(handle));
RegistrarPtr CurrentRegistrar = CreateRegistrar(IsAllUserInstallation(handle), RegContext);
CurrentRegistrar->UnregisterAllAndCleanUpRegistry();
}
catch(RegistryException&)
{
assert(false);
}
}
//-----------------------------------------
// restores lost settings formerly made
// with Register4MsDoc
//-----------------------------------------
void RepairRegister4MsDocSettings(MSIHANDLE handle)
{
try
{
RegistrationContextInformation RegContext(handle, GetOfficeExecutablePath(handle));
RegistrarPtr CurrentRegistrar = CreateRegistrar(IsAllUserInstallation(handle), RegContext);
CurrentRegistrar->RepairRegistrationState();
}
catch(RegistryException&)
{
assert(false);
}
}
bool IsRegisteredFor(MSIHANDLE handle, int State)
{
bool Registered = false;
try
{
RegistrationContextInformation RegContext(handle, GetOfficeExecutablePath(handle));
RegistrarPtr CurrentRegistrar = CreateRegistrar(IsAllUserInstallation(handle), RegContext);
Registered = CurrentRegistrar->IsRegisteredFor(State);
}
catch(RegistryException&)
{
assert(false);
}
return Registered;
}
#define SO60_UNINSTALL_KEY L"Software\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\StarOffice 6.0"
#define SO_BACKUP_KEY L"soffice6.bak"
#define REGMSDOCSTATE L"Reg4MsDocState"
#define SOFTWARE_CLASSES L"Software\\Classes"
int FixReturnRegistrationState(MSIHANDLE handle)
{
int registration_state = 0;
try
{
WindowsRegistry registry;
RegistryValue rv_regmsdocstate = RegistryValue(
new RegistryValueImpl(REGMSDOCSTATE, 0));
RegistryKey so_bak_key;
if (IsAllUserInstallation(handle))
{
RegistryKey hkcr_key = registry.GetClassesRootKey();
if (hkcr_key->HasSubKey(SO_BACKUP_KEY))
so_bak_key = hkcr_key->OpenSubKey(SO_BACKUP_KEY);
else
so_bak_key = hkcr_key->CreateSubKey(SO_BACKUP_KEY);
if (!so_bak_key->HasValue(REGMSDOCSTATE))
{
// set a defined value
so_bak_key->SetValue(rv_regmsdocstate);
RegistryKey hklm_key = registry.GetLocalMachineKey();
if (hklm_key->HasSubKey(SO60_UNINSTALL_KEY))
{
RegistryKey so_uninst_key =
hklm_key->OpenSubKey(SO60_UNINSTALL_KEY);
if (so_uninst_key->HasValue(REGMSDOCSTATE))
so_bak_key->CopyValue(so_uninst_key, REGMSDOCSTATE);
}
}
}
else
{
RegistryKey hkcu_classes_key =
registry.GetCurrentUserKey()->OpenSubKey(SOFTWARE_CLASSES);
so_bak_key = hkcu_classes_key->CreateSubKey(SO_BACKUP_KEY);
if (!so_bak_key->HasValue(REGMSDOCSTATE))
{
// set a defined value
so_bak_key->SetValue(rv_regmsdocstate);
RegistryKey hklm_sftw_classes =
registry.GetLocalMachineKey()->OpenSubKey(SOFTWARE_CLASSES, false);
RegistryKey so_bak_key_old;
if (hklm_sftw_classes->HasSubKey(SO_BACKUP_KEY))
{
so_bak_key_old = hklm_sftw_classes->OpenSubKey(SO_BACKUP_KEY, false);
if (so_bak_key_old->HasValue(REGMSDOCSTATE))
so_bak_key->CopyValue(so_bak_key_old, REGMSDOCSTATE);
}
else // try the uninstall key
{
RegistryKey hklm_key = registry.GetLocalMachineKey();
if (hklm_key->HasSubKey(SO60_UNINSTALL_KEY))
{
RegistryKey so_uninst_key =
hklm_key->OpenSubKey(SO60_UNINSTALL_KEY);
if (so_uninst_key->HasValue(REGMSDOCSTATE))
so_bak_key->CopyValue(so_uninst_key, REGMSDOCSTATE);
}
}
}
}
rv_regmsdocstate = so_bak_key->GetValue(REGMSDOCSTATE);
registration_state = rv_regmsdocstate->GetDataAsInt();
}
catch(RegistryException&)
{
registration_state = 0;
}
return registration_state;
}
<commit_msg>INTEGRATION: CWS mingwport06 (1.5.90); FILE MERGED 2007/08/24 13:12:57 vg 1.5.90.1: #i75499# pragma is for MSVC<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: register.cxx,v $
*
* $Revision: 1.6 $
*
* last change: $Author: kz $ $Date: 2007-09-06 13:29:29 $
*
* 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 _REGISTER_HXX_
#include "register.hxx"
#endif
#ifndef _REGISTRYEXCEPTION_HXX_
#include "registryexception.hxx"
#endif
#ifndef _REGISTRATIONCONTEXTINFORMATION_HXX_
#include "registrationcontextinformation.hxx"
#endif
#ifndef _USERREGISTRAR_HXX_
#include "userregistrar.hxx"
#endif
#ifndef _WINDOWSREGISTRY_HXX_
#include "windowsregistry.hxx"
#endif
#ifndef _STRINGCONVERTER_HXX_
#include "stringconverter.hxx"
#endif
#ifndef INCLUDED_MSIHELPER_HXX
#include "msihelper.hxx"
#endif
#ifdef _MSC_VER
#pragma warning(push, 1) /* disable warnings within system headers */
#pragma warning(disable: 4917)
#endif
#include <shlobj.h>
#ifdef _MSC_VER
#pragma warning(pop)
#endif
#include <assert.h>
#ifdef _MSC_VER
#pragma warning(disable: 4350)
#endif
typedef std::auto_ptr<Registrar> RegistrarPtr;
namespace /* private */
{
RegistrarPtr CreateRegistrar(bool InstallForAllUser, const RegistrationContextInformation& RegCtx)
{
RegistrarPtr RegPtr;
if (InstallForAllUser)
RegPtr = RegistrarPtr(new Registrar(RegCtx));
else
RegPtr = RegistrarPtr(new UserRegistrar(RegCtx));
return RegPtr;
}
} // namespace private
bool query_preselect_registration_for_ms_application(MSIHANDLE handle, int Register)
{
bool preselect = false;
try
{
RegistrationContextInformation RegContext(handle, GetOfficeExecutablePath(handle));
RegistrarPtr CurrentRegistrar = CreateRegistrar(IsAllUserInstallation(handle), RegContext);
if (Register & MSWORD)
preselect = CurrentRegistrar->QueryPreselectMsWordRegistration();
else if (Register & MSEXCEL)
preselect = CurrentRegistrar->QueryPreselectMsExcelRegistration();
else if (Register & MSPOWERPOINT)
preselect = CurrentRegistrar->QueryPreselectMsPowerPointRegistration();
}
catch(RegistryException&)
{
assert(false);
}
return preselect;
}
//-----------------------------------------
// registers StarOffice for MS document
// types and as default HTML editor if
// specified
//-----------------------------------------
void Register4MsDoc(MSIHANDLE handle, int Register)
{
try
{
RegistrationContextInformation RegContext(handle, GetOfficeExecutablePath(handle));
RegistrarPtr CurrentRegistrar = CreateRegistrar(IsAllUserInstallation(handle), RegContext);
if ((Register & MSWORD))
CurrentRegistrar->RegisterForMsWord();
if ((Register & MSEXCEL))
CurrentRegistrar->RegisterForMsExcel();
if ((Register & MSPOWERPOINT))
CurrentRegistrar->RegisterForMsPowerPoint();
if ((Register & HTML_EDITOR))
CurrentRegistrar->RegisterAsHtmlEditorForInternetExplorer();
if ((Register & DEFAULT_SHELL_HTML_EDITOR))
{
CurrentRegistrar->RegisterAsDefaultHtmlEditorForInternetExplorer();
CurrentRegistrar->RegisterAsDefaultShellHtmlEditor();
}
}
catch(RegistryException&)
{
assert(false);
}
if (Register)
SHChangeNotify(SHCNE_ASSOCCHANGED, SHCNF_IDLIST, 0, 0);
}
void Unregister4MsDoc(MSIHANDLE handle, int Unregister)
{
try
{
RegistrationContextInformation RegContext(handle, GetOfficeExecutablePath(handle));
RegistrarPtr CurrentRegistrar = CreateRegistrar(IsAllUserInstallation(handle), RegContext);
if ((Unregister & MSWORD) && CurrentRegistrar->IsRegisteredFor(MSWORD))
CurrentRegistrar->UnregisterForMsWord();
if ((Unregister & HTML_EDITOR) && CurrentRegistrar->IsRegisteredFor(HTML_EDITOR))
CurrentRegistrar->UnregisterAsHtmlEditorForInternetExplorer();
if ((Unregister & MSEXCEL) && CurrentRegistrar->IsRegisteredFor(MSEXCEL))
CurrentRegistrar->UnregisterForMsExcel();
if ((Unregister & MSPOWERPOINT) && CurrentRegistrar->IsRegisteredFor(MSPOWERPOINT))
CurrentRegistrar->UnregisterForMsPowerPoint();
if ((Unregister & DEFAULT_HTML_EDITOR_FOR_IE) && CurrentRegistrar->IsRegisteredFor(DEFAULT_HTML_EDITOR_FOR_IE))
CurrentRegistrar->UnregisterAsDefaultHtmlEditorForInternetExplorer();
if ((Unregister & DEFAULT_SHELL_HTML_EDITOR) && CurrentRegistrar->IsRegisteredFor(DEFAULT_SHELL_HTML_EDITOR))
CurrentRegistrar->UnregisterAsDefaultShellHtmlEditor();
}
catch(RegistryException&)
{
assert(false);
}
if (Unregister)
SHChangeNotify(SHCNE_ASSOCCHANGED, SHCNF_IDLIST, 0, 0);
}
//-----------------------------------------
// restores the entries for the selected
// registry entries
// Algorithm:
//
// 1.
// Target key exist (e.g. '.doc')
// Default value == soffice.?
// Backup key != empty
// Action: Replace Default value with backup
// key
//
// 2.
// Target key exist
// Default value == soffice.?
// Backup key == empty
// Action: delete default value
//
// 3.
// Target key exist
// Default value != soffice.?
// Action: nop
//
// 4.
// Target key does not exist
// Action: nop
//-----------------------------------------
void Unregister4MsDocAll(MSIHANDLE handle)
{
try
{
RegistrationContextInformation RegContext(handle, GetOfficeExecutablePath(handle));
RegistrarPtr CurrentRegistrar = CreateRegistrar(IsAllUserInstallation(handle), RegContext);
CurrentRegistrar->UnregisterAllAndCleanUpRegistry();
}
catch(RegistryException&)
{
assert(false);
}
}
//-----------------------------------------
// restores lost settings formerly made
// with Register4MsDoc
//-----------------------------------------
void RepairRegister4MsDocSettings(MSIHANDLE handle)
{
try
{
RegistrationContextInformation RegContext(handle, GetOfficeExecutablePath(handle));
RegistrarPtr CurrentRegistrar = CreateRegistrar(IsAllUserInstallation(handle), RegContext);
CurrentRegistrar->RepairRegistrationState();
}
catch(RegistryException&)
{
assert(false);
}
}
bool IsRegisteredFor(MSIHANDLE handle, int State)
{
bool Registered = false;
try
{
RegistrationContextInformation RegContext(handle, GetOfficeExecutablePath(handle));
RegistrarPtr CurrentRegistrar = CreateRegistrar(IsAllUserInstallation(handle), RegContext);
Registered = CurrentRegistrar->IsRegisteredFor(State);
}
catch(RegistryException&)
{
assert(false);
}
return Registered;
}
#define SO60_UNINSTALL_KEY L"Software\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\StarOffice 6.0"
#define SO_BACKUP_KEY L"soffice6.bak"
#define REGMSDOCSTATE L"Reg4MsDocState"
#define SOFTWARE_CLASSES L"Software\\Classes"
int FixReturnRegistrationState(MSIHANDLE handle)
{
int registration_state = 0;
try
{
WindowsRegistry registry;
RegistryValue rv_regmsdocstate = RegistryValue(
new RegistryValueImpl(REGMSDOCSTATE, 0));
RegistryKey so_bak_key;
if (IsAllUserInstallation(handle))
{
RegistryKey hkcr_key = registry.GetClassesRootKey();
if (hkcr_key->HasSubKey(SO_BACKUP_KEY))
so_bak_key = hkcr_key->OpenSubKey(SO_BACKUP_KEY);
else
so_bak_key = hkcr_key->CreateSubKey(SO_BACKUP_KEY);
if (!so_bak_key->HasValue(REGMSDOCSTATE))
{
// set a defined value
so_bak_key->SetValue(rv_regmsdocstate);
RegistryKey hklm_key = registry.GetLocalMachineKey();
if (hklm_key->HasSubKey(SO60_UNINSTALL_KEY))
{
RegistryKey so_uninst_key =
hklm_key->OpenSubKey(SO60_UNINSTALL_KEY);
if (so_uninst_key->HasValue(REGMSDOCSTATE))
so_bak_key->CopyValue(so_uninst_key, REGMSDOCSTATE);
}
}
}
else
{
RegistryKey hkcu_classes_key =
registry.GetCurrentUserKey()->OpenSubKey(SOFTWARE_CLASSES);
so_bak_key = hkcu_classes_key->CreateSubKey(SO_BACKUP_KEY);
if (!so_bak_key->HasValue(REGMSDOCSTATE))
{
// set a defined value
so_bak_key->SetValue(rv_regmsdocstate);
RegistryKey hklm_sftw_classes =
registry.GetLocalMachineKey()->OpenSubKey(SOFTWARE_CLASSES, false);
RegistryKey so_bak_key_old;
if (hklm_sftw_classes->HasSubKey(SO_BACKUP_KEY))
{
so_bak_key_old = hklm_sftw_classes->OpenSubKey(SO_BACKUP_KEY, false);
if (so_bak_key_old->HasValue(REGMSDOCSTATE))
so_bak_key->CopyValue(so_bak_key_old, REGMSDOCSTATE);
}
else // try the uninstall key
{
RegistryKey hklm_key = registry.GetLocalMachineKey();
if (hklm_key->HasSubKey(SO60_UNINSTALL_KEY))
{
RegistryKey so_uninst_key =
hklm_key->OpenSubKey(SO60_UNINSTALL_KEY);
if (so_uninst_key->HasValue(REGMSDOCSTATE))
so_bak_key->CopyValue(so_uninst_key, REGMSDOCSTATE);
}
}
}
}
rv_regmsdocstate = so_bak_key->GetValue(REGMSDOCSTATE);
registration_state = rv_regmsdocstate->GetDataAsInt();
}
catch(RegistryException&)
{
registration_state = 0;
}
return registration_state;
}
<|endoftext|>
|
<commit_before>/// \file libport/assert.hh
/// \brief Provide nice assert like macros.
#ifndef LIBPORT_ASSERT_HH
# define LIBPORT_ASSERT_HH
# include <cassert>
# include <cstdlib>
// We have mysterious random aborts on OSX which is compiled with
// NDEBUG. Temporarily disable NDEBUG to have verbose paborts.
# if defined NDEBUG
# define LIBPORT_ASSERT_VERBOSE 0
# else
# define LIBPORT_ASSERT_VERBOSE 1
# endif
# if LIBPORT_ASSERT_VERBOSE
# include <iostream> // std::cerr
# include <libport/cstdio> // libport::strerror.
# endif
# include <libport/compiler.hh>
namespace libport
{
/// A wrapper to std::abort to ensure that it is declared as
/// noreturn (which is not the case of std::abort with MSVC).
ATTRIBUTE_NORETURN
inline
void abort()
{
std::abort();
}
}
/*---------------------------.
| passert -- Pretty assert. |
`---------------------------*/
/// \def passert(Subject, Assertion)
/// Same as assert, but on failure, dump \a Subject of std::cerr.
# if ! LIBPORT_ASSERT_VERBOSE
# define passert(Subject, Assertion)
# else
# define passert(Subject, Assertion) \
((void) ((Assertion) \
? 0 \
: __passert (__FILE__ ":" << __LINE__, \
Subject, Assertion)))
# define __passert(Loc, Subject, Assertion) \
(std::cerr \
<< Loc << ": failed assertion: " << #Assertion << std::endl \
<< Loc << ": with " \
<< #Subject << " = " << Subject << std::endl, \
libport::abort(), \
0)
# endif // LIBPORT_ASSERT_VERBOSE
/*-------------------------.
| pabort -- Pretty abort. |
`-------------------------*/
/// \def pabort(Msg)
///
/// Same as abort, but when NDEBUG is not set, report the Msg using
/// the operator<< on std::cerr. Msg may include << itself. So
/// if Msg is complex, beware of predence issues with << and use parens
/// on the invocation side.
# if ! LIBPORT_ASSERT_VERBOSE
# define pabort(Msg) libport::abort()
# else
# define pabort(Msg) \
((void) (__pabort (__FILE__ ":" << __LINE__, Msg)))
# define __pabort(Loc, Msg) \
(std::cerr << Loc << ": abort: " << Msg << std::endl, \
libport::abort())
# endif // LIBPORT_ASSERT_VERBOSE
/*----------------------------------------------.
| errabort -- perror (well, strerror) + abort. |
`----------------------------------------------*/
/// \def errabort(Msg)
# define errabort(Msg) \
pabort(libport::strerror(errno) << ": " << Msg)
/*--------------------------------------------------------.
| assert_exp -- Require a non-null value, and return it. |
`--------------------------------------------------------*/
# if ! LIBPORT_ASSERT_VERBOSE
# define assert_exp(Obj) (Obj)
# else
// Basically, an assert that can be used in an expression. I meant to
// use "nonnull", but this name is unused by libstdc++, so the #define
// breaks everything.
namespace libport
{
template <typename T>
inline
T
assert_exp_(T t, const char* file, int line, const char* msg)
{
if (!t)
{
std::cerr
<< file << ": " << line << ": failed assertion: " << msg << std::endl;
libport::abort();
}
return t;
}
}
# define assert_exp(Obj) \
libport::assert_exp_(Obj, __FILE__, __LINE__ , #Obj)
# endif // LIBPORT_ASSERT_VERBOSE
#endif // !LIBPORT_ASSERT_HH
<commit_msg>Make pabort print its message even in NDEBUG mode.<commit_after>/// \file libport/assert.hh
/// \brief Provide nice assert like macros.
#ifndef LIBPORT_ASSERT_HH
# define LIBPORT_ASSERT_HH
# include <cassert>
# include <cstdlib>
// We have mysterious random aborts on OSX which is compiled with
// NDEBUG. Temporarily disable NDEBUG to have verbose paborts.
# if defined NDEBUG
# define LIBPORT_ASSERT_VERBOSE 0
# else
# define LIBPORT_ASSERT_VERBOSE 1
# endif
# include <iostream> // std::cerr
# include <libport/cstdio> // libport::strerror.
# include <libport/compiler.hh>
namespace libport
{
/// A wrapper to std::abort to ensure that it is declared as
/// noreturn (which is not the case of std::abort with MSVC).
ATTRIBUTE_NORETURN
inline
void abort()
{
std::abort();
}
}
/*---------------------------.
| passert -- Pretty assert. |
`---------------------------*/
/// \def passert(Subject, Assertion)
/// Same as assert, but on failure, dump \a Subject of std::cerr.
# if ! LIBPORT_ASSERT_VERBOSE
# define passert(Subject, Assertion)
# else
# define passert(Subject, Assertion) \
((void) ((Assertion) \
? 0 \
: __passert (__FILE__ ":" << __LINE__, \
Subject, Assertion)))
# define __passert(Loc, Subject, Assertion) \
(std::cerr \
<< Loc << ": failed assertion: " << #Assertion << std::endl \
<< Loc << ": with " \
<< #Subject << " = " << Subject << std::endl, \
libport::abort(), \
0)
# endif // LIBPORT_ASSERT_VERBOSE
/*-------------------------.
| pabort -- Pretty abort. |
`-------------------------*/
/// \def pabort(Msg)
///
/// Same as abort, but when NDEBUG is not set, report the Msg using
/// the operator<< on std::cerr. Msg may include << itself. So
/// if Msg is complex, beware of predence issues with << and use parens
/// on the invocation side.
# define pabort(Msg) \
((void) (__pabort (__FILE__ ":" << __LINE__, Msg)))
# define __pabort(Loc, Msg) \
(std::cerr << Loc << ": abort: " << Msg << std::endl, \
libport::abort())
/*----------------------------------------------.
| errabort -- perror (well, strerror) + abort. |
`----------------------------------------------*/
/// \def errabort(Msg)
# define errabort(Msg) \
pabort(libport::strerror(errno) << ": " << Msg)
/*--------------------------------------------------------.
| assert_exp -- Require a non-null value, and return it. |
`--------------------------------------------------------*/
# if ! LIBPORT_ASSERT_VERBOSE
# define assert_exp(Obj) (Obj)
# else
// Basically, an assert that can be used in an expression. I meant to
// use "nonnull", but this name is unused by libstdc++, so the #define
// breaks everything.
namespace libport
{
template <typename T>
inline
T
assert_exp_(T t, const char* file, int line, const char* msg)
{
if (!t)
{
std::cerr
<< file << ": " << line << ": failed assertion: " << msg << std::endl;
libport::abort();
}
return t;
}
}
# define assert_exp(Obj) \
libport::assert_exp_(Obj, __FILE__, __LINE__ , #Obj)
# endif // LIBPORT_ASSERT_VERBOSE
#endif // !LIBPORT_ASSERT_HH
<|endoftext|>
|
<commit_before>// This Source Code Form is licensed MPL-2.0: http://mozilla.org/MPL/2.0
#include <websocketpp/config/asio_no_tls.hpp>
#include <websocketpp/server.hpp>
typedef websocketpp::server<websocketpp::config::asio> server;
#include <jsonipc/jsonipc.hh>
#include <bse/bse.hh>
#include <bse/platform.hh>
#include <bse/regex.hh>
#undef B0 // pollution from termios.h
static Bse::ServerH bse_server;
static const bool verbose = false;
// Configure websocket server
struct CustomServerConfig : public websocketpp::config::asio {
static const size_t connection_read_buffer_size = 16384;
};
using ServerEndpoint = websocketpp::server<CustomServerConfig>;
static ServerEndpoint websocket_server;
static std::string
handle_jsonipc (const std::string &message, const websocketpp::connection_hdl &hdl)
{
static Jsonipc::IpcDispatcher jd;
const ptrdiff_t conid = ptrdiff_t (websocket_server.get_con_from_hdl (hdl).get());
if (verbose)
Bse::printerr ("%p: REQUEST: %s\n", conid, message);
const std::string reply = jd.dispatch_message (message);
if (verbose)
Bse::printerr ("%p: REPLY: %s\n", conid, reply);
return reply;
}
static std::string
user_agent_nick (const std::string &useragent)
{
using namespace Bse;
std::string nick;
if (Re::search (R"(\bFirefox/)", useragent))
nick += "Firefox";
else if (Re::search (R"(\bElectron/)", useragent))
nick += "Electron";
else if (Re::search (R"(\bChrome/)", useragent))
nick += "Chrome";
else if (Re::search (R"(\bSafari/)", useragent))
nick += "Safari";
else
nick += "Unknown";
return nick;
}
static bool
ws_validate_connection (websocketpp::connection_hdl hdl)
{
ServerEndpoint::connection_ptr con = websocket_server.get_con_from_hdl (hdl);
// using subprotocol as auth string
const std::vector<std::string> &subprotocols = con->get_requested_subprotocols();
if (subprotocols.size() == 1)
{
if (subprotocols[0] == "auth123")
{
con->select_subprotocol (subprotocols[0]);
return true;
}
}
return false;
}
static void
ws_open_connection (websocketpp::connection_hdl hdl)
{
ServerEndpoint::connection_ptr con = websocket_server.get_con_from_hdl (hdl);
// https://github.com/zaphoyd/websocketpp/issues/694#issuecomment-454623641
const auto &socket = con->get_raw_socket();
const auto &address = socket.remote_endpoint().address();
const int rport = socket.remote_endpoint().port();
const websocketpp::http::parser::request &rq = con->get_request();
const websocketpp::http::parser::header_list &headermap = rq.get_headers();
std::string useragent;
for (auto it : headermap) // request headers
if (it.first == "User-Agent")
useragent = it.second;
std::string nick = user_agent_nick (useragent);
if (!nick.empty())
nick = "(" + nick + ")";
using namespace Bse::AnsiColors;
auto B1 = color (BOLD);
auto B0 = color (BOLD_OFF);
Bse::printout ("%p: %sACCEPT:%s %s:%d/ %s\n", ptrdiff_t (con.get()), B1, B0, address.to_string().c_str(), rport, nick);
// Bse::printout ("User-Agent: %s\n", useragent);
}
static void
ws_message (websocketpp::connection_hdl con, server::message_ptr msg)
{
const std::string &message = msg->get_payload();
// send message to BSE thread and block until its been handled
Aida::ScopedSemaphore sem;
auto handle_wsmsg = [&message, &con, &sem] () {
std::string reply = handle_jsonipc (message, con);
if (!reply.empty())
websocket_server.send (con, reply, websocketpp::frame::opcode::text);
sem.post();
};
bse_server.__iface_ptr__()->__execution_context_mt__().enqueue_mt (handle_wsmsg);
sem.wait();
}
static void
print_usage (bool help)
{
if (!help)
{
Bse::printout ("beast-sound-engine version %s\n", Bse::version());
return;
}
Bse::printout ("Usage: beast-sound-engine [OPTIONS]\n");
Bse::printout (" --help Print command line help\n");
Bse::printout (" --version Print program version\n");
}
int
main (int argc, char *argv[])
{
Bse::init_async (&argc, argv, argv[0]); // Bse::cstrings_to_vector (NULL)
bse_server = Bse::init_server_instance();
// parse arguments
bool seen_dashdash = false;
std::vector<std::string> words;
for (size_t i = 0; i < argc; i++)
if (!argv[i])
continue;
else if (argv[i][0] == '-' && argv[i][1] == '-' && argv[i][2] == 0)
seen_dashdash = true;
else if (!seen_dashdash && argv[i][0] == '-')
{
const char *arg = argv[i] + 1 + (argv[i][1] == '-');
const char *eq = strchr (arg, '=');
const std::string arg_name = !eq ? arg : std::string (arg, eq - arg);
if (arg_name == "version")
{
print_usage (false);
return 0;
}
else if (arg_name == "h" || arg_name == "help")
{
print_usage (true);
return 0;
}
else
{
Bse::printerr ("%s: invalid argument: %s\n", argv[0], argv[i]);
print_usage (true);
return 1;
}
}
else
words.push_back (argv[i]);
const int BEAST_AUDIO_ENGINE_PORT = 27239; // 0x3ea67 % 32768
// setup websocket and run asio loop
websocket_server.set_validate_handler (&ws_validate_connection);
websocket_server.set_open_handler (&ws_open_connection);
websocket_server.set_message_handler (&ws_message);
websocket_server.init_asio();
websocket_server.clear_access_channels (websocketpp::log::alevel::all);
websocket_server.set_reuse_addr (true);
namespace IP = boost::asio::ip;
IP::tcp::endpoint endpoint_local = IP::tcp::endpoint (IP::address::from_string ("127.0.0.1"), BEAST_AUDIO_ENGINE_PORT);
websocket_server.listen (endpoint_local);
websocket_server.start_accept();
using namespace Bse::AnsiColors;
auto B1 = color (BOLD);
auto B0 = color (BOLD_OFF);
Bse::printout ("%sLISTEN:%s ws://localhost:%d/\n", B1, B0, BEAST_AUDIO_ENGINE_PORT);
websocket_server.run();
return 0;
}
<commit_msg>BSE: beast-sound-engine: add JS example comment for echo tests<commit_after>// This Source Code Form is licensed MPL-2.0: http://mozilla.org/MPL/2.0
#include <websocketpp/config/asio_no_tls.hpp>
#include <websocketpp/server.hpp>
typedef websocketpp::server<websocketpp::config::asio> server;
#include <jsonipc/jsonipc.hh>
#include <bse/bse.hh>
#include <bse/platform.hh>
#include <bse/regex.hh>
#undef B0 // pollution from termios.h
static Bse::ServerH bse_server;
static const bool verbose = false;
// Configure websocket server
struct CustomServerConfig : public websocketpp::config::asio {
static const size_t connection_read_buffer_size = 16384;
};
using ServerEndpoint = websocketpp::server<CustomServerConfig>;
static ServerEndpoint websocket_server;
static std::string
handle_jsonipc (const std::string &message, const websocketpp::connection_hdl &hdl)
{
static Jsonipc::IpcDispatcher jd;
const ptrdiff_t conid = ptrdiff_t (websocket_server.get_con_from_hdl (hdl).get());
if (verbose)
Bse::printerr ("%p: REQUEST: %s\n", conid, message);
const std::string reply = jd.dispatch_message (message);
if (verbose)
Bse::printerr ("%p: REPLY: %s\n", conid, reply);
return reply;
}
static std::string
user_agent_nick (const std::string &useragent)
{
using namespace Bse;
std::string nick;
if (Re::search (R"(\bFirefox/)", useragent))
nick += "Firefox";
else if (Re::search (R"(\bElectron/)", useragent))
nick += "Electron";
else if (Re::search (R"(\bChrome/)", useragent))
nick += "Chrome";
else if (Re::search (R"(\bSafari/)", useragent))
nick += "Safari";
else
nick += "Unknown";
return nick;
}
static bool
ws_validate_connection (websocketpp::connection_hdl hdl)
{
ServerEndpoint::connection_ptr con = websocket_server.get_con_from_hdl (hdl);
// using subprotocol as auth string
const std::vector<std::string> &subprotocols = con->get_requested_subprotocols();
if (subprotocols.size() == 1)
{
if (subprotocols[0] == "auth123")
{
con->select_subprotocol (subprotocols[0]);
return true;
}
}
return false;
}
static void
ws_open_connection (websocketpp::connection_hdl hdl)
{
ServerEndpoint::connection_ptr con = websocket_server.get_con_from_hdl (hdl);
// https://github.com/zaphoyd/websocketpp/issues/694#issuecomment-454623641
const auto &socket = con->get_raw_socket();
const auto &address = socket.remote_endpoint().address();
const int rport = socket.remote_endpoint().port();
const websocketpp::http::parser::request &rq = con->get_request();
const websocketpp::http::parser::header_list &headermap = rq.get_headers();
std::string useragent;
for (auto it : headermap) // request headers
if (it.first == "User-Agent")
useragent = it.second;
std::string nick = user_agent_nick (useragent);
if (!nick.empty())
nick = "(" + nick + ")";
using namespace Bse::AnsiColors;
auto B1 = color (BOLD);
auto B0 = color (BOLD_OFF);
Bse::printout ("%p: %sACCEPT:%s %s:%d/ %s\n", ptrdiff_t (con.get()), B1, B0, address.to_string().c_str(), rport, nick);
// Bse::printout ("User-Agent: %s\n", useragent);
}
static void
ws_message (websocketpp::connection_hdl con, server::message_ptr msg)
{
const std::string &message = msg->get_payload();
// send message to BSE thread and block until its been handled
Aida::ScopedSemaphore sem;
auto handle_wsmsg = [&message, &con, &sem] () {
std::string reply = handle_jsonipc (message, con);
if (!reply.empty())
websocket_server.send (con, reply, websocketpp::frame::opcode::text);
sem.post();
};
bse_server.__iface_ptr__()->__execution_context_mt__().enqueue_mt (handle_wsmsg);
sem.wait();
}
static void
print_usage (bool help)
{
if (!help)
{
Bse::printout ("beast-sound-engine version %s\n", Bse::version());
return;
}
Bse::printout ("Usage: beast-sound-engine [OPTIONS]\n");
Bse::printout (" --help Print command line help\n");
Bse::printout (" --version Print program version\n");
}
int
main (int argc, char *argv[])
{
Bse::init_async (&argc, argv, argv[0]); // Bse::cstrings_to_vector (NULL)
bse_server = Bse::init_server_instance();
// parse arguments
bool seen_dashdash = false;
std::vector<std::string> words;
for (size_t i = 0; i < argc; i++)
if (!argv[i])
continue;
else if (argv[i][0] == '-' && argv[i][1] == '-' && argv[i][2] == 0)
seen_dashdash = true;
else if (!seen_dashdash && argv[i][0] == '-')
{
const char *arg = argv[i] + 1 + (argv[i][1] == '-');
const char *eq = strchr (arg, '=');
const std::string arg_name = !eq ? arg : std::string (arg, eq - arg);
if (arg_name == "version")
{
print_usage (false);
return 0;
}
else if (arg_name == "h" || arg_name == "help")
{
print_usage (true);
return 0;
}
else
{
Bse::printerr ("%s: invalid argument: %s\n", argv[0], argv[i]);
print_usage (true);
return 1;
}
}
else
words.push_back (argv[i]);
const int BEAST_AUDIO_ENGINE_PORT = 27239; // 0x3ea67 % 32768
// setup websocket and run asio loop
websocket_server.set_validate_handler (&ws_validate_connection);
websocket_server.set_open_handler (&ws_open_connection);
websocket_server.set_message_handler (&ws_message);
websocket_server.init_asio();
websocket_server.clear_access_channels (websocketpp::log::alevel::all);
websocket_server.set_reuse_addr (true);
namespace IP = boost::asio::ip;
IP::tcp::endpoint endpoint_local = IP::tcp::endpoint (IP::address::from_string ("127.0.0.1"), BEAST_AUDIO_ENGINE_PORT);
websocket_server.listen (endpoint_local);
websocket_server.start_accept();
using namespace Bse::AnsiColors;
auto B1 = color (BOLD);
auto B0 = color (BOLD_OFF);
Bse::printout ("%sLISTEN:%s ws://localhost:%d/\n", B1, B0, BEAST_AUDIO_ENGINE_PORT);
websocket_server.run();
return 0;
}
/* Dumb echo test:
var WebSocket = require ('ws'), c = 0; ws = new WebSocket("ws://localhost:27239/", 'auth123'); ws.onopen=e=>ws.send("Hello!");
ws.onmessage=e=>{if(++c % 1000 == 0) console.log(e.data, c); ws.send("YO"); }; setTimeout(e=>{ws.close();console.log(c/10);},10000);
*/
<|endoftext|>
|
<commit_before>/*****************************************************************************
*
* This file is part of Mapnik (c++ mapping toolkit)
*
* Copyright (C) 2006 Artem Pavlenko
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*
*****************************************************************************/
//$Id: ctrans.hpp 39 2005-04-10 20:39:53Z pavlenko $
#ifndef CTRANS_HPP
#define CTRANS_HPP
#include <algorithm>
#include <mapnik/box2d.hpp>
#include <mapnik/vertex.hpp>
#include <mapnik/coord_array.hpp>
#include <mapnik/proj_transform.hpp>
namespace mapnik {
typedef coord_array<coord2d> CoordinateArray;
template <typename Transform,typename Geometry>
struct MAPNIK_DECL coord_transform
{
coord_transform(Transform const& t, Geometry& geom)
: t_(t), geom_(geom) {}
unsigned vertex(double *x , double *y) const
{
unsigned command = geom_.vertex(x,y);
t_.forward(x,y);
return command;
}
void rewind (unsigned pos)
{
geom_.rewind(pos);
}
private:
Transform const& t_;
Geometry& geom_;
};
template <typename Transform,typename Geometry>
struct MAPNIK_DECL coord_transform2
{
typedef std::size_t size_type;
typedef typename Geometry::value_type value_type;
coord_transform2(Transform const& t,
Geometry const& geom,
proj_transform const& prj_trans)
: t_(t),
geom_(geom),
prj_trans_(prj_trans) {}
unsigned vertex(double * x , double * y) const
{
unsigned command(SEG_MOVETO);
bool ok = false;
bool skipped_points = false;
while (!ok)
{
command = geom_.vertex(x,y);
double z=0;
ok = prj_trans_.backward(*x,*y,z);
if (!ok) {
skipped_points = true;
}
ok = ok || (command == SEG_END);
}
if (skipped_points && (command == SEG_LINETO))
{
command = SEG_MOVETO;
}
t_.forward(x,y);
return command;
}
/*unsigned vertex(double * x , double * y) const
{
unsigned command = geom_.vertex(x,y);
double z=0;
prj_trans_.backward(*x,*y,z);
t_.forward(x,y);
return command;
}*/
void rewind (unsigned pos)
{
geom_.rewind(pos);
}
Geometry const& geom() const
{
return geom_;
}
private:
Transform const& t_;
Geometry const& geom_;
proj_transform const& prj_trans_;
};
template <typename Transform,typename Geometry>
struct MAPNIK_DECL coord_transform3
{
coord_transform3(Transform const& t,
Geometry const& geom,
proj_transform const& prj_trans,
int dx, int dy)
: t_(t),
geom_(geom),
prj_trans_(prj_trans),
dx_(dx), dy_(dy) {}
unsigned vertex(double * x , double * y) const
{
unsigned command = geom_.vertex(x,y);
double z=0;
prj_trans_.backward(*x,*y,z);
t_.forward(x,y);
*x+=dx_;
*y+=dy_;
return command;
}
void rewind (unsigned pos)
{
geom_.rewind(pos);
}
private:
Transform const& t_;
Geometry const& geom_;
proj_transform const& prj_trans_;
int dx_;
int dy_;
};
class CoordTransform
{
private:
int width_;
int height_;
double sx_;
double sy_;
box2d<double> extent_;
double offset_x_;
double offset_y_;
public:
CoordTransform(int width,int height,const box2d<double>& extent,
double offset_x = 0, double offset_y = 0)
:width_(width),height_(height),extent_(extent),offset_x_(offset_x),offset_y_(offset_y)
{
sx_ = (double(width_))/extent_.width();
sy_ = (double(height_))/extent_.height();
}
inline int width() const
{
return width_;
}
inline int height() const
{
return height_;
}
inline double scale_x() const
{
return sx_;
}
inline double scale_y() const
{
return sy_;
}
inline void forward(double * x, double * y) const
{
*x = (*x - extent_.minx()) * sx_ - offset_x_;
*y = (extent_.maxy() - *y) * sy_ - offset_y_;
}
inline void backward(double * x, double * y) const
{
*x = extent_.minx() + (*x + offset_x_)/sx_;
*y = extent_.maxy() - (*y + offset_y_)/sy_;
}
inline coord2d& forward(coord2d& c) const
{
forward(&c.x,&c.y);
return c;
}
inline coord2d& backward(coord2d& c) const
{
backward(&c.x,&c.y);
return c;
}
inline box2d<double> forward(const box2d<double>& e,proj_transform const& prj_trans) const
{
double x0 = e.minx();
double y0 = e.miny();
double x1 = e.maxx();
double y1 = e.maxy();
double z = 0.0;
prj_trans.backward(x0,y0,z);
forward(&x0,&y0);
prj_trans.backward(x1,y1,z);
forward(&x1,&y1);
return box2d<double>(x0,y0,x1,y1);
}
inline box2d<double> forward(const box2d<double>& e) const
{
double x0 = e.minx();
double y0 = e.miny();
double x1 = e.maxx();
double y1 = e.maxy();
forward(&x0,&y0);
forward(&x1,&y1);
return box2d<double>(x0,y0,x1,y1);
}
inline box2d<double> backward(const box2d<double>& e,proj_transform const& prj_trans) const
{
double x0 = e.minx();
double y0 = e.miny();
double x1 = e.maxx();
double y1 = e.maxy();
double z = 0.0;
backward(&x0,&y0);
prj_trans.forward(x0,y0,z);
backward(&x1,&y1);
prj_trans.forward(x1,y1,z);
return box2d<double>(x0,y0,x1,y1);
}
inline box2d<double> backward(const box2d<double>& e) const
{
double x0 = e.minx();
double y0 = e.miny();
double x1 = e.maxx();
double y1 = e.maxy();
backward(&x0,&y0);
backward(&x1,&y1);
return box2d<double>(x0,y0,x1,y1);
}
inline CoordinateArray& forward(CoordinateArray& coords) const
{
for (unsigned i=0;i<coords.size();++i)
{
forward(coords[i]);
}
return coords;
}
inline CoordinateArray& backward(CoordinateArray& coords) const
{
for (unsigned i=0;i<coords.size();++i)
{
backward(coords[i]);
}
return coords;
}
inline box2d<double> const& extent() const
{
return extent_;
}
};
}
#endif //CTRANS_HPP
<commit_msg>code cleanup<commit_after>/*****************************************************************************
*
* This file is part of Mapnik (c++ mapping toolkit)
*
* Copyright (C) 2006 Artem Pavlenko
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*
*****************************************************************************/
//$Id$
#ifndef CTRANS_HPP
#define CTRANS_HPP
#include <algorithm>
#include <mapnik/box2d.hpp>
#include <mapnik/vertex.hpp>
#include <mapnik/coord_array.hpp>
#include <mapnik/proj_transform.hpp>
namespace mapnik
{
typedef coord_array<coord2d> CoordinateArray;
template <typename Transform, typename Geometry>
struct MAPNIK_DECL coord_transform
{
coord_transform(Transform const& t, Geometry& geom)
: t_(t), geom_(geom) {}
unsigned vertex(double *x, double *y) const
{
unsigned command = geom_.vertex(x, y);
t_.forward(x, y);
return command;
}
void rewind(unsigned pos)
{
geom_.rewind(pos);
}
private:
Transform const& t_;
Geometry& geom_;
};
template <typename Transform, typename Geometry>
struct MAPNIK_DECL coord_transform2
{
typedef std::size_t size_type;
typedef typename Geometry::value_type value_type;
coord_transform2(Transform const& t,
Geometry const& geom,
proj_transform const& prj_trans)
: t_(t),
geom_(geom),
prj_trans_(prj_trans) {}
unsigned vertex(double *x, double *y) const
{
unsigned command = SEG_MOVETO;
bool ok = false;
bool skipped_points = false;
double z = 0;
while (!ok && command != SEG_END)
{
command = geom_.vertex(x, y);
ok = prj_trans_.backward(*x, *y, z);
if (!ok) {
skipped_points = true;
}
}
if (skipped_points && (command == SEG_LINETO))
{
command = SEG_MOVETO;
}
t_.forward(x, y);
return command;
}
void rewind(unsigned pos)
{
geom_.rewind(pos);
}
Geometry const& geom() const
{
return geom_;
}
private:
Transform const& t_;
Geometry const& geom_;
proj_transform const& prj_trans_;
};
template <typename Transform, typename Geometry>
struct MAPNIK_DECL coord_transform3
{
coord_transform3(Transform const& t,
Geometry const& geom,
proj_transform const& prj_trans,
int dx, int dy)
: t_(t),
geom_(geom),
prj_trans_(prj_trans),
dx_(dx), dy_(dy) {}
unsigned vertex(double *x, double *y) const
{
unsigned command = geom_.vertex(x, y);
double z = 0;
prj_trans_.backward(*x, *y, z);
t_.forward(x, y);
*x += dx_;
*y += dy_;
return command;
}
void rewind(unsigned pos)
{
geom_.rewind(pos);
}
private:
Transform const& t_;
Geometry const& geom_;
proj_transform const& prj_trans_;
int dx_;
int dy_;
};
class CoordTransform
{
private:
int width_;
int height_;
double sx_;
double sy_;
box2d<double> extent_;
double offset_x_;
double offset_y_;
public:
CoordTransform(int width, int height, const box2d<double>& extent,
double offset_x = 0, double offset_y = 0)
: width_(width), height_(height), extent_(extent),
offset_x_(offset_x), offset_y_(offset_y)
{
sx_ = double(width_) / extent_.width();
sy_ = double(height_) / extent_.height();
}
inline int width() const
{
return width_;
}
inline int height() const
{
return height_;
}
inline double scale_x() const
{
return sx_;
}
inline double scale_y() const
{
return sy_;
}
inline void forward(double *x, double *y) const
{
*x = (*x - extent_.minx()) * sx_ - offset_x_;
*y = (extent_.maxy() - *y) * sy_ - offset_y_;
}
inline void backward(double *x, double *y) const
{
*x = extent_.minx() + (*x + offset_x_) / sx_;
*y = extent_.maxy() - (*y + offset_y_) / sy_;
}
inline coord2d& forward(coord2d& c) const
{
forward(&c.x, &c.y);
return c;
}
inline coord2d& backward(coord2d& c) const
{
backward(&c.x, &c.y);
return c;
}
inline box2d<double> forward(const box2d<double>& e,
proj_transform const& prj_trans) const
{
double x0 = e.minx();
double y0 = e.miny();
double x1 = e.maxx();
double y1 = e.maxy();
double z = 0.0;
prj_trans.backward(x0, y0, z);
forward(&x0, &y0);
prj_trans.backward(x1, y1, z);
forward(&x1, &y1);
return box2d<double>(x0, y0, x1, y1);
}
inline box2d<double> forward(const box2d<double>& e) const
{
double x0 = e.minx();
double y0 = e.miny();
double x1 = e.maxx();
double y1 = e.maxy();
forward(&x0, &y0);
forward(&x1, &y1);
return box2d<double>(x0, y0, x1, y1);
}
inline box2d<double> backward(const box2d<double>& e,
proj_transform const& prj_trans) const
{
double x0 = e.minx();
double y0 = e.miny();
double x1 = e.maxx();
double y1 = e.maxy();
double z = 0.0;
backward(&x0, &y0);
prj_trans.forward(x0, y0, z);
backward(&x1, &y1);
prj_trans.forward(x1, y1, z);
return box2d<double>(x0, y0, x1, y1);
}
inline box2d<double> backward(const box2d<double>& e) const
{
double x0 = e.minx();
double y0 = e.miny();
double x1 = e.maxx();
double y1 = e.maxy();
backward(&x0, &y0);
backward(&x1, &y1);
return box2d<double>(x0, y0, x1, y1);
}
inline CoordinateArray& forward(CoordinateArray& coords) const
{
for (unsigned i = 0; i < coords.size(); ++i)
{
forward(coords[i]);
}
return coords;
}
inline CoordinateArray& backward(CoordinateArray& coords) const
{
for (unsigned i = 0; i < coords.size(); ++i)
{
backward(coords[i]);
}
return coords;
}
inline box2d<double> const& extent() const
{
return extent_;
}
};
}
#endif //CTRANS_HPP
<|endoftext|>
|
<commit_before>/*****************************************************************************
*
* This file is part of Mapnik (c++ mapping toolkit)
*
* Copyright (C) 2015 Artem Pavlenko
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*
*****************************************************************************/
#ifndef MAPNIK_MARKER_HPP
#define MAPNIK_MARKER_HPP
// mapnik
#include <mapnik/image.hpp>
#include <mapnik/svg/svg_storage.hpp>
#include <mapnik/svg/svg_path_adapter.hpp>
#include <mapnik/util/variant.hpp>
#pragma GCC diagnostic push
#include <mapnik/warning_ignore_agg.hpp>
#include "agg_array.h"
#pragma GCC diagnostic pop
// stl
#include <deque>
#include <memory>
namespace mapnik
{
struct image_any;
namespace svg { struct path_attributes; }
using svg::svg_path_adapter;
using svg_attribute_type = std::deque<svg::path_attributes>;
using svg_storage_type = svg::svg_storage<svg::svg_path_storage, svg_attribute_type>;
using svg_path_ptr = std::shared_ptr<svg_storage_type>;
using image_ptr = std::shared_ptr<image_any>;
struct marker_rgba8
{
public:
marker_rgba8()
: bitmap_data_(4,4,true,true)
{
// create default OGC 4x4 black pixel
bitmap_data_.set(0xff000000);
}
explicit marker_rgba8(image_rgba8 const& data)
: bitmap_data_(data) {}
explicit marker_rgba8(image_rgba8 && data) noexcept
: bitmap_data_(std::move(data)) {}
box2d<double> bounding_box() const
{
std::size_t _width = bitmap_data_.width();
std::size_t _height = bitmap_data_.height();
return box2d<double>(static_cast<double>(0), static_cast<double>(0), static_cast<double>(_width), static_cast<double>(_height));
}
inline double width() const
{
return static_cast<double>(bitmap_data_.width());
}
inline double height() const
{
return static_cast<double>(bitmap_data_.height());
}
image_rgba8 const& get_data() const
{
return bitmap_data_;
}
private:
image_rgba8 bitmap_data_;
};
struct marker_svg
{
public:
marker_svg() = default;
explicit marker_svg(mapnik::svg_path_ptr data) noexcept
: vector_data_(data) {}
inline box2d<double> bounding_box() const
{
return vector_data_->bounding_box();
}
inline double width() const
{
return vector_data_->bounding_box().width();
}
inline double height() const
{
return vector_data_->bounding_box().height();
}
inline mapnik::svg_path_ptr get_data() const
{
return vector_data_;
}
inline std::tuple<double,double> dimensions() const
{
return std::make_tuple(vector_data_->width(), vector_data_->height());
}
private:
mapnik::svg_path_ptr vector_data_;
};
struct marker_null
{
public:
inline box2d<double> bounding_box() const
{
return box2d<double>();
}
inline double width() const
{
return 0;
}
inline double height() const
{
return 0;
}
};
using marker_base = util::variant<marker_null,
marker_rgba8,
marker_svg>;
namespace detail {
struct get_marker_bbox_visitor
{
template <typename T>
box2d<double> operator()(T & data) const
{
return data.bounding_box();
}
};
struct get_marker_width_visitor
{
template <typename T>
double operator()(T const& data) const
{
return data.width();
}
};
struct get_marker_height_visitor
{
template <typename T>
double operator()(T const& data) const
{
return data.height();
}
};
} // end detail ns
struct marker : marker_base
{
marker() = default;
template <typename T>
marker(T && _data)
noexcept(std::is_nothrow_constructible<marker_base, T && >::value)
: marker_base(std::forward<T>(_data)) {}
double width() const
{
return util::apply_visitor(detail::get_marker_width_visitor(),*this);
}
double height() const
{
return util::apply_visitor(detail::get_marker_height_visitor(),*this);
}
box2d<double> bounding_box() const
{
return util::apply_visitor(detail::get_marker_bbox_visitor(),*this);
}
};
} // end mapnik ns
#endif // MAPNIK_MARKER_HPP
<commit_msg>libc++ implementation of std::deque<T> needs T to be complete<commit_after>/*****************************************************************************
*
* This file is part of Mapnik (c++ mapping toolkit)
*
* Copyright (C) 2015 Artem Pavlenko
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*
*****************************************************************************/
#ifndef MAPNIK_MARKER_HPP
#define MAPNIK_MARKER_HPP
// mapnik
#include <mapnik/image.hpp>
#include <mapnik/svg/svg_storage.hpp>
#include <mapnik/svg/svg_path_adapter.hpp>
#include <mapnik/svg/svg_path_attributes.hpp>
#include <mapnik/util/variant.hpp>
// stl
#include <deque>
#include <memory>
namespace mapnik
{
struct image_any;
using svg::svg_path_adapter;
using svg_attribute_type = std::deque<svg::path_attributes>;
using svg_storage_type = svg::svg_storage<svg::svg_path_storage, svg_attribute_type>;
using svg_path_ptr = std::shared_ptr<svg_storage_type>;
using image_ptr = std::shared_ptr<image_any>;
struct marker_rgba8
{
public:
marker_rgba8()
: bitmap_data_(4,4,true,true)
{
// create default OGC 4x4 black pixel
bitmap_data_.set(0xff000000);
}
explicit marker_rgba8(image_rgba8 const& data)
: bitmap_data_(data) {}
explicit marker_rgba8(image_rgba8 && data) noexcept
: bitmap_data_(std::move(data)) {}
box2d<double> bounding_box() const
{
std::size_t _width = bitmap_data_.width();
std::size_t _height = bitmap_data_.height();
return box2d<double>(static_cast<double>(0), static_cast<double>(0), static_cast<double>(_width), static_cast<double>(_height));
}
inline double width() const
{
return static_cast<double>(bitmap_data_.width());
}
inline double height() const
{
return static_cast<double>(bitmap_data_.height());
}
image_rgba8 const& get_data() const
{
return bitmap_data_;
}
private:
image_rgba8 bitmap_data_;
};
struct marker_svg
{
public:
marker_svg() = default;
explicit marker_svg(mapnik::svg_path_ptr data) noexcept
: vector_data_(data) {}
inline box2d<double> bounding_box() const
{
return vector_data_->bounding_box();
}
inline double width() const
{
return vector_data_->bounding_box().width();
}
inline double height() const
{
return vector_data_->bounding_box().height();
}
inline mapnik::svg_path_ptr get_data() const
{
return vector_data_;
}
inline std::tuple<double,double> dimensions() const
{
return std::make_tuple(vector_data_->width(), vector_data_->height());
}
private:
mapnik::svg_path_ptr vector_data_;
};
struct marker_null
{
public:
inline box2d<double> bounding_box() const
{
return box2d<double>();
}
inline double width() const
{
return 0;
}
inline double height() const
{
return 0;
}
};
using marker_base = util::variant<marker_null,
marker_rgba8,
marker_svg>;
namespace detail {
struct get_marker_bbox_visitor
{
template <typename T>
box2d<double> operator()(T & data) const
{
return data.bounding_box();
}
};
struct get_marker_width_visitor
{
template <typename T>
double operator()(T const& data) const
{
return data.width();
}
};
struct get_marker_height_visitor
{
template <typename T>
double operator()(T const& data) const
{
return data.height();
}
};
} // end detail ns
struct marker : marker_base
{
marker() = default;
template <typename T>
marker(T && _data)
noexcept(std::is_nothrow_constructible<marker_base, T && >::value)
: marker_base(std::forward<T>(_data)) {}
double width() const
{
return util::apply_visitor(detail::get_marker_width_visitor(),*this);
}
double height() const
{
return util::apply_visitor(detail::get_marker_height_visitor(),*this);
}
box2d<double> bounding_box() const
{
return util::apply_visitor(detail::get_marker_bbox_visitor(),*this);
}
};
} // end mapnik ns
#endif // MAPNIK_MARKER_HPP
<|endoftext|>
|
<commit_before>// Copyright 2018 Google LLC
//
// 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 "google/cloud/log.h"
#include "google/cloud/internal/getenv.h"
#include <array>
#include <cstdint>
#include <ctime>
#include <iomanip>
namespace google {
namespace cloud {
inline namespace GOOGLE_CLOUD_CPP_NS {
static_assert(sizeof(Severity) <= sizeof(int),
"Expected Severity to fit in an integer");
static_assert(static_cast<int>(Severity::GCP_LS_LOWEST) <
static_cast<int>(Severity::GCP_LS_HIGHEST),
"Expect LOWEST severity to be smaller than HIGHEST severity");
namespace {
struct Timestamp {
explicit Timestamp(std::chrono::system_clock::time_point const& tp) {
auto const tt = std::chrono::system_clock::to_time_t(tp);
#if defined(_WIN32)
gmtime_s(&tm, &tt);
#else
gmtime_r(&tt, &tm);
#endif
auto const ss = tp - std::chrono::system_clock::from_time_t(tt);
nanos = static_cast<std::int32_t>(
std::chrono::duration_cast<std::chrono::nanoseconds>(ss).count());
}
std::tm tm;
std::int32_t nanos;
};
std::ostream& operator<<(std::ostream& os, Timestamp const& ts) {
auto const prev = os.fill(' ');
auto constexpr kTmYearOffset = 1900;
os << std::setw(4) << ts.tm.tm_year + kTmYearOffset;
os.fill('0');
os << '-' << std::setw(2) << ts.tm.tm_mon + 1;
os << '-' << std::setw(2) << ts.tm.tm_mday;
os << 'T' << std::setw(2) << ts.tm.tm_hour;
os << ':' << std::setw(2) << ts.tm.tm_min;
os << ':' << std::setw(2) << ts.tm.tm_sec;
// NOLINTNEXTLINE(readability-magic-numbers)
os << '.' << std::setw(9) << ts.nanos << 'Z';
os.fill(prev);
return os;
}
auto constexpr kSeverityCount = static_cast<int>(Severity::GCP_LS_HIGHEST) + 1;
// Double braces needed to workaround a clang-3.8 bug.
std::array<char const*, kSeverityCount> constexpr kSeverityNames{{
"TRACE",
"DEBUG",
"INFO",
"NOTICE",
"WARNING",
"ERROR",
"CRITICAL",
"ALERT",
"FATAL",
}};
} // namespace
std::ostream& operator<<(std::ostream& os, Severity x) {
auto index = static_cast<int>(x);
return os << kSeverityNames[index];
}
std::ostream& operator<<(std::ostream& os, LogRecord const& rhs) {
return os << Timestamp{rhs.timestamp} << " [" << rhs.severity << "] "
<< rhs.message << " (" << rhs.filename << ':' << rhs.lineno << ')';
}
LogSink::LogSink()
: empty_(true),
minimum_severity_(static_cast<int>(Severity::GCP_LS_LOWEST_ENABLED)),
next_id_(0),
clog_backend_id_(0) {}
LogSink& LogSink::Instance() {
static auto* const kInstance = [] {
auto* p = new LogSink;
if (internal::GetEnv("GOOGLE_CLOUD_CPP_ENABLE_CLOG").has_value()) {
p->EnableStdClogImpl();
}
return p;
}();
return *kInstance;
}
// NOLINTNEXTLINE(google-runtime-int)
long LogSink::AddBackend(std::shared_ptr<LogBackend> backend) {
std::unique_lock<std::mutex> lk(mu_);
return AddBackendImpl(std::move(backend));
}
// NOLINTNEXTLINE(google-runtime-int)
void LogSink::RemoveBackend(long id) {
std::unique_lock<std::mutex> lk(mu_);
RemoveBackendImpl(id);
}
void LogSink::ClearBackends() {
std::unique_lock<std::mutex> lk(mu_);
backends_.clear();
clog_backend_id_ = 0;
empty_.store(backends_.empty());
}
std::size_t LogSink::BackendCount() const {
std::unique_lock<std::mutex> lk(mu_);
return backends_.size();
}
void LogSink::Log(LogRecord log_record) {
// Make a copy of the backends because calling user-defined functions while
// holding a lock is a bad idea: the application may change the backends while
// we are holding this lock, and soon deadlock occurs.
auto copy = [this]() {
std::unique_lock<std::mutex> lk(mu_);
return backends_;
}();
if (copy.empty()) {
return;
}
// In general, we just give each backend a const-reference and the backends
// must make a copy if needed. But if there is only one backend we can give
// the backend an opportunity to optimize things by transferring ownership of
// the LogRecord to it.
if (copy.size() == 1) {
copy.begin()->second->ProcessWithOwnership(std::move(log_record));
return;
}
for (auto& kv : copy) {
kv.second->Process(log_record);
}
}
namespace {
class StdClogBackend : public LogBackend {
public:
StdClogBackend() = default;
void Process(LogRecord const& lr) override {
std::clog << lr << "\n";
if (lr.severity >= Severity::GCP_LS_WARNING) {
std::clog << std::flush;
}
}
void ProcessWithOwnership(LogRecord lr) override { Process(lr); }
};
} // namespace
void LogSink::EnableStdClogImpl() {
std::unique_lock<std::mutex> lk(mu_);
if (clog_backend_id_ != 0) {
return;
}
clog_backend_id_ = AddBackendImpl(std::make_shared<StdClogBackend>());
}
void LogSink::DisableStdClogImpl() {
std::unique_lock<std::mutex> lk(mu_);
if (clog_backend_id_ == 0) {
return;
}
RemoveBackendImpl(clog_backend_id_);
clog_backend_id_ = 0;
}
// NOLINTNEXTLINE(google-runtime-int)
long LogSink::AddBackendImpl(std::shared_ptr<LogBackend> backend) {
auto const id = ++next_id_;
backends_.emplace(id, std::move(backend));
empty_.store(backends_.empty());
return id;
}
// NOLINTNEXTLINE(google-runtime-int)
void LogSink::RemoveBackendImpl(long id) {
auto it = backends_.find(id);
if (backends_.end() == it) {
return;
}
backends_.erase(it);
empty_.store(backends_.empty());
}
} // namespace GOOGLE_CLOUD_CPP_NS
} // namespace cloud
} // namespace google
<commit_msg>refactor: use absl::Time for the google/cloud/log.h timestamp (#4690)<commit_after>// Copyright 2018 Google LLC
//
// 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 "google/cloud/log.h"
#include "google/cloud/internal/getenv.h"
#include "absl/time/time.h"
#include <array>
namespace google {
namespace cloud {
inline namespace GOOGLE_CLOUD_CPP_NS {
static_assert(sizeof(Severity) <= sizeof(int),
"Expected Severity to fit in an integer");
static_assert(static_cast<int>(Severity::GCP_LS_LOWEST) <
static_cast<int>(Severity::GCP_LS_HIGHEST),
"Expect LOWEST severity to be smaller than HIGHEST severity");
namespace {
struct Timestamp {
explicit Timestamp(std::chrono::system_clock::time_point const& tp)
: t(absl::FromChrono(tp)) {}
absl::Time t;
};
std::ostream& operator<<(std::ostream& os, Timestamp const& ts) {
auto constexpr kFormat = "%E4Y-%m-%dT%H:%M:%E9SZ";
return os << absl::FormatTime(kFormat, ts.t, absl::UTCTimeZone());
}
auto constexpr kSeverityCount = static_cast<int>(Severity::GCP_LS_HIGHEST) + 1;
// Double braces needed to workaround a clang-3.8 bug.
std::array<char const*, kSeverityCount> constexpr kSeverityNames{{
"TRACE",
"DEBUG",
"INFO",
"NOTICE",
"WARNING",
"ERROR",
"CRITICAL",
"ALERT",
"FATAL",
}};
} // namespace
std::ostream& operator<<(std::ostream& os, Severity x) {
auto index = static_cast<int>(x);
return os << kSeverityNames[index];
}
std::ostream& operator<<(std::ostream& os, LogRecord const& rhs) {
return os << Timestamp{rhs.timestamp} << " [" << rhs.severity << "] "
<< rhs.message << " (" << rhs.filename << ':' << rhs.lineno << ')';
}
LogSink::LogSink()
: empty_(true),
minimum_severity_(static_cast<int>(Severity::GCP_LS_LOWEST_ENABLED)),
next_id_(0),
clog_backend_id_(0) {}
LogSink& LogSink::Instance() {
static auto* const kInstance = [] {
auto* p = new LogSink;
if (internal::GetEnv("GOOGLE_CLOUD_CPP_ENABLE_CLOG").has_value()) {
p->EnableStdClogImpl();
}
return p;
}();
return *kInstance;
}
// NOLINTNEXTLINE(google-runtime-int)
long LogSink::AddBackend(std::shared_ptr<LogBackend> backend) {
std::unique_lock<std::mutex> lk(mu_);
return AddBackendImpl(std::move(backend));
}
// NOLINTNEXTLINE(google-runtime-int)
void LogSink::RemoveBackend(long id) {
std::unique_lock<std::mutex> lk(mu_);
RemoveBackendImpl(id);
}
void LogSink::ClearBackends() {
std::unique_lock<std::mutex> lk(mu_);
backends_.clear();
clog_backend_id_ = 0;
empty_.store(backends_.empty());
}
std::size_t LogSink::BackendCount() const {
std::unique_lock<std::mutex> lk(mu_);
return backends_.size();
}
void LogSink::Log(LogRecord log_record) {
// Make a copy of the backends because calling user-defined functions while
// holding a lock is a bad idea: the application may change the backends while
// we are holding this lock, and soon deadlock occurs.
auto copy = [this]() {
std::unique_lock<std::mutex> lk(mu_);
return backends_;
}();
if (copy.empty()) {
return;
}
// In general, we just give each backend a const-reference and the backends
// must make a copy if needed. But if there is only one backend we can give
// the backend an opportunity to optimize things by transferring ownership of
// the LogRecord to it.
if (copy.size() == 1) {
copy.begin()->second->ProcessWithOwnership(std::move(log_record));
return;
}
for (auto& kv : copy) {
kv.second->Process(log_record);
}
}
namespace {
class StdClogBackend : public LogBackend {
public:
StdClogBackend() = default;
void Process(LogRecord const& lr) override {
std::clog << lr << "\n";
if (lr.severity >= Severity::GCP_LS_WARNING) {
std::clog << std::flush;
}
}
void ProcessWithOwnership(LogRecord lr) override { Process(lr); }
};
} // namespace
void LogSink::EnableStdClogImpl() {
std::unique_lock<std::mutex> lk(mu_);
if (clog_backend_id_ != 0) {
return;
}
clog_backend_id_ = AddBackendImpl(std::make_shared<StdClogBackend>());
}
void LogSink::DisableStdClogImpl() {
std::unique_lock<std::mutex> lk(mu_);
if (clog_backend_id_ == 0) {
return;
}
RemoveBackendImpl(clog_backend_id_);
clog_backend_id_ = 0;
}
// NOLINTNEXTLINE(google-runtime-int)
long LogSink::AddBackendImpl(std::shared_ptr<LogBackend> backend) {
auto const id = ++next_id_;
backends_.emplace(id, std::move(backend));
empty_.store(backends_.empty());
return id;
}
// NOLINTNEXTLINE(google-runtime-int)
void LogSink::RemoveBackendImpl(long id) {
auto it = backends_.find(id);
if (backends_.end() == it) {
return;
}
backends_.erase(it);
empty_.store(backends_.empty());
}
} // namespace GOOGLE_CLOUD_CPP_NS
} // namespace cloud
} // namespace google
<|endoftext|>
|
<commit_before>#ifndef NN_RELU_HPP
#define NN_RELU_HPP
#include <math.h>
#include "map.hpp"
namespace nnlib
{
/// Rectified linear activation function.
template <typename T = double>
class ReLU : public Map<T>
{
public:
ReLU(T leak = 0.1) :
m_leak(leak)
{}
ReLU(const ReLU &module) :
m_leak(module.m_leak)
{}
ReLU(const Serialized &node) :
m_leak(node.get<T>("leak"))
{}
ReLU &operator=(const ReLU &module)
{
m_leak = module.m_leak;
return *this;
}
/// Save to a serialized node.
virtual void save(Serialized &node) const override
{
Map<T>::save(node);
node.set("leak", m_leak);
}
/// Get the "leak" for this ReLU. 0 if non-leaky.
T leak() const
{
return m_leak;
}
/// Set the "leak" for this ReLU. 0 <= leak < 1.
ReLU &leak(T leak)
{
NNAssertGreaterThanOrEquals(leak, 0, "Expected positive leak!");
NNAssertLessThan(leak, 1, "Expected leak to be a percentage!");
m_leak = leak;
return *this;
}
/// Single element forward.
virtual T forwardOne(const T &x) override
{
return x > 0 ? x : m_leak * x;
}
/// Single element backward.
virtual T backwardOne(const T &x, const T &y) override
{
return x > 0 ? 1 : m_leak;
}
private:
T m_leak;
};
}
NNRegisterType(ReLU, Module);
#endif
<commit_msg>Added an assert to ReLU constructor.<commit_after>#ifndef NN_RELU_HPP
#define NN_RELU_HPP
#include <math.h>
#include "map.hpp"
namespace nnlib
{
/// Rectified linear activation function.
template <typename T = double>
class ReLU : public Map<T>
{
public:
ReLU(T leak = 0.1) :
m_leak(leak)
{
NNAssertGreaterThanOrEquals(leak, 0, "Expected positive leak!");
NNAssertLessThan(leak, 1, "Expected leak to be a percentage!");
}
ReLU(const ReLU &module) :
m_leak(module.m_leak)
{}
ReLU(const Serialized &node) :
m_leak(node.get<T>("leak"))
{}
ReLU &operator=(const ReLU &module)
{
m_leak = module.m_leak;
return *this;
}
/// Save to a serialized node.
virtual void save(Serialized &node) const override
{
Map<T>::save(node);
node.set("leak", m_leak);
}
/// Get the "leak" for this ReLU. 0 if non-leaky.
T leak() const
{
return m_leak;
}
/// Set the "leak" for this ReLU. 0 <= leak < 1.
ReLU &leak(T leak)
{
NNAssertGreaterThanOrEquals(leak, 0, "Expected positive leak!");
NNAssertLessThan(leak, 1, "Expected leak to be a percentage!");
m_leak = leak;
return *this;
}
/// Single element forward.
virtual T forwardOne(const T &x) override
{
return x > 0 ? x : m_leak * x;
}
/// Single element backward.
virtual T backwardOne(const T &x, const T &y) override
{
return x > 0 ? 1 : m_leak;
}
private:
T m_leak;
};
}
NNRegisterType(ReLU, Module);
#endif
<|endoftext|>
|
<commit_before>/*
This file is part of BGSLibrary.
BGSLibrary 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.
BGSLibrary 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 BGSLibrary. If not, see <http://www.gnu.org/licenses/>.
*/
/****************************************************************************
*
* GrimsonGMM.cpp
*
* Purpose: Implementation of the Gaussian mixture model (GMM) background
* subtraction described in:
* "Adaptive background mixture models for real-time tracking"
* by Chris Stauffer and W.E.L Grimson
*
* Author: Donovan Parks, September 2007
*
* This code is based on code by Z. Zivkovic's written for his enhanced GMM
* background subtraction algorithm:
*
* "Improved adaptive Gausian mixture model for background subtraction"
* Z.Zivkovic
* International Conference Pattern Recognition, UK, August, 2004
*
*
* "Efficient Adaptive Density Estimapion per Image Pixel for the
* Task of Background Subtraction"
* Z.Zivkovic, F. van der Heijden
* Pattern Recognition Letters, vol. 27, no. 7, pages 773-780, 2006.
*
* Zivkovic's code can be obtained at: www.zoranz.net
******************************************************************************/
#include "GrimsonGMM.h"
using namespace Algorithms::BackgroundSubtraction;
int compareGMM(const void* _gmm1, const void* _gmm2)
{
GMM gmm1 = *(GMM*)_gmm1;
GMM gmm2 = *(GMM*)_gmm2;
if(gmm1.significants < gmm2.significants)
return 1;
else if(gmm1.significants == gmm2.significants)
return 0;
else
return -1;
}
GrimsonGMM::GrimsonGMM()
{
m_modes = NULL;
}
GrimsonGMM::~GrimsonGMM()
{
if(m_modes != NULL)
delete[] m_modes;
}
void GrimsonGMM::Initalize(const BgsParams& param)
{
m_params = (GrimsonParams&)param;
// Tbf - the threshold
m_bg_threshold = 0.75f; // 1-cf from the paper
// Tgenerate - the threshold
m_variance = 36.0f; // sigma for the new mode
// GMM for each pixel
m_modes = new GMM[m_params.Size()*m_params.MaxModes()];
// used modes per pixel
m_modes_per_pixel = cvCreateImage(cvSize(m_params.Width(), m_params.Height()), IPL_DEPTH_8U, 1);
m_background = cvCreateImage(cvSize(m_params.Width(), m_params.Height()), IPL_DEPTH_8U, 3);
}
RgbImage* GrimsonGMM::Background()
{
return &m_background;
}
void GrimsonGMM::InitModel(const RgbImage& data)
{
m_modes_per_pixel.Clear();
for(unsigned int i = 0; i < m_params.Size()*m_params.MaxModes(); ++i)
{
m_modes[i].weight = 0;
m_modes[i].variance = 0;
m_modes[i].muR = 0;
m_modes[i].muG = 0;
m_modes[i].muB = 0;
m_modes[i].significants = 0;
}
}
void GrimsonGMM::Update(int frame_num, const RgbImage& data, const BwImage& update_mask)
{
// it doesn't make sense to have conditional updates in the GMM framework
}
void GrimsonGMM::SubtractPixel(long posPixel, const RgbPixel& pixel, unsigned char& numModes,
unsigned char& low_threshold, unsigned char& high_threshold)
{
// calculate distances to the modes (+ sort???)
// here we need to go in descending order!!!
long pos;
bool bFitsPDF=false;
bool bBackgroundLow=false;
bool bBackgroundHigh=false;
float fOneMinAlpha = 1-m_params.Alpha();
float totalWeight = 0.0f;
// calculate number of Gaussians to include in the background model
int backgroundGaussians = 0;
double sum = 0.0;
for(int i = 0; i < numModes; ++i)
{
if(sum < m_bg_threshold)
{
backgroundGaussians++;
sum += m_modes[posPixel+i].weight;
}
else
{
break;
}
}
// update all distributions and check for match with current pixel
for (int iModes=0; iModes < numModes; iModes++)
{
pos=posPixel+iModes;
float weight = m_modes[pos].weight;
// fit not found yet
if (!bFitsPDF)
{
//check if it belongs to some of the modes
//calculate distance
float var = m_modes[pos].variance;
float muR = m_modes[pos].muR;
float muG = m_modes[pos].muG;
float muB = m_modes[pos].muB;
float dR=muR - pixel(0);
float dG=muG - pixel(1);
float dB=muB - pixel(2);
// calculate the squared distance
float dist = (dR*dR + dG*dG + dB*dB);
if(dist < m_params.HighThreshold()*var && iModes < backgroundGaussians)
bBackgroundHigh = true;
// a match occurs when the pixel is within sqrt(fTg) standard deviations of the distribution
if(dist < m_params.LowThreshold()*var)
{
bFitsPDF=true;
// check if this Gaussian is part of the background model
if(iModes < backgroundGaussians)
bBackgroundLow = true;
//update distribution
float k = m_params.Alpha()/weight;
weight = fOneMinAlpha*weight + m_params.Alpha();
m_modes[pos].weight = weight;
m_modes[pos].muR = muR - k*(dR);
m_modes[pos].muG = muG - k*(dG);
m_modes[pos].muB = muB - k*(dB);
//limit the variance
float sigmanew = var + k*(dist-var);
m_modes[pos].variance = sigmanew < 4 ? 4 : sigmanew > 5*m_variance ? 5*m_variance : sigmanew;
m_modes[pos].significants = m_modes[pos].weight / sqrt(m_modes[pos].variance);
}
else
{
weight = fOneMinAlpha*weight;
if (weight < 0.0)
{
weight=0.0;
numModes--;
}
m_modes[pos].weight = weight;
m_modes[pos].significants = m_modes[pos].weight / sqrt(m_modes[pos].variance);
}
}
else
{
weight = fOneMinAlpha*weight;
if (weight < 0.0)
{
weight=0.0;
numModes--;
}
m_modes[pos].weight = weight;
m_modes[pos].significants = m_modes[pos].weight / sqrt(m_modes[pos].variance);
}
totalWeight += weight;
}
// renormalize weights so they add to one
double invTotalWeight = 1.0 / totalWeight;
for (int iLocal = 0; iLocal < numModes; iLocal++)
{
m_modes[posPixel + iLocal].weight *= (float)invTotalWeight;
m_modes[posPixel + iLocal].significants = m_modes[posPixel + iLocal].weight
/ sqrt(m_modes[posPixel + iLocal].variance);
}
// Sort significance values so they are in desending order.
qsort(&m_modes[posPixel], numModes, sizeof(GMM), compareGMM);
// make new mode if needed and exit
if (!bFitsPDF)
{
if (numModes < m_params.MaxModes())
{
numModes++;
}
else
{
// the weakest mode will be replaced
}
pos = posPixel + numModes-1;
m_modes[pos].muR = pixel.ch[0];
m_modes[pos].muG = pixel.ch[1];
m_modes[pos].muB = pixel.ch[2];
m_modes[pos].variance = m_variance;
m_modes[pos].significants = 0; // will be set below
if (numModes==1)
m_modes[pos].weight = 1;
else
m_modes[pos].weight = m_params.Alpha();
//renormalize weights
int iLocal;
float sum = 0.0;
for (iLocal = 0; iLocal < numModes; iLocal++)
{
sum += m_modes[posPixel+ iLocal].weight;
}
double invSum = 1.0/sum;
for (iLocal = 0; iLocal < numModes; iLocal++)
{
m_modes[posPixel + iLocal].weight *= (float)invSum;
m_modes[posPixel + iLocal].significants = m_modes[posPixel + iLocal].weight
/ sqrt(m_modes[posPixel + iLocal].variance);
}
}
// Sort significance values so they are in desending order.
qsort(&(m_modes[posPixel]), numModes, sizeof(GMM), compareGMM);
if(bBackgroundLow)
{
low_threshold = BACKGROUND;
}
else
{
low_threshold = FOREGROUND;
}
if(bBackgroundHigh)
{
high_threshold = BACKGROUND;
}
else
{
high_threshold = FOREGROUND;
}
}
///////////////////////////////////////////////////////////////////////////////
//Input:
// data - a pointer to the data of a RGB image of the same size
//Output:
// output - a pointer to the data of a gray value image of the same size
// (the memory should already be reserved)
// values: 255-foreground, 125-shadow, 0-background
///////////////////////////////////////////////////////////////////////////////
void GrimsonGMM::Subtract(int frame_num, const RgbImage& data,
BwImage& low_threshold_mask, BwImage& high_threshold_mask)
{
unsigned char low_threshold, high_threshold;
long posPixel;
// update each pixel of the image
for(unsigned int r = 0; r < m_params.Height(); ++r)
{
for(unsigned int c = 0; c < m_params.Width(); ++c)
{
// update model + background subtract
posPixel=(r*m_params.Width()+c)*m_params.MaxModes();
SubtractPixel(posPixel, data(r,c), m_modes_per_pixel(r,c), low_threshold, high_threshold);
low_threshold_mask(r,c) = low_threshold;
high_threshold_mask(r,c) = high_threshold;
m_background(r,c,0) = (unsigned char)m_modes[posPixel].muR;
m_background(r,c,1) = (unsigned char)m_modes[posPixel].muG;
m_background(r,c,2) = (unsigned char)m_modes[posPixel].muB;
}
}
}
<commit_msg>Update GrimsonGMM.cpp<commit_after>/*
This file is part of BGSLibrary.
BGSLibrary 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.
BGSLibrary 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 BGSLibrary. If not, see <http://www.gnu.org/licenses/>.
*/
/****************************************************************************
*
* GrimsonGMM.cpp
*
* Purpose: Implementation of the Gaussian mixture model (GMM) background
* subtraction described in:
* "Adaptive background mixture models for real-time tracking"
* by Chris Stauffer and W.E.L Grimson
*
* Author: Donovan Parks, September 2007
*
* This code is based on code by Z. Zivkovic's written for his enhanced GMM
* background subtraction algorithm:
*
* "Improved adaptive Gausian mixture model for background subtraction"
* Z.Zivkovic
* International Conference Pattern Recognition, UK, August, 2004
*
*
* "Efficient Adaptive Density Estimapion per Image Pixel for the
* Task of Background Subtraction"
* Z.Zivkovic, F. van der Heijden
* Pattern Recognition Letters, vol. 27, no. 7, pages 773-780, 2006.
*
* Zivkovic's code can be obtained at: www.zoranz.net
******************************************************************************/
#include "GrimsonGMM.h"
using namespace Algorithms::BackgroundSubtraction;
int compareGMM(const void* _gmm1, const void* _gmm2)
{
GMM gmm1 = *(GMM*)_gmm1;
GMM gmm2 = *(GMM*)_gmm2;
if(gmm1.significants < gmm2.significants)
return 1;
else if(gmm1.significants == gmm2.significants)
return 0;
else
return -1;
}
GrimsonGMM::GrimsonGMM()
{
m_modes = NULL;
}
GrimsonGMM::~GrimsonGMM()
{
delete[] m_modes;
}
void GrimsonGMM::Initalize(const BgsParams& param)
{
m_params = (GrimsonParams&)param;
// Tbf - the threshold
m_bg_threshold = 0.75f; // 1-cf from the paper
// Tgenerate - the threshold
m_variance = 36.0f; // sigma for the new mode
// GMM for each pixel
m_modes = new GMM[m_params.Size()*m_params.MaxModes()];
// used modes per pixel
m_modes_per_pixel = cvCreateImage(cvSize(m_params.Width(), m_params.Height()), IPL_DEPTH_8U, 1);
m_background = cvCreateImage(cvSize(m_params.Width(), m_params.Height()), IPL_DEPTH_8U, 3);
}
RgbImage* GrimsonGMM::Background()
{
return &m_background;
}
void GrimsonGMM::InitModel(const RgbImage& data)
{
m_modes_per_pixel.Clear();
for(unsigned int i = 0; i < m_params.Size()*m_params.MaxModes(); ++i)
{
m_modes[i].weight = 0;
m_modes[i].variance = 0;
m_modes[i].muR = 0;
m_modes[i].muG = 0;
m_modes[i].muB = 0;
m_modes[i].significants = 0;
}
}
void GrimsonGMM::Update(int frame_num, const RgbImage& data, const BwImage& update_mask)
{
// it doesn't make sense to have conditional updates in the GMM framework
}
void GrimsonGMM::SubtractPixel(long posPixel, const RgbPixel& pixel, unsigned char& numModes,
unsigned char& low_threshold, unsigned char& high_threshold)
{
// calculate distances to the modes (+ sort???)
// here we need to go in descending order!!!
long pos;
bool bFitsPDF=false;
bool bBackgroundLow=false;
bool bBackgroundHigh=false;
float fOneMinAlpha = 1-m_params.Alpha();
float totalWeight = 0.0f;
// calculate number of Gaussians to include in the background model
int backgroundGaussians = 0;
double sum = 0.0;
for(int i = 0; i < numModes; ++i)
{
if(sum < m_bg_threshold)
{
backgroundGaussians++;
sum += m_modes[posPixel+i].weight;
}
else
{
break;
}
}
// update all distributions and check for match with current pixel
for (int iModes=0; iModes < numModes; iModes++)
{
pos=posPixel+iModes;
float weight = m_modes[pos].weight;
// fit not found yet
if (!bFitsPDF)
{
//check if it belongs to some of the modes
//calculate distance
float var = m_modes[pos].variance;
float muR = m_modes[pos].muR;
float muG = m_modes[pos].muG;
float muB = m_modes[pos].muB;
float dR=muR - pixel(0);
float dG=muG - pixel(1);
float dB=muB - pixel(2);
// calculate the squared distance
float dist = (dR*dR + dG*dG + dB*dB);
if(dist < m_params.HighThreshold()*var && iModes < backgroundGaussians)
bBackgroundHigh = true;
// a match occurs when the pixel is within sqrt(fTg) standard deviations of the distribution
if(dist < m_params.LowThreshold()*var)
{
bFitsPDF=true;
// check if this Gaussian is part of the background model
if(iModes < backgroundGaussians)
bBackgroundLow = true;
//update distribution
float k = m_params.Alpha()/weight;
weight = fOneMinAlpha*weight + m_params.Alpha();
m_modes[pos].weight = weight;
m_modes[pos].muR = muR - k*(dR);
m_modes[pos].muG = muG - k*(dG);
m_modes[pos].muB = muB - k*(dB);
//limit the variance
float sigmanew = var + k*(dist-var);
m_modes[pos].variance = sigmanew < 4 ? 4 : sigmanew > 5*m_variance ? 5*m_variance : sigmanew;
m_modes[pos].significants = m_modes[pos].weight / sqrt(m_modes[pos].variance);
}
else
{
weight = fOneMinAlpha*weight;
if (weight < 0.0)
{
weight=0.0;
numModes--;
}
m_modes[pos].weight = weight;
m_modes[pos].significants = m_modes[pos].weight / sqrt(m_modes[pos].variance);
}
}
else
{
weight = fOneMinAlpha*weight;
if (weight < 0.0)
{
weight=0.0;
numModes--;
}
m_modes[pos].weight = weight;
m_modes[pos].significants = m_modes[pos].weight / sqrt(m_modes[pos].variance);
}
totalWeight += weight;
}
// renormalize weights so they add to one
double invTotalWeight = 1.0 / totalWeight;
for (int iLocal = 0; iLocal < numModes; iLocal++)
{
m_modes[posPixel + iLocal].weight *= (float)invTotalWeight;
m_modes[posPixel + iLocal].significants = m_modes[posPixel + iLocal].weight
/ sqrt(m_modes[posPixel + iLocal].variance);
}
// Sort significance values so they are in desending order.
qsort(&m_modes[posPixel], numModes, sizeof(GMM), compareGMM);
// make new mode if needed and exit
if (!bFitsPDF)
{
if (numModes < m_params.MaxModes())
{
numModes++;
}
else
{
// the weakest mode will be replaced
}
pos = posPixel + numModes-1;
m_modes[pos].muR = pixel.ch[0];
m_modes[pos].muG = pixel.ch[1];
m_modes[pos].muB = pixel.ch[2];
m_modes[pos].variance = m_variance;
m_modes[pos].significants = 0; // will be set below
if (numModes==1)
m_modes[pos].weight = 1;
else
m_modes[pos].weight = m_params.Alpha();
//renormalize weights
int iLocal;
float sum = 0.0;
for (iLocal = 0; iLocal < numModes; iLocal++)
{
sum += m_modes[posPixel+ iLocal].weight;
}
double invSum = 1.0/sum;
for (iLocal = 0; iLocal < numModes; iLocal++)
{
m_modes[posPixel + iLocal].weight *= (float)invSum;
m_modes[posPixel + iLocal].significants = m_modes[posPixel + iLocal].weight
/ sqrt(m_modes[posPixel + iLocal].variance);
}
}
// Sort significance values so they are in desending order.
qsort(&(m_modes[posPixel]), numModes, sizeof(GMM), compareGMM);
if(bBackgroundLow)
{
low_threshold = BACKGROUND;
}
else
{
low_threshold = FOREGROUND;
}
if(bBackgroundHigh)
{
high_threshold = BACKGROUND;
}
else
{
high_threshold = FOREGROUND;
}
}
///////////////////////////////////////////////////////////////////////////////
//Input:
// data - a pointer to the data of a RGB image of the same size
//Output:
// output - a pointer to the data of a gray value image of the same size
// (the memory should already be reserved)
// values: 255-foreground, 125-shadow, 0-background
///////////////////////////////////////////////////////////////////////////////
void GrimsonGMM::Subtract(int frame_num, const RgbImage& data,
BwImage& low_threshold_mask, BwImage& high_threshold_mask)
{
unsigned char low_threshold, high_threshold;
long posPixel;
// update each pixel of the image
for(unsigned int r = 0; r < m_params.Height(); ++r)
{
for(unsigned int c = 0; c < m_params.Width(); ++c)
{
// update model + background subtract
posPixel=(r*m_params.Width()+c)*m_params.MaxModes();
SubtractPixel(posPixel, data(r,c), m_modes_per_pixel(r,c), low_threshold, high_threshold);
low_threshold_mask(r,c) = low_threshold;
high_threshold_mask(r,c) = high_threshold;
m_background(r,c,0) = (unsigned char)m_modes[posPixel].muR;
m_background(r,c,1) = (unsigned char)m_modes[posPixel].muG;
m_background(r,c,2) = (unsigned char)m_modes[posPixel].muB;
}
}
}
<|endoftext|>
|
<commit_before>//
// Copyright(c) 2015 Gabi Melman.
// Distributed under the MIT License (http://opensource.org/licenses/MIT)
//
//
// bench.cpp : spdlog benchmarks
//
#include "spdlog/async.h"
#include "spdlog/sinks/basic_file_sink.h"
#include "spdlog/sinks/daily_file_sink.h"
#include "spdlog/sinks/null_sink.h"
#include "spdlog/sinks/rotating_file_sink.h"
#include "spdlog/spdlog.h"
#include "utils.h"
#include <atomic>
#include <cstdlib> // EXIT_FAILURE
#include <iostream>
#include <memory>
#include <string>
#include <thread>
using namespace std;
using namespace std::chrono;
using namespace spdlog;
using namespace spdlog::sinks;
using namespace utils;
void bench(int howmany, std::shared_ptr<spdlog::logger> log);
void bench_mt(int howmany, std::shared_ptr<spdlog::logger> log, int thread_count);
int main(int argc, char *argv[])
{
int queue_size = 1000000;
int howmany = 1000000;
int threads = 10;
int file_size = 30 * 1024 * 1024;
int rotating_files = 5;
try
{
if (argc > 1)
howmany = atoi(argv[1]);
if (argc > 2)
threads = atoi(argv[2]);
if (argc > 3)
queue_size = atoi(argv[3]);
cout << "*******************************************************************************\n";
cout << "Single thread, " << format(howmany) << " iterations" << endl;
cout << "*******************************************************************************\n";
auto basic_st = spdlog::basic_logger_mt("basic_st", "logs/basic_st.log", true);
bench(howmany, basic_st);
auto rotating_st = spdlog::rotating_logger_st("rotating_st", "logs/rotating_st.log", file_size, rotating_files);
bench(howmany, rotating_st);
auto daily_st = spdlog::daily_logger_st("daily_st", "logs/daily_st.log");
bench(howmany, daily_st);
bench(howmany, spdlog::create<null_sink_st>("null_st"));
cout << "\n*******************************************************************************\n";
cout << threads << " threads sharing same logger, " << format(howmany) << " iterations" << endl;
cout << "*******************************************************************************\n";
auto basic_mt = spdlog::basic_logger_mt("basic_mt", "logs/basic_mt.log", true);
bench_mt(howmany, basic_mt, threads);
auto rotating_mt = spdlog::rotating_logger_mt("rotating_mt", "logs/rotating_mt.log", file_size, rotating_files);
bench_mt(howmany, rotating_mt, threads);
auto daily_mt = spdlog::daily_logger_mt("daily_mt", "logs/daily_mt.log");
bench_mt(howmany, daily_mt, threads);
bench(howmany, spdlog::create<null_sink_st>("null_mt"));
cout << "\n*******************************************************************************\n";
cout << "async logging.. " << threads << " threads sharing same logger, " << format(howmany) << " iterations " << endl;
cout << "*******************************************************************************\n";
for (int i = 0; i < 3; ++i)
{
spdlog::init_thread_pool(queue_size, 1);
auto as = spdlog::basic_logger_mt<spdlog::async_factory>("async", "logs/basic_async.log", true);
bench_mt(howmany, as, threads);
spdlog::drop("async");
}
}
catch (std::exception &ex)
{
std::cerr << "Error: " << ex.what() << std::endl;
perror("Last error");
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}
void bench(int howmany, std::shared_ptr<spdlog::logger> log)
{
using std::chrono::high_resolution_clock;
cout << log->name() << "...\t\t" << flush;
auto start = high_resolution_clock::now();
for (auto i = 0; i < howmany; ++i)
{
log->info("Hello logger: msg number {}", i);
}
auto delta = high_resolution_clock::now() - start;
auto delta_d = duration_cast<duration<double>>(delta).count();
cout << "Elapsed: " << delta_d << "\t" << format(int(howmany / delta_d)) << "/sec" << endl;
}
void bench_mt(int howmany, std::shared_ptr<spdlog::logger> log, int thread_count)
{
using std::chrono::high_resolution_clock;
cout << log->name() << "...\t\t" << flush;
vector<thread> threads;
auto start = high_resolution_clock::now();
for (int t = 0; t < thread_count; ++t)
{
threads.push_back(std::thread([&]() {
for (int j = 0; j < howmany / thread_count; j++)
{
log->info("Hello logger: msg number {}", j);
}
}));
}
for (auto &t : threads)
{
t.join();
};
auto delta = high_resolution_clock::now() - start;
auto delta_d = duration_cast<duration<double>>(delta).count();
cout << "Elapsed: " << delta_d << "\t" << format(int(howmany / delta_d)) << "/sec" << endl;
}
<commit_msg>bench fix<commit_after>//
// Copyright(c) 2015 Gabi Melman.
// Distributed under the MIT License (http://opensource.org/licenses/MIT)
//
//
// bench.cpp : spdlog benchmarks
//
#include "spdlog/async.h"
#include "spdlog/sinks/basic_file_sink.h"
#include "spdlog/sinks/daily_file_sink.h"
#include "spdlog/sinks/null_sink.h"
#include "spdlog/sinks/rotating_file_sink.h"
#include "spdlog/spdlog.h"
#include "utils.h"
#include <atomic>
#include <cstdlib> // EXIT_FAILURE
#include <iostream>
#include <memory>
#include <string>
#include <thread>
using namespace std;
using namespace std::chrono;
using namespace spdlog;
using namespace spdlog::sinks;
using namespace utils;
void bench(int howmany, std::shared_ptr<spdlog::logger> log);
void bench_mt(int howmany, std::shared_ptr<spdlog::logger> log, int thread_count);
int main(int argc, char *argv[])
{
int howmany = 1000000;
int queue_size = howmany + 2;
int threads = 10;
int file_size = 30 * 1024 * 1024;
int rotating_files = 5;
try
{
if (argc > 1)
howmany = atoi(argv[1]);
if (argc > 2)
threads = atoi(argv[2]);
if (argc > 3)
queue_size = atoi(argv[3]);
cout << "*******************************************************************************\n";
cout << "Single thread, " << format(howmany) << " iterations" << endl;
cout << "*******************************************************************************\n";
auto basic_st = spdlog::basic_logger_mt("basic_st", "logs/basic_st.log", true);
bench(howmany, basic_st);
auto rotating_st = spdlog::rotating_logger_st("rotating_st", "logs/rotating_st.log", file_size, rotating_files);
bench(howmany, rotating_st);
auto daily_st = spdlog::daily_logger_st("daily_st", "logs/daily_st.log");
bench(howmany, daily_st);
bench(howmany, spdlog::create<null_sink_st>("null_st"));
cout << "\n*******************************************************************************\n";
cout << threads << " threads sharing same logger, " << format(howmany) << " iterations" << endl;
cout << "*******************************************************************************\n";
auto basic_mt = spdlog::basic_logger_mt("basic_mt", "logs/basic_mt.log", true);
bench_mt(howmany, basic_mt, threads);
auto rotating_mt = spdlog::rotating_logger_mt("rotating_mt", "logs/rotating_mt.log", file_size, rotating_files);
bench_mt(howmany, rotating_mt, threads);
auto daily_mt = spdlog::daily_logger_mt("daily_mt", "logs/daily_mt.log");
bench_mt(howmany, daily_mt, threads);
bench(howmany, spdlog::create<null_sink_st>("null_mt"));
cout << "\n*******************************************************************************\n";
cout << "async logging.. " << threads << " threads sharing same logger, " << format(howmany) << " iterations " << endl;
cout << "*******************************************************************************\n";
for (int i = 0; i < 3; ++i)
{
spdlog::init_thread_pool(queue_size, 1);
auto as = spdlog::basic_logger_mt<spdlog::async_factory>("async", "logs/basic_async.log", true);
bench_mt(howmany, as, threads);
spdlog::drop("async");
}
}
catch (std::exception &ex)
{
std::cerr << "Error: " << ex.what() << std::endl;
perror("Last error");
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}
void bench(int howmany, std::shared_ptr<spdlog::logger> log)
{
using std::chrono::high_resolution_clock;
cout << log->name() << "...\t\t" << flush;
auto start = high_resolution_clock::now();
for (auto i = 0; i < howmany; ++i)
{
log->info("Hello logger: msg number {}", i);
}
auto delta = high_resolution_clock::now() - start;
auto delta_d = duration_cast<duration<double>>(delta).count();
cout << "Elapsed: " << delta_d << "\t" << format(int(howmany / delta_d)) << "/sec" << endl;
}
void bench_mt(int howmany, std::shared_ptr<spdlog::logger> log, int thread_count)
{
using std::chrono::high_resolution_clock;
cout << log->name() << "...\t\t" << flush;
vector<thread> threads;
auto start = high_resolution_clock::now();
for (int t = 0; t < thread_count; ++t)
{
threads.push_back(std::thread([&]() {
for (int j = 0; j < howmany / thread_count; j++)
{
log->info("Hello logger: msg number {}", j);
}
}));
}
for (auto &t : threads)
{
t.join();
};
auto delta = high_resolution_clock::now() - start;
auto delta_d = duration_cast<duration<double>>(delta).count();
cout << "Elapsed: " << delta_d << "\t" << format(int(howmany / delta_d)) << "/sec" << endl;
}
<|endoftext|>
|
<commit_before>
#include <gloperate/rendering/ColorGradientPreparation.h>
#include <cppexpose/reflection/AbstractProperty.h>
#include <gloperate/rendering/AbstractColorGradient.h>
#include <gloperate/rendering/ColorGradientList.h>
namespace gloperate
{
ColorGradientPreparation::ColorGradientPreparation(const ColorGradientList & gradients, const std::pair<std::uint32_t, std::uint32_t> & iconSize)
: ColorGradientPreparation(gradients, iconSize, {})
{
}
ColorGradientPreparation::ColorGradientPreparation(const ColorGradientList & gradients, const std::pair<std::uint32_t, std::uint32_t> & iconSize, const std::set<std::string> & whitelist)
: m_gradients(gradients)
, m_iconSize(iconSize)
, m_whitelist(whitelist)
{
}
const ColorGradientList & ColorGradientPreparation::gradients() const
{
return m_gradients;
}
const std::pair<std::uint32_t, std::uint32_t> & ColorGradientPreparation::iconSize() const
{
return m_iconSize;
}
std::vector<std::string> ColorGradientPreparation::names() const
{
std::vector<std::string> result;
fillNames(result);
return result;
}
void ColorGradientPreparation::fillNames(std::vector<std::string> & names) const
{
names.clear();
for (const auto & pair : m_gradients.gradients())
{
if (!m_whitelist.empty() && m_whitelist.count(pair.first) == 0)
{
continue;
}
names.push_back(pair.first);
}
}
std::vector<std::vector<unsigned char>> ColorGradientPreparation::pixmaps() const
{
std::vector<std::vector<unsigned char>> result;
fillPixmaps(result);
return result;
}
void ColorGradientPreparation::fillPixmaps(std::vector<std::vector<unsigned char>> & pixmaps) const
{
pixmaps.clear();
for (const auto & pair : m_gradients.gradients())
{
if (!m_whitelist.empty() && m_whitelist.count(pair.first) == 0)
{
continue;
}
const AbstractColorGradient * gradient = pair.second;
std::vector<unsigned char> gradientData(m_iconSize.first * m_iconSize.second * sizeof(std::uint32_t));
for (size_t i = 0; i < m_iconSize.second; ++i)
{
gradient->fillPixelData(gradientData.data()+i*m_iconSize.first*sizeof(std::uint32_t), m_iconSize.first);
}
pixmaps.push_back(gradientData);
}
}
void ColorGradientPreparation::configureProperty(cppexpose::AbstractProperty * property) const
{
property->setOption("choices", cppexpose::Variant::arrayFromValues(names()));
property->setOption("pixmapSize", cppexpose::Variant::fromValue(iconSize()));
property->setOption("pixmaps", cppexpose::Variant::arrayFromValues(pixmaps()));
}
} // namespace gloperate
<commit_msg>Adjust to changed interface in cppexpose<commit_after>
#include <gloperate/rendering/ColorGradientPreparation.h>
#include <cppexpose/reflection/AbstractProperty.h>
#include <gloperate/rendering/AbstractColorGradient.h>
#include <gloperate/rendering/ColorGradientList.h>
namespace gloperate
{
ColorGradientPreparation::ColorGradientPreparation(const ColorGradientList & gradients, const std::pair<std::uint32_t, std::uint32_t> & iconSize)
: ColorGradientPreparation(gradients, iconSize, {})
{
}
ColorGradientPreparation::ColorGradientPreparation(const ColorGradientList & gradients, const std::pair<std::uint32_t, std::uint32_t> & iconSize, const std::set<std::string> & whitelist)
: m_gradients(gradients)
, m_iconSize(iconSize)
, m_whitelist(whitelist)
{
}
const ColorGradientList & ColorGradientPreparation::gradients() const
{
return m_gradients;
}
const std::pair<std::uint32_t, std::uint32_t> & ColorGradientPreparation::iconSize() const
{
return m_iconSize;
}
std::vector<std::string> ColorGradientPreparation::names() const
{
std::vector<std::string> result;
fillNames(result);
return result;
}
void ColorGradientPreparation::fillNames(std::vector<std::string> & names) const
{
names.clear();
for (const auto & pair : m_gradients.gradients())
{
if (!m_whitelist.empty() && m_whitelist.count(pair.first) == 0)
{
continue;
}
names.push_back(pair.first);
}
}
std::vector<std::vector<unsigned char>> ColorGradientPreparation::pixmaps() const
{
std::vector<std::vector<unsigned char>> result;
fillPixmaps(result);
return result;
}
void ColorGradientPreparation::fillPixmaps(std::vector<std::vector<unsigned char>> & pixmaps) const
{
pixmaps.clear();
for (const auto & pair : m_gradients.gradients())
{
if (!m_whitelist.empty() && m_whitelist.count(pair.first) == 0)
{
continue;
}
const AbstractColorGradient * gradient = pair.second;
std::vector<unsigned char> gradientData(m_iconSize.first * m_iconSize.second * sizeof(std::uint32_t));
for (size_t i = 0; i < m_iconSize.second; ++i)
{
gradient->fillPixelData(gradientData.data()+i*m_iconSize.first*sizeof(std::uint32_t), m_iconSize.first);
}
pixmaps.push_back(gradientData);
}
}
void ColorGradientPreparation::configureProperty(cppexpose::AbstractProperty * property) const
{
property->setOption("choices", cppexpose::Variant::fromVector(names()));
property->setOption("pixmapSize", cppexpose::Variant::fromValue(iconSize()));
property->setOption("pixmaps", cppexpose::Variant::fromVector(pixmaps()));
}
} // namespace gloperate
<|endoftext|>
|
<commit_before>/*
* Copyright (c) 2015 - 2022, Intel Corporation
* SPDX-License-Identifier: BSD-3-Clause
*/
#include "config.h"
#include <string>
#include <cstdint>
#include "geopm/Exception.hpp"
#include "geopm/Agg.hpp"
#include "geopm/Helper.hpp"
#include "geopm_sched.h"
#include "LevelZeroDevicePoolImp.hpp"
namespace geopm
{
const LevelZeroDevicePool &levelzero_device_pool()
{
static LevelZeroDevicePoolImp instance(levelzero());
return instance;
}
LevelZeroDevicePoolImp::LevelZeroDevicePoolImp(const LevelZero &levelzero)
: m_levelzero(levelzero)
{
}
LevelZeroDevicePoolImp::LevelZeroDevicePoolImp()
: LevelZeroDevicePoolImp(levelzero())
{
}
int LevelZeroDevicePoolImp::num_gpu(int domain) const
{
if (domain != GEOPM_DOMAIN_GPU
&& domain != GEOPM_DOMAIN_GPU_CHIP) {
throw Exception("LevelZeroDevicePool::" + std::string(__func__) +
": domain " + std::to_string(domain) + " is not supported.",
GEOPM_ERROR_INVALID, __FILE__, __LINE__);
}
return m_levelzero.num_gpu(domain);
}
void LevelZeroDevicePoolImp::check_idx_range(int domain, unsigned int domain_idx) const
{
if (domain_idx >= (unsigned int) num_gpu(domain)) {
throw Exception("LevelZeroDevicePool::" + std::string(__func__) + ": domain "
+ std::to_string(domain) + " idx " + std::to_string(domain_idx) +
" is out of range.", GEOPM_ERROR_INVALID, __FILE__, __LINE__);
}
}
void LevelZeroDevicePoolImp::check_domain_exists(int size, const char *func, int line) const
{
if (size == 0) {
throw Exception("LevelZeroDevicePool::" + std::string(func) +
": Not supported on this hardware for the specified "
"LevelZero domain",
GEOPM_ERROR_INVALID, __FILE__, line);
}
}
std::pair<unsigned int, unsigned int> LevelZeroDevicePoolImp::subdevice_device_conversion(unsigned int sub_idx) const
{
check_idx_range(GEOPM_DOMAIN_GPU_CHIP, sub_idx);
unsigned int device_idx = 0;
int subdevice_idx = 0;
// TODO: this assumes a simple split of subdevice to device.
// This may need to be adjusted based upon user preference or use case
if (num_gpu(GEOPM_DOMAIN_GPU_CHIP) %
num_gpu(GEOPM_DOMAIN_GPU) != 0) {
throw Exception("LevelZeroDevicePool::" + std::string(__func__) +
": GEOPM Requires the number" +
" of subdevices to be evenly divisible by the number of devices. ",
GEOPM_ERROR_INVALID, __FILE__, __LINE__);
}
int num_subdevice_per_device = num_gpu(GEOPM_DOMAIN_GPU_CHIP) /
num_gpu(GEOPM_DOMAIN_GPU);
device_idx = sub_idx / num_subdevice_per_device;
check_idx_range(GEOPM_DOMAIN_GPU, device_idx);
subdevice_idx = sub_idx % num_subdevice_per_device;
return {device_idx, subdevice_idx};
}
double LevelZeroDevicePoolImp::frequency_status(int domain, unsigned int domain_idx,
int l0_domain) const
{
if (domain != GEOPM_DOMAIN_GPU_CHIP) {
throw Exception("LevelZeroDevicePool::" + std::string(__func__) +
": domain " + std::to_string(domain) +
" is not supported for the frequency domain.",
GEOPM_ERROR_INVALID, __FILE__, __LINE__);
}
std::pair<unsigned int, unsigned int> dev_subdev_idx_pair;
dev_subdev_idx_pair = subdevice_device_conversion(domain_idx);
check_domain_exists(m_levelzero.frequency_domain_count(
dev_subdev_idx_pair.first, l0_domain),
__func__, __LINE__);
return m_levelzero.frequency_status(dev_subdev_idx_pair.first, l0_domain,
dev_subdev_idx_pair.second);
}
double LevelZeroDevicePoolImp::frequency_min(int domain, unsigned int domain_idx,
int l0_domain) const
{
if (domain != GEOPM_DOMAIN_GPU_CHIP) {
throw Exception("LevelZeroDevicePool::" + std::string(__func__) +
": domain " + std::to_string(domain) +
" is not supported for the frequency domain.",
GEOPM_ERROR_INVALID, __FILE__, __LINE__);
}
std::pair<unsigned int, unsigned int> dev_subdev_idx_pair;
dev_subdev_idx_pair = subdevice_device_conversion(domain_idx);
check_domain_exists(m_levelzero.frequency_domain_count(dev_subdev_idx_pair.first,
l0_domain), __func__, __LINE__);
return m_levelzero.frequency_min(dev_subdev_idx_pair.first,
l0_domain, dev_subdev_idx_pair.second);
}
double LevelZeroDevicePoolImp::frequency_max(int domain, unsigned int domain_idx,
int l0_domain) const
{
if (domain != GEOPM_DOMAIN_GPU_CHIP) {
throw Exception("LevelZeroDevicePool::" + std::string(__func__) +
": domain " + std::to_string(domain) +
" is not supported for the frequency domain.",
GEOPM_ERROR_INVALID, __FILE__, __LINE__);
}
std::pair<unsigned int, unsigned int> dev_subdev_idx_pair;
dev_subdev_idx_pair = subdevice_device_conversion(domain_idx);
check_domain_exists(m_levelzero.frequency_domain_count(
dev_subdev_idx_pair.first, l0_domain), __func__, __LINE__);
return m_levelzero.frequency_max(dev_subdev_idx_pair.first, l0_domain,
dev_subdev_idx_pair.second);
}
uint32_t LevelZeroDevicePoolImp::frequency_throttle_reasons(int domain, unsigned int domain_idx,
int l0_domain) const
{
if (domain != GEOPM_DOMAIN_GPU_CHIP) {
throw Exception("LevelZeroDevicePool::" + std::string(__func__) +
": domain " + std::to_string(domain) +
" is not supported for the frequency domain.",
GEOPM_ERROR_INVALID, __FILE__, __LINE__);
}
std::pair<unsigned int, unsigned int> dev_subdev_idx_pair;
dev_subdev_idx_pair = subdevice_device_conversion(domain_idx);
check_domain_exists(m_levelzero.frequency_domain_count(
dev_subdev_idx_pair.first, l0_domain), __func__, __LINE__);
return m_levelzero.frequency_throttle_reasons(dev_subdev_idx_pair.first, l0_domain,
dev_subdev_idx_pair.second);
}
std::pair<double, double> LevelZeroDevicePoolImp::frequency_range(int domain,
unsigned int domain_idx,
int l0_domain) const
{
if (domain != GEOPM_DOMAIN_GPU_CHIP) {
throw Exception("LevelZeroDevicePool::" + std::string(__func__) +
": domain " + std::to_string(domain) +
" is not supported for the frequency domain.",
GEOPM_ERROR_INVALID, __FILE__, __LINE__);
}
std::pair<unsigned int, unsigned int> dev_subdev_idx_pair;
dev_subdev_idx_pair = subdevice_device_conversion(domain_idx);
check_domain_exists(m_levelzero.frequency_domain_count(
dev_subdev_idx_pair.first, l0_domain), __func__, __LINE__);
return m_levelzero.frequency_range(dev_subdev_idx_pair.first, l0_domain,
dev_subdev_idx_pair.second);
}
std::pair<uint64_t, uint64_t> LevelZeroDevicePoolImp::active_time_pair(int domain,
unsigned int domain_idx,
int l0_domain) const
{
if (domain != GEOPM_DOMAIN_GPU_CHIP) {
throw Exception("LevelZeroDevicePool::" + std::string(__func__) +
": domain " + std::to_string(domain) +
" is not supported for the engine domain.",
GEOPM_ERROR_INVALID, __FILE__, __LINE__);
}
// TODO: Some devices may not support ZES_ENGINE_GROUP_COMPUTE/COPY_ALL. In that case this should be a
// device level signal that handles aggregation of domains directly here
std::pair<unsigned int, unsigned int> dev_subdev_idx_pair;
dev_subdev_idx_pair = subdevice_device_conversion(domain_idx);
check_domain_exists(m_levelzero.engine_domain_count(
dev_subdev_idx_pair.first, l0_domain),
__func__, __LINE__);
return m_levelzero.active_time_pair(dev_subdev_idx_pair.first, l0_domain,
dev_subdev_idx_pair.second);
}
uint64_t LevelZeroDevicePoolImp::active_time_timestamp(int domain,
unsigned int domain_idx,
int l0_domain) const
{
if (domain != GEOPM_DOMAIN_GPU_CHIP) {
throw Exception("LevelZeroDevicePool::" + std::string(__func__) +
": domain " + std::to_string(domain) +
" is not supported for the engine domain.",
GEOPM_ERROR_INVALID, __FILE__, __LINE__);
}
// TODO: Some devices may not support ZES_ENGINE_GROUP_COMPUTE/COPY_ALL. In that case this should be a
// device level signal that handles aggregation of domains directly here
std::pair<unsigned int, unsigned int> dev_subdev_idx_pair;
dev_subdev_idx_pair = subdevice_device_conversion(domain_idx);
check_domain_exists(m_levelzero.engine_domain_count(
dev_subdev_idx_pair.first, l0_domain),
__func__, __LINE__);
return m_levelzero.active_time_timestamp(dev_subdev_idx_pair.first, l0_domain,
dev_subdev_idx_pair.second);
}
uint64_t LevelZeroDevicePoolImp::active_time(int domain, unsigned int domain_idx,
int l0_domain) const
{
if (domain != GEOPM_DOMAIN_GPU_CHIP) {
throw Exception("LevelZeroDevicePool::" + std::string(__func__) +
": domain " +std::to_string(domain) +
" is not supported for the engine domain.",
GEOPM_ERROR_INVALID, __FILE__, __LINE__);
}
//TODO: Some devices may not support ZES_ENGINE_GROUP_COMPUTE/COPY_ALL. In that case this should be a
// device level signal that handles aggregation of domains directly here
std::pair<unsigned int, unsigned int> dev_subdev_idx_pair;
dev_subdev_idx_pair = subdevice_device_conversion(domain_idx);
check_domain_exists(m_levelzero.engine_domain_count(
dev_subdev_idx_pair.first, l0_domain),
__func__, __LINE__);
return m_levelzero.active_time(dev_subdev_idx_pair.first, l0_domain,
dev_subdev_idx_pair.second);
}
int32_t LevelZeroDevicePoolImp::power_limit_min(int domain, unsigned int domain_idx,
int l0_domain) const
{
if (domain != GEOPM_DOMAIN_GPU) {
throw Exception("LevelZeroDevicePool::" + std::string(__func__) +
": domain " + std::to_string(domain) +
" is not supported for the power domain.",
GEOPM_ERROR_INVALID, __FILE__, __LINE__);
}
check_idx_range(domain, domain_idx);
return m_levelzero.power_limit_min(domain_idx);
}
int32_t LevelZeroDevicePoolImp::power_limit_max(int domain,
unsigned int domain_idx,
int l0_domain) const
{
if (domain != GEOPM_DOMAIN_GPU) {
throw Exception("LevelZeroDevicePool::" + std::string(__func__) +
": domain " + std::to_string(domain) +
" is not supported for the power domain.",
GEOPM_ERROR_INVALID, __FILE__, __LINE__);
}
check_idx_range(domain, domain_idx);
return m_levelzero.power_limit_max(domain_idx);
}
int32_t LevelZeroDevicePoolImp::power_limit_tdp(int domain,
unsigned int domain_idx,
int l0_domain) const
{
if (domain != GEOPM_DOMAIN_GPU) {
throw Exception("LevelZeroDevicePool::" + std::string(__func__) +
": domain " + std::to_string(domain) +
" is not supported for the power domain.",
GEOPM_ERROR_INVALID, __FILE__, __LINE__);
}
check_idx_range(domain, domain_idx);
return m_levelzero.power_limit_tdp(domain_idx);
}
std::pair<uint64_t, uint64_t> LevelZeroDevicePoolImp::energy_pair(int domain,
unsigned int domain_idx,
int l0_domain) const
{
if (domain != GEOPM_DOMAIN_GPU) {
throw Exception("LevelZeroDevicePool::" + std::string(__func__) +
": domain " + std::to_string(domain) +
" is not supported for the power domain.",
GEOPM_ERROR_INVALID, __FILE__, __LINE__);
}
check_idx_range(domain, domain_idx);
return m_levelzero.energy_pair(domain_idx);
}
uint64_t LevelZeroDevicePoolImp::energy_timestamp(int domain,
unsigned int domain_idx,
int l0_domain) const
{
if (domain != GEOPM_DOMAIN_GPU) {
throw Exception("LevelZeroDevicePool::" + std::string(__func__) +
": domain " + std::to_string(domain) +
" is not supported for the power domain.",
GEOPM_ERROR_INVALID, __FILE__, __LINE__);
}
check_idx_range(domain, domain_idx);
return m_levelzero.energy_timestamp(domain_idx);
}
uint64_t LevelZeroDevicePoolImp::energy(int domain, unsigned int domain_idx,
int l0_domain) const
{
if (domain != GEOPM_DOMAIN_GPU) {
throw Exception("LevelZeroDevicePool::" + std::string(__func__) +
": domain " + std::to_string(domain) +
" is not supported for the power domain.",
GEOPM_ERROR_INVALID, __FILE__, __LINE__);
}
check_idx_range(domain, domain_idx);
return m_levelzero.energy(domain_idx);
}
void LevelZeroDevicePoolImp::frequency_control(int domain, unsigned int domain_idx,
int l0_domain, double range_min,
double range_max) const
{
if (domain != GEOPM_DOMAIN_GPU_CHIP) {
throw Exception("LevelZeroDevicePool::" + std::string(__func__) +
": domain " + std::to_string(domain) +
" is not supported for the frequency domain.",
GEOPM_ERROR_INVALID, __FILE__, __LINE__);
}
std::pair<unsigned int, unsigned int> dev_subdev_idx_pair;
dev_subdev_idx_pair = subdevice_device_conversion(domain_idx);
check_domain_exists(m_levelzero.frequency_domain_count(
dev_subdev_idx_pair.first, l0_domain),
__func__, __LINE__);
m_levelzero.frequency_control(dev_subdev_idx_pair.first, l0_domain,
dev_subdev_idx_pair.second, range_min,
range_max);
}
}
<commit_msg>Error message update for clarity.<commit_after>/*
* Copyright (c) 2015 - 2022, Intel Corporation
* SPDX-License-Identifier: BSD-3-Clause
*/
#include "config.h"
#include <string>
#include <cstdint>
#include "geopm/Exception.hpp"
#include "geopm/Agg.hpp"
#include "geopm/Helper.hpp"
#include "geopm_sched.h"
#include "LevelZeroDevicePoolImp.hpp"
namespace geopm
{
const LevelZeroDevicePool &levelzero_device_pool()
{
static LevelZeroDevicePoolImp instance(levelzero());
return instance;
}
LevelZeroDevicePoolImp::LevelZeroDevicePoolImp(const LevelZero &levelzero)
: m_levelzero(levelzero)
{
}
LevelZeroDevicePoolImp::LevelZeroDevicePoolImp()
: LevelZeroDevicePoolImp(levelzero())
{
}
int LevelZeroDevicePoolImp::num_gpu(int domain) const
{
if (domain != GEOPM_DOMAIN_GPU
&& domain != GEOPM_DOMAIN_GPU_CHIP) {
throw Exception("LevelZeroDevicePool::" + std::string(__func__) +
": domain " + std::to_string(domain) + " is not supported.",
GEOPM_ERROR_INVALID, __FILE__, __LINE__);
}
return m_levelzero.num_gpu(domain);
}
void LevelZeroDevicePoolImp::check_idx_range(int domain, unsigned int domain_idx) const
{
if (domain_idx >= (unsigned int) num_gpu(domain)) {
throw Exception("LevelZeroDevicePool::" + std::string(__func__) + ": domain "
+ std::to_string(domain) + " idx " + std::to_string(domain_idx) +
" is out of range.", GEOPM_ERROR_INVALID, __FILE__, __LINE__);
}
}
void LevelZeroDevicePoolImp::check_domain_exists(int size, const char *func, int line) const
{
if (size == 0) {
throw Exception("LevelZeroDevicePool::" + std::string(func) +
": Not supported on this hardware for the specified "
"LevelZero domain",
GEOPM_ERROR_INVALID, __FILE__, line);
}
}
std::pair<unsigned int, unsigned int> LevelZeroDevicePoolImp::subdevice_device_conversion(unsigned int sub_idx) const
{
check_idx_range(GEOPM_DOMAIN_GPU_CHIP, sub_idx);
unsigned int device_idx = 0;
int subdevice_idx = 0;
// TODO: this assumes a simple split of subdevice to device.
// This may need to be adjusted based upon user preference or use case
if (num_gpu(GEOPM_DOMAIN_GPU_CHIP) %
num_gpu(GEOPM_DOMAIN_GPU) != 0) {
throw Exception("LevelZeroDevicePool::" + std::string(__func__) +
": GEOPM Requires the number" +
" of subdevices to be evenly divisible by the number of devices. ",
GEOPM_ERROR_INVALID, __FILE__, __LINE__);
}
int num_subdevice_per_device = num_gpu(GEOPM_DOMAIN_GPU_CHIP) /
num_gpu(GEOPM_DOMAIN_GPU);
device_idx = sub_idx / num_subdevice_per_device;
check_idx_range(GEOPM_DOMAIN_GPU, device_idx);
subdevice_idx = sub_idx % num_subdevice_per_device;
return {device_idx, subdevice_idx};
}
double LevelZeroDevicePoolImp::frequency_status(int domain, unsigned int domain_idx,
int l0_domain) const
{
if (domain != GEOPM_DOMAIN_GPU_CHIP) {
throw Exception("LevelZeroDevicePool::" + std::string(__func__) +
": domain " + std::to_string(domain) +
" is not supported for the frequency domain.",
GEOPM_ERROR_INVALID, __FILE__, __LINE__);
}
std::pair<unsigned int, unsigned int> dev_subdev_idx_pair;
dev_subdev_idx_pair = subdevice_device_conversion(domain_idx);
check_domain_exists(m_levelzero.frequency_domain_count(
dev_subdev_idx_pair.first, l0_domain),
__func__, __LINE__);
return m_levelzero.frequency_status(dev_subdev_idx_pair.first, l0_domain,
dev_subdev_idx_pair.second);
}
double LevelZeroDevicePoolImp::frequency_min(int domain, unsigned int domain_idx,
int l0_domain) const
{
if (domain != GEOPM_DOMAIN_GPU_CHIP) {
throw Exception("LevelZeroDevicePool::" + std::string(__func__) +
": domain " + std::to_string(domain) +
" is not supported for the frequency domain.",
GEOPM_ERROR_INVALID, __FILE__, __LINE__);
}
std::pair<unsigned int, unsigned int> dev_subdev_idx_pair;
dev_subdev_idx_pair = subdevice_device_conversion(domain_idx);
check_domain_exists(m_levelzero.frequency_domain_count(dev_subdev_idx_pair.first,
l0_domain), __func__, __LINE__);
return m_levelzero.frequency_min(dev_subdev_idx_pair.first,
l0_domain, dev_subdev_idx_pair.second);
}
double LevelZeroDevicePoolImp::frequency_max(int domain, unsigned int domain_idx,
int l0_domain) const
{
if (domain != GEOPM_DOMAIN_GPU_CHIP) {
throw Exception("LevelZeroDevicePool::" + std::string(__func__) +
": domain " + std::to_string(domain) +
" is not supported for the frequency domain.",
GEOPM_ERROR_INVALID, __FILE__, __LINE__);
}
std::pair<unsigned int, unsigned int> dev_subdev_idx_pair;
dev_subdev_idx_pair = subdevice_device_conversion(domain_idx);
check_domain_exists(m_levelzero.frequency_domain_count(
dev_subdev_idx_pair.first, l0_domain), __func__, __LINE__);
return m_levelzero.frequency_max(dev_subdev_idx_pair.first, l0_domain,
dev_subdev_idx_pair.second);
}
uint32_t LevelZeroDevicePoolImp::frequency_throttle_reasons(int domain, unsigned int domain_idx,
int l0_domain) const
{
if (domain != GEOPM_DOMAIN_GPU_CHIP) {
throw Exception("LevelZeroDevicePool::" + std::string(__func__) +
": domain " + std::to_string(domain) +
" is not supported for reading the \"frequency throttle reason\"",
GEOPM_ERROR_INVALID, __FILE__, __LINE__);
}
std::pair<unsigned int, unsigned int> dev_subdev_idx_pair;
dev_subdev_idx_pair = subdevice_device_conversion(domain_idx);
check_domain_exists(m_levelzero.frequency_domain_count(
dev_subdev_idx_pair.first, l0_domain), __func__, __LINE__);
return m_levelzero.frequency_throttle_reasons(dev_subdev_idx_pair.first, l0_domain,
dev_subdev_idx_pair.second);
}
std::pair<double, double> LevelZeroDevicePoolImp::frequency_range(int domain,
unsigned int domain_idx,
int l0_domain) const
{
if (domain != GEOPM_DOMAIN_GPU_CHIP) {
throw Exception("LevelZeroDevicePool::" + std::string(__func__) +
": domain " + std::to_string(domain) +
" is not supported for the frequency domain.",
GEOPM_ERROR_INVALID, __FILE__, __LINE__);
}
std::pair<unsigned int, unsigned int> dev_subdev_idx_pair;
dev_subdev_idx_pair = subdevice_device_conversion(domain_idx);
check_domain_exists(m_levelzero.frequency_domain_count(
dev_subdev_idx_pair.first, l0_domain), __func__, __LINE__);
return m_levelzero.frequency_range(dev_subdev_idx_pair.first, l0_domain,
dev_subdev_idx_pair.second);
}
std::pair<uint64_t, uint64_t> LevelZeroDevicePoolImp::active_time_pair(int domain,
unsigned int domain_idx,
int l0_domain) const
{
if (domain != GEOPM_DOMAIN_GPU_CHIP) {
throw Exception("LevelZeroDevicePool::" + std::string(__func__) +
": domain " + std::to_string(domain) +
" is not supported for the engine domain.",
GEOPM_ERROR_INVALID, __FILE__, __LINE__);
}
// TODO: Some devices may not support ZES_ENGINE_GROUP_COMPUTE/COPY_ALL. In that case this should be a
// device level signal that handles aggregation of domains directly here
std::pair<unsigned int, unsigned int> dev_subdev_idx_pair;
dev_subdev_idx_pair = subdevice_device_conversion(domain_idx);
check_domain_exists(m_levelzero.engine_domain_count(
dev_subdev_idx_pair.first, l0_domain),
__func__, __LINE__);
return m_levelzero.active_time_pair(dev_subdev_idx_pair.first, l0_domain,
dev_subdev_idx_pair.second);
}
uint64_t LevelZeroDevicePoolImp::active_time_timestamp(int domain,
unsigned int domain_idx,
int l0_domain) const
{
if (domain != GEOPM_DOMAIN_GPU_CHIP) {
throw Exception("LevelZeroDevicePool::" + std::string(__func__) +
": domain " + std::to_string(domain) +
" is not supported for the engine domain.",
GEOPM_ERROR_INVALID, __FILE__, __LINE__);
}
// TODO: Some devices may not support ZES_ENGINE_GROUP_COMPUTE/COPY_ALL. In that case this should be a
// device level signal that handles aggregation of domains directly here
std::pair<unsigned int, unsigned int> dev_subdev_idx_pair;
dev_subdev_idx_pair = subdevice_device_conversion(domain_idx);
check_domain_exists(m_levelzero.engine_domain_count(
dev_subdev_idx_pair.first, l0_domain),
__func__, __LINE__);
return m_levelzero.active_time_timestamp(dev_subdev_idx_pair.first, l0_domain,
dev_subdev_idx_pair.second);
}
uint64_t LevelZeroDevicePoolImp::active_time(int domain, unsigned int domain_idx,
int l0_domain) const
{
if (domain != GEOPM_DOMAIN_GPU_CHIP) {
throw Exception("LevelZeroDevicePool::" + std::string(__func__) +
": domain " +std::to_string(domain) +
" is not supported for the engine domain.",
GEOPM_ERROR_INVALID, __FILE__, __LINE__);
}
//TODO: Some devices may not support ZES_ENGINE_GROUP_COMPUTE/COPY_ALL. In that case this should be a
// device level signal that handles aggregation of domains directly here
std::pair<unsigned int, unsigned int> dev_subdev_idx_pair;
dev_subdev_idx_pair = subdevice_device_conversion(domain_idx);
check_domain_exists(m_levelzero.engine_domain_count(
dev_subdev_idx_pair.first, l0_domain),
__func__, __LINE__);
return m_levelzero.active_time(dev_subdev_idx_pair.first, l0_domain,
dev_subdev_idx_pair.second);
}
int32_t LevelZeroDevicePoolImp::power_limit_min(int domain, unsigned int domain_idx,
int l0_domain) const
{
if (domain != GEOPM_DOMAIN_GPU) {
throw Exception("LevelZeroDevicePool::" + std::string(__func__) +
": domain " + std::to_string(domain) +
" is not supported for the power domain.",
GEOPM_ERROR_INVALID, __FILE__, __LINE__);
}
check_idx_range(domain, domain_idx);
return m_levelzero.power_limit_min(domain_idx);
}
int32_t LevelZeroDevicePoolImp::power_limit_max(int domain,
unsigned int domain_idx,
int l0_domain) const
{
if (domain != GEOPM_DOMAIN_GPU) {
throw Exception("LevelZeroDevicePool::" + std::string(__func__) +
": domain " + std::to_string(domain) +
" is not supported for the power domain.",
GEOPM_ERROR_INVALID, __FILE__, __LINE__);
}
check_idx_range(domain, domain_idx);
return m_levelzero.power_limit_max(domain_idx);
}
int32_t LevelZeroDevicePoolImp::power_limit_tdp(int domain,
unsigned int domain_idx,
int l0_domain) const
{
if (domain != GEOPM_DOMAIN_GPU) {
throw Exception("LevelZeroDevicePool::" + std::string(__func__) +
": domain " + std::to_string(domain) +
" is not supported for the power domain.",
GEOPM_ERROR_INVALID, __FILE__, __LINE__);
}
check_idx_range(domain, domain_idx);
return m_levelzero.power_limit_tdp(domain_idx);
}
std::pair<uint64_t, uint64_t> LevelZeroDevicePoolImp::energy_pair(int domain,
unsigned int domain_idx,
int l0_domain) const
{
if (domain != GEOPM_DOMAIN_GPU) {
throw Exception("LevelZeroDevicePool::" + std::string(__func__) +
": domain " + std::to_string(domain) +
" is not supported for the power domain.",
GEOPM_ERROR_INVALID, __FILE__, __LINE__);
}
check_idx_range(domain, domain_idx);
return m_levelzero.energy_pair(domain_idx);
}
uint64_t LevelZeroDevicePoolImp::energy_timestamp(int domain,
unsigned int domain_idx,
int l0_domain) const
{
if (domain != GEOPM_DOMAIN_GPU) {
throw Exception("LevelZeroDevicePool::" + std::string(__func__) +
": domain " + std::to_string(domain) +
" is not supported for the power domain.",
GEOPM_ERROR_INVALID, __FILE__, __LINE__);
}
check_idx_range(domain, domain_idx);
return m_levelzero.energy_timestamp(domain_idx);
}
uint64_t LevelZeroDevicePoolImp::energy(int domain, unsigned int domain_idx,
int l0_domain) const
{
if (domain != GEOPM_DOMAIN_GPU) {
throw Exception("LevelZeroDevicePool::" + std::string(__func__) +
": domain " + std::to_string(domain) +
" is not supported for the power domain.",
GEOPM_ERROR_INVALID, __FILE__, __LINE__);
}
check_idx_range(domain, domain_idx);
return m_levelzero.energy(domain_idx);
}
void LevelZeroDevicePoolImp::frequency_control(int domain, unsigned int domain_idx,
int l0_domain, double range_min,
double range_max) const
{
if (domain != GEOPM_DOMAIN_GPU_CHIP) {
throw Exception("LevelZeroDevicePool::" + std::string(__func__) +
": domain " + std::to_string(domain) +
" is not supported for the frequency domain.",
GEOPM_ERROR_INVALID, __FILE__, __LINE__);
}
std::pair<unsigned int, unsigned int> dev_subdev_idx_pair;
dev_subdev_idx_pair = subdevice_device_conversion(domain_idx);
check_domain_exists(m_levelzero.frequency_domain_count(
dev_subdev_idx_pair.first, l0_domain),
__func__, __LINE__);
m_levelzero.frequency_control(dev_subdev_idx_pair.first, l0_domain,
dev_subdev_idx_pair.second, range_min,
range_max);
}
}
<|endoftext|>
|
<commit_before>/**
* This file is part of libstreamswtich, which belongs to StreamSwitch
* project.
*
* Copyright (C) 2014 OpenSight (www.opensight.cn)
*
* StreamSwitch is an extensible and scalable media stream server for
* multi-protocol environment.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published
* by the Free Software Foundation, either version 3 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 Affero 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, see <http://www.gnu.org/licenses/>.
**/
/**
* stsw_stream_parser.cc
* StreamParser class implementation file, define methods of the StreamParser
* class.
* StreamParser is the default parser for a ffmpeg AV stream, other
* parser can inherit this class to override its methods for a specified
* codec. All other streams would be associated this default parser
*
* author: OpenSight Team
* date: 2015-10-27
**/
#include "stsw_stream_parser.h"
#include <stdint.h>
#include "../stsw_ffmpeg_demuxer.h"
#include "../stsw_ffmpeg_source_global.h"
#include "stsw_h264or5_parser.h"
#include "stsw_mpeg4_parser.h"
extern "C"{
#include <libavcodec/avcodec.h>
}
StreamParser::StreamParser()
:is_init_(false), stream_index_(0), demuxer_(NULL), stream_(NULL), is_live_(true),
gop_started_(false),
last_pts_(AV_NOPTS_VALUE), last_dur_(0)
{
last_live_ts_.tv_sec = 0;
last_live_ts_.tv_usec = 0;
}
StreamParser::~StreamParser()
{
}
int StreamParser::Init(FFmpegDemuxer *demuxer, int stream_index)
{
int ret = 0;
if(is_init_){
return 0;
}
demuxer_ = demuxer;
stream_index_ = stream_index;
stream_ = demuxer->fmt_ctx_->streams[stream_index];
is_live_ =
(demuxer->meta_.play_type == stream_switch::STREAM_PLAY_TYPE_LIVE);
gop_started_ = false;
last_pts_ = AV_NOPTS_VALUE;
last_dur_ = 0;
last_live_ts_.tv_sec = 0;
last_live_ts_.tv_usec = 0;
is_init_ = true;
return 0;
}
void StreamParser::Uninit()
{
if(!is_init_){
return;
}
is_init_ = false;
stream_index_ = 0;
demuxer_ = NULL;
stream_ = NULL;
is_live_ = true;
gop_started_ = false;
last_pts_ = AV_NOPTS_VALUE;
last_dur_ = 0;
last_live_ts_.tv_sec = 0;
last_live_ts_.tv_usec = 0;
return;
}
int StreamParser::Parse(stream_switch::MediaFrameInfo *frame_info,
AVPacket *pkt,
bool* is_meta_changed)
{
int ret = 0;
if(pkt->flags & AV_PKT_FLAG_CORRUPT){
//for corrupt packet, juet ignore and drop
return FFMPEG_SOURCE_ERR_DROP;
}
ret = DoUpdateFrameInfo(frame_info, pkt);
if(ret){
return ret;
}
ret = DoUpdateMeta(pkt, is_meta_changed);
if(ret){
return ret;
}
if(frame_info->frame_type == stream_switch::MEDIA_FRAME_TYPE_KEY_FRAME){
gop_started_ = true;
}
if(!gop_started_){
return FFMPEG_SOURCE_ERR_DROP;
}
return 0;
}
void StreamParser::reset()
{
gop_started_ = false;
return;
}
bool StreamParser::IsMetaReady()
{
return true;
}
int StreamParser::DoUpdateFrameInfo(stream_switch::MediaFrameInfo *frame_info,
AVPacket *pkt)
{
frame_info->ssrc = 0;
frame_info->sub_stream_index = stream_index_;
if(pkt->flags & AV_PKT_FLAG_KEY){
frame_info->frame_type = stream_switch::MEDIA_FRAME_TYPE_KEY_FRAME;
}else{
frame_info->frame_type = stream_switch::MEDIA_FRAME_TYPE_DATA_FRAME;
}
//calculate timestamp
if(is_live_){
if(last_pts_ == AV_NOPTS_VALUE){
//this is the first (has pts) packet to parse, use it as base
last_pts_ = pkt->pts;
last_dur_ = pkt->duration;
gettimeofday(&last_live_ts_, NULL);
frame_info->timestamp = last_live_ts_;
}else{
if(pkt->pts == AV_NOPTS_VALUE){
// no pts for this packet, may be because of B frame situation,
// which is not support for live stream, use the last packt time
frame_info->timestamp = last_live_ts_;
last_dur_ += pkt->duration;
}else {
int64_t pts_delta = 0;
if(pkt->pts < last_pts_ ||
(pkt->pts - last_pts_) * stream_->time_base.num / stream_->time_base.den > 60) {
//this pts lose sync with the last pts, try to guess their delta
if(last_dur_ > 0){
//if duration is known, used last duration as delta
pts_delta = last_dur_;
}else if (stream_->codec->codec_type == AVMEDIA_TYPE_VIDEO &&
stream_->avg_frame_rate.den &&
stream_->avg_frame_rate.num){
//make use of average fps to calculate delta
pts_delta = (stream_->avg_frame_rate.den * stream_->time_base.den) /
(stream_->avg_frame_rate.num * stream_->time_base.num);
}else{
//no any way to know delta
pts_delta = 0;
}
}else{
//normal case
pts_delta = pkt->pts - last_pts_;
}
frame_info->timestamp.tv_sec =
(pts_delta * stream_->time_base.num) / stream_->time_base.den +
last_live_ts_.tv_sec;
frame_info->timestamp.tv_usec =
((pts_delta * stream_->time_base.num) % stream_->time_base.den)
* 1000000 / stream_->time_base.den +
last_live_ts_.tv_usec;
while(frame_info->timestamp.tv_usec >= 1000000){
frame_info->timestamp.tv_sec ++;
frame_info->timestamp.tv_usec -= 1000000;
}
last_pts_ = pkt->pts;
last_dur_ = pkt->duration;
last_live_ts_ = frame_info->timestamp;
}//if(pkt->pts == AV_NOPTS_VALUE){
}//if(pkt->pts == AV_NOPTS_VALUE){
}else{ // replay
int64_t pts;
//for non-live mode, use pts directly
if(pkt->pts == AV_NOPTS_VALUE){
if(last_pts_ != AV_NOPTS_VALUE){
pts = last_pts_;
}else{
pts = 0;
}
}else{
pts = pkt->pts;
last_pts_ = pts;
last_dur_ = pkt->duration;
}
frame_info->timestamp.tv_sec =
(pts * stream_->time_base.num) / stream_->time_base.den;
frame_info->timestamp.tv_usec =
((pts * stream_->time_base.num) % stream_->time_base.den)
* 1000000 / stream_->time_base.den;
}
return 0;
}
int StreamParser::DoUpdateMeta(AVPacket *pkt, bool* is_meta_changed)
{
if(is_meta_changed != NULL){
(*is_meta_changed) = false;
}
return 0;
}
template<class T>
StreamParser* StreamParserFatcory()
{
return new T;
}
struct ParserInfo {
const int codec_id;
StreamParser* (*factory)();
const char name[32];
};
//FIXME this should be simplified!
static const ParserInfo parser_infos[] = {
{ AV_CODEC_ID_H264, StreamParserFatcory<H264or5Parser>, "H264" },
{ AV_CODEC_ID_H265, StreamParserFatcory<H264or5Parser>, "H265" },
{ AV_CODEC_ID_MPEG4, StreamParserFatcory<Mpeg4Parser>, "MP4V-ES" },
{ AV_CODEC_ID_AAC, NULL, "MPEG4-GENERIC" },
{ AV_CODEC_ID_AMR_NB, NULL, "AMR" },
{ AV_CODEC_ID_PCM_MULAW, NULL, "PCMU"},
{ AV_CODEC_ID_PCM_ALAW, NULL, "PCMA"},
{ AV_CODEC_ID_NONE, NULL, "NONE"}//XXX ...
};
const char * CodecNameFromId(int codec_id)
{
const ParserInfo *parser_info = parser_infos;
while (parser_info->codec_id != AV_CODEC_ID_NONE) {
if (parser_info->codec_id == codec_id){
if(parser_info->name != NULL){
return parser_info->name;
}else{
return avcodec_get_name((enum AVCodecID)codec_id);
}
}
parser_info++;
}
return avcodec_get_name((enum AVCodecID)codec_id);
}
StreamParser * NewStreamParser(int codec_id)
{
const ParserInfo *parser_info = parser_infos;
while (parser_info->codec_id != AV_CODEC_ID_NONE) {
if (parser_info->codec_id == codec_id){
if(parser_info->factory != NULL){
return parser_info->factory();
}else{
return new StreamParser();
}
}
parser_info++;
}
return new StreamParser();
}
<commit_msg>change AAC codec name<commit_after>/**
* This file is part of libstreamswtich, which belongs to StreamSwitch
* project.
*
* Copyright (C) 2014 OpenSight (www.opensight.cn)
*
* StreamSwitch is an extensible and scalable media stream server for
* multi-protocol environment.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published
* by the Free Software Foundation, either version 3 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 Affero 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, see <http://www.gnu.org/licenses/>.
**/
/**
* stsw_stream_parser.cc
* StreamParser class implementation file, define methods of the StreamParser
* class.
* StreamParser is the default parser for a ffmpeg AV stream, other
* parser can inherit this class to override its methods for a specified
* codec. All other streams would be associated this default parser
*
* author: OpenSight Team
* date: 2015-10-27
**/
#include "stsw_stream_parser.h"
#include <stdint.h>
#include "../stsw_ffmpeg_demuxer.h"
#include "../stsw_ffmpeg_source_global.h"
#include "stsw_h264or5_parser.h"
#include "stsw_mpeg4_parser.h"
extern "C"{
#include <libavcodec/avcodec.h>
}
StreamParser::StreamParser()
:is_init_(false), stream_index_(0), demuxer_(NULL), stream_(NULL), is_live_(true),
gop_started_(false),
last_pts_(AV_NOPTS_VALUE), last_dur_(0)
{
last_live_ts_.tv_sec = 0;
last_live_ts_.tv_usec = 0;
}
StreamParser::~StreamParser()
{
}
int StreamParser::Init(FFmpegDemuxer *demuxer, int stream_index)
{
int ret = 0;
if(is_init_){
return 0;
}
demuxer_ = demuxer;
stream_index_ = stream_index;
stream_ = demuxer->fmt_ctx_->streams[stream_index];
is_live_ =
(demuxer->meta_.play_type == stream_switch::STREAM_PLAY_TYPE_LIVE);
gop_started_ = false;
last_pts_ = AV_NOPTS_VALUE;
last_dur_ = 0;
last_live_ts_.tv_sec = 0;
last_live_ts_.tv_usec = 0;
is_init_ = true;
return 0;
}
void StreamParser::Uninit()
{
if(!is_init_){
return;
}
is_init_ = false;
stream_index_ = 0;
demuxer_ = NULL;
stream_ = NULL;
is_live_ = true;
gop_started_ = false;
last_pts_ = AV_NOPTS_VALUE;
last_dur_ = 0;
last_live_ts_.tv_sec = 0;
last_live_ts_.tv_usec = 0;
return;
}
int StreamParser::Parse(stream_switch::MediaFrameInfo *frame_info,
AVPacket *pkt,
bool* is_meta_changed)
{
int ret = 0;
if(pkt->flags & AV_PKT_FLAG_CORRUPT){
//for corrupt packet, juet ignore and drop
return FFMPEG_SOURCE_ERR_DROP;
}
ret = DoUpdateFrameInfo(frame_info, pkt);
if(ret){
return ret;
}
ret = DoUpdateMeta(pkt, is_meta_changed);
if(ret){
return ret;
}
if(frame_info->frame_type == stream_switch::MEDIA_FRAME_TYPE_KEY_FRAME){
gop_started_ = true;
}
if(!gop_started_){
return FFMPEG_SOURCE_ERR_DROP;
}
return 0;
}
void StreamParser::reset()
{
gop_started_ = false;
return;
}
bool StreamParser::IsMetaReady()
{
return true;
}
int StreamParser::DoUpdateFrameInfo(stream_switch::MediaFrameInfo *frame_info,
AVPacket *pkt)
{
frame_info->ssrc = 0;
frame_info->sub_stream_index = stream_index_;
if(pkt->flags & AV_PKT_FLAG_KEY){
frame_info->frame_type = stream_switch::MEDIA_FRAME_TYPE_KEY_FRAME;
}else{
frame_info->frame_type = stream_switch::MEDIA_FRAME_TYPE_DATA_FRAME;
}
//calculate timestamp
if(is_live_){
if(last_pts_ == AV_NOPTS_VALUE){
//this is the first (has pts) packet to parse, use it as base
last_pts_ = pkt->pts;
last_dur_ = pkt->duration;
gettimeofday(&last_live_ts_, NULL);
frame_info->timestamp = last_live_ts_;
}else{
if(pkt->pts == AV_NOPTS_VALUE){
// no pts for this packet, may be because of B frame situation,
// which is not support for live stream, use the last packt time
frame_info->timestamp = last_live_ts_;
last_dur_ += pkt->duration;
}else {
int64_t pts_delta = 0;
if(pkt->pts < last_pts_ ||
(pkt->pts - last_pts_) * stream_->time_base.num / stream_->time_base.den > 60) {
//this pts lose sync with the last pts, try to guess their delta
if(last_dur_ > 0){
//if duration is known, used last duration as delta
pts_delta = last_dur_;
}else if (stream_->codec->codec_type == AVMEDIA_TYPE_VIDEO &&
stream_->avg_frame_rate.den &&
stream_->avg_frame_rate.num){
//make use of average fps to calculate delta
pts_delta = (stream_->avg_frame_rate.den * stream_->time_base.den) /
(stream_->avg_frame_rate.num * stream_->time_base.num);
}else{
//no any way to know delta
pts_delta = 0;
}
}else{
//normal case
pts_delta = pkt->pts - last_pts_;
}
frame_info->timestamp.tv_sec =
(pts_delta * stream_->time_base.num) / stream_->time_base.den +
last_live_ts_.tv_sec;
frame_info->timestamp.tv_usec =
((pts_delta * stream_->time_base.num) % stream_->time_base.den)
* 1000000 / stream_->time_base.den +
last_live_ts_.tv_usec;
while(frame_info->timestamp.tv_usec >= 1000000){
frame_info->timestamp.tv_sec ++;
frame_info->timestamp.tv_usec -= 1000000;
}
last_pts_ = pkt->pts;
last_dur_ = pkt->duration;
last_live_ts_ = frame_info->timestamp;
}//if(pkt->pts == AV_NOPTS_VALUE){
}//if(pkt->pts == AV_NOPTS_VALUE){
}else{ // replay
int64_t pts;
//for non-live mode, use pts directly
if(pkt->pts == AV_NOPTS_VALUE){
if(last_pts_ != AV_NOPTS_VALUE){
pts = last_pts_;
}else{
pts = 0;
}
}else{
pts = pkt->pts;
last_pts_ = pts;
last_dur_ = pkt->duration;
}
frame_info->timestamp.tv_sec =
(pts * stream_->time_base.num) / stream_->time_base.den;
frame_info->timestamp.tv_usec =
((pts * stream_->time_base.num) % stream_->time_base.den)
* 1000000 / stream_->time_base.den;
}
return 0;
}
int StreamParser::DoUpdateMeta(AVPacket *pkt, bool* is_meta_changed)
{
if(is_meta_changed != NULL){
(*is_meta_changed) = false;
}
return 0;
}
template<class T>
StreamParser* StreamParserFatcory()
{
return new T;
}
struct ParserInfo {
const int codec_id;
StreamParser* (*factory)();
const char name[32];
};
//FIXME this should be simplified!
static const ParserInfo parser_infos[] = {
{ AV_CODEC_ID_H264, StreamParserFatcory<H264or5Parser>, "H264" },
{ AV_CODEC_ID_H265, StreamParserFatcory<H264or5Parser>, "H265" },
{ AV_CODEC_ID_MPEG4, StreamParserFatcory<Mpeg4Parser>, "MP4V-ES" },
{ AV_CODEC_ID_AAC, NULL, "AAC" },
{ AV_CODEC_ID_AMR_NB, NULL, "AMR" },
{ AV_CODEC_ID_PCM_MULAW, NULL, "PCMU"},
{ AV_CODEC_ID_PCM_ALAW, NULL, "PCMA"},
{ AV_CODEC_ID_NONE, NULL, "NONE"}//XXX ...
};
const char * CodecNameFromId(int codec_id)
{
const ParserInfo *parser_info = parser_infos;
while (parser_info->codec_id != AV_CODEC_ID_NONE) {
if (parser_info->codec_id == codec_id){
if(parser_info->name != NULL){
return parser_info->name;
}else{
return avcodec_get_name((enum AVCodecID)codec_id);
}
}
parser_info++;
}
return avcodec_get_name((enum AVCodecID)codec_id);
}
StreamParser * NewStreamParser(int codec_id)
{
const ParserInfo *parser_info = parser_infos;
while (parser_info->codec_id != AV_CODEC_ID_NONE) {
if (parser_info->codec_id == codec_id){
if(parser_info->factory != NULL){
return parser_info->factory();
}else{
return new StreamParser();
}
}
parser_info++;
}
return new StreamParser();
}
<|endoftext|>
|
<commit_before>/**
* @project zqrpc
* @file include/zqrpc/ZSocket.hpp
* @author S Roychowdhury <sroycode @ gmail DOT com>
* @version 0.1
*
* @section LICENSE
*
* Copyright (c) 2014 S Roychowdhury
*
* 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.
*
* @section DESCRIPTION
*
* ZSocket.hpp : Send and Recv
*
*/
#ifndef _ZQRPC_ZSOCKET_HPP_
#define _ZQRPC_ZSOCKET_HPP_
#include <stdint.h>
#include <cstring>
#include <boost/thread.hpp>
#include "zmq.hpp"
#include "ZError.hpp"
#include "RpcHeaders.hh"
namespace zqrpc {
class ZSocket {
friend class RpcServer;
public:
ZSocket(zmq::context_t* context, int type, const std::string& id)
: socket_(*context,type)
{
if (id.length()>0)
socket_.setsockopt(ZMQ_IDENTITY, id.c_str(), id.length());
}
~ZSocket() {
}
void connect(const char* url) {
socket_.connect(url);
}
void disconnect(const char* url) {
if ( socket_.connected() ) socket_.disconnect(url);
}
void bind(const char* url) {
socket_.bind(url);
}
void unbind(const char* url) {
if (strncmp(url,"inproc",6)!=0) socket_.unbind(url);
}
void close() {
socket_.close();
}
void SetOption(int type,std::string opt) {
socket_.setsockopt(type, opt.c_str(), opt.length());
}
void SetLinger(int linger = -1) {
socket_.setsockopt(ZMQ_LINGER, &linger, sizeof(int));
}
template<typename T>
bool Send(const T& frames) {
std::size_t fleft= frames.size();
if(!fleft) return true;
for (typename T::const_iterator it = frames.begin(); it!=frames.end(); ++it,--fleft) {
zmq::message_t msg (it->length());
memcpy ((void *) msg.data (), it->c_str(), it->length());
// DLOG(INFO) << std::string(static_cast<char*>(msg.data()), msg.size()) << std::endl;
if (! socket_.send(msg, (fleft==1) ? 0 : ZMQ_SNDMORE) )
throw ZError(ZEC_CONNECTIONERROR,"cannot send data frame");
}
return true;
}
template<typename T>
T BlockingRecv() {
T frames;
bool more=false;
do {
zmq::message_t msg(0);
if (!socket_.recv(&msg, 0)) throw zqrpc::RetryException();
frames.push_back(std::string(static_cast<char*>(msg.data()), msg.size()));
// DLOG(INFO) << std::string(static_cast<char*>(msg.data()), msg.size()) << std::endl;
more = msg.more();
} while(more);
return frames;
}
template<typename T>
T NonBlockingRecv() {
T frames;
zmq::message_t msg(0);
bool more=false;
do {
if (!socket_.recv(&msg, ZMQ_DONTWAIT)) throw zqrpc::RetryException();
frames.push_back(std::string(static_cast<char*>(msg.data()), msg.size()));
more = msg.more();
} while(more);
return frames;
}
bool Poll(long timeout) {
zmq::pollitem_t items[] = { { socket_, 0, ZMQ_POLLIN, 0 } };
zmq::poll (&items[0], 1, timeout);
return (items[0].revents & ZMQ_POLLIN);
// DLOG(INFO) << "Polling End" << std::endl;
}
private:
zmq::socket_t socket_;
ZSocket(const ZSocket&);
void operator=(const ZSocket&);
};
} // namespace
#endif
<commit_msg>Wed Aug 13 10:06:16 IST 2014<commit_after>/**
* @project zqrpc
* @file include/zqrpc/ZSocket.hpp
* @author S Roychowdhury <sroycode @ gmail DOT com>
* @version 0.1
*
* @section LICENSE
*
* Copyright (c) 2014 S Roychowdhury
*
* 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.
*
* @section DESCRIPTION
*
* ZSocket.hpp : Send and Recv
*
*/
#ifndef _ZQRPC_ZSOCKET_HPP_
#define _ZQRPC_ZSOCKET_HPP_
#include <stdint.h>
#include <cstring>
#include <boost/thread.hpp>
#include "zmq.hpp"
#include "ZError.hpp"
#include "RpcHeaders.hh"
namespace zqrpc {
class ZSocket {
friend class RpcServer;
public:
ZSocket(zmq::context_t* context, int type, const std::string& id)
: socket_(*context,type)
{
if (id.length()>0)
socket_.setsockopt(ZMQ_IDENTITY, id.c_str(), id.length());
}
~ZSocket() {
}
void connect(const char* url) {
socket_.connect(url);
}
void disconnect(const char* url) {
if ( socket_.connected() ) socket_.disconnect(url);
}
void bind(const char* url) {
socket_.bind(url);
}
void unbind(const char* url) {
if (strncmp(url,"inproc",6)!=0) socket_.unbind(url);
}
void close() {
socket_.close();
}
void SetOption(int type,std::string opt) {
socket_.setsockopt(type, opt.c_str(), opt.length());
}
void SetLinger(int linger = -1) {
socket_.setsockopt(ZMQ_LINGER, &linger, sizeof(int));
}
template<typename T>
bool Send(const T& frames) {
std::size_t fleft= frames.size();
if(!fleft) return true;
for (typename T::const_iterator it = frames.begin(); it!=frames.end(); ++it,--fleft) {
zmq::message_t msg (it->length());
memcpy ((void *) msg.data (), it->c_str(), it->length());
// DLOG(INFO) << std::string(static_cast<char*>(msg.data()), msg.size()) << std::endl;
if (! socket_.send(msg, (fleft==1) ? 0 : ZMQ_SNDMORE) )
throw ZError(ZEC_CONNECTIONERROR,"cannot send data frame");
}
return true;
}
template<typename T>
T BlockingRecv() {
T frames;
bool more=false;
do {
zmq::message_t msg(0);
if (!socket_.recv(&msg, 0)) throw zqrpc::RetryException();
frames.push_back(std::string(static_cast<char*>(msg.data()), msg.size()));
// DLOG(INFO) << std::string(static_cast<char*>(msg.data()), msg.size()) << std::endl;
more = msg.more();
} while(more);
return frames;
}
template<typename T>
T NonBlockingRecv() {
T frames;
zmq::message_t msg(0);
bool more=false;
do {
if (!socket_.recv(&msg, ZMQ_DONTWAIT)) throw zqrpc::RetryException();
frames.push_back(std::string(static_cast<char*>(msg.data()), msg.size()));
more = msg.more();
} while(more);
return frames;
}
bool Poll(long timeout) {
zmq::pollitem_t items[] = { { socket_, 0, ZMQ_POLLIN, 0 } };
zmq::poll (&items[0], 1, timeout);
return (items[0].revents & ZMQ_POLLIN);
// DLOG(INFO) << "Polling End" << std::endl;
}
private:
zmq::socket_t socket_;
ZSocket(const ZSocket&);
void operator=(const ZSocket&);
};
} // namespace
#endif
<|endoftext|>
|
<commit_before>#include "types_mapping.hpp"
#include "classificator.hpp"
#include "../base/string_utils.hpp"
#include "../base/stl_add.hpp"
void IndexAndTypeMapping::Load(istream & s)
{
Classificator const & c = classif();
string v;
vector<string> path;
uint32_t ind = 0;
while (s.good())
{
v.clear();
s >> v;
if (!v.empty())
{
path.clear();
strings::Tokenize(v, "|", MakeBackInsertFunctor(path));
Add(ind++, c.GetTypeByPath(path));
}
}
}
void IndexAndTypeMapping::Add(uint32_t ind, uint32_t type)
{
ASSERT_EQUAL ( ind, m_types.size(), () );
m_types.push_back(type);
m_map.insert(make_pair(type, ind));
}
uint32_t IndexAndTypeMapping::GetIndex(uint32_t t) const
{
MapT::const_iterator i = m_map.find(t);
CHECK ( i != m_map.end(), (t, classif().GetFullObjectName(t)) );
return i->second;
}
<commit_msg>readded check for duplicate style names<commit_after>#include "types_mapping.hpp"
#include "classificator.hpp"
#include "../base/string_utils.hpp"
#include "../base/stl_add.hpp"
void IndexAndTypeMapping::Load(istream & s)
{
Classificator const & c = classif();
string v;
vector<string> path;
uint32_t ind = 0;
while (s.good())
{
v.clear();
s >> v;
if (!v.empty())
{
path.clear();
strings::Tokenize(v, "|", MakeBackInsertFunctor(path));
Add(ind++, c.GetTypeByPath(path));
}
}
}
void IndexAndTypeMapping::Add(uint32_t ind, uint32_t type)
{
ASSERT_EQUAL ( ind, m_types.size(), () );
m_types.push_back(type);
if (!m_map.insert(make_pair(type, ind)).second)
{
string const name = classif().GetFullObjectName(type);
CHECK_EQUAL(name, "mapswithme|", ());
}
}
uint32_t IndexAndTypeMapping::GetIndex(uint32_t t) const
{
MapT::const_iterator i = m_map.find(t);
CHECK ( i != m_map.end(), (t, classif().GetFullObjectName(t)) );
return i->second;
}
<|endoftext|>
|
<commit_before>/**
* @file lltoast.cpp
* @brief This class implements a placeholder for any notification panel.
*
* $LicenseInfo:firstyear=2000&license=viewergpl$
*
* Copyright (c) 2000-2009, Linden Research, Inc.
*
* Second Life Viewer Source Code
* The source code in this file ("Source Code") is provided by Linden Lab
* to you under the terms of the GNU General Public License, version 2.0
* ("GPL"), unless you have obtained a separate licensing agreement
* ("Other License"), formally executed by you and Linden Lab. Terms of
* the GPL can be found in doc/GPL-license.txt in this distribution, or
* online at http://secondlifegrid.net/programs/open_source/licensing/gplv2
*
* There are special exceptions to the terms and conditions of the GPL as
* it is applied to this Source Code. View the full text of the exception
* in the file doc/FLOSS-exception.txt in this software distribution, or
* online at
* http://secondlifegrid.net/programs/open_source/licensing/flossexception
*
* By copying, modifying or distributing this software, you acknowledge
* that you have read and understood your obligations described above,
* and agree to abide by those obligations.
*
* ALL LINDEN LAB SOURCE CODE IS PROVIDED "AS IS." LINDEN LAB MAKES NO
* WARRANTIES, EXPRESS, IMPLIED OR OTHERWISE, REGARDING ITS ACCURACY,
* COMPLETENESS OR PERFORMANCE.
* $/LicenseInfo$
*/
#include "llviewerprecompiledheaders.h" // must be first include
#include "lltoast.h"
#include "llbutton.h"
#include "llfocusmgr.h"
#include "llnotifications.h"
#include "llviewercontrol.h"
using namespace LLNotificationsUI;
//--------------------------------------------------------------------------
LLToast::Params::Params()
: can_fade("can_fade", true),
can_be_stored("can_be_stored", true),
is_modal("is_modal", false),
is_tip("is_tip", false),
enable_hide_btn("enable_hide_btn", true),
force_show("force_show", false),
force_store("force_store", false),
fading_time_secs("fading_time_secs", gSavedSettings.getS32("ToastFadingTime")),
lifetime_secs("lifetime_secs", gSavedSettings.getS32("NotificationToastLifeTime"))
{};
LLToast::LLToast(const LLToast::Params& p)
: LLModalDialog(LLSD(), p.is_modal),
mPanel(p.panel),
mToastLifetime(p.lifetime_secs),
mToastFadingTime(p.fading_time_secs),
mNotificationID(p.notif_id),
mSessionID(p.session_id),
mCanFade(p.can_fade),
mCanBeStored(p.can_be_stored),
mHideBtnEnabled(p.enable_hide_btn),
mHideBtn(NULL),
mNotification(p.notification),
mIsHidden(false),
mHideBtnPressed(false),
mIsTip(p.is_tip)
{
LLUICtrlFactory::getInstance()->buildFloater(this, "panel_toast.xml", NULL);
setCanDrag(FALSE);
if(mPanel)
{
insertPanel(mPanel);
}
if(mHideBtnEnabled)
{
mHideBtn = getChild<LLButton>("hide_btn");
mHideBtn->setClickedCallback(boost::bind(&LLToast::hide,this));
}
// init callbacks if present
if(!p.on_delete_toast().empty())
mOnDeleteToastSignal.connect(p.on_delete_toast());
if(!p.on_mouse_enter().empty())
mOnMouseEnterSignal.connect(p.on_mouse_enter());
}
//--------------------------------------------------------------------------
BOOL LLToast::postBuild()
{
if(!mCanFade)
{
mTimer.stop();
}
if (mIsTip)
{
mTextEditor = mPanel->getChild<LLTextEditor>("text_editor_box");
if (mTextEditor)
{
mTextEditor->setMouseUpCallback(boost::bind(&LLToast::hide,this));
mPanel->setMouseUpCallback(boost::bind(&LLToast::handleTipToastClick, this, _2, _3, _4));
}
}
return TRUE;
}
//--------------------------------------------------------------------------
void LLToast::handleTipToastClick(S32 x, S32 y, MASK mask)
{
if (!mTextEditor->getRect().pointInRect(x, y))
{
hide();
}
}
//--------------------------------------------------------------------------
void LLToast::setHideButtonEnabled(bool enabled)
{
if(mHideBtn)
mHideBtn->setEnabled(enabled);
}
//--------------------------------------------------------------------------
LLToast::~LLToast()
{
mOnToastDestroyedSignal(this);
}
//--------------------------------------------------------------------------
void LLToast::setAndStartTimer(F32 period)
{
if(mCanFade)
{
mToastLifetime = period;
mTimer.start();
}
}
//--------------------------------------------------------------------------
bool LLToast::lifetimeHasExpired()
{
if (mTimer.getStarted())
{
F32 elapsed_time = mTimer.getElapsedTimeF32();
if ((mToastLifetime - elapsed_time) <= mToastFadingTime)
{
setBackgroundOpaque(FALSE);
}
if (elapsed_time > mToastLifetime)
{
return true;
}
}
return false;
}
//--------------------------------------------------------------------------
void LLToast::hide()
{
setVisible(FALSE);
mTimer.stop();
mIsHidden = true;
mOnFadeSignal(this);
}
//--------------------------------------------------------------------------
void LLToast::setCanFade(bool can_fade)
{
mCanFade = can_fade;
if(!mCanFade)
mTimer.stop();
}
//--------------------------------------------------------------------------
void LLToast::tick()
{
if(mCanFade)
{
hide();
}
}
//--------------------------------------------------------------------------
void LLToast::reshapeToPanel()
{
LLPanel* panel = getPanel();
if(!panel)
return;
LLRect panel_rect;
panel_rect = panel->getRect();
reshape(panel_rect.getWidth(), panel_rect.getHeight());
panel_rect.setLeftTopAndSize(0, panel_rect.getHeight(), panel_rect.getWidth(), panel_rect.getHeight());
panel->setRect(panel_rect);
LLRect toast_rect = getRect();
toast_rect.setLeftTopAndSize(toast_rect.mLeft,toast_rect.mTop,panel_rect.getWidth(), panel_rect.getHeight());
setRect(toast_rect);
}
void LLToast::insertPanel(LLPanel* panel)
{
addChild(panel);
reshapeToPanel();
}
//--------------------------------------------------------------------------
void LLToast::draw()
{
if(lifetimeHasExpired())
{
tick();
}
LLFloater::draw();
}
//--------------------------------------------------------------------------
void LLToast::setVisible(BOOL show)
{
if(mIsHidden)
{
// this toast is invisible after fade until its ScreenChannel will allow it
//
// (EXT-1849) according to this bug a toast can be resurrected from
// invisible state if it faded during a teleportation
// then it fades a second time and causes a crash
return;
}
if(show)
{
setBackgroundOpaque(TRUE);
if(!mTimer.getStarted() && mCanFade)
{
mTimer.start();
}
LLModalDialog::setFrontmost(FALSE);
}
LLFloater::setVisible(show);
if(mPanel)
{
if(!mPanel->isDead())
{
mPanel->setVisible(show);
}
}
}
//--------------------------------------------------------------------------
void LLToast::onMouseEnter(S32 x, S32 y, MASK mask)
{
mOnToastHoverSignal(this, MOUSE_ENTER);
//toasts fading is management by Screen Channel
sendChildToFront(mHideBtn);
if(mHideBtn && mHideBtn->getEnabled())
mHideBtn->setVisible(TRUE);
mOnMouseEnterSignal(this);
LLModalDialog::onMouseEnter(x, y, mask);
}
//--------------------------------------------------------------------------
void LLToast::onMouseLeave(S32 x, S32 y, MASK mask)
{
mOnToastHoverSignal(this, MOUSE_LEAVE);
//toasts fading is management by Screen Channel
if(mHideBtn && mHideBtn->getEnabled())
{
if( mHideBtnPressed )
{
mHideBtnPressed = false;
return;
}
mHideBtn->setVisible(FALSE);
}
LLModalDialog::onMouseLeave(x, y, mask);
}
void LLNotificationsUI::LLToast::stopFading()
{
if(mCanFade)
{
stopTimer();
}
}
void LLNotificationsUI::LLToast::startFading()
{
if(mCanFade)
{
resetTimer();
}
}
//--------------------------------------------------------------------------
BOOL LLToast::handleMouseDown(S32 x, S32 y, MASK mask)
{
if(mHideBtn && mHideBtn->getEnabled())
{
mHideBtnPressed = mHideBtn->getRect().pointInRect(x, y);
}
return LLFloater::handleMouseDown(x, y, mask);
}
//--------------------------------------------------------------------------
bool LLToast::isNotificationValid()
{
if(mNotification)
{
return !mNotification->isCancelled();
}
return false;
}
//--------------------------------------------------------------------------
<commit_msg>fixed EXT-3374 “[BSI] Notifications and dialogs are semi-transparent (not opaque) even when in focus”, made toast opaque when became hovered;<commit_after>/**
* @file lltoast.cpp
* @brief This class implements a placeholder for any notification panel.
*
* $LicenseInfo:firstyear=2000&license=viewergpl$
*
* Copyright (c) 2000-2009, Linden Research, Inc.
*
* Second Life Viewer Source Code
* The source code in this file ("Source Code") is provided by Linden Lab
* to you under the terms of the GNU General Public License, version 2.0
* ("GPL"), unless you have obtained a separate licensing agreement
* ("Other License"), formally executed by you and Linden Lab. Terms of
* the GPL can be found in doc/GPL-license.txt in this distribution, or
* online at http://secondlifegrid.net/programs/open_source/licensing/gplv2
*
* There are special exceptions to the terms and conditions of the GPL as
* it is applied to this Source Code. View the full text of the exception
* in the file doc/FLOSS-exception.txt in this software distribution, or
* online at
* http://secondlifegrid.net/programs/open_source/licensing/flossexception
*
* By copying, modifying or distributing this software, you acknowledge
* that you have read and understood your obligations described above,
* and agree to abide by those obligations.
*
* ALL LINDEN LAB SOURCE CODE IS PROVIDED "AS IS." LINDEN LAB MAKES NO
* WARRANTIES, EXPRESS, IMPLIED OR OTHERWISE, REGARDING ITS ACCURACY,
* COMPLETENESS OR PERFORMANCE.
* $/LicenseInfo$
*/
#include "llviewerprecompiledheaders.h" // must be first include
#include "lltoast.h"
#include "llbutton.h"
#include "llfocusmgr.h"
#include "llnotifications.h"
#include "llviewercontrol.h"
using namespace LLNotificationsUI;
//--------------------------------------------------------------------------
LLToast::Params::Params()
: can_fade("can_fade", true),
can_be_stored("can_be_stored", true),
is_modal("is_modal", false),
is_tip("is_tip", false),
enable_hide_btn("enable_hide_btn", true),
force_show("force_show", false),
force_store("force_store", false),
fading_time_secs("fading_time_secs", gSavedSettings.getS32("ToastFadingTime")),
lifetime_secs("lifetime_secs", gSavedSettings.getS32("NotificationToastLifeTime"))
{};
LLToast::LLToast(const LLToast::Params& p)
: LLModalDialog(LLSD(), p.is_modal),
mPanel(p.panel),
mToastLifetime(p.lifetime_secs),
mToastFadingTime(p.fading_time_secs),
mNotificationID(p.notif_id),
mSessionID(p.session_id),
mCanFade(p.can_fade),
mCanBeStored(p.can_be_stored),
mHideBtnEnabled(p.enable_hide_btn),
mHideBtn(NULL),
mNotification(p.notification),
mIsHidden(false),
mHideBtnPressed(false),
mIsTip(p.is_tip)
{
LLUICtrlFactory::getInstance()->buildFloater(this, "panel_toast.xml", NULL);
setCanDrag(FALSE);
if(mPanel)
{
insertPanel(mPanel);
}
if(mHideBtnEnabled)
{
mHideBtn = getChild<LLButton>("hide_btn");
mHideBtn->setClickedCallback(boost::bind(&LLToast::hide,this));
}
// init callbacks if present
if(!p.on_delete_toast().empty())
mOnDeleteToastSignal.connect(p.on_delete_toast());
if(!p.on_mouse_enter().empty())
mOnMouseEnterSignal.connect(p.on_mouse_enter());
}
//--------------------------------------------------------------------------
BOOL LLToast::postBuild()
{
if(!mCanFade)
{
mTimer.stop();
}
if (mIsTip)
{
mTextEditor = mPanel->getChild<LLTextEditor>("text_editor_box");
if (mTextEditor)
{
mTextEditor->setMouseUpCallback(boost::bind(&LLToast::hide,this));
mPanel->setMouseUpCallback(boost::bind(&LLToast::handleTipToastClick, this, _2, _3, _4));
}
}
return TRUE;
}
//--------------------------------------------------------------------------
void LLToast::handleTipToastClick(S32 x, S32 y, MASK mask)
{
if (!mTextEditor->getRect().pointInRect(x, y))
{
hide();
}
}
//--------------------------------------------------------------------------
void LLToast::setHideButtonEnabled(bool enabled)
{
if(mHideBtn)
mHideBtn->setEnabled(enabled);
}
//--------------------------------------------------------------------------
LLToast::~LLToast()
{
mOnToastDestroyedSignal(this);
}
//--------------------------------------------------------------------------
void LLToast::setAndStartTimer(F32 period)
{
if(mCanFade)
{
mToastLifetime = period;
mTimer.start();
}
}
//--------------------------------------------------------------------------
bool LLToast::lifetimeHasExpired()
{
if (mTimer.getStarted())
{
F32 elapsed_time = mTimer.getElapsedTimeF32();
if ((mToastLifetime - elapsed_time) <= mToastFadingTime)
{
setBackgroundOpaque(FALSE);
}
if (elapsed_time > mToastLifetime)
{
return true;
}
}
return false;
}
//--------------------------------------------------------------------------
void LLToast::hide()
{
setVisible(FALSE);
mTimer.stop();
mIsHidden = true;
mOnFadeSignal(this);
}
//--------------------------------------------------------------------------
void LLToast::setCanFade(bool can_fade)
{
mCanFade = can_fade;
if(!mCanFade)
mTimer.stop();
}
//--------------------------------------------------------------------------
void LLToast::tick()
{
if(mCanFade)
{
hide();
}
}
//--------------------------------------------------------------------------
void LLToast::reshapeToPanel()
{
LLPanel* panel = getPanel();
if(!panel)
return;
LLRect panel_rect;
panel_rect = panel->getRect();
reshape(panel_rect.getWidth(), panel_rect.getHeight());
panel_rect.setLeftTopAndSize(0, panel_rect.getHeight(), panel_rect.getWidth(), panel_rect.getHeight());
panel->setRect(panel_rect);
LLRect toast_rect = getRect();
toast_rect.setLeftTopAndSize(toast_rect.mLeft,toast_rect.mTop,panel_rect.getWidth(), panel_rect.getHeight());
setRect(toast_rect);
}
void LLToast::insertPanel(LLPanel* panel)
{
addChild(panel);
reshapeToPanel();
}
//--------------------------------------------------------------------------
void LLToast::draw()
{
if(lifetimeHasExpired())
{
tick();
}
LLFloater::draw();
}
//--------------------------------------------------------------------------
void LLToast::setVisible(BOOL show)
{
if(mIsHidden)
{
// this toast is invisible after fade until its ScreenChannel will allow it
//
// (EXT-1849) according to this bug a toast can be resurrected from
// invisible state if it faded during a teleportation
// then it fades a second time and causes a crash
return;
}
if(show)
{
setBackgroundOpaque(TRUE);
if(!mTimer.getStarted() && mCanFade)
{
mTimer.start();
}
LLModalDialog::setFrontmost(FALSE);
}
LLFloater::setVisible(show);
if(mPanel)
{
if(!mPanel->isDead())
{
mPanel->setVisible(show);
}
}
}
//--------------------------------------------------------------------------
void LLToast::onMouseEnter(S32 x, S32 y, MASK mask)
{
mOnToastHoverSignal(this, MOUSE_ENTER);
setBackgroundOpaque(TRUE);
//toasts fading is management by Screen Channel
sendChildToFront(mHideBtn);
if(mHideBtn && mHideBtn->getEnabled())
mHideBtn->setVisible(TRUE);
mOnMouseEnterSignal(this);
LLModalDialog::onMouseEnter(x, y, mask);
}
//--------------------------------------------------------------------------
void LLToast::onMouseLeave(S32 x, S32 y, MASK mask)
{
mOnToastHoverSignal(this, MOUSE_LEAVE);
//toasts fading is management by Screen Channel
if(mHideBtn && mHideBtn->getEnabled())
{
if( mHideBtnPressed )
{
mHideBtnPressed = false;
return;
}
mHideBtn->setVisible(FALSE);
}
LLModalDialog::onMouseLeave(x, y, mask);
}
void LLNotificationsUI::LLToast::stopFading()
{
if(mCanFade)
{
stopTimer();
}
}
void LLNotificationsUI::LLToast::startFading()
{
if(mCanFade)
{
resetTimer();
}
}
//--------------------------------------------------------------------------
BOOL LLToast::handleMouseDown(S32 x, S32 y, MASK mask)
{
if(mHideBtn && mHideBtn->getEnabled())
{
mHideBtnPressed = mHideBtn->getRect().pointInRect(x, y);
}
return LLFloater::handleMouseDown(x, y, mask);
}
//--------------------------------------------------------------------------
bool LLToast::isNotificationValid()
{
if(mNotification)
{
return !mNotification->isCancelled();
}
return false;
}
//--------------------------------------------------------------------------
<|endoftext|>
|
<commit_before>/*
* Copyright 2013-2016 Christian Lockley
*
* 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 "watchdogd.hpp"
#include "sub.hpp"
#include "init.hpp"
#include "pidfile.hpp"
#include "daemon.hpp"
#include "logutils.hpp"
int Daemonize(struct cfgoptions *const s)
{
assert(s != NULL);
if (s == NULL) {
return -1;
}
if (IsDaemon(s) == 0) { //shall we daemonize?
return 0;
}
kill(getppid(), SIGUSR1);
SetLogTarget(SYSTEM_LOG);
return 0;
}
<commit_msg>change log level before daemonizing<commit_after>/*
* Copyright 2013-2016 Christian Lockley
*
* 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 "watchdogd.hpp"
#include "sub.hpp"
#include "init.hpp"
#include "pidfile.hpp"
#include "daemon.hpp"
#include "logutils.hpp"
int Daemonize(struct cfgoptions *const s)
{
assert(s != NULL);
if (s == NULL) {
return -1;
}
if (IsDaemon(s) == 0) { //shall we daemonize?
return 0;
}
SetLogTarget(SYSTEM_LOG);
kill(getppid(), SIGUSR1);
return 0;
}
<|endoftext|>
|
<commit_before>/*=========================================================================
Program: ORFEO Toolbox
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) Centre National d'Etudes Spatiales. All rights reserved.
See OTBCopyright.txt for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notices for more information.
=========================================================================*/
#include "otbWrapperQtWidgetView.h"
#include "otbWrapperQtWidgetParameterGroup.h"
#include "otbWrapperQtWidgetParameterFactory.h"
#include "otbWrapperQtWidgetProgressReport.h"
#include "otbWrapperOutputImageParameter.h"
#include "otbWrapperParameterGroup.h"
#include "otbWrapperQtWidgetSimpleProgressReport.h"
#include "itksys/SystemTools.hxx"
namespace otb
{
namespace Wrapper
{
QtWidgetView::QtWidgetView(Application* app)
{
m_Model = new QtWidgetModel(app);
m_Application = app;
}
QtWidgetView::~QtWidgetView()
{
}
void QtWidgetView::CreateGui()
{
// Create a VBoxLayout with the header, the input widgets, and the footer
QVBoxLayout *mainLayout = new QVBoxLayout();
QTabWidget *tab = new QTabWidget();
tab->addTab(CreateInputWidgets(), "Parameters");
QTextEdit *log = new QTextEdit();
connect( m_Model->GetLogOutput(), SIGNAL(NewContentLog(QString)), log, SLOT(append(QString) ) );
tab->addTab(log, "Logs");
QtWidgetProgressReport* prog = new QtWidgetProgressReport(m_Model);
prog->SetApplication(m_Application);
tab->addTab(prog, "Progress");
tab->addTab(CreateDoc(), "Documentation");
mainLayout->addWidget(tab);
m_Message = new QLabel("<center><font color=\"#FF0000\">Select parameters</font></center>");
connect( m_Model, SIGNAL(SetApplicationReady(bool)), this, SLOT(UpdateMessageAfterApplicationReady(bool)) );
mainLayout->addWidget(m_Message);
QtWidgetSimpleProgressReport * progressReport = new QtWidgetSimpleProgressReport(m_Model);
progressReport->SetApplication(m_Application);
QHBoxLayout *footLayout = new QHBoxLayout;
footLayout->addWidget(progressReport);
footLayout->addWidget(CreateFooter());
mainLayout->addLayout(footLayout);
QGroupBox *mainGroup = new QGroupBox();
mainGroup->setLayout(mainLayout);
QVBoxLayout *finalLayout = new QVBoxLayout();
finalLayout->addWidget(mainGroup);
// Make the final layout to the widget
this->setLayout(finalLayout);
}
void QtWidgetView::UpdateMessageAfterExcuteClicked()
{
m_Message->setText("<center><font color=\"#FF0000\">Running</font></center>");
}
void QtWidgetView::UpdateMessageAfterApplicationReady( bool val )
{
if(val == true)
m_Message->setText("<center><font color=\"#00FF00\">Ready to run</font></center>");
else
m_Message->setText("<center><font color=\"#FF0000\">Select parameters</font></center>");
}
QWidget* QtWidgetView::CreateInputWidgets()
{
QScrollArea *scrollArea = new QScrollArea;
// Put the main group inside a scroll area
scrollArea->setWidget(QtWidgetParameterFactory::CreateQtWidget(m_Model->GetApplication()->GetParameterList(), m_Model));
scrollArea->setHorizontalScrollBarPolicy(Qt::ScrollBarAsNeeded);
scrollArea->setVerticalScrollBarPolicy(Qt::ScrollBarAsNeeded);
scrollArea->setWidgetResizable(true);
return scrollArea;
}
QWidget* QtWidgetView::CreateFooter()
{
// an HLayout with two buttons : Execute and Quit
QGroupBox *footerGroup = new QGroupBox;
QHBoxLayout *footerLayout = new QHBoxLayout;
footerGroup->setFixedHeight(40);
footerGroup->setContentsMargins(0, 0, 0, 0);
footerLayout->setContentsMargins(5, 5, 5, 5);
m_ExecButton = new QPushButton(footerGroup);
m_ExecButton->setDefault(true);
m_ExecButton->setEnabled(false);
m_ExecButton->setText(QObject::tr("Execute"));
connect( m_ExecButton, SIGNAL(clicked()), m_Model, SLOT(ExecuteAndWriteOutputSlot() ) );
connect( m_Model, SIGNAL(SetApplicationReady(bool)), m_ExecButton, SLOT(setEnabled(bool)) );
connect( m_ExecButton, SIGNAL(clicked()), this, SLOT(UpdateMessageAfterExcuteClicked() ) );
m_QuitButton = new QPushButton(footerGroup);
m_QuitButton->setText(QObject::tr("Quit"));
connect( m_QuitButton, SIGNAL(clicked()), this, SLOT(CloseSlot()) );
// Put the buttons on the right
footerLayout->addStretch();
footerLayout->addWidget(m_ExecButton);
footerLayout->addWidget(m_QuitButton);
footerGroup->setLayout(footerLayout);
return footerGroup;
}
QWidget* QtWidgetView::CreateDoc()
{
QTextEdit *text = new QTextEdit;
text->setReadOnly(true);
QTextDocument * doc = new QTextDocument();
itk::OStringStream oss;
oss << "<center><h2>" << m_Application->GetDocName() << "</center></h2>";
oss << "<h3>Brief Description</h3>";
oss << "<body>" << m_Application->GetDescription() << "</body>";
oss << "<h3>Tags</h3>";
oss << "<body>";
if (m_Application->GetDocTags().size() > 0)
{
for (unsigned int i = 0; i < m_Application->GetDocTags().size() - 1; i++)
{
oss << m_Application->GetDocTags()[i] << ", ";
;
}
oss << m_Application->GetDocTags()[m_Application->GetDocTags().size() - 1];
}
oss << "</body>";
oss << "<h3>Long Description</h3>";
oss << "<body>" << m_Application->GetDocLongDescription() << "</body>";
std::string val;
this->SetDocParameters(val);
oss << val;
oss << "<h3>Limitations</h3>";
oss << "<body>" << m_Application->GetDocLimitations() << "</body>";
oss << "<h3>Authors</h3>";
oss << "<body>" << m_Application->GetDocAuthors() << "</body>";
oss << "<h3>See also</h3>";
oss << "<body>" << m_Application->GetDocSeeAlso() << "</body>";
oss << "<h3>Command line example</h3>";
oss << "<code>" << m_Application->GetDocCLExample() << "</code>";
doc->setHtml(oss.str().c_str());
text->setDocument(doc);
//std::cout<<text->toHtml().toStdString()<<std::endl;
return text;
}
void QtWidgetView::SetDocParameters( std::string & val )
{
const std::vector<std::string> appKeyList = m_Application->GetParametersKeys( false );
const unsigned int nbOfParam = appKeyList.size();
itk::OStringStream oss;
oss << "<h3>Parameters</h3>";
// Mandatory parameters
oss << "<h4>Mandatory parameters</h4>";
std::string paramDocs("");
this->GetDocParameters( paramDocs, true );
oss<<paramDocs;
paramDocs ="";
// Optional parameters
oss << "<h4>Optional parameters</h4>";
oss << "<body><li>";
this->GetDocParameters( paramDocs, false );
oss<<paramDocs;
val.append(oss.str());
}
void QtWidgetView::GetDocParameters( std::string & val, bool mandatory)
{
itk::OStringStream oss;
const std::vector<std::string> appKeyList = m_Application->GetParametersKeys( false );
const unsigned int nbOfParam = appKeyList.size();
std::string paramDocs("");
for( unsigned int i=0; i<nbOfParam; i++ )
{
const std::string key(appKeyList[i]);
Parameter::Pointer param = m_Application->GetParameterByKey( key );
if( param->GetMandatory() == mandatory )
{
if( m_Application->GetParameterType(key) != ParameterType_Group )
{
oss << "<i>" << param->GetName() << ":</i><br />";
oss << param->GetDescription()<< "<br />";
oss << "<br />";
}
else
{
oss << "<b><i>=== "<<param->GetName()<<"</i></b> ("<<param->GetDescription()<<"):<br />";
std::string grDoc;
GetDocParameterGroup( grDoc, key, 1);
oss<<grDoc;
}
}
}
if( oss.str() == "" )
oss << "None";
val = oss.str();
}
void QtWidgetView::GetDocParameterGroup( std::string & val, const std::string & key, int level )
{
std::string spaces, equals;
for(unsigned int i=0; i<level; i++)
{
spaces.append(" ");
equals.append("===");
}
equals.append("===");
Parameter * paramGr = m_Application->GetParameterByKey( key );
if( !dynamic_cast<ParameterGroup *>(paramGr) )
{
itkGenericExceptionMacro("Invlaid parameter type for key "<<key<<", wait for ParameterGroup...");
}
ParameterGroup * group = dynamic_cast<ParameterGroup *>(paramGr);
const std::vector<std::string> appKeyList = group->GetParametersKeys( false );
unsigned int nbOfParam = appKeyList.size();
itk::OStringStream oss;
for( unsigned int i=0; i<nbOfParam; i++ )
{
const std::string fullKey(std::string(key).append(".").append(appKeyList[i]));
Parameter::Pointer param = m_Application->GetParameterByKey( fullKey );
if( m_Application->GetParameterType(fullKey) != ParameterType_Group )
{
oss << "<i>" << spaces << param->GetName()<< ":</i><br />";
oss << spaces << param->GetDescription()<<"<br>";
oss << "<br />";
}
else
{
oss << "<b><i>" << equals << param->GetName()<<"</i></b> ("<<param->GetDescription()<<")<br />";
std::string grDoc;
GetDocParameterGroup( grDoc, fullKey, level+1);
oss<<grDoc;
}
}
val.append(oss.str());
}
void QtWidgetView::CloseSlot()
{
// Close the widget
this->close();
// Emit a signal to close any widget that this gui belonging to
emit QuitSignal();
}
}
}
<commit_msg>WRG: remove warning.<commit_after>/*=========================================================================
Program: ORFEO Toolbox
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) Centre National d'Etudes Spatiales. All rights reserved.
See OTBCopyright.txt for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notices for more information.
=========================================================================*/
#include "otbWrapperQtWidgetView.h"
#include "otbWrapperQtWidgetParameterGroup.h"
#include "otbWrapperQtWidgetParameterFactory.h"
#include "otbWrapperQtWidgetProgressReport.h"
#include "otbWrapperOutputImageParameter.h"
#include "otbWrapperParameterGroup.h"
#include "otbWrapperQtWidgetSimpleProgressReport.h"
#include "itksys/SystemTools.hxx"
namespace otb
{
namespace Wrapper
{
QtWidgetView::QtWidgetView(Application* app)
{
m_Model = new QtWidgetModel(app);
m_Application = app;
}
QtWidgetView::~QtWidgetView()
{
}
void QtWidgetView::CreateGui()
{
// Create a VBoxLayout with the header, the input widgets, and the footer
QVBoxLayout *mainLayout = new QVBoxLayout();
QTabWidget *tab = new QTabWidget();
tab->addTab(CreateInputWidgets(), "Parameters");
QTextEdit *log = new QTextEdit();
connect( m_Model->GetLogOutput(), SIGNAL(NewContentLog(QString)), log, SLOT(append(QString) ) );
tab->addTab(log, "Logs");
QtWidgetProgressReport* prog = new QtWidgetProgressReport(m_Model);
prog->SetApplication(m_Application);
tab->addTab(prog, "Progress");
tab->addTab(CreateDoc(), "Documentation");
mainLayout->addWidget(tab);
m_Message = new QLabel("<center><font color=\"#FF0000\">Select parameters</font></center>");
connect( m_Model, SIGNAL(SetApplicationReady(bool)), this, SLOT(UpdateMessageAfterApplicationReady(bool)) );
mainLayout->addWidget(m_Message);
QtWidgetSimpleProgressReport * progressReport = new QtWidgetSimpleProgressReport(m_Model);
progressReport->SetApplication(m_Application);
QHBoxLayout *footLayout = new QHBoxLayout;
footLayout->addWidget(progressReport);
footLayout->addWidget(CreateFooter());
mainLayout->addLayout(footLayout);
QGroupBox *mainGroup = new QGroupBox();
mainGroup->setLayout(mainLayout);
QVBoxLayout *finalLayout = new QVBoxLayout();
finalLayout->addWidget(mainGroup);
// Make the final layout to the widget
this->setLayout(finalLayout);
}
void QtWidgetView::UpdateMessageAfterExcuteClicked()
{
m_Message->setText("<center><font color=\"#FF0000\">Running</font></center>");
}
void QtWidgetView::UpdateMessageAfterApplicationReady( bool val )
{
if(val == true)
m_Message->setText("<center><font color=\"#00FF00\">Ready to run</font></center>");
else
m_Message->setText("<center><font color=\"#FF0000\">Select parameters</font></center>");
}
QWidget* QtWidgetView::CreateInputWidgets()
{
QScrollArea *scrollArea = new QScrollArea;
// Put the main group inside a scroll area
scrollArea->setWidget(QtWidgetParameterFactory::CreateQtWidget(m_Model->GetApplication()->GetParameterList(), m_Model));
scrollArea->setHorizontalScrollBarPolicy(Qt::ScrollBarAsNeeded);
scrollArea->setVerticalScrollBarPolicy(Qt::ScrollBarAsNeeded);
scrollArea->setWidgetResizable(true);
return scrollArea;
}
QWidget* QtWidgetView::CreateFooter()
{
// an HLayout with two buttons : Execute and Quit
QGroupBox *footerGroup = new QGroupBox;
QHBoxLayout *footerLayout = new QHBoxLayout;
footerGroup->setFixedHeight(40);
footerGroup->setContentsMargins(0, 0, 0, 0);
footerLayout->setContentsMargins(5, 5, 5, 5);
m_ExecButton = new QPushButton(footerGroup);
m_ExecButton->setDefault(true);
m_ExecButton->setEnabled(false);
m_ExecButton->setText(QObject::tr("Execute"));
connect( m_ExecButton, SIGNAL(clicked()), m_Model, SLOT(ExecuteAndWriteOutputSlot() ) );
connect( m_Model, SIGNAL(SetApplicationReady(bool)), m_ExecButton, SLOT(setEnabled(bool)) );
connect( m_ExecButton, SIGNAL(clicked()), this, SLOT(UpdateMessageAfterExcuteClicked() ) );
m_QuitButton = new QPushButton(footerGroup);
m_QuitButton->setText(QObject::tr("Quit"));
connect( m_QuitButton, SIGNAL(clicked()), this, SLOT(CloseSlot()) );
// Put the buttons on the right
footerLayout->addStretch();
footerLayout->addWidget(m_ExecButton);
footerLayout->addWidget(m_QuitButton);
footerGroup->setLayout(footerLayout);
return footerGroup;
}
QWidget* QtWidgetView::CreateDoc()
{
QTextEdit *text = new QTextEdit;
text->setReadOnly(true);
QTextDocument * doc = new QTextDocument();
itk::OStringStream oss;
oss << "<center><h2>" << m_Application->GetDocName() << "</center></h2>";
oss << "<h3>Brief Description</h3>";
oss << "<body>" << m_Application->GetDescription() << "</body>";
oss << "<h3>Tags</h3>";
oss << "<body>";
if (m_Application->GetDocTags().size() > 0)
{
for (unsigned int i = 0; i < m_Application->GetDocTags().size() - 1; i++)
{
oss << m_Application->GetDocTags()[i] << ", ";
;
}
oss << m_Application->GetDocTags()[m_Application->GetDocTags().size() - 1];
}
oss << "</body>";
oss << "<h3>Long Description</h3>";
oss << "<body>" << m_Application->GetDocLongDescription() << "</body>";
std::string val;
this->SetDocParameters(val);
oss << val;
oss << "<h3>Limitations</h3>";
oss << "<body>" << m_Application->GetDocLimitations() << "</body>";
oss << "<h3>Authors</h3>";
oss << "<body>" << m_Application->GetDocAuthors() << "</body>";
oss << "<h3>See also</h3>";
oss << "<body>" << m_Application->GetDocSeeAlso() << "</body>";
oss << "<h3>Command line example</h3>";
oss << "<code>" << m_Application->GetDocCLExample() << "</code>";
doc->setHtml(oss.str().c_str());
text->setDocument(doc);
//std::cout<<text->toHtml().toStdString()<<std::endl;
return text;
}
void QtWidgetView::SetDocParameters( std::string & val )
{
const std::vector<std::string> appKeyList = m_Application->GetParametersKeys( false );
const unsigned int nbOfParam = appKeyList.size();
itk::OStringStream oss;
oss << "<h3>Parameters</h3>";
// Mandatory parameters
oss << "<h4>Mandatory parameters</h4>";
std::string paramDocs("");
this->GetDocParameters( paramDocs, true );
oss<<paramDocs;
paramDocs ="";
// Optional parameters
oss << "<h4>Optional parameters</h4>";
oss << "<body><li>";
this->GetDocParameters( paramDocs, false );
oss<<paramDocs;
val.append(oss.str());
}
void QtWidgetView::GetDocParameters( std::string & val, bool mandatory)
{
itk::OStringStream oss;
const std::vector<std::string> appKeyList = m_Application->GetParametersKeys( false );
const unsigned int nbOfParam = appKeyList.size();
std::string paramDocs("");
for( unsigned int i=0; i<nbOfParam; i++ )
{
const std::string key(appKeyList[i]);
Parameter::Pointer param = m_Application->GetParameterByKey( key );
if( param->GetMandatory() == mandatory )
{
if( m_Application->GetParameterType(key) != ParameterType_Group )
{
oss << "<i>" << param->GetName() << ":</i><br />";
oss << param->GetDescription()<< "<br />";
oss << "<br />";
}
else
{
oss << "<b><i>=== "<<param->GetName()<<"</i></b> ("<<param->GetDescription()<<"):<br />";
std::string grDoc;
GetDocParameterGroup( grDoc, key, 1);
oss<<grDoc;
}
}
}
if( oss.str() == "" )
oss << "None";
val = oss.str();
}
void QtWidgetView::GetDocParameterGroup( std::string & val, const std::string & key, int level )
{
std::string spaces, equals;
for(int i=0; i<level; i++)
{
spaces.append(" ");
equals.append("===");
}
equals.append("===");
Parameter * paramGr = m_Application->GetParameterByKey( key );
if( !dynamic_cast<ParameterGroup *>(paramGr) )
{
itkGenericExceptionMacro("Invlaid parameter type for key "<<key<<", wait for ParameterGroup...");
}
ParameterGroup * group = dynamic_cast<ParameterGroup *>(paramGr);
const std::vector<std::string> appKeyList = group->GetParametersKeys( false );
unsigned int nbOfParam = appKeyList.size();
itk::OStringStream oss;
for( unsigned int i=0; i<nbOfParam; i++ )
{
const std::string fullKey(std::string(key).append(".").append(appKeyList[i]));
Parameter::Pointer param = m_Application->GetParameterByKey( fullKey );
if( m_Application->GetParameterType(fullKey) != ParameterType_Group )
{
oss << "<i>" << spaces << param->GetName()<< ":</i><br />";
oss << spaces << param->GetDescription()<<"<br>";
oss << "<br />";
}
else
{
oss << "<b><i>" << equals << param->GetName()<<"</i></b> ("<<param->GetDescription()<<")<br />";
std::string grDoc;
GetDocParameterGroup( grDoc, fullKey, level+1);
oss<<grDoc;
}
}
val.append(oss.str());
}
void QtWidgetView::CloseSlot()
{
// Close the widget
this->close();
// Emit a signal to close any widget that this gui belonging to
emit QuitSignal();
}
}
}
<|endoftext|>
|
<commit_before>// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
//
// This file is based on the SMSLib library.
//
// SMSLib Sudden Motion Sensor Access Library
// Copyright (c) 2010 Suitable Systems
// All rights reserved.
//
// Developed by: Daniel Griscom
// Suitable Systems
// http://www.suitable.com
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the
// "Software"), to deal with 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:
//
// - Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimers.
//
// - Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimers in the
// documentation and/or other materials provided with the distribution.
//
// - Neither the names of Suitable Systems nor the names of its
// contributors may be used to endorse or promote products derived from
// this Software without specific prior written permission.
//
// 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 CONTRIBUTORS 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 WITH THE SOFTWARE.
//
// For more information about SMSLib, see
// <http://www.suitable.com/tools/smslib.html>
// or contact
// Daniel Griscom
// Suitable Systems
// 1 Centre Street, Suite 204
// Wakefield, MA 01880
// (781) 665-0053
#include "chrome/browser/device_orientation/accelerometer_mac.h"
#include <math.h> // For isfinite.
#include <sys/sysctl.h>
#include "base/logging.h"
#include "base/scoped_ptr.h"
#include "chrome/browser/device_orientation/orientation.h"
namespace device_orientation {
struct AccelerometerMac::GenericMacbookSensor {
// Name of device to be read.
const char* service_name;
// Number of bytes of the axis data.
int axis_size;
// Default calibration value for zero g.
float zero_g;
// Default calibration value for one g (negative when axis is inverted).
float one_g;
// Kernel function index.
unsigned int function;
// Size of the sensor record to be sent/received.
unsigned int record_size;
};
struct AccelerometerMac::AxisData {
// Location of the first byte representing the axis in the sensor data.
int index;
// Axis inversion flag. The value changes often between models.
bool inverted;
};
// Sudden Motion Sensor descriptor.
struct AccelerometerMac::SensorDescriptor {
// Prefix of model to be tested.
const char* model_name;
// Axis-specific data (x,y,z order).
AxisData axis[3];
};
// Typical sensor parameters in MacBook models.
const AccelerometerMac::GenericMacbookSensor
AccelerometerMac::kGenericSensor = {
"SMCMotionSensor", 2,
0, 251,
5, 40
};
// Supported sensor descriptors. Add entries here to enhance compatibility.
// All non-tested entries from SMSLib have been removed.
const AccelerometerMac::SensorDescriptor
AccelerometerMac::kSupportedSensors[] = {
// Tested by S.Selz. (via avi) on a 13" MacBook.
{ "MacBook2,1", { { 0, true }, { 2, false }, { 4, true } } },
// Tested by avi on a 13" MacBook.
{ "MacBook7,1", { { 0, true }, { 2, true }, { 4, false } } },
// Tested by sfiera, pjw on a 13" MacBook Air.
{ "MacBookAir2,1", { { 0, true }, { 2, true }, { 4, false } } },
// Note: MacBookAir3,1 (11" MacBook Air) and MacBookAir3,2 (13" MacBook Air)
// have no accelerometer sensors.
// Not tested; data acquired by avi from L.V. from a 17" MacBook Pro.
{ "MacBookPro2,1", { { 0, true }, { 2, false }, { 4, true } } },
// Tested by leandrogracia on a 15" MacBook Pro.
{ "MacBookPro2,2", { { 0, true }, { 2, true }, { 4, false } } },
// Tested by leandrogracia on a 15" MacBook Pro.
// TODO(avi): this model name was also used for the 17" version; verify that
// these parameters are also valid for that model.
{ "MacBookPro3,1", { { 0, false }, { 2, true }, { 4, true } } },
// Tested by leandrogracia on a 15" MacBook Pro.
// TODO(avi): this model name was also used for the 17" version; verify that
// these parameters are also valid for that model.
{ "MacBookPro4,1", { { 0, true }, { 2, true }, { 4, false } } },
// Tested by leandrogracia on a 15" MacBook Pro.
{ "MacBookPro5,1", { { 0, false }, { 2, false }, { 4, false } } },
// Tested by S.Selz. (via avi) on a 15" MacBook Pro.
{ "MacBookPro5,2", { { 0, false }, { 2, false }, { 4, false } } },
// Tested by dmaclach on a 15" MacBook Pro.
{ "MacBookPro5,3", { { 2, false }, { 0, false }, { 4, true } } },
// Tested by leandrogracia on a 15" MacBook Pro.
{ "MacBookPro5,4", { { 0, false }, { 2, false }, { 4, false } } },
// Tested by leandrogracia on a 13" MacBook Pro.
{ "MacBookPro5,5", { { 0, true }, { 2, true }, { 4, false } } },
// Tested by khom, leadpipe on a 17" MacBook Pro.
{ "MacBookPro6,1", { { 0, false }, { 2, false }, { 4, false } } },
// Tested by leandrogracia on a 15" MacBook Pro.
{ "MacBookPro6,2", { { 0, true }, { 2, false }, { 4, true } } },
// Tested by leandrogracia on a 13" MacBook Pro.
{ "MacBookPro7,1", { { 0, true }, { 2, true }, { 4, false } } },
// Generic MacBook accelerometer sensor data, used for for both future models
// and past models for which there has been no testing. Note that this generic
// configuration may well have problems with inverted axes.
// TODO(avi): Find these past models and test on them; test on future models.
// MacBook1,1
// MacBook3,1
// MacBook4,1
// MacBook5,1
// MacBook5,2
// MacBook6,1
// MacBookAir1,1
// MacBookPro1,1
// MacBookPro1,2
// MacBookPro5,2
{ "", { { 0, true }, { 2, true }, { 4, false } } }
};
// Create a AccelerometerMac object and return NULL if no valid sensor found.
DataFetcher* AccelerometerMac::Create() {
scoped_ptr<AccelerometerMac> accelerometer(new AccelerometerMac);
return accelerometer->Init() ? accelerometer.release() : NULL;
}
AccelerometerMac::~AccelerometerMac() {
IOServiceClose(io_connection_);
}
AccelerometerMac::AccelerometerMac()
: sensor_(NULL),
io_connection_(0) {
}
// Retrieve per-axis accelerometer values.
//
// Axes and angles are defined according to the W3C DeviceOrientation Draft.
// See here: http://dev.w3.org/geo/api/spec-source-orientation.html
//
// Note: only beta and gamma angles are provided. Alpha is set to zero.
//
// Returns false in case of error or non-properly initialized object.
//
bool AccelerometerMac::GetOrientation(Orientation* orientation) {
DCHECK(sensor_);
// Reset output record memory buffer.
std::fill(output_record_.begin(), output_record_.end(), 0x00);
// Read record data from memory.
const size_t kInputSize = kGenericSensor.record_size;
size_t output_size = kGenericSensor.record_size;
if (IOConnectCallStructMethod(io_connection_, kGenericSensor.function,
static_cast<const char *>(&input_record_[0]), kInputSize,
&output_record_[0], &output_size) != KERN_SUCCESS) {
return false;
}
// Calculate per-axis calibrated values.
float axis_value[3];
for (int i = 0; i < 3; ++i) {
int sensor_value = 0;
int size = kGenericSensor.axis_size;
int index = sensor_->axis[i].index;
// Important Note: little endian is assumed as this code is mac-only
// and PowerPC is currently not supported.
memcpy(&sensor_value, &output_record_[index], size);
sensor_value = ExtendSign(sensor_value, size);
// Correct value using the current calibration.
axis_value[i] = static_cast<float>(sensor_value - kGenericSensor.zero_g) /
kGenericSensor.one_g;
// Make sure we reject any NaN or infinite values.
if (!isfinite(axis_value[i]))
return false;
// Clamp value to the [-1, 1] range.
if (axis_value[i] < -1.0)
axis_value[i] = -1.0;
else if (axis_value[i] > 1.0)
axis_value[i] = 1.0;
// Apply axis inversion.
if (sensor_->axis[i].inverted)
axis_value[i] = -axis_value[i];
}
// Transform the accelerometer values to W3C draft angles.
//
// Accelerometer values are just dot products of the sensor axes
// by the gravity vector 'g' with the result for the z axis inverted.
//
// To understand this transformation calculate the 3rd row of the z-x-y
// Euler angles rotation matrix (because of the 'g' vector, only 3rd row
// affects to the result). Note that z-x-y matrix means R = Ry * Rx * Rz.
// Then, assume alpha = 0 and you get this:
//
// x_acc = sin(gamma)
// y_acc = - cos(gamma) * sin(beta)
// z_acc = cos(beta) * cos(gamma)
//
// After that the rest is just a bit of trigonometry.
//
// Also note that alpha can't be provided but it's assumed to be always zero.
// This is necessary in order to provide enough information to solve
// the equations.
//
const double kRad2deg = 180.0 / M_PI;
orientation->alpha_ = 0.0;
orientation->beta_ = kRad2deg * atan2(-axis_value[1], axis_value[2]);
orientation->gamma_ = kRad2deg * asin(axis_value[0]);
// Make sure that the interval boundaries comply with the specification.
if (orientation->beta_ >= 180.0)
orientation->beta_ -= 360.0;
if (orientation->gamma_ >= 90.0)
orientation->gamma_ -= 180.0;
DCHECK_GE(orientation->beta_, -180.0);
DCHECK_LT(orientation->beta_, 180.0);
DCHECK_GE(orientation->gamma_, -90.0);
DCHECK_LT(orientation->gamma_, 90.0);
orientation->can_provide_alpha_ = false;
orientation->can_provide_beta_ = true;
orientation->can_provide_gamma_ = true;
return true;
}
// Probe the local hardware looking for a supported sensor device
// and initialize an I/O connection to it.
bool AccelerometerMac::Init() {
// Allocate local variables for model name string (size from SMSLib).
static const int kNameSize = 32;
char local_model[kNameSize];
// Request model name to the kernel.
size_t name_size = kNameSize;
int params[2] = { CTL_HW, HW_MODEL };
if (sysctl(params, 2, local_model, &name_size, NULL, 0) != 0)
return NULL;
const SensorDescriptor* sensor_candidate = NULL;
// Look for the current model in the supported sensor list.
io_object_t device = 0;
const int kNumSensors = arraysize(kSupportedSensors);
for (int i = 0; i < kNumSensors; ++i) {
// Check if the supported sensor model name is a prefix
// of the local hardware model (empty names are accepted).
const char* p1 = kSupportedSensors[i].model_name;
for (const char* p2 = local_model; *p1 != '\0' && *p1 == *p2; ++p1, ++p2)
continue;
if (*p1 != '\0')
continue;
// Local hardware found in the supported sensor list.
sensor_candidate = &kSupportedSensors[i];
// Get a dictionary of the services matching to the one in the sensor.
CFMutableDictionaryRef dict =
IOServiceMatching(kGenericSensor.service_name);
if (dict == NULL)
continue;
// Get an iterator for the matching services.
io_iterator_t device_iterator;
if (IOServiceGetMatchingServices(kIOMasterPortDefault, dict,
&device_iterator) != KERN_SUCCESS) {
continue;
}
// Get the first device in the list.
if ((device = IOIteratorNext(device_iterator)) == 0)
continue;
// Try to open device.
kern_return_t result;
result = IOServiceOpen(device, mach_task_self(), 0, &io_connection_);
IOObjectRelease(device);
if (result != KERN_SUCCESS || io_connection_ == 0)
return false;
// Local sensor service confirmed by IOKit.
sensor_ = sensor_candidate;
break;
}
if (sensor_ == NULL)
return false;
// Allocate and initialize input/output records.
input_record_.resize(kGenericSensor.record_size, 0x01);
output_record_.resize(kGenericSensor.record_size, 0x00);
// Try to retrieve the current orientation.
Orientation test_orientation;
return GetOrientation(&test_orientation);
}
// Extend the sign of an integer of less than 32 bits to a 32-bit integer.
int AccelerometerMac::ExtendSign(int value, size_t size) {
switch (size) {
case 1:
if (value & 0x00000080)
return value | 0xffffff00;
break;
case 2:
if (value & 0x00008000)
return value | 0xffff0000;
break;
case 3:
if (value & 0x00800000)
return value | 0xff000000;
break;
default:
LOG(FATAL) << "Invalid integer size for sign extension: " << size;
}
return value;
}
} // namespace device_orientation
<commit_msg>Accelerometer: Fix IOKit iterator leak, note that a configuration is verified.<commit_after>// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
//
// This file is based on the SMSLib library.
//
// SMSLib Sudden Motion Sensor Access Library
// Copyright (c) 2010 Suitable Systems
// All rights reserved.
//
// Developed by: Daniel Griscom
// Suitable Systems
// http://www.suitable.com
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the
// "Software"), to deal with 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:
//
// - Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimers.
//
// - Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimers in the
// documentation and/or other materials provided with the distribution.
//
// - Neither the names of Suitable Systems nor the names of its
// contributors may be used to endorse or promote products derived from
// this Software without specific prior written permission.
//
// 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 CONTRIBUTORS 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 WITH THE SOFTWARE.
//
// For more information about SMSLib, see
// <http://www.suitable.com/tools/smslib.html>
// or contact
// Daniel Griscom
// Suitable Systems
// 1 Centre Street, Suite 204
// Wakefield, MA 01880
// (781) 665-0053
#include "chrome/browser/device_orientation/accelerometer_mac.h"
#include <math.h> // For isfinite.
#include <sys/sysctl.h>
#include "base/logging.h"
#include "base/scoped_ptr.h"
#include "chrome/browser/device_orientation/orientation.h"
namespace device_orientation {
struct AccelerometerMac::GenericMacbookSensor {
// Name of device to be read.
const char* service_name;
// Number of bytes of the axis data.
int axis_size;
// Default calibration value for zero g.
float zero_g;
// Default calibration value for one g (negative when axis is inverted).
float one_g;
// Kernel function index.
unsigned int function;
// Size of the sensor record to be sent/received.
unsigned int record_size;
};
struct AccelerometerMac::AxisData {
// Location of the first byte representing the axis in the sensor data.
int index;
// Axis inversion flag. The value changes often between models.
bool inverted;
};
// Sudden Motion Sensor descriptor.
struct AccelerometerMac::SensorDescriptor {
// Prefix of model to be tested.
const char* model_name;
// Axis-specific data (x,y,z order).
AxisData axis[3];
};
// Typical sensor parameters in MacBook models.
const AccelerometerMac::GenericMacbookSensor
AccelerometerMac::kGenericSensor = {
"SMCMotionSensor", 2,
0, 251,
5, 40
};
// Supported sensor descriptors. Add entries here to enhance compatibility.
// All non-tested entries from SMSLib have been removed.
const AccelerometerMac::SensorDescriptor
AccelerometerMac::kSupportedSensors[] = {
// Tested by S.Selz. (via avi) on a 13" MacBook.
{ "MacBook2,1", { { 0, true }, { 2, false }, { 4, true } } },
// Tested by avi on a 13" MacBook.
{ "MacBook7,1", { { 0, true }, { 2, true }, { 4, false } } },
// Tested by sfiera, pjw on a 13" MacBook Air.
{ "MacBookAir2,1", { { 0, true }, { 2, true }, { 4, false } } },
// Note: MacBookAir3,1 (11" MacBook Air) and MacBookAir3,2 (13" MacBook Air)
// have no accelerometer sensors.
// Tested by L.V. (via avi) on a 17" MacBook Pro.
{ "MacBookPro2,1", { { 0, true }, { 2, false }, { 4, true } } },
// Tested by leandrogracia on a 15" MacBook Pro.
{ "MacBookPro2,2", { { 0, true }, { 2, true }, { 4, false } } },
// Tested by leandrogracia on a 15" MacBook Pro.
// TODO(avi): this model name was also used for the 17" version; verify that
// these parameters are also valid for that model.
{ "MacBookPro3,1", { { 0, false }, { 2, true }, { 4, true } } },
// Tested by leandrogracia on a 15" MacBook Pro.
// TODO(avi): this model name was also used for the 17" version; verify that
// these parameters are also valid for that model.
{ "MacBookPro4,1", { { 0, true }, { 2, true }, { 4, false } } },
// Tested by leandrogracia on a 15" MacBook Pro.
{ "MacBookPro5,1", { { 0, false }, { 2, false }, { 4, false } } },
// Tested by S.Selz. (via avi) on a 15" MacBook Pro.
{ "MacBookPro5,2", { { 0, false }, { 2, false }, { 4, false } } },
// Tested by dmaclach on a 15" MacBook Pro.
{ "MacBookPro5,3", { { 2, false }, { 0, false }, { 4, true } } },
// Tested by leandrogracia on a 15" MacBook Pro.
{ "MacBookPro5,4", { { 0, false }, { 2, false }, { 4, false } } },
// Tested by leandrogracia on a 13" MacBook Pro.
{ "MacBookPro5,5", { { 0, true }, { 2, true }, { 4, false } } },
// Tested by khom, leadpipe on a 17" MacBook Pro.
{ "MacBookPro6,1", { { 0, false }, { 2, false }, { 4, false } } },
// Tested by leandrogracia on a 15" MacBook Pro.
{ "MacBookPro6,2", { { 0, true }, { 2, false }, { 4, true } } },
// Tested by leandrogracia on a 13" MacBook Pro.
{ "MacBookPro7,1", { { 0, true }, { 2, true }, { 4, false } } },
// Generic MacBook accelerometer sensor data, used for for both future models
// and past models for which there has been no testing. Note that this generic
// configuration may well have problems with inverted axes.
// TODO(avi): Find these past models and test on them; test on future models.
// MacBook1,1
// MacBook3,1
// MacBook4,1
// MacBook5,1
// MacBook5,2
// MacBook6,1
// MacBookAir1,1
// MacBookPro1,1
// MacBookPro1,2
// MacBookPro5,2
{ "", { { 0, true }, { 2, true }, { 4, false } } }
};
// Create a AccelerometerMac object and return NULL if no valid sensor found.
DataFetcher* AccelerometerMac::Create() {
scoped_ptr<AccelerometerMac> accelerometer(new AccelerometerMac);
return accelerometer->Init() ? accelerometer.release() : NULL;
}
AccelerometerMac::~AccelerometerMac() {
IOServiceClose(io_connection_);
}
AccelerometerMac::AccelerometerMac()
: sensor_(NULL),
io_connection_(0) {
}
// Retrieve per-axis accelerometer values.
//
// Axes and angles are defined according to the W3C DeviceOrientation Draft.
// See here: http://dev.w3.org/geo/api/spec-source-orientation.html
//
// Note: only beta and gamma angles are provided. Alpha is set to zero.
//
// Returns false in case of error or non-properly initialized object.
//
bool AccelerometerMac::GetOrientation(Orientation* orientation) {
DCHECK(sensor_);
// Reset output record memory buffer.
std::fill(output_record_.begin(), output_record_.end(), 0x00);
// Read record data from memory.
const size_t kInputSize = kGenericSensor.record_size;
size_t output_size = kGenericSensor.record_size;
if (IOConnectCallStructMethod(io_connection_, kGenericSensor.function,
static_cast<const char *>(&input_record_[0]), kInputSize,
&output_record_[0], &output_size) != KERN_SUCCESS) {
return false;
}
// Calculate per-axis calibrated values.
float axis_value[3];
for (int i = 0; i < 3; ++i) {
int sensor_value = 0;
int size = kGenericSensor.axis_size;
int index = sensor_->axis[i].index;
// Important Note: little endian is assumed as this code is mac-only
// and PowerPC is currently not supported.
memcpy(&sensor_value, &output_record_[index], size);
sensor_value = ExtendSign(sensor_value, size);
// Correct value using the current calibration.
axis_value[i] = static_cast<float>(sensor_value - kGenericSensor.zero_g) /
kGenericSensor.one_g;
// Make sure we reject any NaN or infinite values.
if (!isfinite(axis_value[i]))
return false;
// Clamp value to the [-1, 1] range.
if (axis_value[i] < -1.0)
axis_value[i] = -1.0;
else if (axis_value[i] > 1.0)
axis_value[i] = 1.0;
// Apply axis inversion.
if (sensor_->axis[i].inverted)
axis_value[i] = -axis_value[i];
}
// Transform the accelerometer values to W3C draft angles.
//
// Accelerometer values are just dot products of the sensor axes
// by the gravity vector 'g' with the result for the z axis inverted.
//
// To understand this transformation calculate the 3rd row of the z-x-y
// Euler angles rotation matrix (because of the 'g' vector, only 3rd row
// affects to the result). Note that z-x-y matrix means R = Ry * Rx * Rz.
// Then, assume alpha = 0 and you get this:
//
// x_acc = sin(gamma)
// y_acc = - cos(gamma) * sin(beta)
// z_acc = cos(beta) * cos(gamma)
//
// After that the rest is just a bit of trigonometry.
//
// Also note that alpha can't be provided but it's assumed to be always zero.
// This is necessary in order to provide enough information to solve
// the equations.
//
const double kRad2deg = 180.0 / M_PI;
orientation->alpha_ = 0.0;
orientation->beta_ = kRad2deg * atan2(-axis_value[1], axis_value[2]);
orientation->gamma_ = kRad2deg * asin(axis_value[0]);
// Make sure that the interval boundaries comply with the specification.
if (orientation->beta_ >= 180.0)
orientation->beta_ -= 360.0;
if (orientation->gamma_ >= 90.0)
orientation->gamma_ -= 180.0;
DCHECK_GE(orientation->beta_, -180.0);
DCHECK_LT(orientation->beta_, 180.0);
DCHECK_GE(orientation->gamma_, -90.0);
DCHECK_LT(orientation->gamma_, 90.0);
orientation->can_provide_alpha_ = false;
orientation->can_provide_beta_ = true;
orientation->can_provide_gamma_ = true;
return true;
}
// Probe the local hardware looking for a supported sensor device
// and initialize an I/O connection to it.
bool AccelerometerMac::Init() {
// Allocate local variables for model name string (size from SMSLib).
static const int kNameSize = 32;
char local_model[kNameSize];
// Request model name to the kernel.
size_t name_size = kNameSize;
int params[2] = { CTL_HW, HW_MODEL };
if (sysctl(params, 2, local_model, &name_size, NULL, 0) != 0)
return NULL;
const SensorDescriptor* sensor_candidate = NULL;
// Look for the current model in the supported sensor list.
const int kNumSensors = arraysize(kSupportedSensors);
for (int i = 0; i < kNumSensors; ++i) {
// Check if the supported sensor model name is a prefix
// of the local hardware model (empty names are accepted).
const char* p1 = kSupportedSensors[i].model_name;
for (const char* p2 = local_model; *p1 != '\0' && *p1 == *p2; ++p1, ++p2)
continue;
if (*p1 != '\0')
continue;
// Local hardware found in the supported sensor list.
sensor_candidate = &kSupportedSensors[i];
// Get a dictionary of the services matching to the one in the sensor.
CFMutableDictionaryRef dict =
IOServiceMatching(kGenericSensor.service_name);
if (dict == NULL)
continue;
// Get an iterator for the matching services.
io_iterator_t device_iterator;
if (IOServiceGetMatchingServices(kIOMasterPortDefault, dict,
&device_iterator) != KERN_SUCCESS) {
continue;
}
// Get the first device in the list.
io_object_t device = IOIteratorNext(device_iterator);
IOObjectRelease(device_iterator);
if (device == 0)
continue;
// Try to open device.
kern_return_t result;
result = IOServiceOpen(device, mach_task_self(), 0, &io_connection_);
IOObjectRelease(device);
if (result != KERN_SUCCESS || io_connection_ == 0)
return false;
// Local sensor service confirmed by IOKit.
sensor_ = sensor_candidate;
break;
}
if (sensor_ == NULL)
return false;
// Allocate and initialize input/output records.
input_record_.resize(kGenericSensor.record_size, 0x01);
output_record_.resize(kGenericSensor.record_size, 0x00);
// Try to retrieve the current orientation.
Orientation test_orientation;
return GetOrientation(&test_orientation);
}
// Extend the sign of an integer of less than 32 bits to a 32-bit integer.
int AccelerometerMac::ExtendSign(int value, size_t size) {
switch (size) {
case 1:
if (value & 0x00000080)
return value | 0xffffff00;
break;
case 2:
if (value & 0x00008000)
return value | 0xffff0000;
break;
case 3:
if (value & 0x00800000)
return value | 0xff000000;
break;
default:
LOG(FATAL) << "Invalid integer size for sign extension: " << size;
}
return value;
}
} // namespace device_orientation
<|endoftext|>
|
<commit_before>#include "vtkCellDistanceSelector.h"
#include <vtkCell.h>
#include <vtkCellData.h>
#include <vtkIdList.h>
#include <vtkObjectFactory.h>
#include <vtkPointData.h>
#include <vtkDataSet.h>
#include <vtkUnstructuredGrid.h>
#include <vtkStructuredGrid.h>
#include <vtkPolyData.h>
#include <vtkCellLinks.h>
#include <vtkInformation.h>
#include <vtkInformationVector.h>
#include <vtkCompositeDataSet.h>
#include <vtkCompositeDataIterator.h>
#include <vtkSelection.h>
#include <vtkSelectionNode.h>
#include <vtkIdTypeArray.h>
#include <vtkSmartPointer.h>
#include <map>
#include <vector>
vtkStandardNewMacro(vtkCellDistanceSelector);
// ----------------------------------------------------------------------
vtkCellDistanceSelector::vtkCellDistanceSelector()
{
this->Distance = 1;
this->IncludeSeed = 1;
this->AddIntermediate = 1;
this->SetNumberOfInputPorts( 2 );
}
// ----------------------------------------------------------------------
vtkCellDistanceSelector::~vtkCellDistanceSelector()
{
}
// ----------------------------------------------------------------------
void vtkCellDistanceSelector::SetDataObjectConnection ( vtkAlgorithmOutput* in )
{
this->SetInputConnection( 1, in );
}
// ----------------------------------------------------------------------
void vtkCellDistanceSelector::PrintSelf( ostream& os, vtkIndent indent )
{
this->Superclass::PrintSelf( os, indent );
}
// ----------------------------------------------------------------------
int vtkCellDistanceSelector::FillInputPortInformation( int port, vtkInformation* info )
{
switch ( port )
{
case 0:
info->Set(vtkAlgorithm::INPUT_REQUIRED_DATA_TYPE(), "vtkSelection" );
break;
case 1:
info->Set(vtkAlgorithm::INPUT_REQUIRED_DATA_TYPE(), "vtkCompositeDataSet" );
break;
}
return 1;
}
// ----------------------------------------------------------------------
void vtkCellDistanceSelector::AddSelectionNode( vtkSelection* output,
vtkSmartPointer<vtkDataArray> outIndices,
int composite_index, int d )
{
vtkSmartPointer<vtkSelectionNode> outSelNode = vtkSmartPointer<vtkSelectionNode>::New();
outSelNode->SetContentType( vtkSelectionNode::INDICES );
outSelNode->SetFieldType( vtkSelectionNode::CELL );
outSelNode->GetProperties()->Set( vtkSelectionNode::COMPOSITE_INDEX(), composite_index );
// NB: Use HIERARCHICAL_LEVEL key to store distance to original cells
outSelNode->GetProperties()->Set( vtkSelectionNode::HIERARCHICAL_LEVEL(), d );
outSelNode->SetSelectionList( outIndices );
output->AddNode( outSelNode );
}
// ----------------------------------------------------------------------
int vtkCellDistanceSelector::RequestData( vtkInformation* vtkNotUsed( request ),
vtkInformationVector** inputVector,
vtkInformationVector* outputVector )
{
vtkInformation* inSelectionInfo = inputVector[0]->GetInformationObject( 0 );
vtkInformation* inDataObjectInfo = inputVector[1]->GetInformationObject( 0 );
vtkInformation* outInfo = outputVector->GetInformationObject( 0 );
vtkSelection* inputSelection =
vtkSelection::SafeDownCast( inSelectionInfo->Get( vtkDataObject::DATA_OBJECT() ) );
vtkCompositeDataSet* compositeInput =
vtkCompositeDataSet::SafeDownCast( inDataObjectInfo->Get(vtkDataObject::DATA_OBJECT() ) );
vtkSelection* output =
vtkSelection::SafeDownCast(outInfo->Get( vtkDataObject::DATA_OBJECT() ) );
if ( ! compositeInput )
{
vtkErrorMacro(<<"Missing input data object");
return 0;
}
if ( ! inputSelection )
{
vtkErrorMacro(<<"Missing input selection");
return 0;
}
std::map<int,std::vector<vtkSelectionNode*> > partSelections;
int nSelNodes = inputSelection->GetNumberOfNodes();
for ( int i = 0; i < nSelNodes; ++ i )
{
vtkSelectionNode* sn = inputSelection->GetNode( i );
int composite_index = sn->GetProperties()->Get(vtkSelectionNode::COMPOSITE_INDEX() ) ;
partSelections[composite_index].push_back( sn );
}
vtkCompositeDataIterator* inputIterator = compositeInput->NewIterator();
inputIterator->SkipEmptyNodesOn();
inputIterator->InitTraversal();
inputIterator->GoToFirstItem();
while ( ! inputIterator->IsDoneWithTraversal() )
{
vtkDataSet * input = vtkDataSet::SafeDownCast( inputIterator->GetCurrentDataObject() );
// NB: composite indices start at 1
int composite_index = inputIterator->GetCurrentFlatIndex();
inputIterator->GoToNextItem();
std::vector<vtkSelectionNode*>::iterator selNodeIt = partSelections[composite_index].begin();
while ( selNodeIt != partSelections[composite_index].end() )
{
vtkSelectionNode* selectionNode = *selNodeIt;
++ selNodeIt;
vtkDataArray* selectionList = vtkDataArray::SafeDownCast( selectionNode->GetSelectionList() );
vtkIdType numSeeds = selectionList->GetNumberOfTuples();
if ( numSeeds > 0
&& selectionNode->GetContentType() == vtkSelectionNode::INDICES
&& selectionNode->GetFieldType() == vtkSelectionNode::CELL
&& input->GetNumberOfCells() > 0 )
{
vtkIdType numCells = input->GetNumberOfCells();
vtkUnstructuredGrid* ug_input = vtkUnstructuredGrid::SafeDownCast( input );
vtkStructuredGrid* sg_input = vtkStructuredGrid::SafeDownCast( input );
vtkPolyData* pd_input = vtkPolyData::SafeDownCast( input);
vtkCellLinks * links = 0;
if (ug_input != 0)
{
if ( ! ug_input->GetCellLinks() )
{
ug_input->BuildLinks();
}
links = ug_input->GetCellLinks();
}
std::vector<int> flags( numCells, 0 );
vtkSmartPointer<vtkIdTypeArray> outIndices = vtkSmartPointer<vtkIdTypeArray>::New();
outIndices->SetNumberOfTuples( numSeeds );
int seedCount = 0;
for ( int i = 0; i < numSeeds; ++ i )
{
vtkIdType cellIndex = static_cast<vtkIdType> ( selectionList->GetTuple1( i ) );
if( cellIndex>=0 && cellIndex<numCells )
{
flags[cellIndex] = true;
outIndices->SetTuple1( seedCount++, cellIndex );
}
else
{
vtkWarningMacro(<<"Cell index out of bounds in selection ("<<cellIndex<<"/"<<numCells<<")\n");
}
}
outIndices->SetNumberOfTuples( seedCount );
vtkSmartPointer<vtkIdTypeArray> finalIndices = vtkSmartPointer<vtkIdTypeArray>::New();
vtkSmartPointer<vtkIntArray> cellDistance = vtkSmartPointer<vtkIntArray>::New();
cellDistance->SetName("Cell Distance");
// Iterate over increasing topological distance until desired distance is met
for ( int d = 0; d < this->Distance; ++ d )
{
vtkSmartPointer<vtkIdTypeArray> nextIndices = vtkSmartPointer<vtkIdTypeArray>::New();
if ( ug_input )
{
int nIndices = outIndices->GetNumberOfTuples();
for ( int i = 0; i < nIndices; ++ i )
{
vtkIdType cellIndex = static_cast<vtkIdType>( outIndices->GetTuple1( i ) );
vtkIdType * points;
vtkIdType n;
ug_input->GetCellPoints(cellIndex, n, points);
for ( int k = 0; k < n; ++ k )
{
vtkIdType pid = points[k];
int np = links->GetNcells( pid );
vtkIdType* cells = links->GetCells( pid );
for ( int j = 0; j < np; ++ j )
{
vtkIdType cid = cells[j];
if( cid >= 0 && cid < numCells )
{
if ( ! flags[cid] )
{
flags[cid] = true;
nextIndices->InsertNextValue( cid );
}
}
else
{
vtkWarningMacro(<<"Selection's cell index out of bounds ("<<cid<<"/"<<numCells<<")\n");
}
}
}
}
} // if ( ug_input )
else if ( pd_input )
{
pd_input->BuildLinks();
int nIndices = outIndices->GetNumberOfTuples();
for ( int i = 0; i < nIndices; ++ i )
{
vtkIdType cellIndex = static_cast<vtkIdType>( outIndices->GetTuple1( i) );
vtkIdType* points;
vtkIdType n;
pd_input->GetCellPoints(cellIndex, n, points);
for ( int k = 0; k < n; ++ k )
{
vtkIdType pid = points[k];
short unsigned int np;
vtkIdType* cells;
pd_input->GetPointCells(pid, np, cells);
for ( int j = 0; j < np; j++)
{
vtkIdType cid = cells[j];
if( cid>=0 && cid<numCells )
{
if (!flags[cid])
{
flags[cid] = true;
nextIndices->InsertNextValue(cid);
}
}
else
{
vtkWarningMacro(<<"Selection's cell index out of bounds ("<<cid<<"/"<<numCells<<")\n");
}
}
}
}
} // else if ( ug_input )
else if (sg_input != 0)
{
int dim[3];
sg_input->GetDimensions(dim);
dim[0]--;
dim[1]--;
dim[2]--;
int nIndices = outIndices->GetNumberOfTuples();
for ( int i = 0; i < nIndices; ++ i )
{
vtkIdType cellIndex = static_cast<vtkIdType>( outIndices->GetTuple1( i ) );
vtkIdType cellId = cellIndex;
vtkIdType ijk[3];
for ( int c = 0; c < 3; c++)
{
if (dim[c] <= 1)
{
ijk[c] = 0;
}
else
{
ijk[c] = cellId % dim[c];
cellId /= dim[c];
}
}
for ( int k = -1; k <= 1; k++)
{
for ( int j = -1; j <= 1; j++)
{
for ( int l = -1; l <= 1; ++ l )
{
int I = ijk[0] + l, J = ijk[1] + j, K = ijk[2] + k;
if ( i >= 0 && I < dim[0] && J >= 0 && J
< dim[1] && K >= 0 && K < dim[2])
{
cellId = I + J * dim[0] + K * dim[0] * dim[1];
if( cellId >= 0 && cellId < numCells )
{
if ( ! flags[cellId] )
{
flags[cellId] = true;
nextIndices->InsertNextValue( cellId );
}
}
else
{
vtkWarningMacro(<<"Selection's cell index out of bounds ("<<cellId<<"/"<<numCells<<")\n");
}
}
} // l
} // j
} // k
}
} // else if ( sg_input )
else
{
vtkErrorMacro(<<"Unsupported data type : "<<input->GetClassName()<<"\n");
}
if( ( ! d && this->IncludeSeed ) || ( d > 0 && this->AddIntermediate ) )
{
int ni = outIndices->GetNumberOfTuples();
for( int i = 0; i < ni; ++ i )
{
cellDistance->InsertNextTuple1( d );
finalIndices->InsertNextTuple1( outIndices->GetTuple1( i ) );
}
}
outIndices = nextIndices;
} // for ( int d = 0; d < this->Distance; ++ d )
if( ( ! this->Distance && this->IncludeSeed ) || ( this->Distance > 0 && this->AddIntermediate ) )
{
int ni = outIndices->GetNumberOfTuples();
for( int i=0;i<ni;++ i )
{
cellDistance->InsertNextTuple1( this->Distance );
finalIndices->InsertNextTuple1( outIndices->GetTuple1( i ) );
}
}
if( finalIndices->GetNumberOfTuples() > 0 )
{
vtkSmartPointer<vtkSelectionNode> outSelNode = vtkSmartPointer<vtkSelectionNode>::New();
outSelNode->SetContentType( vtkSelectionNode::INDICES );
outSelNode->SetFieldType( vtkSelectionNode::CELL );
outSelNode->GetProperties()->Set( vtkSelectionNode::COMPOSITE_INDEX(), composite_index );
outSelNode->SetSelectionList( finalIndices );
outSelNode->GetSelectionData()->AddArray( cellDistance );
output->AddNode( outSelNode );
}
} // if numSeeds > 0 etc.
} // while selNodeIt
} // while inputIterator
return 1;
}
<commit_msg>Fixed a leak (composite iterator deletion)<commit_after>#include "vtkCellDistanceSelector.h"
#include <vtkCell.h>
#include <vtkCellData.h>
#include <vtkIdList.h>
#include <vtkObjectFactory.h>
#include <vtkPointData.h>
#include <vtkDataSet.h>
#include <vtkUnstructuredGrid.h>
#include <vtkStructuredGrid.h>
#include <vtkPolyData.h>
#include <vtkCellLinks.h>
#include <vtkInformation.h>
#include <vtkInformationVector.h>
#include <vtkCompositeDataSet.h>
#include <vtkCompositeDataIterator.h>
#include <vtkSelection.h>
#include <vtkSelectionNode.h>
#include <vtkIdTypeArray.h>
#include <vtkSmartPointer.h>
#include <map>
#include <vector>
vtkStandardNewMacro(vtkCellDistanceSelector);
// ----------------------------------------------------------------------
vtkCellDistanceSelector::vtkCellDistanceSelector()
{
this->Distance = 1;
this->IncludeSeed = 1;
this->AddIntermediate = 1;
this->SetNumberOfInputPorts( 2 );
}
// ----------------------------------------------------------------------
vtkCellDistanceSelector::~vtkCellDistanceSelector()
{
}
// ----------------------------------------------------------------------
void vtkCellDistanceSelector::SetDataObjectConnection ( vtkAlgorithmOutput* in )
{
this->SetInputConnection( 1, in );
}
// ----------------------------------------------------------------------
void vtkCellDistanceSelector::PrintSelf( ostream& os, vtkIndent indent )
{
this->Superclass::PrintSelf( os, indent );
}
// ----------------------------------------------------------------------
int vtkCellDistanceSelector::FillInputPortInformation( int port, vtkInformation* info )
{
switch ( port )
{
case 0:
info->Set(vtkAlgorithm::INPUT_REQUIRED_DATA_TYPE(), "vtkSelection" );
break;
case 1:
info->Set(vtkAlgorithm::INPUT_REQUIRED_DATA_TYPE(), "vtkCompositeDataSet" );
break;
}
return 1;
}
// ----------------------------------------------------------------------
void vtkCellDistanceSelector::AddSelectionNode( vtkSelection* output,
vtkSmartPointer<vtkDataArray> outIndices,
int composite_index, int d )
{
vtkSmartPointer<vtkSelectionNode> outSelNode = vtkSmartPointer<vtkSelectionNode>::New();
outSelNode->SetContentType( vtkSelectionNode::INDICES );
outSelNode->SetFieldType( vtkSelectionNode::CELL );
outSelNode->GetProperties()->Set( vtkSelectionNode::COMPOSITE_INDEX(), composite_index );
// NB: Use HIERARCHICAL_LEVEL key to store distance to original cells
outSelNode->GetProperties()->Set( vtkSelectionNode::HIERARCHICAL_LEVEL(), d );
outSelNode->SetSelectionList( outIndices );
output->AddNode( outSelNode );
}
// ----------------------------------------------------------------------
int vtkCellDistanceSelector::RequestData( vtkInformation* vtkNotUsed( request ),
vtkInformationVector** inputVector,
vtkInformationVector* outputVector )
{
vtkInformation* inSelectionInfo = inputVector[0]->GetInformationObject( 0 );
vtkInformation* inDataObjectInfo = inputVector[1]->GetInformationObject( 0 );
vtkInformation* outInfo = outputVector->GetInformationObject( 0 );
vtkSelection* inputSelection =
vtkSelection::SafeDownCast( inSelectionInfo->Get( vtkDataObject::DATA_OBJECT() ) );
vtkCompositeDataSet* compositeInput =
vtkCompositeDataSet::SafeDownCast( inDataObjectInfo->Get(vtkDataObject::DATA_OBJECT() ) );
vtkSelection* output =
vtkSelection::SafeDownCast(outInfo->Get( vtkDataObject::DATA_OBJECT() ) );
if ( ! compositeInput )
{
vtkErrorMacro(<<"Missing input data object");
return 0;
}
if ( ! inputSelection )
{
vtkErrorMacro(<<"Missing input selection");
return 0;
}
std::map<int,std::vector<vtkSelectionNode*> > partSelections;
int nSelNodes = inputSelection->GetNumberOfNodes();
for ( int i = 0; i < nSelNodes; ++ i )
{
vtkSelectionNode* sn = inputSelection->GetNode( i );
int composite_index = sn->GetProperties()->Get(vtkSelectionNode::COMPOSITE_INDEX() ) ;
partSelections[composite_index].push_back( sn );
}
vtkCompositeDataIterator* inputIterator = compositeInput->NewIterator();
inputIterator->SkipEmptyNodesOn();
inputIterator->InitTraversal();
inputIterator->GoToFirstItem();
while ( ! inputIterator->IsDoneWithTraversal() )
{
vtkDataSet * input = vtkDataSet::SafeDownCast( inputIterator->GetCurrentDataObject() );
// NB: composite indices start at 1
int composite_index = inputIterator->GetCurrentFlatIndex();
inputIterator->GoToNextItem();
std::vector<vtkSelectionNode*>::iterator selNodeIt = partSelections[composite_index].begin();
while ( selNodeIt != partSelections[composite_index].end() )
{
vtkSelectionNode* selectionNode = *selNodeIt;
++ selNodeIt;
vtkDataArray* selectionList = vtkDataArray::SafeDownCast( selectionNode->GetSelectionList() );
vtkIdType numSeeds = selectionList->GetNumberOfTuples();
if ( numSeeds > 0
&& selectionNode->GetContentType() == vtkSelectionNode::INDICES
&& selectionNode->GetFieldType() == vtkSelectionNode::CELL
&& input->GetNumberOfCells() > 0 )
{
vtkIdType numCells = input->GetNumberOfCells();
vtkUnstructuredGrid* ug_input = vtkUnstructuredGrid::SafeDownCast( input );
vtkStructuredGrid* sg_input = vtkStructuredGrid::SafeDownCast( input );
vtkPolyData* pd_input = vtkPolyData::SafeDownCast( input);
vtkCellLinks * links = 0;
if (ug_input != 0)
{
if ( ! ug_input->GetCellLinks() )
{
ug_input->BuildLinks();
}
links = ug_input->GetCellLinks();
}
std::vector<int> flags( numCells, 0 );
vtkSmartPointer<vtkIdTypeArray> outIndices = vtkSmartPointer<vtkIdTypeArray>::New();
outIndices->SetNumberOfTuples( numSeeds );
int seedCount = 0;
for ( int i = 0; i < numSeeds; ++ i )
{
vtkIdType cellIndex = static_cast<vtkIdType> ( selectionList->GetTuple1( i ) );
if( cellIndex>=0 && cellIndex<numCells )
{
flags[cellIndex] = true;
outIndices->SetTuple1( seedCount++, cellIndex );
}
else
{
vtkWarningMacro(<<"Cell index out of bounds in selection ("<<cellIndex<<"/"<<numCells<<")\n");
}
}
outIndices->SetNumberOfTuples( seedCount );
vtkSmartPointer<vtkIdTypeArray> finalIndices = vtkSmartPointer<vtkIdTypeArray>::New();
vtkSmartPointer<vtkIntArray> cellDistance = vtkSmartPointer<vtkIntArray>::New();
cellDistance->SetName("Cell Distance");
// Iterate over increasing topological distance until desired distance is met
for ( int d = 0; d < this->Distance; ++ d )
{
vtkSmartPointer<vtkIdTypeArray> nextIndices = vtkSmartPointer<vtkIdTypeArray>::New();
if ( ug_input )
{
int nIndices = outIndices->GetNumberOfTuples();
for ( int i = 0; i < nIndices; ++ i )
{
vtkIdType cellIndex = static_cast<vtkIdType>( outIndices->GetTuple1( i ) );
vtkIdType * points;
vtkIdType n;
ug_input->GetCellPoints(cellIndex, n, points);
for ( int k = 0; k < n; ++ k )
{
vtkIdType pid = points[k];
int np = links->GetNcells( pid );
vtkIdType* cells = links->GetCells( pid );
for ( int j = 0; j < np; ++ j )
{
vtkIdType cid = cells[j];
if( cid >= 0 && cid < numCells )
{
if ( ! flags[cid] )
{
flags[cid] = true;
nextIndices->InsertNextValue( cid );
}
}
else
{
vtkWarningMacro(<<"Selection's cell index out of bounds ("<<cid<<"/"<<numCells<<")\n");
}
}
}
}
} // if ( ug_input )
else if ( pd_input )
{
pd_input->BuildLinks();
int nIndices = outIndices->GetNumberOfTuples();
for ( int i = 0; i < nIndices; ++ i )
{
vtkIdType cellIndex = static_cast<vtkIdType>( outIndices->GetTuple1( i) );
vtkIdType* points;
vtkIdType n;
pd_input->GetCellPoints(cellIndex, n, points);
for ( int k = 0; k < n; ++ k )
{
vtkIdType pid = points[k];
short unsigned int np;
vtkIdType* cells;
pd_input->GetPointCells(pid, np, cells);
for ( int j = 0; j < np; j++)
{
vtkIdType cid = cells[j];
if( cid>=0 && cid<numCells )
{
if (!flags[cid])
{
flags[cid] = true;
nextIndices->InsertNextValue(cid);
}
}
else
{
vtkWarningMacro(<<"Selection's cell index out of bounds ("<<cid<<"/"<<numCells<<")\n");
}
}
}
}
} // else if ( ug_input )
else if (sg_input != 0)
{
int dim[3];
sg_input->GetDimensions(dim);
dim[0]--;
dim[1]--;
dim[2]--;
int nIndices = outIndices->GetNumberOfTuples();
for ( int i = 0; i < nIndices; ++ i )
{
vtkIdType cellIndex = static_cast<vtkIdType>( outIndices->GetTuple1( i ) );
vtkIdType cellId = cellIndex;
vtkIdType ijk[3];
for ( int c = 0; c < 3; c++)
{
if (dim[c] <= 1)
{
ijk[c] = 0;
}
else
{
ijk[c] = cellId % dim[c];
cellId /= dim[c];
}
}
for ( int k = -1; k <= 1; k++)
{
for ( int j = -1; j <= 1; j++)
{
for ( int l = -1; l <= 1; ++ l )
{
int I = ijk[0] + l, J = ijk[1] + j, K = ijk[2] + k;
if ( i >= 0 && I < dim[0] && J >= 0 && J
< dim[1] && K >= 0 && K < dim[2])
{
cellId = I + J * dim[0] + K * dim[0] * dim[1];
if( cellId >= 0 && cellId < numCells )
{
if ( ! flags[cellId] )
{
flags[cellId] = true;
nextIndices->InsertNextValue( cellId );
}
}
else
{
vtkWarningMacro(<<"Selection's cell index out of bounds ("<<cellId<<"/"<<numCells<<")\n");
}
}
} // l
} // j
} // k
}
} // else if ( sg_input )
else
{
vtkErrorMacro(<<"Unsupported data type : "<<input->GetClassName()<<"\n");
}
if( ( ! d && this->IncludeSeed ) || ( d > 0 && this->AddIntermediate ) )
{
int ni = outIndices->GetNumberOfTuples();
for( int i = 0; i < ni; ++ i )
{
cellDistance->InsertNextTuple1( d );
finalIndices->InsertNextTuple1( outIndices->GetTuple1( i ) );
}
}
outIndices = nextIndices;
} // for ( int d = 0; d < this->Distance; ++ d )
if( ( ! this->Distance && this->IncludeSeed ) || ( this->Distance > 0 && this->AddIntermediate ) )
{
int ni = outIndices->GetNumberOfTuples();
for( int i=0;i<ni;++ i )
{
cellDistance->InsertNextTuple1( this->Distance );
finalIndices->InsertNextTuple1( outIndices->GetTuple1( i ) );
}
}
if( finalIndices->GetNumberOfTuples() > 0 )
{
vtkSmartPointer<vtkSelectionNode> outSelNode = vtkSmartPointer<vtkSelectionNode>::New();
outSelNode->SetContentType( vtkSelectionNode::INDICES );
outSelNode->SetFieldType( vtkSelectionNode::CELL );
outSelNode->GetProperties()->Set( vtkSelectionNode::COMPOSITE_INDEX(), composite_index );
outSelNode->SetSelectionList( finalIndices );
outSelNode->GetSelectionData()->AddArray( cellDistance );
output->AddNode( outSelNode );
}
} // if numSeeds > 0 etc.
} // while selNodeIt
} // while inputIterator
// Clean up
inputIterator->Delete();
return 1;
}
<|endoftext|>
|
<commit_before>//////////////////////////////////////////////////////////////////////////
#include "ExperimentalD3D12.hpp"
#include "Application/iWindowedApplication.hpp"
#include "Application/WindowFlags.hpp"
#include "Application/WindowDesc.hpp"
#include "Graphics/ImageFlags.hpp"
#include "Logging/Logging.hpp"
#include "Math/Constants.hpp"
#include "Graphics/ImageDesc.hpp"
#include "Graphics/Format.hpp"
using namespace Cpf;
#define WINDOW_TITLE "Hello Triangle: " CPF_STRINGIZE(GFX_ADAPTER)
bool ExperimentalD3D12::_CreateWindow()
{
//////////////////////////////////////////////////////////////////////////
// Create the window.
mpApplication->GetEmitter()->On<iApplication::OnQuit>([]() {
CPF_LOG(Experimental, Info) << "**** Quit requested.";
return true;
});
// Create the window.
Math::Vector2i mWindowSize(1200, 800);
WindowDesc windowDesc;
windowDesc.mpTitle = WINDOW_TITLE;
windowDesc.mX = 0; // iWindow::Centered();
windowDesc.mY = 0; // iWindow::Centered();
windowDesc.mWidth = mWindowSize.x;
windowDesc.mHeight = mWindowSize.y;
windowDesc.mFlags = WindowFlags::eResizable | WindowFlags::eShown;
mpApplication->Create(&windowDesc, mpWindow.AsTypePP());
if (mpWindow)
{
mpWindow->GetEmitter()->On<iWindow::OnResize>(Bind(&ExperimentalD3D12::_Resize, this, Placeholders::_1, Placeholders::_2));
return true;
}
return false;
}
void ExperimentalD3D12::_Resize(int32_t x, int32_t y)
{
if (mpSwapChain)
{
mFOV = Math::kDegToRad * 33.0f;
float halfFov = tan(mFOV / 2.0f);
mViewportSize = halfFov;
mpSwapChain->Resize(x, y);
// Recreate the depth buffers.
// TODO: There should only be a single depth buffer.
mpDepthBuffer.Assign(nullptr);
mpDepthBufferView.Assign(nullptr);
Graphics::ImageDesc depthBufferDesc
{
x, y,
1,
1,
Graphics::Format::eD32f,
{ 1, 0 },
Graphics::ImageFlags::eAllowDepthStencil
};
mpDevice->CreateImage2D(&depthBufferDesc, nullptr, mpDepthBuffer.AsTypePP());
mpDevice->CreateDepthStencilView(mpDepthBuffer, nullptr, mpDepthBufferView.AsTypePP());
}
}
<commit_msg>Changed testing window size.<commit_after>//////////////////////////////////////////////////////////////////////////
#include "ExperimentalD3D12.hpp"
#include "Application/iWindowedApplication.hpp"
#include "Application/WindowFlags.hpp"
#include "Application/WindowDesc.hpp"
#include "Graphics/ImageFlags.hpp"
#include "Logging/Logging.hpp"
#include "Math/Constants.hpp"
#include "Graphics/ImageDesc.hpp"
#include "Graphics/Format.hpp"
using namespace Cpf;
#define WINDOW_TITLE "Hello Triangle: " CPF_STRINGIZE(GFX_ADAPTER)
bool ExperimentalD3D12::_CreateWindow()
{
//////////////////////////////////////////////////////////////////////////
// Create the window.
mpApplication->GetEmitter()->On<iApplication::OnQuit>([]() {
CPF_LOG(Experimental, Info) << "**** Quit requested.";
return true;
});
// Create the window.
Math::Vector2i mWindowSize(1200, 800);
WindowDesc windowDesc;
windowDesc.mpTitle = WINDOW_TITLE;
windowDesc.mX = iWindow::Centered();
windowDesc.mY = iWindow::Centered();
windowDesc.mWidth = mWindowSize.x;
windowDesc.mHeight = mWindowSize.y;
windowDesc.mFlags = WindowFlags::eResizable | WindowFlags::eShown;
mpApplication->Create(&windowDesc, mpWindow.AsTypePP());
if (mpWindow)
{
mpWindow->GetEmitter()->On<iWindow::OnResize>(Bind(&ExperimentalD3D12::_Resize, this, Placeholders::_1, Placeholders::_2));
return true;
}
return false;
}
void ExperimentalD3D12::_Resize(int32_t x, int32_t y)
{
if (mpSwapChain)
{
mFOV = Math::kDegToRad * 33.0f;
float halfFov = tan(mFOV / 2.0f);
mViewportSize = halfFov;
mpSwapChain->Resize(x, y);
// Recreate the depth buffers.
// TODO: There should only be a single depth buffer.
mpDepthBuffer.Assign(nullptr);
mpDepthBufferView.Assign(nullptr);
Graphics::ImageDesc depthBufferDesc
{
x, y,
1,
1,
Graphics::Format::eD32f,
{ 1, 0 },
Graphics::ImageFlags::eAllowDepthStencil
};
mpDevice->CreateImage2D(&depthBufferDesc, nullptr, mpDepthBuffer.AsTypePP());
mpDevice->CreateDepthStencilView(mpDepthBuffer, nullptr, mpDepthBufferView.AsTypePP());
}
}
<|endoftext|>
|
<commit_before>/* IBM_PROLOG_BEGIN_TAG */
/* This is an automatically generated prolog. */
/* */
/* $Source: src/import/chips/ocmb/explorer/procedures/hwp/memory/exp_getidec.C $ */
/* */
/* OpenPOWER HostBoot Project */
/* */
/* Contributors Listed Below - COPYRIGHT 2019 */
/* [+] International Business Machines Corp. */
/* */
/* */
/* Licensed under the Apache License, Version 2.0 (the "License"); */
/* you may not use this file except in compliance with the License. */
/* You may obtain a copy of the License at */
/* */
/* http://www.apache.org/licenses/LICENSE-2.0 */
/* */
/* Unless required by applicable law or agreed to in writing, software */
/* distributed under the License is distributed on an "AS IS" BASIS, */
/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or */
/* implied. See the License for the specific language governing */
/* permissions and limitations under the License. */
/* */
/* IBM_PROLOG_END_TAG */
///
/// @file exp_getidec.C
/// @brief Contains function to lookup Chip ID and EC values of Explorer Chip
///
/// *HWP HWP Owner: Christian Geddes <crgeddes@us.ibm.com>
/// *HWP HWP Backup: <none>
/// *HWP Team: Hostboot
/// *HWP Level: 2
/// *HWP Consumed by: Hostboot / Cronus
#include <fapi2.H>
#include <exp_getidec.H>
#include <lib/shared/exp_consts.H>
#include <chips/ocmb/explorer/common/include/explorer_scom_addresses.H>
#include <chips/ocmb/explorer/common/include/explorer_scom_addresses_fixes.H>
#include <chips/ocmb/explorer/common/include/explorer_scom_addresses_fld.H>
#include <chips/ocmb/explorer/common/include/explorer_scom_addresses_fld_fixes.H>
#include <generic/memory/mss_git_data_helper.H>
extern "C"
{
///
/// @brief Lookup the Chip ID and EC level values for this explorer chip
/// @param[in] i_target Explorer OCMB chip
/// @param[out] o_chipId Explorer Chip ID
/// @param[out] o_chipEc Explorer Chip EC
/// @return fapi2:ReturnCode FAPI2_RC_SUCCESS if success, else error code.
///
fapi2::ReturnCode exp_getidec(const fapi2::Target<fapi2::TARGET_TYPE_OCMB_CHIP>& i_target,
uint16_t& o_chipId,
uint8_t& o_chipEc)
{
mss::display_git_commit_info("exp_getidec");
uint8_t l_majorEc = 0;
uint8_t l_minorEc = 0;
uint8_t l_location = 0;
uint8_t l_chipBaseId = 0;
fapi2::buffer<uint64_t> l_reg_buffer;
FAPI_TRY(fapi2::getScom( i_target,
static_cast<uint64_t>(mss::exp::idec_consts::EXPLR_CHIP_INFO_REG),
l_reg_buffer ),
"exp_getidec: could not read explorer chip_info register register 0x%08x",
mss::exp::idec_consts::EXPLR_CHIP_INFO_REG);
l_reg_buffer.extractToRight<mss::exp::idec_consts::MAJOR_EC_BIT_START,
mss::exp::idec_consts::MAJOR_EC_BIT_LENGTH>(l_majorEc);
l_reg_buffer.extractToRight<mss::exp::idec_consts::LOCATION_BIT_START,
mss::exp::idec_consts::LOCATION_BIT_LENGTH>(l_location);
l_reg_buffer.extractToRight<mss::exp::idec_consts::CHIPID_BIT_START,
mss::exp::idec_consts::CHIPID_BIT_LENGTH>(l_chipBaseId);
// Due to design errors we must read the minor ec (2nd nibble) from a different register
FAPI_TRY(fapi2::getScom( i_target, static_cast<uint64_t>(EXPLR_EFUSE_IMAGE_OUT_3), l_reg_buffer ),
"exp_getidec: could not read explorer efuse_out3 register 0x%08x", EXPLR_EFUSE_IMAGE_OUT_3);
l_reg_buffer.extractToRight<EXPLR_EFUSE_IMAGE_OUT_3_ENTERPRISE_MODE_EC_MINOR,
EXPLR_EFUSE_IMAGE_OUT_3_ENTERPRISE_MODE_EC_MINOR_LEN>(l_minorEc);
// Major EC 0:3
// Minor EC 4:7
o_chipEc = (l_majorEc << 4) | l_minorEc;
// Location 0:3
// Empty 4:7
// ChipId 8:15
o_chipId = (l_location << 12) | l_chipBaseId;
FAPI_DBG("EC found 0x%.02x chipId found 0x%.04x", o_chipEc, o_chipId);
fapi_try_exit:
return fapi2::current_err;
}
} // extern "C"
<commit_msg>cleaned up paths<commit_after>/* IBM_PROLOG_BEGIN_TAG */
/* This is an automatically generated prolog. */
/* */
/* $Source: src/import/chips/ocmb/explorer/procedures/hwp/memory/exp_getidec.C $ */
/* */
/* OpenPOWER HostBoot Project */
/* */
/* Contributors Listed Below - COPYRIGHT 2019,2020 */
/* [+] International Business Machines Corp. */
/* */
/* */
/* Licensed under the Apache License, Version 2.0 (the "License"); */
/* you may not use this file except in compliance with the License. */
/* You may obtain a copy of the License at */
/* */
/* http://www.apache.org/licenses/LICENSE-2.0 */
/* */
/* Unless required by applicable law or agreed to in writing, software */
/* distributed under the License is distributed on an "AS IS" BASIS, */
/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or */
/* implied. See the License for the specific language governing */
/* permissions and limitations under the License. */
/* */
/* IBM_PROLOG_END_TAG */
///
/// @file exp_getidec.C
/// @brief Contains function to lookup Chip ID and EC values of Explorer Chip
///
/// *HWP HWP Owner: Christian Geddes <crgeddes@us.ibm.com>
/// *HWP HWP Backup: <none>
/// *HWP Team: Hostboot
/// *HWP Level: 2
/// *HWP Consumed by: Hostboot / Cronus
#include <fapi2.H>
#include <exp_getidec.H>
#include <lib/shared/exp_consts.H>
#include <explorer_scom_addresses.H>
#include <explorer_scom_addresses_fixes.H>
#include <explorer_scom_addresses_fld.H>
#include <explorer_scom_addresses_fld_fixes.H>
#include <generic/memory/mss_git_data_helper.H>
extern "C"
{
///
/// @brief Lookup the Chip ID and EC level values for this explorer chip
/// @param[in] i_target Explorer OCMB chip
/// @param[out] o_chipId Explorer Chip ID
/// @param[out] o_chipEc Explorer Chip EC
/// @return fapi2:ReturnCode FAPI2_RC_SUCCESS if success, else error code.
///
fapi2::ReturnCode exp_getidec(const fapi2::Target<fapi2::TARGET_TYPE_OCMB_CHIP>& i_target,
uint16_t& o_chipId,
uint8_t& o_chipEc)
{
mss::display_git_commit_info("exp_getidec");
uint8_t l_majorEc = 0;
uint8_t l_minorEc = 0;
uint8_t l_location = 0;
uint8_t l_chipBaseId = 0;
fapi2::buffer<uint64_t> l_reg_buffer;
FAPI_TRY(fapi2::getScom( i_target,
static_cast<uint64_t>(mss::exp::idec_consts::EXPLR_CHIP_INFO_REG),
l_reg_buffer ),
"exp_getidec: could not read explorer chip_info register register 0x%08x",
mss::exp::idec_consts::EXPLR_CHIP_INFO_REG);
l_reg_buffer.extractToRight<mss::exp::idec_consts::MAJOR_EC_BIT_START,
mss::exp::idec_consts::MAJOR_EC_BIT_LENGTH>(l_majorEc);
l_reg_buffer.extractToRight<mss::exp::idec_consts::LOCATION_BIT_START,
mss::exp::idec_consts::LOCATION_BIT_LENGTH>(l_location);
l_reg_buffer.extractToRight<mss::exp::idec_consts::CHIPID_BIT_START,
mss::exp::idec_consts::CHIPID_BIT_LENGTH>(l_chipBaseId);
// Due to design errors we must read the minor ec (2nd nibble) from a different register
FAPI_TRY(fapi2::getScom( i_target, static_cast<uint64_t>(EXPLR_EFUSE_IMAGE_OUT_3), l_reg_buffer ),
"exp_getidec: could not read explorer efuse_out3 register 0x%08x", EXPLR_EFUSE_IMAGE_OUT_3);
l_reg_buffer.extractToRight<EXPLR_EFUSE_IMAGE_OUT_3_ENTERPRISE_MODE_EC_MINOR,
EXPLR_EFUSE_IMAGE_OUT_3_ENTERPRISE_MODE_EC_MINOR_LEN>(l_minorEc);
// Major EC 0:3
// Minor EC 4:7
o_chipEc = (l_majorEc << 4) | l_minorEc;
// Location 0:3
// Empty 4:7
// ChipId 8:15
o_chipId = (l_location << 12) | l_chipBaseId;
FAPI_DBG("EC found 0x%.02x chipId found 0x%.04x", o_chipEc, o_chipId);
fapi_try_exit:
return fapi2::current_err;
}
} // extern "C"
<|endoftext|>
|
<commit_before>/* IBM_PROLOG_BEGIN_TAG */
/* This is an automatically generated prolog. */
/* */
/* $Source: src/import/chips/p9/procedures/hwp/pm/p9_cpu_special_wakeup_core.C $ */
/* */
/* OpenPOWER HostBoot Project */
/* */
/* Contributors Listed Below - COPYRIGHT 2015,2019 */
/* [+] International Business Machines Corp. */
/* */
/* */
/* Licensed under the Apache License, Version 2.0 (the "License"); */
/* you may not use this file except in compliance with the License. */
/* You may obtain a copy of the License at */
/* */
/* http://www.apache.org/licenses/LICENSE-2.0 */
/* */
/* Unless required by applicable law or agreed to in writing, software */
/* distributed under the License is distributed on an "AS IS" BASIS, */
/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or */
/* implied. See the License for the specific language governing */
/* permissions and limitations under the License. */
/* */
/* IBM_PROLOG_END_TAG */
///
/// @file : p9_cpu_special_wakeup_core.C
/// @brief : HWP to perform special wakeup of a core
// *HWP HW Owner : Greg Still <stillgs@us.ibm.com>
// *HWP FW Owner : Prem S Jha <premjha2@in.ibm.com>
// *HWP Team : PM
// *HWP Level : 3
// *HWP Consumed by : OCC:FSP:HOST:CRO
// -----------------------------------------------------------------------------
// Includes
// -----------------------------------------------------------------------------
#include <p9_cpu_special_wakeup.H>
#include <p9_cpu_special_wakeup_lib.H>
#include <p9_ppe_defs.H>
#include <p9_ppe_utils.H>
fapi2::ReturnCode collectCoreTimeoutFailInfo( const fapi2::Target < fapi2::TARGET_TYPE_CORE>& i_target,
ProcessingValues_t i_processing_info );
/// ----------------------------------------------------------------------------
///
/// @brief Sets a normal core chiplet into special wakeup state.
/// @param[in] i_target core target
/// @param[in] i_operation Special Wakeup Operation i.e. assert or deassert
/// @param[in] i_entity entity to be considered for special wakeup.
/// @return fapi2 return code.
///
fapi2::ReturnCode p9_cpu_special_wakeup_core(
const fapi2::Target < fapi2::TARGET_TYPE_CORE>& i_target,
const p9specialWakeup::PROC_SPCWKUP_OPS i_operation,
const p9specialWakeup::PROC_SPCWKUP_ENTITY i_entity )
{
FAPI_INF(">> p9_cpu_special_wakeup_core");
fapi2::ReturnCode l_rc;
uint8_t l_spWakeUpInProg = 0;
ProcessingValues_t l_processing_info;
auto l_eqTarget = i_target.getParent<fapi2::TARGET_TYPE_EQ>();
FAPI_ATTR_GET( fapi2::ATTR_CORE_INSIDE_SPECIAL_WAKEUP,
i_target,
l_spWakeUpInProg );
// A special wakeup is already in progress. In all likelyhood, a special
// wakeup has timed out and we are in FFDC collection path. During this
// FFDC collection, we SCOMed a register which itself needs a special
// wakeup.
if( l_spWakeUpInProg )
{
FAPI_INF("exiting core recurssion");
return fapi2::FAPI2_RC_SUCCESS;
}
p9specialWakeup::blockWakeupRecurssion( l_eqTarget, p9specialWakeup::BLOCK );
l_rc = _special_wakeup<fapi2::TARGET_TYPE_CORE> (
i_target,
i_operation,
i_entity,
l_processing_info );
if( l_rc == (uint32_t)fapi2::RC_INTERNAL_SPCWKUP_TIMEOUT )
{
collectCoreTimeoutFailInfo( i_target, l_processing_info );
}
p9specialWakeup::blockWakeupRecurssion( l_eqTarget, p9specialWakeup::UNBLOCK );
FAPI_INF("<< p9_cpu_special_wakeup_core" );
return fapi2::current_err;
}
// -----------------------------------------------------------------------------
///
/// @brief Collect FFDC for EQ Special Wakeup timeout
/// @param[in] i_target core target
/// @param[in] i_operation info pertaining to special wakeup
/// @return fapi2 return code.
///
fapi2::ReturnCode collectCoreTimeoutFailInfo( const fapi2::Target < fapi2::TARGET_TYPE_CORE>& i_target,
ProcessingValues_t i_processing_info )
{
FAPI_INF(">> collectCoreTimeoutFailInfo" );
fapi2::buffer<uint64_t> l_CPMMR;
fapi2::buffer<uint64_t> l_GPMMR;
fapi2::buffer<uint64_t> l_spWakeupRegVal;
fapi2::buffer<uint64_t> l_histRegVal;
fapi2::getScom( i_target, C_CPPM_CPMMR, l_CPMMR );
fapi2::getScom( i_target, C_PPM_GPMMR_SCOM, l_GPMMR );
fapi2::getScom( i_target, i_processing_info.spwkup_address[0], l_spWakeupRegVal );
fapi2::getScom( i_target, i_processing_info.history_address[0], l_histRegVal );
fapi2::Target < fapi2::TARGET_TYPE_EX> parentExTgt = i_target.getParent <fapi2::TARGET_TYPE_EX>();
uint8_t l_exPos = 0;
FAPI_ATTR_GET( fapi2::ATTR_CHIP_UNIT_POS, parentExTgt, l_exPos );
std::vector<uint64_t> l_cmeBaseAddress;
std::vector<uint64_t> l_sgpeBaseAddress;
l_sgpeBaseAddress.push_back( SGPE_BASE_ADDRESS );
l_cmeBaseAddress.push_back( getCmeBaseAddress( l_exPos ) );
FAPI_ASSERT( false ,
fapi2::SPCWKUP_CORE_TIMEOUT().
set_POLLCOUNT( i_processing_info.poll_count ).
set_SP_WKUP_REG_VALUE( l_spWakeupRegVal ).
set_HISTORY_VALUE( l_histRegVal ).
set_ENTITY( i_processing_info.entity ).
set_CPMMR( l_CPMMR ).
set_GPMMR( l_GPMMR ).
set_EQ_TARGET( i_target.getParent <fapi2::TARGET_TYPE_EQ>() ).
set_EX_TARGET( parentExTgt ).
set_CORE_TARGET( i_target ).
set_PROC_CHIP_TARGET( i_processing_info.procTgt ).
set_CME_BASE_ADDRESS( l_cmeBaseAddress ).
set_SGPE_BASE_ADDRESS( l_sgpeBaseAddress ).
set_CME_STATE_MODE( XIRS ).
set_SGPE_STATE_MODE( XIRS ),
"Timed Out In Setting Core Special Wakeup");
fapi_try_exit:
FAPI_INF("<< collectCoreTimeoutFailInfo" );
return fapi2::current_err;
}
// -----------------------------------------------------------------------------
/// @param[in] i_chipletTarget core target
/// @param[in] i_processing_info struct storing processing info
/// @param[in] i_msgId Id pertaining to debug message string.
/// @return fapi2 return code.
fapi2::ReturnCode spwkup_deassert( const fapi2::Target<fapi2::TARGET_TYPE_CORE>& i_chipletTarget,
const ProcessingValues_t i_processing_info,
p9specialWakeup::SpecialWakeUpMsg i_msgId )
{
FAPI_INF("> spwkup_deassert Core" );
uint64_t l_address = i_processing_info.spwkup_address[0];
FAPI_TRY(_spwkup_deassert(i_chipletTarget, l_address, i_msgId));
fapi_try_exit:
FAPI_INF("< spwkup_deassert Core" );
return fapi2::current_err;
}
// -----------------------------------------------------------------------------
///
/// @brief Set addresses for a core target type
/// @param[in] i_target core target
/// @param[in] i_structure struct storing processing info
/// @param[in] i_entity entity to be considered for special wakeup.
/// @return fapi2 return code.
///
template<>
fapi2::ReturnCode set_addresses(const fapi2::Target<fapi2::TARGET_TYPE_CORE>& i_target,
ProcessingValues_t& i_structure,
const uint32_t i_entity )
{
FAPI_INF(">> set_addresses for Core");
uint8_t l_core_num = 0;
FAPI_TRY(FAPI_ATTR_GET( fapi2::ATTR_CHIP_UNIT_POS, i_target, l_core_num),
"fapiGetAttribute of ATTR_CHIP_UNIT_POS");
FAPI_DBG("Core %d being procesed.", l_core_num);
i_structure.spwkup_address[0] = SPCWKUP_ADDR[i_entity][p9specialWakeup::SPW_CORE]
+ 0x01000000 * l_core_num;
i_structure.history_address[0] = SPCWKUP_HIST_ADDR[i_entity][p9specialWakeup::SPW_CORE]
+ 0x01000000 * l_core_num;
i_structure.netctrl_address[0] = SPCWKUP_NETCTRL0_ADDR[p9specialWakeup::SPW_CORE]
+ 0x01000000 * l_core_num;
i_structure.gpmmr_address[0] = SPCWKUP_GPMMR_ADDR[p9specialWakeup::SPW_CORE]
+ 0x01000000 * l_core_num;
i_structure.num_addresses = 1;
FAPI_DBG("i_structure.spwkup_address[%d] = 0x%08llX \n "
"i_structure.history_address[%d] = 0x%08llX \n "
"i_structure.netctrl_address[%d] = 0x%08llX \n "
"i_structure.gpmmr_addresss[%d] = 0x%08llX \n " ,
0, i_structure.spwkup_address[0],
0, i_structure.history_address[0],
0, i_structure.netctrl_address[0],
0, i_structure.gpmmr_address[0]);
fapi_try_exit:
FAPI_INF("<< set_addresses for Core");
return fapi2::current_err;
}
<commit_msg>PM: Use auto-special wake-up to cover PM complex reset window<commit_after>/* IBM_PROLOG_BEGIN_TAG */
/* This is an automatically generated prolog. */
/* */
/* $Source: src/import/chips/p9/procedures/hwp/pm/p9_cpu_special_wakeup_core.C $ */
/* */
/* OpenPOWER HostBoot Project */
/* */
/* Contributors Listed Below - COPYRIGHT 2015,2019 */
/* [+] International Business Machines Corp. */
/* */
/* */
/* Licensed under the Apache License, Version 2.0 (the "License"); */
/* you may not use this file except in compliance with the License. */
/* You may obtain a copy of the License at */
/* */
/* http://www.apache.org/licenses/LICENSE-2.0 */
/* */
/* Unless required by applicable law or agreed to in writing, software */
/* distributed under the License is distributed on an "AS IS" BASIS, */
/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or */
/* implied. See the License for the specific language governing */
/* permissions and limitations under the License. */
/* */
/* IBM_PROLOG_END_TAG */
///
/// @file : p9_cpu_special_wakeup_core.C
/// @brief : HWP to perform special wakeup of a core
// *HWP HW Owner : Greg Still <stillgs@us.ibm.com>
// *HWP FW Owner : Prem S Jha <premjha2@in.ibm.com>
// *HWP Team : PM
// *HWP Level : 3
// *HWP Consumed by : OCC:FSP:HOST:CRO
// -----------------------------------------------------------------------------
// Includes
// -----------------------------------------------------------------------------
#include <p9_cpu_special_wakeup.H>
#include <p9_cpu_special_wakeup_lib.H>
#include <p9_ppe_defs.H>
#include <p9_ppe_utils.H>
#include <p9n2_quad_scom_addresses.H>
#include <p9n2_quad_scom_addresses_fld.H>
fapi2::ReturnCode collectCoreTimeoutFailInfo( const fapi2::Target < fapi2::TARGET_TYPE_CORE>& i_target,
ProcessingValues_t i_processing_info );
/// ----------------------------------------------------------------------------
///
/// @brief Sets a normal core chiplet into special wakeup state.
/// @param[in] i_target core target
/// @param[in] i_operation Special Wakeup Operation i.e. assert or deassert
/// @param[in] i_entity entity to be considered for special wakeup.
/// @return fapi2 return code.
///
fapi2::ReturnCode p9_cpu_special_wakeup_core(
const fapi2::Target < fapi2::TARGET_TYPE_CORE>& i_target,
const p9specialWakeup::PROC_SPCWKUP_OPS i_operation,
const p9specialWakeup::PROC_SPCWKUP_ENTITY i_entity )
{
FAPI_INF(">> p9_cpu_special_wakeup_core");
fapi2::ReturnCode l_rc;
fapi2::buffer<uint64_t> l_cpmmrRegVal;
fapi2::buffer<uint64_t> l_lmcrRegVal;
uint8_t l_spWakeUpInProg = 0;
uint8_t l_corePos = 0;
uint8_t l_autoSplWkUpBitPos = 12; //EQ_CME_SCOM_LMCR_C0_AUTO_SPECIAL_WAKEUP_DISABLE
uint8_t l_lmcr_fail_state = 0;
ProcessingValues_t l_processing_info;
auto l_eqTarget = i_target.getParent<fapi2::TARGET_TYPE_EQ>();
auto l_exTarget = i_target.getParent<fapi2::TARGET_TYPE_EX>();
FAPI_ATTR_GET( fapi2::ATTR_CHIP_UNIT_POS,
i_target,
l_corePos );
l_autoSplWkUpBitPos = l_autoSplWkUpBitPos + ( l_corePos & 0x01) ;
FAPI_ATTR_GET( fapi2::ATTR_CORE_INSIDE_SPECIAL_WAKEUP,
i_target,
l_spWakeUpInProg );
// A special wakeup is already in progress. In all likelyhood, a special
// wakeup has timed out and we are in FFDC collection path. During this
// FFDC collection, we SCOMed a register which itself needs a special
// wakeup.
if( l_spWakeUpInProg )
{
FAPI_INF("exiting core recurssion");
return fapi2::FAPI2_RC_SUCCESS;
}
p9specialWakeup::blockWakeupRecurssion( l_eqTarget, p9specialWakeup::BLOCK );
//Not using FAPI TRY to avoid chances of RC corruption
l_rc = getScom( i_target, P9N2_C_CPPM_CPMMR_SCOM, l_cpmmrRegVal );
if( l_rc )
{
FAPI_ERR("Failed to SCOM CPMMR Reg, Core Pos %d", l_corePos );
return l_rc;
}
l_rc = getScom( l_exTarget, EX_CME_SCOM_LMCR_SCOM, l_lmcrRegVal );
if( (l_rc) && (l_rc != (uint32_t)PIB_CHIPLET_OFFLINE_ERR ))
{
FAPI_ERR("Failed to SCOM LMCR Reg, EX Pos %d", (l_corePos >> 1 ) );
return l_rc;
}
else if ((l_rc) && (l_rc == (uint32_t)PIB_CHIPLET_OFFLINE_ERR ))
{
l_rc = fapi2::FAPI2_RC_SUCCESS;
l_lmcr_fail_state = 1;
}
if( !l_lmcrRegVal.getBit( l_autoSplWkUpBitPos ) &&
!l_lmcr_fail_state)
{
if( l_cpmmrRegVal.getBit( P9N2_EX_CPPM_CPMMR_WKUP_NOTIFY_SELECT ) )
{
//If auto special wakeup is enabled and Special wakeup signal is not
//getting routed towards CME, let us route it towards CME so that
//CME HW asserts DONE bit without CME Firmware's intervention.
FAPI_DBG("Enabling Auto Special Wakeup For Core %d", l_corePos );
l_cpmmrRegVal.clearBit( P9N2_EX_CPPM_CPMMR_WKUP_NOTIFY_SELECT );
putScom( i_target, P9N2_C_CPPM_CPMMR_SCOM, l_cpmmrRegVal );
}
}
l_rc = _special_wakeup<fapi2::TARGET_TYPE_CORE> (
i_target,
i_operation,
i_entity,
l_processing_info );
if( l_rc == (uint32_t)fapi2::RC_INTERNAL_SPCWKUP_TIMEOUT )
{
collectCoreTimeoutFailInfo( i_target, l_processing_info );
}
p9specialWakeup::blockWakeupRecurssion( l_eqTarget, p9specialWakeup::UNBLOCK );
FAPI_INF("<< p9_cpu_special_wakeup_core" );
return fapi2::current_err;
}
// -----------------------------------------------------------------------------
///
/// @brief Collect FFDC for EQ Special Wakeup timeout
/// @param[in] i_target core target
/// @param[in] i_operation info pertaining to special wakeup
/// @return fapi2 return code.
///
fapi2::ReturnCode collectCoreTimeoutFailInfo( const fapi2::Target < fapi2::TARGET_TYPE_CORE>& i_target,
ProcessingValues_t i_processing_info )
{
FAPI_INF(">> collectCoreTimeoutFailInfo" );
fapi2::buffer<uint64_t> l_CPMMR;
fapi2::buffer<uint64_t> l_GPMMR;
fapi2::buffer<uint64_t> l_spWakeupRegVal;
fapi2::buffer<uint64_t> l_histRegVal;
fapi2::getScom( i_target, C_CPPM_CPMMR, l_CPMMR );
fapi2::getScom( i_target, C_PPM_GPMMR_SCOM, l_GPMMR );
fapi2::getScom( i_target, i_processing_info.spwkup_address[0], l_spWakeupRegVal );
fapi2::getScom( i_target, i_processing_info.history_address[0], l_histRegVal );
fapi2::Target < fapi2::TARGET_TYPE_EX> parentExTgt = i_target.getParent <fapi2::TARGET_TYPE_EX>();
uint8_t l_exPos = 0;
FAPI_ATTR_GET( fapi2::ATTR_CHIP_UNIT_POS, parentExTgt, l_exPos );
std::vector<uint64_t> l_cmeBaseAddress;
std::vector<uint64_t> l_sgpeBaseAddress;
l_sgpeBaseAddress.push_back( SGPE_BASE_ADDRESS );
l_cmeBaseAddress.push_back( getCmeBaseAddress( l_exPos ) );
FAPI_ASSERT( false ,
fapi2::SPCWKUP_CORE_TIMEOUT().
set_POLLCOUNT( i_processing_info.poll_count ).
set_SP_WKUP_REG_VALUE( l_spWakeupRegVal ).
set_HISTORY_VALUE( l_histRegVal ).
set_ENTITY( i_processing_info.entity ).
set_CPMMR( l_CPMMR ).
set_GPMMR( l_GPMMR ).
set_EQ_TARGET( i_target.getParent <fapi2::TARGET_TYPE_EQ>() ).
set_EX_TARGET( parentExTgt ).
set_CORE_TARGET( i_target ).
set_PROC_CHIP_TARGET( i_processing_info.procTgt ).
set_CME_BASE_ADDRESS( l_cmeBaseAddress ).
set_SGPE_BASE_ADDRESS( l_sgpeBaseAddress ).
set_CME_STATE_MODE( XIRS ).
set_SGPE_STATE_MODE( XIRS ),
"Timed Out In Setting Core Special Wakeup");
fapi_try_exit:
FAPI_INF("<< collectCoreTimeoutFailInfo" );
return fapi2::current_err;
}
// -----------------------------------------------------------------------------
/// @param[in] i_chipletTarget core target
/// @param[in] i_processing_info struct storing processing info
/// @param[in] i_msgId Id pertaining to debug message string.
/// @return fapi2 return code.
fapi2::ReturnCode spwkup_deassert( const fapi2::Target<fapi2::TARGET_TYPE_CORE>& i_chipletTarget,
const ProcessingValues_t i_processing_info,
p9specialWakeup::SpecialWakeUpMsg i_msgId )
{
FAPI_INF("> spwkup_deassert Core" );
uint64_t l_address = i_processing_info.spwkup_address[0];
FAPI_TRY(_spwkup_deassert(i_chipletTarget, l_address, i_msgId));
fapi_try_exit:
FAPI_INF("< spwkup_deassert Core" );
return fapi2::current_err;
}
// -----------------------------------------------------------------------------
///
/// @brief Set addresses for a core target type
/// @param[in] i_target core target
/// @param[in] i_structure struct storing processing info
/// @param[in] i_entity entity to be considered for special wakeup.
/// @return fapi2 return code.
///
template<>
fapi2::ReturnCode set_addresses(const fapi2::Target<fapi2::TARGET_TYPE_CORE>& i_target,
ProcessingValues_t& i_structure,
const uint32_t i_entity )
{
FAPI_INF(">> set_addresses for Core");
uint8_t l_core_num = 0;
FAPI_TRY(FAPI_ATTR_GET( fapi2::ATTR_CHIP_UNIT_POS, i_target, l_core_num),
"fapiGetAttribute of ATTR_CHIP_UNIT_POS");
FAPI_DBG("Core %d being procesed.", l_core_num);
i_structure.spwkup_address[0] = SPCWKUP_ADDR[i_entity][p9specialWakeup::SPW_CORE]
+ 0x01000000 * l_core_num;
i_structure.history_address[0] = SPCWKUP_HIST_ADDR[i_entity][p9specialWakeup::SPW_CORE]
+ 0x01000000 * l_core_num;
i_structure.netctrl_address[0] = SPCWKUP_NETCTRL0_ADDR[p9specialWakeup::SPW_CORE]
+ 0x01000000 * l_core_num;
i_structure.gpmmr_address[0] = SPCWKUP_GPMMR_ADDR[p9specialWakeup::SPW_CORE]
+ 0x01000000 * l_core_num;
i_structure.num_addresses = 1;
FAPI_DBG("i_structure.spwkup_address[%d] = 0x%08llX \n "
"i_structure.history_address[%d] = 0x%08llX \n "
"i_structure.netctrl_address[%d] = 0x%08llX \n "
"i_structure.gpmmr_addresss[%d] = 0x%08llX \n " ,
0, i_structure.spwkup_address[0],
0, i_structure.history_address[0],
0, i_structure.netctrl_address[0],
0, i_structure.gpmmr_address[0]);
fapi_try_exit:
FAPI_INF("<< set_addresses for Core");
return fapi2::current_err;
}
<|endoftext|>
|
<commit_before>//-----------------------------------------------------------------------------
// Copyright (c) 2012 GarageGames, LLC
//
// 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 "platform/platform.h"
#include "T3D/physics/physx3/px3Collision.h"
#include "math/mPoint3.h"
#include "math/mMatrix.h"
#include "T3D/physics/physx3/px3.h"
#include "T3D/physics/physx3/px3Casts.h"
#include "T3D/physics/physx3/px3World.h"
#include "T3D/physics/physx3/px3Stream.h"
Px3Collision::Px3Collision()
{
}
Px3Collision::~Px3Collision()
{
for ( U32 i=0; i < mColShapes.size(); i++ )
{
Px3CollisionDesc *desc = mColShapes[i];
delete desc->pGeometry;
// Delete the descriptor.
delete desc;
}
mColShapes.clear();
}
void Px3Collision::addPlane( const PlaneF &plane )
{
physx::PxVec3 pos = px3Cast<physx::PxVec3>(plane.getPosition());
Px3CollisionDesc *desc = new Px3CollisionDesc;
desc->pGeometry = new physx::PxPlaneGeometry();
desc->pose = physx::PxTransform(pos, physx::PxQuat(physx::PxHalfPi, physx::PxVec3(0.0f, -1.0f, 0.0f)));
mColShapes.push_back(desc);
}
void Px3Collision::addBox( const Point3F &halfWidth,const MatrixF &localXfm )
{
Px3CollisionDesc *desc = new Px3CollisionDesc;
desc->pGeometry = new physx::PxBoxGeometry(px3Cast<physx::PxVec3>(halfWidth));
desc->pose = px3Cast<physx::PxTransform>(localXfm);
mColShapes.push_back(desc);
}
void Px3Collision::addSphere( F32 radius,
const MatrixF &localXfm )
{
Px3CollisionDesc *desc = new Px3CollisionDesc;
desc->pGeometry = new physx::PxSphereGeometry(radius);
desc->pose = px3Cast<physx::PxTransform>(localXfm);
mColShapes.push_back(desc);
}
void Px3Collision::addCapsule( F32 radius,
F32 height,
const MatrixF &localXfm )
{
Px3CollisionDesc *desc = new Px3CollisionDesc;
desc->pGeometry = new physx::PxCapsuleGeometry(radius,height*0.5);//uses half height
desc->pose = px3Cast<physx::PxTransform>(localXfm);
mColShapes.push_back(desc);
}
bool Px3Collision::addConvex( const Point3F *points,
U32 count,
const MatrixF &localXfm )
{
physx::PxCooking *cooking = Px3World::getCooking();
physx::PxConvexMeshDesc convexDesc;
convexDesc.points.data = points;
convexDesc.points.stride = sizeof(Point3F);
convexDesc.points.count = count;
convexDesc.flags = physx::PxConvexFlag::eFLIPNORMALS|physx::PxConvexFlag::eCOMPUTE_CONVEX | physx::PxConvexFlag::eINFLATE_CONVEX;
Px3MemOutStream stream;
if(!cooking->cookConvexMesh(convexDesc,stream))
return false;
physx::PxConvexMesh* convexMesh;
Px3MemInStream in(stream.getData(), stream.getSize());
convexMesh = gPhysics3SDK->createConvexMesh(in);
Px3CollisionDesc *desc = new Px3CollisionDesc;
physx::PxVec3 scale = px3Cast<physx::PxVec3>(localXfm.getScale());
physx::PxQuat rotation = px3Cast<physx::PxQuat>(QuatF(localXfm));
physx::PxMeshScale meshScale(scale,rotation);
desc->pGeometry = new physx::PxConvexMeshGeometry(convexMesh,meshScale);
desc->pose = px3Cast<physx::PxTransform>(localXfm);
mColShapes.push_back(desc);
return true;
}
bool Px3Collision::addTriangleMesh( const Point3F *vert,
U32 vertCount,
const U32 *index,
U32 triCount,
const MatrixF &localXfm )
{
physx::PxCooking *cooking = Px3World::getCooking();
physx::PxTriangleMeshDesc meshDesc;
meshDesc.points.count = vertCount;
meshDesc.points.data = vert;
meshDesc.points.stride = sizeof(Point3F);
meshDesc.triangles.count = triCount;
meshDesc.triangles.data = index;
meshDesc.triangles.stride = 3*sizeof(U32);
meshDesc.flags = physx::PxMeshFlag::eFLIPNORMALS;
Px3MemOutStream stream;
if(!cooking->cookTriangleMesh(meshDesc,stream))
return false;
physx::PxTriangleMesh *mesh;
Px3MemInStream in(stream.getData(), stream.getSize());
mesh = gPhysics3SDK->createTriangleMesh(in);
Px3CollisionDesc *desc = new Px3CollisionDesc;
desc->pGeometry = new physx::PxTriangleMeshGeometry(mesh);
desc->pose = px3Cast<physx::PxTransform>(localXfm);
mColShapes.push_back(desc);
return true;
}
bool Px3Collision::addHeightfield( const U16 *heights,
const bool *holes,
U32 blockSize,
F32 metersPerSample,
const MatrixF &localXfm )
{
const F32 heightScale = 0.03125f;
physx::PxHeightFieldSample* samples = (physx::PxHeightFieldSample*) new physx::PxHeightFieldSample[blockSize*blockSize];
memset(samples,0,blockSize*blockSize*sizeof(physx::PxHeightFieldSample));
physx::PxHeightFieldDesc heightFieldDesc;
heightFieldDesc.nbColumns = blockSize;
heightFieldDesc.nbRows = blockSize;
heightFieldDesc.thickness = -10.f;
heightFieldDesc.convexEdgeThreshold = 0;
heightFieldDesc.format = physx::PxHeightFieldFormat::eS16_TM;
heightFieldDesc.samples.data = samples;
heightFieldDesc.samples.stride = sizeof(physx::PxHeightFieldSample);
physx::PxU8 *currentByte = (physx::PxU8*)heightFieldDesc.samples.data;
for ( U32 row = 0; row < blockSize; row++ )
{
const U32 tess = ( row + 1 ) % 2;
for ( U32 column = 0; column < blockSize; column++ )
{
physx::PxHeightFieldSample *currentSample = (physx::PxHeightFieldSample*)currentByte;
U32 index = ( blockSize - row - 1 ) + ( column * blockSize );
currentSample->height = (physx::PxI16)heights[ index ];
if ( holes && holes[ getMax( (S32)index - 1, 0 ) ] ) // row index for holes adjusted so PhysX collision shape better matches rendered terrain
{
currentSample->materialIndex0 = physx::PxHeightFieldMaterial::eHOLE;
currentSample->materialIndex1 = physx::PxHeightFieldMaterial::eHOLE;
}
else
{
currentSample->materialIndex0 = 0;
currentSample->materialIndex1 = 0;
}
int flag = ( column + tess ) % 2;
if(flag)
currentSample->setTessFlag();
else
currentSample->clearTessFlag();
currentByte += heightFieldDesc.samples.stride;
}
}
physx::PxHeightField * hf = gPhysics3SDK->createHeightField(heightFieldDesc);
physx::PxHeightFieldGeometry *geom = new physx::PxHeightFieldGeometry(hf,physx::PxMeshGeometryFlags(),heightScale,metersPerSample,metersPerSample);
physx::PxTransform pose= physx::PxTransform(physx::PxQuat(Float_HalfPi, physx::PxVec3(1, 0, 0 )));
physx::PxTransform pose1= physx::PxTransform(physx::PxQuat(Float_Pi, physx::PxVec3(0, 0, 1 )));
physx::PxTransform pose2 = pose1 * pose;
pose2.p = physx::PxVec3(( blockSize - 1 ) * metersPerSample, 0, 0 );
Px3CollisionDesc *desc = new Px3CollisionDesc;
desc->pGeometry = geom;
desc->pose = pose2;
mColShapes.push_back(desc);
return true;
}
<commit_msg>- Fixed memory leak when creating terrain with physx 3<commit_after>//-----------------------------------------------------------------------------
// Copyright (c) 2012 GarageGames, LLC
//
// 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 "platform/platform.h"
#include "T3D/physics/physx3/px3Collision.h"
#include "math/mPoint3.h"
#include "math/mMatrix.h"
#include "T3D/physics/physx3/px3.h"
#include "T3D/physics/physx3/px3Casts.h"
#include "T3D/physics/physx3/px3World.h"
#include "T3D/physics/physx3/px3Stream.h"
Px3Collision::Px3Collision()
{
}
Px3Collision::~Px3Collision()
{
for ( U32 i=0; i < mColShapes.size(); i++ )
{
Px3CollisionDesc *desc = mColShapes[i];
delete desc->pGeometry;
// Delete the descriptor.
delete desc;
}
mColShapes.clear();
}
void Px3Collision::addPlane( const PlaneF &plane )
{
physx::PxVec3 pos = px3Cast<physx::PxVec3>(plane.getPosition());
Px3CollisionDesc *desc = new Px3CollisionDesc;
desc->pGeometry = new physx::PxPlaneGeometry();
desc->pose = physx::PxTransform(pos, physx::PxQuat(physx::PxHalfPi, physx::PxVec3(0.0f, -1.0f, 0.0f)));
mColShapes.push_back(desc);
}
void Px3Collision::addBox( const Point3F &halfWidth,const MatrixF &localXfm )
{
Px3CollisionDesc *desc = new Px3CollisionDesc;
desc->pGeometry = new physx::PxBoxGeometry(px3Cast<physx::PxVec3>(halfWidth));
desc->pose = px3Cast<physx::PxTransform>(localXfm);
mColShapes.push_back(desc);
}
void Px3Collision::addSphere( F32 radius,
const MatrixF &localXfm )
{
Px3CollisionDesc *desc = new Px3CollisionDesc;
desc->pGeometry = new physx::PxSphereGeometry(radius);
desc->pose = px3Cast<physx::PxTransform>(localXfm);
mColShapes.push_back(desc);
}
void Px3Collision::addCapsule( F32 radius,
F32 height,
const MatrixF &localXfm )
{
Px3CollisionDesc *desc = new Px3CollisionDesc;
desc->pGeometry = new physx::PxCapsuleGeometry(radius,height*0.5);//uses half height
desc->pose = px3Cast<physx::PxTransform>(localXfm);
mColShapes.push_back(desc);
}
bool Px3Collision::addConvex( const Point3F *points,
U32 count,
const MatrixF &localXfm )
{
physx::PxCooking *cooking = Px3World::getCooking();
physx::PxConvexMeshDesc convexDesc;
convexDesc.points.data = points;
convexDesc.points.stride = sizeof(Point3F);
convexDesc.points.count = count;
convexDesc.flags = physx::PxConvexFlag::eFLIPNORMALS|physx::PxConvexFlag::eCOMPUTE_CONVEX | physx::PxConvexFlag::eINFLATE_CONVEX;
Px3MemOutStream stream;
if(!cooking->cookConvexMesh(convexDesc,stream))
return false;
physx::PxConvexMesh* convexMesh;
Px3MemInStream in(stream.getData(), stream.getSize());
convexMesh = gPhysics3SDK->createConvexMesh(in);
Px3CollisionDesc *desc = new Px3CollisionDesc;
physx::PxVec3 scale = px3Cast<physx::PxVec3>(localXfm.getScale());
physx::PxQuat rotation = px3Cast<physx::PxQuat>(QuatF(localXfm));
physx::PxMeshScale meshScale(scale,rotation);
desc->pGeometry = new physx::PxConvexMeshGeometry(convexMesh,meshScale);
desc->pose = px3Cast<physx::PxTransform>(localXfm);
mColShapes.push_back(desc);
return true;
}
bool Px3Collision::addTriangleMesh( const Point3F *vert,
U32 vertCount,
const U32 *index,
U32 triCount,
const MatrixF &localXfm )
{
physx::PxCooking *cooking = Px3World::getCooking();
physx::PxTriangleMeshDesc meshDesc;
meshDesc.points.count = vertCount;
meshDesc.points.data = vert;
meshDesc.points.stride = sizeof(Point3F);
meshDesc.triangles.count = triCount;
meshDesc.triangles.data = index;
meshDesc.triangles.stride = 3*sizeof(U32);
meshDesc.flags = physx::PxMeshFlag::eFLIPNORMALS;
Px3MemOutStream stream;
if(!cooking->cookTriangleMesh(meshDesc,stream))
return false;
physx::PxTriangleMesh *mesh;
Px3MemInStream in(stream.getData(), stream.getSize());
mesh = gPhysics3SDK->createTriangleMesh(in);
Px3CollisionDesc *desc = new Px3CollisionDesc;
desc->pGeometry = new physx::PxTriangleMeshGeometry(mesh);
desc->pose = px3Cast<physx::PxTransform>(localXfm);
mColShapes.push_back(desc);
return true;
}
bool Px3Collision::addHeightfield( const U16 *heights,
const bool *holes,
U32 blockSize,
F32 metersPerSample,
const MatrixF &localXfm )
{
const F32 heightScale = 0.03125f;
physx::PxHeightFieldSample* samples = (physx::PxHeightFieldSample*) new physx::PxHeightFieldSample[blockSize*blockSize];
memset(samples,0,blockSize*blockSize*sizeof(physx::PxHeightFieldSample));
physx::PxHeightFieldDesc heightFieldDesc;
heightFieldDesc.nbColumns = blockSize;
heightFieldDesc.nbRows = blockSize;
heightFieldDesc.thickness = -10.f;
heightFieldDesc.convexEdgeThreshold = 0;
heightFieldDesc.format = physx::PxHeightFieldFormat::eS16_TM;
heightFieldDesc.samples.data = samples;
heightFieldDesc.samples.stride = sizeof(physx::PxHeightFieldSample);
physx::PxU8 *currentByte = (physx::PxU8*)heightFieldDesc.samples.data;
for ( U32 row = 0; row < blockSize; row++ )
{
const U32 tess = ( row + 1 ) % 2;
for ( U32 column = 0; column < blockSize; column++ )
{
physx::PxHeightFieldSample *currentSample = (physx::PxHeightFieldSample*)currentByte;
U32 index = ( blockSize - row - 1 ) + ( column * blockSize );
currentSample->height = (physx::PxI16)heights[ index ];
if ( holes && holes[ getMax( (S32)index - 1, 0 ) ] ) // row index for holes adjusted so PhysX collision shape better matches rendered terrain
{
currentSample->materialIndex0 = physx::PxHeightFieldMaterial::eHOLE;
currentSample->materialIndex1 = physx::PxHeightFieldMaterial::eHOLE;
}
else
{
currentSample->materialIndex0 = 0;
currentSample->materialIndex1 = 0;
}
int flag = ( column + tess ) % 2;
if(flag)
currentSample->clearTessFlag();
else
currentSample->setTessFlag();
currentByte += heightFieldDesc.samples.stride;
}
}
physx::PxHeightField * hf = gPhysics3SDK->createHeightField(heightFieldDesc);
physx::PxHeightFieldGeometry *geom = new physx::PxHeightFieldGeometry(hf,physx::PxMeshGeometryFlags(),heightScale,metersPerSample,metersPerSample);
physx::PxTransform pose= physx::PxTransform(physx::PxQuat(Float_HalfPi, physx::PxVec3(1, 0, 0 )));
physx::PxTransform pose1= physx::PxTransform(physx::PxQuat(Float_Pi, physx::PxVec3(0, 0, 1 )));
physx::PxTransform pose2 = pose1 * pose;
pose2.p = physx::PxVec3(( blockSize - 1 ) * metersPerSample, 0, 0 );
Px3CollisionDesc *desc = new Px3CollisionDesc;
desc->pGeometry = geom;
desc->pose = pose2;
mColShapes.push_back(desc);
SAFE_DELETE(samples);
return true;
}
<|endoftext|>
|
<commit_before>/***************************************************************************
**
** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Karoliina T. Salminen <karoliina.t.salminen@nokia.com>
**
** This file is part of duicontrolpanel.
**
**
** This library is free software; you can redistribute it and/or
** modify it under the terms of the GNU Lesser General Public
** License version 2.1 as published by the Free Software Foundation
** and appearing in the file LICENSE.LGPL included in the packaging
** of this file.
**
****************************************************************************/
#include "dcpqmlwidget.h"
#include <MLabel>
#include <dcpdebug.h>
#include <QGraphicsLinearLayout>
#include <QDeclarativeError>
#include <QDeclarativeEngine>
#include <QDeclarativeComponent>
#include <QDeclarativeItem>
#include <MApplicationPage>
#include <QGraphicsSceneResizeEvent>
#include <QDebug>
DcpQmlWidget::DcpQmlWidget(const QString& qmlPath):
m_Object (0),
m_HandlesItsOwnWindow (false)
DcpQmlWidget::DcpQmlWidget(const QString& qmlPath)
{
// for the error labels:
new QGraphicsLinearLayout(Qt::Vertical, this);
// get as much space as possible:
setSizePolicy (QSizePolicy::Expanding, QSizePolicy::Expanding);
// create the qml widget:
QDeclarativeEngine *engine = new QDeclarativeEngine (this);
QDeclarativeComponent component(engine, QUrl::fromLocalFile(qmlPath));
m_Object =
qobject_cast<QGraphicsObject *>(component.create());
if (m_Object) {
// all fine, make it visible
m_Object->setParentItem (this);
m_HandlesItsOwnWindow =
QString(m_Object->metaObject()->className()).startsWith ("PageStackWindow_");
if (handlesItsOwnWindow()) {
} else {
setPreferredSize (m_Object->boundingRect().size());
enableAutoTitle();
}
} else {
// error happened
createErrorLabel (QString("Error loading %1").arg(qmlPath));
foreach (QDeclarativeError error, component.errors()) {
createErrorLabel (error.toString());
}
}
}
void DcpQmlWidget::resizeEvent ( QGraphicsSceneResizeEvent * event )
{
if (!handlesItsOwnWindow()) return;
// handle the size of the main m_Object (it is not a widget, so could
// not put it into a layout)
QDeclarativeItem* item = qobject_cast<QDeclarativeItem*>(m_Object);
dcp_failfunc_unless (item);
item->setSize (event->newSize());
}
void DcpQmlWidget::polishEvent ()
{
if (!handlesItsOwnWindow()) return;
// hide everything on the page (qml displays its window totally)
QGraphicsWidget* item = this;
MApplicationPage* page = 0;
do {
page = qobject_cast<MApplicationPage*>(item);
item = item->parentWidget();
} while (!page);
dcp_failfunc_unless (page);
page->setComponentsDisplayMode (MApplicationPage::AllComponents,
MApplicationPageModel::Hide);
}
bool DcpQmlWidget::pagePans () const
{
return !handlesItsOwnWindow();
}
bool DcpQmlWidget::handlesItsOwnWindow() const
{
return m_HandlesItsOwnWindow;
}
void DcpQmlWidget::createErrorLabel(const QString& text)
{
MLabel* label;
label = new MLabel(this);
label->setText(text);
label->setWrapMode (QTextOption::WrapAtWordBoundaryOrAnywhere);
label->setWordWrap (true);
label->setStyleName ("CommonBodyTextInverted");
((QGraphicsLinearLayout*)(layout()))->addItem(label);
DCP_WARNING(qPrintable(text));
}
void DcpQmlWidget::requestPage (int id)
{
emit changeWidget (id);
}
<commit_msg>little merge mistake<commit_after>/***************************************************************************
**
** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Karoliina T. Salminen <karoliina.t.salminen@nokia.com>
**
** This file is part of duicontrolpanel.
**
**
** This library is free software; you can redistribute it and/or
** modify it under the terms of the GNU Lesser General Public
** License version 2.1 as published by the Free Software Foundation
** and appearing in the file LICENSE.LGPL included in the packaging
** of this file.
**
****************************************************************************/
#include "dcpqmlwidget.h"
#include <MLabel>
#include <dcpdebug.h>
#include <QGraphicsLinearLayout>
#include <QDeclarativeError>
#include <QDeclarativeEngine>
#include <QDeclarativeComponent>
#include <QDeclarativeItem>
#include <MApplicationPage>
#include <QGraphicsSceneResizeEvent>
#include <QDebug>
DcpQmlWidget::DcpQmlWidget(const QString& qmlPath):
m_Object (0),
m_HandlesItsOwnWindow (false)
{
// for the error labels:
new QGraphicsLinearLayout(Qt::Vertical, this);
// get as much space as possible:
setSizePolicy (QSizePolicy::Expanding, QSizePolicy::Expanding);
// create the qml widget:
QDeclarativeEngine *engine = new QDeclarativeEngine (this);
QDeclarativeComponent component(engine, QUrl::fromLocalFile(qmlPath));
m_Object =
qobject_cast<QGraphicsObject *>(component.create());
if (m_Object) {
// all fine, make it visible
m_Object->setParentItem (this);
m_HandlesItsOwnWindow =
QString(m_Object->metaObject()->className()).startsWith ("PageStackWindow_");
if (handlesItsOwnWindow()) {
} else {
setPreferredSize (m_Object->boundingRect().size());
enableAutoTitle();
}
} else {
// error happened
createErrorLabel (QString("Error loading %1").arg(qmlPath));
foreach (QDeclarativeError error, component.errors()) {
createErrorLabel (error.toString());
}
}
}
void DcpQmlWidget::resizeEvent ( QGraphicsSceneResizeEvent * event )
{
if (!handlesItsOwnWindow()) return;
// handle the size of the main m_Object (it is not a widget, so could
// not put it into a layout)
QDeclarativeItem* item = qobject_cast<QDeclarativeItem*>(m_Object);
dcp_failfunc_unless (item);
item->setSize (event->newSize());
}
void DcpQmlWidget::polishEvent ()
{
if (!handlesItsOwnWindow()) return;
// hide everything on the page (qml displays its window totally)
QGraphicsWidget* item = this;
MApplicationPage* page = 0;
do {
page = qobject_cast<MApplicationPage*>(item);
item = item->parentWidget();
} while (!page);
dcp_failfunc_unless (page);
page->setComponentsDisplayMode (MApplicationPage::AllComponents,
MApplicationPageModel::Hide);
}
bool DcpQmlWidget::pagePans () const
{
return !handlesItsOwnWindow();
}
bool DcpQmlWidget::handlesItsOwnWindow() const
{
return m_HandlesItsOwnWindow;
}
void DcpQmlWidget::createErrorLabel(const QString& text)
{
MLabel* label;
label = new MLabel(this);
label->setText(text);
label->setWrapMode (QTextOption::WrapAtWordBoundaryOrAnywhere);
label->setWordWrap (true);
label->setStyleName ("CommonBodyTextInverted");
((QGraphicsLinearLayout*)(layout()))->addItem(label);
DCP_WARNING(qPrintable(text));
}
void DcpQmlWidget::requestPage (int id)
{
emit changeWidget (id);
}
<|endoftext|>
|
<commit_before>#include "fingerprint.h"
using namespace v8;
using v8::FunctionTemplate;
extern int initalized;
typedef struct __ENROLL_DATA__ {
uv_async_t async;
Nan::Persistent<Function> callback;
unsigned char *fingerprint_data;
size_t fingerprint_size;
int result;
} ENROLL_DATA;
typedef struct __ENROLL_STOP__ {
uv_async_t async;
Nan::Persistent<Function> callback;
} ENROLL_STOP;
static const char *enroll_result_to_name (int result)
{
switch (result) {
case FP_ENROLL_COMPLETE:
return "enroll-completed";
case FP_ENROLL_FAIL:
return "enroll-failed";
case FP_ENROLL_PASS:
return "enroll-stage-passed";
case FP_ENROLL_RETRY:
return "enroll-retry-scan";
case FP_ENROLL_RETRY_TOO_SHORT:
return "enroll-swipe-too-short";
case FP_ENROLL_RETRY_CENTER_FINGER:
return "enroll-finger-not-centered";
case FP_ENROLL_RETRY_REMOVE_FINGER:
return "enroll-remove-and-retry";
default:
return "enroll-unknown-error";
}
}
void enroll_stopped_after(uv_handle_t* handle)
{
ENROLL_STOP *data = container_of((uv_async_t *)handle, ENROLL_STOP, async);
if(!data)
return;
delete data;
}
void report_enroll_stopped(uv_async_t *handle, int status)
{
ENROLL_STOP *data = container_of(handle, ENROLL_STOP, async);
Nan::HandleScope();
if(!data)
return;
Nan::Callback callback(Nan::New<Function>(data->callback));
callback.Call(0, NULL);
uv_close((uv_handle_t*)&data->async, enroll_stopped_after);
}
static void enroll_stop_cb(struct fp_dev *dev, void *user_data)
{
ENROLL_STOP *data = (ENROLL_STOP*)user_data;
if(!data)
return;
uv_async_send(&data->async);
}
NAN_METHOD(enrollStop) {
struct fp_dev *dev;
bool ret = false;
ENROLL_STOP *data;
if(info.Length() != 2)
return;
dev = toFPDev(info[0]->ToNumber()->Value());
if(initalized != 0 || dev == NULL)
goto error;
data = new ENROLL_STOP;
data->callback.Reset(v8::Local<v8::Function>::Cast(info[1]));
uv_async_init(uv_default_loop(), &data->async, report_enroll_stopped);
ret = fp_async_enroll_stop(dev, enroll_stop_cb, data) == 0;
error:
info.GetReturnValue().Set(Nan::New(ret));
return;
}
void enroll_after(uv_handle_t* handle)
{
ENROLL_DATA *enrollData = container_of((uv_async_t *)handle, ENROLL_DATA, async);
if(!enrollData)
return;
if(enrollData->fingerprint_data)
free(enrollData->fingerprint_data);
enrollData->fingerprint_data = NULL;
enrollData->fingerprint_size = 0;
delete enrollData;
}
void report_enroll_progress(uv_async_t *handle, int status)
{
ENROLL_DATA *enrollData = container_of(handle, ENROLL_DATA, async);
Nan::HandleScope();
if(!enrollData)
return;
printf("report enroll progress: result: %d\n", enrollData->result);
Nan::Callback callback(Nan::New<Function>(enrollData->callback));
Local<Value> argv[3];
argv[0] = Nan::New(enrollData->result);
argv[1] = Nan::New(enroll_result_to_name(enrollData->result)).ToLocalChecked();
argv[2] = Nan::Null();
if(enrollData->result == FP_ENROLL_COMPLETE)
argv[2] = Nan::CopyBuffer((const char*)enrollData->fingerprint_data, enrollData->fingerprint_size).ToLocalChecked();
callback.Call(3, argv);
if(enrollData->result == FP_ENROLL_FAIL || enrollData->result == FP_ENROLL_COMPLETE) {
uv_close((uv_handle_t*)&enrollData->async, enroll_after);
}
}
static void enroll_stage_cb(struct fp_dev *dev, int result, struct fp_print_data *print, struct fp_img *img, void *user_data)
{
ENROLL_DATA *enrollData = (ENROLL_DATA*)user_data;
if(!enrollData || result < 0)
return;
enrollData->result = result;
if(print && result == FP_ENROLL_COMPLETE)
enrollData->fingerprint_size = fp_print_data_get_data(print, &enrollData->fingerprint_data);
uv_async_send(&enrollData->async);
if(img) fp_img_free(img);
if(print) fp_print_data_free(print);
}
NAN_METHOD(enrollStart) {
int r;
struct fp_dev *dev;
bool ret = false;
ENROLL_DATA *enrollData;
if(info.Length() != 2)
return;
dev = toFPDev(info[0]->ToNumber()->Value());
if(initalized != 0 || dev == NULL)
goto error;
enrollData = new ENROLL_DATA;
if(!enrollData)
goto error;
enrollData->fingerprint_data = NULL;
enrollData->fingerprint_size = 0;
enrollData->result = -1;
uv_async_init(uv_default_loop(), &enrollData->async, report_enroll_progress);
enrollData->callback.Reset(v8::Local<v8::Function>::Cast(info[1]));
r = fp_async_enroll_start(dev, enroll_stage_cb, (void*)enrollData);
if (r < 0 || r == FP_ENROLL_FAIL) {
printf("Enroll failed with error %d\n", r);
goto error;
}
ret = true;
error:
info.GetReturnValue().Set(Nan::New(ret));
return;
}
<commit_msg>compile with older uv<commit_after>#include "fingerprint.h"
using namespace v8;
using v8::FunctionTemplate;
extern int initalized;
typedef struct __ENROLL_DATA__ {
uv_async_t async;
Nan::Persistent<Function> callback;
unsigned char *fingerprint_data;
size_t fingerprint_size;
int result;
} ENROLL_DATA;
typedef struct __ENROLL_STOP__ {
uv_async_t async;
Nan::Persistent<Function> callback;
} ENROLL_STOP;
static const char *enroll_result_to_name (int result)
{
switch (result) {
case FP_ENROLL_COMPLETE:
return "enroll-completed";
case FP_ENROLL_FAIL:
return "enroll-failed";
case FP_ENROLL_PASS:
return "enroll-stage-passed";
case FP_ENROLL_RETRY:
return "enroll-retry-scan";
case FP_ENROLL_RETRY_TOO_SHORT:
return "enroll-swipe-too-short";
case FP_ENROLL_RETRY_CENTER_FINGER:
return "enroll-finger-not-centered";
case FP_ENROLL_RETRY_REMOVE_FINGER:
return "enroll-remove-and-retry";
default:
return "enroll-unknown-error";
}
}
void enroll_stopped_after(uv_handle_t* handle)
{
ENROLL_STOP *data = container_of((uv_async_t *)handle, ENROLL_STOP, async);
if(!data)
return;
delete data;
}
#ifdef OLD_UV_RUN_SIGNATURE
void report_enroll_stopped(uv_async_t *handle, int status)
#else
void report_enroll_stopped(uv_async_t *handle)
#endif
{
ENROLL_STOP *data = container_of(handle, ENROLL_STOP, async);
Nan::HandleScope();
if(!data)
return;
Nan::Callback callback(Nan::New<Function>(data->callback));
callback.Call(0, NULL);
uv_close((uv_handle_t*)&data->async, enroll_stopped_after);
}
static void enroll_stop_cb(struct fp_dev *dev, void *user_data)
{
ENROLL_STOP *data = (ENROLL_STOP*)user_data;
if(!data)
return;
uv_async_send(&data->async);
}
NAN_METHOD(enrollStop) {
struct fp_dev *dev;
bool ret = false;
ENROLL_STOP *data;
if(info.Length() != 2)
return;
dev = toFPDev(info[0]->ToNumber()->Value());
if(initalized != 0 || dev == NULL)
goto error;
data = new ENROLL_STOP;
data->callback.Reset(v8::Local<v8::Function>::Cast(info[1]));
uv_async_init(uv_default_loop(), &data->async, report_enroll_stopped);
ret = fp_async_enroll_stop(dev, enroll_stop_cb, data) == 0;
error:
info.GetReturnValue().Set(Nan::New(ret));
return;
}
void enroll_after(uv_handle_t* handle)
{
ENROLL_DATA *enrollData = container_of((uv_async_t *)handle, ENROLL_DATA, async);
if(!enrollData)
return;
if(enrollData->fingerprint_data)
free(enrollData->fingerprint_data);
enrollData->fingerprint_data = NULL;
enrollData->fingerprint_size = 0;
delete enrollData;
}
#ifdef OLD_UV_RUN_SIGNATURE
void report_enroll_progress(uv_async_t *handle, int status)
#else
void report_enroll_progress(uv_async_t *handle)
#endif
{
ENROLL_DATA *enrollData = container_of(handle, ENROLL_DATA, async);
Nan::HandleScope();
if(!enrollData)
return;
printf("report enroll progress: result: %d\n", enrollData->result);
Nan::Callback callback(Nan::New<Function>(enrollData->callback));
Local<Value> argv[3];
argv[0] = Nan::New(enrollData->result);
argv[1] = Nan::New(enroll_result_to_name(enrollData->result)).ToLocalChecked();
argv[2] = Nan::Null();
if(enrollData->result == FP_ENROLL_COMPLETE)
argv[2] = Nan::CopyBuffer((const char*)enrollData->fingerprint_data, enrollData->fingerprint_size).ToLocalChecked();
callback.Call(3, argv);
if(enrollData->result == FP_ENROLL_FAIL || enrollData->result == FP_ENROLL_COMPLETE) {
uv_close((uv_handle_t*)&enrollData->async, enroll_after);
}
}
static void enroll_stage_cb(struct fp_dev *dev, int result, struct fp_print_data *print, struct fp_img *img, void *user_data)
{
ENROLL_DATA *enrollData = (ENROLL_DATA*)user_data;
if(!enrollData || result < 0)
return;
enrollData->result = result;
if(print && result == FP_ENROLL_COMPLETE)
enrollData->fingerprint_size = fp_print_data_get_data(print, &enrollData->fingerprint_data);
uv_async_send(&enrollData->async);
if(img) fp_img_free(img);
if(print) fp_print_data_free(print);
}
NAN_METHOD(enrollStart) {
int r;
struct fp_dev *dev;
bool ret = false;
ENROLL_DATA *enrollData;
if(info.Length() != 2)
return;
dev = toFPDev(info[0]->ToNumber()->Value());
if(initalized != 0 || dev == NULL)
goto error;
enrollData = new ENROLL_DATA;
if(!enrollData)
goto error;
enrollData->fingerprint_data = NULL;
enrollData->fingerprint_size = 0;
enrollData->result = -1;
uv_async_init(uv_default_loop(), &enrollData->async, report_enroll_progress);
enrollData->callback.Reset(v8::Local<v8::Function>::Cast(info[1]));
r = fp_async_enroll_start(dev, enroll_stage_cb, (void*)enrollData);
if (r < 0 || r == FP_ENROLL_FAIL) {
printf("Enroll failed with error %d\n", r);
goto error;
}
ret = true;
error:
info.GetReturnValue().Set(Nan::New(ret));
return;
}
<|endoftext|>
|
<commit_before>/**
* Copyright (C) 2012 by INdT
*
* 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
* 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 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.
*
* @author Rodrigo Goncalves de Oliveira <rodrigo.goncalves@openbossa.org>
* @author Roger Felipe Zanoni da Silva <roger.zanoni@openbossa.org>
*/
#include "entity.h"
#include "enums.h"
#include "scene.h"
#include "game.h"
#include "behavior.h"
#include "fixture.h"
#include "material.h"
Entity::Entity(Scene *parent)
: Box2DBaseItem(parent)
, m_updateInterval(0)
, m_scene(0)
, m_behavior(0)
, m_body(0)
, m_linearDamping(0.0f)
, m_angularDamping(0.0f)
, m_bodyType(Quasi::StaticBodyType)
, m_bullet(false)
, m_sleepingAllowed(true)
, m_fixedRotation(false)
, m_active(true)
, m_sensorFixture(0)
{
setTransformOrigin(Center);
connect(this, SIGNAL(rotationChanged()), SLOT(onRotationChanged()));
}
Entity::~Entity()
{
if (!m_world || !m_body)
return;
#if QT_VERSION >= 0x050000
QQuickItem *child;
#else
QGraphicsItem *child;
#endif
foreach (child, childItems())
if (Fixture *fixture = dynamic_cast<Fixture *>(child))
delete fixture;
m_worldPtr->DestroyBody(m_body);
m_body = 0;
}
void Entity::update(const int &delta)
{
if ((m_updateInterval && m_updateTime.elapsed() >= m_updateInterval)
|| !m_updateInterval) {
m_updateTime.restart();
if (m_behavior) {
m_behavior->setDelta(delta);
m_behavior->setEntity(this);
m_behavior->update(delta);
m_behavior->setEntity(0);
}
}
#if QT_VERSION >= 0x050000
QQuickItem *child;
#else
QGraphicsItem *child;
#endif
foreach (child, childItems())
if (Entity *item = dynamic_cast<Entity *>(child))
item->update(delta);
}
int Entity::updateInterval() const
{
return m_updateInterval;
}
void Entity::setUpdateInterval(const int &updateInterval)
{
if (m_updateInterval != updateInterval) {
m_updateInterval = updateInterval;
emit updateIntervalChanged();
m_updateTime.restart();
}
}
Scene *Entity::scene() const
{
return m_scene;
}
void Entity::setScene(Scene *scene)
{
m_scene = scene;
}
Game *Entity::game() const
{
if (m_scene)
return m_scene->game();
return 0;
}
Behavior *Entity::behavior() const
{
return m_behavior;
}
void Entity::setBehavior(Behavior *behavior)
{
if (m_behavior == behavior)
return;
m_behavior = behavior;
emit behaviorChanged();
}
void Entity::componentComplete()
{
if (!m_initialized)
initialize();
}
b2Body *Entity::body() const
{
return m_body;
}
void Entity::onRotationChanged()
{
if (!m_synchronizing && m_body) {
m_body->SetTransform(m_body->GetPosition(),
(rotation() * 2 * b2_pi) / -360.0);
}
}
/*
* Shamelessly stolen from qml-box2d project at gitorious
*
* https://gitorious.org/qml-box2d/qml-box2d
*/
void Entity::initialize()
{
if (m_initialized || !m_world)
return;
b2BodyDef bodyDef;
bodyDef.type = static_cast<b2BodyType>(m_bodyType);
bodyDef.position.Set((x() + width() / 2.0) / m_scaleRatio,
(-y() - height() / 2.0) / m_scaleRatio);
bodyDef.angle = -(rotation() * (2 * b2_pi)) / 360.0;
bodyDef.linearDamping = m_linearDamping;
bodyDef.angularDamping = m_angularDamping;
bodyDef.bullet = m_bullet;
bodyDef.allowSleep = m_sleepingAllowed;
bodyDef.fixedRotation = m_fixedRotation;
m_body = m_worldPtr->CreateBody(&bodyDef);
initializeFixtures();
m_initialized = true;
}
qreal Entity::linearDamping() const
{
return m_linearDamping;
}
void Entity::setLinearDamping(const qreal &linearDamping)
{
if (m_linearDamping != linearDamping) {
m_linearDamping = linearDamping;
if (m_body)
m_body->SetLinearDamping(linearDamping);
emit linearDampingChanged();
}
}
qreal Entity::angularDamping() const
{
return m_angularDamping;
}
void Entity::setAngularDamping(const qreal &angularDamping)
{
if (m_angularDamping != angularDamping) {
m_angularDamping = angularDamping;
if (m_body)
m_body->SetAngularDamping(angularDamping);
emit angularDampingChanged();
}
}
Quasi::BodyType Entity::bodyType() const
{
return m_bodyType;
}
void Entity::setBodyType(const Quasi::BodyType &bodyType)
{
if (m_bodyType != bodyType) {
m_bodyType = bodyType;
if (m_body)
m_body->SetType((b2BodyType)bodyType);
emit bodyTypeChanged();
}
}
bool Entity::bullet() const
{
return m_bullet;
}
void Entity::setBullet(const bool &bullet)
{
if (m_bullet != bullet) {
m_bullet = bullet;
if (m_body)
m_body->SetBullet(bullet);
emit bulletChanged();
}
}
bool Entity::sleepingAllowed() const
{
return m_sleepingAllowed;
}
void Entity::setSleepingAllowed(const bool &sleepingAllowed)
{
if (m_sleepingAllowed != sleepingAllowed) {
m_sleepingAllowed = sleepingAllowed;
if (m_body)
m_body->SetSleepingAllowed(sleepingAllowed);
emit sleepingAllowedChanged();
}
}
bool Entity::fixedRotation() const
{
return m_fixedRotation;
}
void Entity::setFixedRotation(const bool &fixedRotation)
{
if (m_fixedRotation != fixedRotation) {
m_fixedRotation = fixedRotation;
if (m_body)
m_body->SetFixedRotation(fixedRotation);
emit fixedRotationChanged();
}
}
bool Entity::active() const
{
return m_active;
}
void Entity::setActive(const bool &active)
{
if (m_active != active) {
m_active = active;
if (m_body)
m_body->SetActive(active);
emit activeChanged();
}
}
void Entity::applyTorque(const float &torque)
{
if (m_body)
m_body->ApplyTorque(torque);
}
void Entity::applyLinearImpulse(const QPointF &impulse, const QPointF &point)
{
if (m_body) {
m_body->ApplyLinearImpulse(b2Vec2(impulse.x() / m_scaleRatio,
-impulse.y() / m_scaleRatio),
b2Vec2(point.x() / m_scaleRatio,
-point.y() / m_scaleRatio));
}
}
void Entity::setLinearVelocity(const QPointF &velocity)
{
if (m_body) {
m_body->SetLinearVelocity(b2Vec2(velocity.x() / m_scaleRatio,
-velocity.y() / m_scaleRatio));
}
}
void Entity::setAngularVelocity(const float &velocity)
{
if (m_body) {
m_body->SetAngularVelocity(velocity);
}
}
void Entity::geometryChanged(const QRectF &newGeometry,
const QRectF &oldGeometry)
{
if (!m_synchronizing && m_body) {
if (newGeometry.topLeft() != oldGeometry.topLeft()) {
const QPointF pos = newGeometry.topLeft();
m_body->SetTransform(b2Vec2((pos.x() + width() / 2.0) / m_scaleRatio,
(-pos.y() - height() / 2.0) / m_scaleRatio),
m_body->GetAngle());
}
}
#if QT_VERSION >= 0x050000
QQuickItem::geometryChanged(newGeometry, oldGeometry);
#else
QDeclarativeItem::geometryChanged(newGeometry, oldGeometry);
#endif
}
b2Vec2 Entity::b2TransformOrigin() const
{
b2Vec2 vec;
if (m_body)
vec = m_body->GetPosition();
return vec;
}
float Entity::b2Angle() const
{
float32 angle = 0.0f;
if (m_body)
angle = m_body->GetAngle();
return angle;
}
void Entity::initializeFixtures()
{
#if QT_VERSION >= 0x050000
QQuickItem *item;
#else
QGraphicsItem *item;
#endif
bool createSensor = true;
foreach (item, childItems()) {
if (Fixture *fixture = dynamic_cast<Fixture *>(item)) {
createSensor = false;
fixture->setWorld(m_world);
fixture->setBody(this);
fixture->initialize();
}
}
if (createSensor)
createSensorFixture();
}
#if QT_VERSION >= 0x050000
void Entity::itemChange(ItemChange change, const ItemChangeData &data)
#else
QVariant Entity::itemChange(GraphicsItemChange change, const QVariant &value)
#endif
{
if (isComponentComplete() && change == ItemChildAddedChange) {
#if QT_VERSION >= 0x050000
QQuickItem *child = data.item;
#else
QGraphicsItem *child = value.value<QGraphicsItem *>();
#endif
if (Fixture *fixture = dynamic_cast<Fixture *>(child)) {
destroySensorFixture();
fixture->setWorld(m_world);
fixture->setBody(this);
fixture->initialize();
}
}
#if QT_VERSION >= 0x050000
Box2DBaseItem::itemChange(change, data);
#else
return Box2DBaseItem::itemChange(change, value);
#endif
}
void Entity::createSensorFixture()
{
setBodyType(Quasi::DynamicBodyType);
m_body->SetGravityScale(0);
m_sensorFixture = new Fixture(this);
m_sensorFixture->setMaterial(new Material(this));
m_sensorFixture->setWidth(width());
m_sensorFixture->setHeight(height());
m_sensorFixture->setShapeItem(this);
m_sensorFixture->setWorld(m_world);
m_sensorFixture->setBody(this);
m_sensorFixture->setSensor(true);
m_sensorFixture->updateFixture();
}
void Entity::destroySensorFixture()
{
if (!m_sensorFixture)
return;
m_sensorFixture->deleteLater();
m_sensorFixture = 0;
}
<commit_msg>Fix declarative items initialization chain<commit_after>/**
* Copyright (C) 2012 by INdT
*
* 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
* 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 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.
*
* @author Rodrigo Goncalves de Oliveira <rodrigo.goncalves@openbossa.org>
* @author Roger Felipe Zanoni da Silva <roger.zanoni@openbossa.org>
*/
#include "entity.h"
#include "enums.h"
#include "scene.h"
#include "game.h"
#include "behavior.h"
#include "fixture.h"
#include "material.h"
Entity::Entity(Scene *parent)
: Box2DBaseItem(parent)
, m_updateInterval(0)
, m_scene(0)
, m_behavior(0)
, m_body(0)
, m_linearDamping(0.0f)
, m_angularDamping(0.0f)
, m_bodyType(Quasi::StaticBodyType)
, m_bullet(false)
, m_sleepingAllowed(true)
, m_fixedRotation(false)
, m_active(true)
, m_sensorFixture(0)
{
setTransformOrigin(Center);
connect(this, SIGNAL(rotationChanged()), SLOT(onRotationChanged()));
}
Entity::~Entity()
{
if (!m_world || !m_body)
return;
#if QT_VERSION >= 0x050000
QQuickItem *child;
#else
QGraphicsItem *child;
#endif
foreach (child, childItems())
if (Fixture *fixture = dynamic_cast<Fixture *>(child))
delete fixture;
m_worldPtr->DestroyBody(m_body);
m_body = 0;
}
void Entity::update(const int &delta)
{
if ((m_updateInterval && m_updateTime.elapsed() >= m_updateInterval)
|| !m_updateInterval) {
m_updateTime.restart();
if (m_behavior) {
m_behavior->setDelta(delta);
m_behavior->setEntity(this);
m_behavior->update(delta);
m_behavior->setEntity(0);
}
}
#if QT_VERSION >= 0x050000
QQuickItem *child;
#else
QGraphicsItem *child;
#endif
foreach (child, childItems())
if (Entity *item = dynamic_cast<Entity *>(child))
item->update(delta);
}
int Entity::updateInterval() const
{
return m_updateInterval;
}
void Entity::setUpdateInterval(const int &updateInterval)
{
if (m_updateInterval != updateInterval) {
m_updateInterval = updateInterval;
emit updateIntervalChanged();
m_updateTime.restart();
}
}
Scene *Entity::scene() const
{
return m_scene;
}
void Entity::setScene(Scene *scene)
{
m_scene = scene;
}
Game *Entity::game() const
{
if (m_scene)
return m_scene->game();
return 0;
}
Behavior *Entity::behavior() const
{
return m_behavior;
}
void Entity::setBehavior(Behavior *behavior)
{
if (m_behavior == behavior)
return;
m_behavior = behavior;
emit behaviorChanged();
}
void Entity::componentComplete()
{
Box2DBaseItem::componentComplete();
if (!m_initialized)
initialize();
}
b2Body *Entity::body() const
{
return m_body;
}
void Entity::onRotationChanged()
{
if (!m_synchronizing && m_body) {
m_body->SetTransform(m_body->GetPosition(),
(rotation() * 2 * b2_pi) / -360.0);
}
}
/*
* Shamelessly stolen from qml-box2d project at gitorious
*
* https://gitorious.org/qml-box2d/qml-box2d
*/
void Entity::initialize()
{
if (m_initialized || !m_world)
return;
b2BodyDef bodyDef;
bodyDef.type = static_cast<b2BodyType>(m_bodyType);
bodyDef.position.Set((x() + width() / 2.0) / m_scaleRatio,
(-y() - height() / 2.0) / m_scaleRatio);
bodyDef.angle = -(rotation() * (2 * b2_pi)) / 360.0;
bodyDef.linearDamping = m_linearDamping;
bodyDef.angularDamping = m_angularDamping;
bodyDef.bullet = m_bullet;
bodyDef.allowSleep = m_sleepingAllowed;
bodyDef.fixedRotation = m_fixedRotation;
m_body = m_worldPtr->CreateBody(&bodyDef);
initializeFixtures();
m_initialized = true;
}
qreal Entity::linearDamping() const
{
return m_linearDamping;
}
void Entity::setLinearDamping(const qreal &linearDamping)
{
if (m_linearDamping != linearDamping) {
m_linearDamping = linearDamping;
if (m_body)
m_body->SetLinearDamping(linearDamping);
emit linearDampingChanged();
}
}
qreal Entity::angularDamping() const
{
return m_angularDamping;
}
void Entity::setAngularDamping(const qreal &angularDamping)
{
if (m_angularDamping != angularDamping) {
m_angularDamping = angularDamping;
if (m_body)
m_body->SetAngularDamping(angularDamping);
emit angularDampingChanged();
}
}
Quasi::BodyType Entity::bodyType() const
{
return m_bodyType;
}
void Entity::setBodyType(const Quasi::BodyType &bodyType)
{
if (m_bodyType != bodyType) {
m_bodyType = bodyType;
if (m_body)
m_body->SetType((b2BodyType)bodyType);
emit bodyTypeChanged();
}
}
bool Entity::bullet() const
{
return m_bullet;
}
void Entity::setBullet(const bool &bullet)
{
if (m_bullet != bullet) {
m_bullet = bullet;
if (m_body)
m_body->SetBullet(bullet);
emit bulletChanged();
}
}
bool Entity::sleepingAllowed() const
{
return m_sleepingAllowed;
}
void Entity::setSleepingAllowed(const bool &sleepingAllowed)
{
if (m_sleepingAllowed != sleepingAllowed) {
m_sleepingAllowed = sleepingAllowed;
if (m_body)
m_body->SetSleepingAllowed(sleepingAllowed);
emit sleepingAllowedChanged();
}
}
bool Entity::fixedRotation() const
{
return m_fixedRotation;
}
void Entity::setFixedRotation(const bool &fixedRotation)
{
if (m_fixedRotation != fixedRotation) {
m_fixedRotation = fixedRotation;
if (m_body)
m_body->SetFixedRotation(fixedRotation);
emit fixedRotationChanged();
}
}
bool Entity::active() const
{
return m_active;
}
void Entity::setActive(const bool &active)
{
if (m_active != active) {
m_active = active;
if (m_body)
m_body->SetActive(active);
emit activeChanged();
}
}
void Entity::applyTorque(const float &torque)
{
if (m_body)
m_body->ApplyTorque(torque);
}
void Entity::applyLinearImpulse(const QPointF &impulse, const QPointF &point)
{
if (m_body) {
m_body->ApplyLinearImpulse(b2Vec2(impulse.x() / m_scaleRatio,
-impulse.y() / m_scaleRatio),
b2Vec2(point.x() / m_scaleRatio,
-point.y() / m_scaleRatio));
}
}
void Entity::setLinearVelocity(const QPointF &velocity)
{
if (m_body) {
m_body->SetLinearVelocity(b2Vec2(velocity.x() / m_scaleRatio,
-velocity.y() / m_scaleRatio));
}
}
void Entity::setAngularVelocity(const float &velocity)
{
if (m_body) {
m_body->SetAngularVelocity(velocity);
}
}
void Entity::geometryChanged(const QRectF &newGeometry,
const QRectF &oldGeometry)
{
if (!m_synchronizing && m_body) {
if (newGeometry.topLeft() != oldGeometry.topLeft()) {
const QPointF pos = newGeometry.topLeft();
m_body->SetTransform(b2Vec2((pos.x() + width() / 2.0) / m_scaleRatio,
(-pos.y() - height() / 2.0) / m_scaleRatio),
m_body->GetAngle());
}
}
#if QT_VERSION >= 0x050000
QQuickItem::geometryChanged(newGeometry, oldGeometry);
#else
QDeclarativeItem::geometryChanged(newGeometry, oldGeometry);
#endif
}
b2Vec2 Entity::b2TransformOrigin() const
{
b2Vec2 vec;
if (m_body)
vec = m_body->GetPosition();
return vec;
}
float Entity::b2Angle() const
{
float32 angle = 0.0f;
if (m_body)
angle = m_body->GetAngle();
return angle;
}
void Entity::initializeFixtures()
{
#if QT_VERSION >= 0x050000
QQuickItem *item;
#else
QGraphicsItem *item;
#endif
bool createSensor = true;
foreach (item, childItems()) {
if (Fixture *fixture = dynamic_cast<Fixture *>(item)) {
createSensor = false;
fixture->setWorld(m_world);
fixture->setBody(this);
fixture->initialize();
}
}
if (createSensor)
createSensorFixture();
}
#if QT_VERSION >= 0x050000
void Entity::itemChange(ItemChange change, const ItemChangeData &data)
#else
QVariant Entity::itemChange(GraphicsItemChange change, const QVariant &value)
#endif
{
if (isComponentComplete() && change == ItemChildAddedChange) {
#if QT_VERSION >= 0x050000
QQuickItem *child = data.item;
#else
QGraphicsItem *child = value.value<QGraphicsItem *>();
#endif
if (Fixture *fixture = dynamic_cast<Fixture *>(child)) {
destroySensorFixture();
fixture->setWorld(m_world);
fixture->setBody(this);
fixture->initialize();
}
}
#if QT_VERSION >= 0x050000
Box2DBaseItem::itemChange(change, data);
#else
return Box2DBaseItem::itemChange(change, value);
#endif
}
void Entity::createSensorFixture()
{
setBodyType(Quasi::DynamicBodyType);
m_body->SetGravityScale(0);
m_sensorFixture = new Fixture(this);
m_sensorFixture->setMaterial(new Material(this));
m_sensorFixture->setWidth(width());
m_sensorFixture->setHeight(height());
m_sensorFixture->setShapeItem(this);
m_sensorFixture->setWorld(m_world);
m_sensorFixture->setBody(this);
m_sensorFixture->setSensor(true);
m_sensorFixture->updateFixture();
}
void Entity::destroySensorFixture()
{
if (!m_sensorFixture)
return;
m_sensorFixture->deleteLater();
m_sensorFixture = 0;
}
<|endoftext|>
|
<commit_before>// Copyright 2010-2013 RethinkDB, all rights reserved.
#ifndef ERRORS_HPP_
#define ERRORS_HPP_
#include <errno.h>
#include <signal.h>
#include <stdlib.h>
#ifndef DISABLE_BREAKPOINTS
#ifdef __linux__
#if defined __i386 || defined __x86_64
#define BREAKPOINT __asm__ volatile ("int3")
#else /* not x86/amd64 */
#define BREAKPOINT (raise(SIGTRAP))
#endif /* x86/amd64 */
#endif /* __linux__ */
#ifdef __MACH__
#define BREAKPOINT (raise(SIGTRAP))
#endif
#else /* Breakpoints Disabled */
#define BREAKPOINT
#endif /* DISABLE_BREAKPOINTS */
#define CT_ASSERT(e) do { enum { compile_time_assert_error = 1/(!!(e)) }; } while (0)
#ifndef NDEBUG
#define DEBUG_ONLY(...) __VA_ARGS__
#define DEBUG_ONLY_CODE(expr) do { expr; } while (0)
#else
#define DEBUG_ONLY(...)
#define DEBUG_ONLY_CODE(expr) ((void)(0))
#endif
#define NORETURN __attribute__((__noreturn__))
/* Accessors to errno.
* Please access errno *only* through these access functions.
* Accessing errno directly is unsafe in the context of
* coroutines because compiler optimizations can interfer with TLS, which
* might be used for errno.
* See thread_local.hpp for a more detailed explanation of the issue. */
int get_errno();
void set_errno(int new_errno);
/* The following line can be useful for identifying illegal direct access in our
* code. However it cannot be turned on in general because some system headers use
* errno and don't compile with this. */
//#pragma GCC poison errno
/* Error handling
*
* There are several ways to report errors in RethinkDB:
* fail_due_to_user_error(msg, ...) fail and report line number/stack trace. Should only be used when the user
* is at fault (e.g. provided wrong database file name) and it is reasonable to
* fail instead of handling the problem more gracefully.
*
* The following macros are used only for the cases of programmer error checking. For the time being they are also used
* for system error checking (especially the *_err variants).
*
* crash(msg, ...) always fails and reports line number and such. Never returns.
* crash_or_trap(msg, ...) same as above, but traps into debugger if it is present instead of terminating.
* That means that it possibly can return, and one can continue stepping through the code in the debugger.
* All off the rassert/guarantee functions use crash_or_trap.
* rassert(cond) makes sure cond is true and is a no-op in release mode
* rassert(cond, msg, ...) ditto, with additional message and possibly some arguments used for formatting
* rassert_err(cond) same as rassert(cond), but also print errno error description
* rassert_err(cond, msg, ...) same as rassert(cond, msg, ...), but also print errno error description
* guarantee(cond) same as rassert(cond), but the check is still done in release mode. Do not use for expensive checks!
* guarantee(cond, msg, ...) same as rassert(cond, msg, ...), but the check is still done in release mode. Do not use for expensive checks!
* guarantee_err(cond) same as guarantee(cond), but also print errno error description
* guarantee_err(cond, msg, ...) same as guarantee(cond, msg, ...), but also print errno error description
* guarantee_xerr(cond, err, msg, ...) same as guarantee_err(cond, msg, ...), but also allows to specify errno as err argument
* (useful for async io functions, which return negated errno)
*
* The names rassert* are used instead of assert* because /usr/include/assert.h undefines assert macro and redefines it with its own version
* every single time it gets included.
*/
#ifndef NDEBUG
#define DEBUG_VAR
#else
#define DEBUG_VAR __attribute__((unused))
#endif
#define UNUSED __attribute__((unused))
#define MUST_USE __attribute__((warn_unused_result))
#define fail_due_to_user_error(msg, ...) do { \
report_user_error(msg, ##__VA_ARGS__); \
BREAKPOINT; \
exit(EXIT_FAILURE); \
} while (0)
#define crash(msg, ...) do { \
report_fatal_error(__FILE__, __LINE__, msg, ##__VA_ARGS__); \
BREAKPOINT; /* this used to be abort(), but it didn't cause VALGRIND to print a backtrace */ \
abort(); \
} while (0)
#define crash_1_13_block
#define crash_or_trap(msg, ...) do { \
report_fatal_error(__FILE__, __LINE__, msg, ##__VA_ARGS__); \
BREAKPOINT; \
} while (0)
void report_fatal_error(const char*, int, const char*, ...) __attribute__((format (printf, 3, 4)));
void report_user_error(const char*, ...) __attribute__((format (printf, 1, 2)));
// Our usual crash() method does not work well in out-of-memory conditions, because
// it performs heap-allocations itself. Use `crash_oom()` instead for these cases.
void crash_oom();
// Possibly using buf to store characters, returns a pointer to a strerror-style error string. This
// has the same contract as the GNU (char *)-returning strerror_r. The return value is a pointer to
// a nul-terminated string, either equal to buf or pointing at a statically allocated string.
MUST_USE const char *errno_string_maybe_using_buffer(int errsv, char *buf, size_t buflen);
#define stringify(x) #x
#define format_assert_message(assert_type, cond) assert_type " failed: [" stringify(cond) "] "
#define guarantee(cond, msg...) do { \
if (!(cond)) { \
crash_or_trap(format_assert_message("Guarantee", cond) msg); \
} \
} while (0)
#define guarantee_xerr(cond, err, msg, args...) do { \
int guarantee_xerr_errsv = (err); \
if (!(cond)) { \
if (guarantee_xerr_errsv == 0) { \
crash_or_trap(format_assert_message("Guarantee", cond) msg, ##args); \
} else { \
char guarantee_xerr_buf[250]; \
const char *errstr = errno_string_maybe_using_buffer(guarantee_xerr_errsv, guarantee_xerr_buf, sizeof(guarantee_xerr_buf)); \
crash_or_trap(format_assert_message("Guarantee", cond) " (errno %d - %s) " msg, guarantee_xerr_errsv, errstr, ##args); \
} \
} \
} while (0)
#define guarantee_err(cond, msg, args...) guarantee_xerr(cond, get_errno(), msg, ##args)
#define unreachable(msg, ...) crash("Unreachable code: " msg, ##__VA_ARGS__) // can't use crash_or_trap since code needs to depend on its noreturn property
#define not_implemented(msg, ...) crash_or_trap("Not implemented: " msg, ##__VA_ARGS__)
#ifdef NDEBUG
#define rassert(cond, msg...) ((void)(0))
#define rassert_err(cond, msg...) ((void)(0))
#else
#define rassert(cond, msg...) do { \
if (!(cond)) { \
crash_or_trap(format_assert_message("Assertion", cond) msg); \
} \
} while (0)
#define rassert_err(cond, msg, args...) do { \
int rassert_err_errsv = get_errno(); \
if (!(cond)) { \
if (rassert_err_errsv == 0) { \
crash_or_trap(format_assert_message("Assert", cond) msg); \
} else { \
char rassert_err_buf[250]; \
const char *errstr = errno_string_maybe_using_buffer(rassert_err_errsv, rassert_err_buf, sizeof(rassert_err_buf)); \
crash_or_trap(format_assert_message("Assert", cond) " (errno %d - %s) " msg, rassert_err_errsv, errstr, ##args); \
} \
} \
} while (0)
#endif
void install_generic_crash_handler();
void install_new_oom_handler();
// If you include errors.hpp before including a Boost library, then Boost assertion
// failures will be forwarded to the RethinkDB error mechanism.
#define BOOST_ENABLE_ASSERT_HANDLER
namespace boost {
void assertion_failed(char const * expr, char const * function, char const * file, long line); // NOLINT(runtime/int)
}
#define DISABLE_COPYING(T) \
T(const T&) = delete; \
T& operator=(const T&) = delete
/* Put these after functions to indicate what they throw. In release mode, they
turn into noops so that the compiler doesn't have to generate exception-checking
code everywhere. If you need to add an exception specification for compatibility
with e.g. a virtual method, don't use these, or your code won't compile in
release mode. */
#ifdef NDEBUG
#define THROWS_NOTHING
#define THROWS_ONLY(...)
#else
#define THROWS_NOTHING throw ()
#define THROWS_ONLY(...) throw (__VA_ARGS__)
#endif
// This is a workaround for old versions of boost causing a compilation error
#include <boost/version.hpp> // NOLINT(build/include_order)
#if (BOOST_VERSION >= 104200) && (BOOST_VERSION <= 104399)
#include <boost/config.hpp> // NOLINT(build/include_order)
#undef BOOST_HAS_RVALUE_REFS
#endif
#ifdef __GNUC__
#define GNUC_VERSION (__GNUC__ * 10000 + __GNUC_MINOR__ * 100 + __GNUC_PATCHLEVEL__)
#endif
/** RVALUE_THIS
*
* This macro is used to annotate methods that treat *this as an
* rvalue reference. On compilers that support it, it expands to &&
* and all uses of the method on non-rvlaue *this are reported as
* errors.
*
* The supported compilers are clang >= 2.9 and gcc >= 4.8.1
*
**/
#if defined(__clang__)
#if __has_extension(cxx_rvalue_references)
#define RVALUE_THIS &&
#else
#define RVALUE_THIS
#endif
#elif __GNUC__ > 4 || (__GNUC__ == 4 && \
(__GNUC_MINOR__ > 8 || (__GNUC_MINOR__ == 8 && \
__GNUC_PATCHLEVEL__ > 1)))
#define RVALUE_THIS &&
#else
#define RVALUE_THIS
#endif
#if defined(__clang__)
#if !__has_extension(cxx_override_control)
#define override
#define final
#endif
#elif GNUC_VERSION < 40700
#define override
#define final
#endif
#endif /* ERRORS_HPP_ */
<commit_msg>remove dead code<commit_after>// Copyright 2010-2013 RethinkDB, all rights reserved.
#ifndef ERRORS_HPP_
#define ERRORS_HPP_
#include <errno.h>
#include <signal.h>
#include <stdlib.h>
#ifndef DISABLE_BREAKPOINTS
#ifdef __linux__
#if defined __i386 || defined __x86_64
#define BREAKPOINT __asm__ volatile ("int3")
#else /* not x86/amd64 */
#define BREAKPOINT (raise(SIGTRAP))
#endif /* x86/amd64 */
#endif /* __linux__ */
#ifdef __MACH__
#define BREAKPOINT (raise(SIGTRAP))
#endif
#else /* Breakpoints Disabled */
#define BREAKPOINT
#endif /* DISABLE_BREAKPOINTS */
#define CT_ASSERT(e) do { enum { compile_time_assert_error = 1/(!!(e)) }; } while (0)
#ifndef NDEBUG
#define DEBUG_ONLY(...) __VA_ARGS__
#define DEBUG_ONLY_CODE(expr) do { expr; } while (0)
#else
#define DEBUG_ONLY(...)
#define DEBUG_ONLY_CODE(expr) ((void)(0))
#endif
#define NORETURN __attribute__((__noreturn__))
/* Accessors to errno.
* Please access errno *only* through these access functions.
* Accessing errno directly is unsafe in the context of
* coroutines because compiler optimizations can interfer with TLS, which
* might be used for errno.
* See thread_local.hpp for a more detailed explanation of the issue. */
int get_errno();
void set_errno(int new_errno);
/* The following line can be useful for identifying illegal direct access in our
* code. However it cannot be turned on in general because some system headers use
* errno and don't compile with this. */
//#pragma GCC poison errno
/* Error handling
*
* There are several ways to report errors in RethinkDB:
* fail_due_to_user_error(msg, ...) fail and report line number/stack trace. Should only be used when the user
* is at fault (e.g. provided wrong database file name) and it is reasonable to
* fail instead of handling the problem more gracefully.
*
* The following macros are used only for the cases of programmer error checking. For the time being they are also used
* for system error checking (especially the *_err variants).
*
* crash(msg, ...) always fails and reports line number and such. Never returns.
* crash_or_trap(msg, ...) same as above, but traps into debugger if it is present instead of terminating.
* That means that it possibly can return, and one can continue stepping through the code in the debugger.
* All off the rassert/guarantee functions use crash_or_trap.
* rassert(cond) makes sure cond is true and is a no-op in release mode
* rassert(cond, msg, ...) ditto, with additional message and possibly some arguments used for formatting
* rassert_err(cond) same as rassert(cond), but also print errno error description
* rassert_err(cond, msg, ...) same as rassert(cond, msg, ...), but also print errno error description
* guarantee(cond) same as rassert(cond), but the check is still done in release mode. Do not use for expensive checks!
* guarantee(cond, msg, ...) same as rassert(cond, msg, ...), but the check is still done in release mode. Do not use for expensive checks!
* guarantee_err(cond) same as guarantee(cond), but also print errno error description
* guarantee_err(cond, msg, ...) same as guarantee(cond, msg, ...), but also print errno error description
* guarantee_xerr(cond, err, msg, ...) same as guarantee_err(cond, msg, ...), but also allows to specify errno as err argument
* (useful for async io functions, which return negated errno)
*
* The names rassert* are used instead of assert* because /usr/include/assert.h undefines assert macro and redefines it with its own version
* every single time it gets included.
*/
#ifndef NDEBUG
#define DEBUG_VAR
#else
#define DEBUG_VAR __attribute__((unused))
#endif
#define UNUSED __attribute__((unused))
#define MUST_USE __attribute__((warn_unused_result))
#define fail_due_to_user_error(msg, ...) do { \
report_user_error(msg, ##__VA_ARGS__); \
BREAKPOINT; \
exit(EXIT_FAILURE); \
} while (0)
#define crash(msg, ...) do { \
report_fatal_error(__FILE__, __LINE__, msg, ##__VA_ARGS__); \
BREAKPOINT; /* this used to be abort(), but it didn't cause VALGRIND to print a backtrace */ \
abort(); \
} while (0)
#define crash_or_trap(msg, ...) do { \
report_fatal_error(__FILE__, __LINE__, msg, ##__VA_ARGS__); \
BREAKPOINT; \
} while (0)
void report_fatal_error(const char*, int, const char*, ...) __attribute__((format (printf, 3, 4)));
void report_user_error(const char*, ...) __attribute__((format (printf, 1, 2)));
// Our usual crash() method does not work well in out-of-memory conditions, because
// it performs heap-allocations itself. Use `crash_oom()` instead for these cases.
void crash_oom();
// Possibly using buf to store characters, returns a pointer to a strerror-style error string. This
// has the same contract as the GNU (char *)-returning strerror_r. The return value is a pointer to
// a nul-terminated string, either equal to buf or pointing at a statically allocated string.
MUST_USE const char *errno_string_maybe_using_buffer(int errsv, char *buf, size_t buflen);
#define stringify(x) #x
#define format_assert_message(assert_type, cond) assert_type " failed: [" stringify(cond) "] "
#define guarantee(cond, msg...) do { \
if (!(cond)) { \
crash_or_trap(format_assert_message("Guarantee", cond) msg); \
} \
} while (0)
#define guarantee_xerr(cond, err, msg, args...) do { \
int guarantee_xerr_errsv = (err); \
if (!(cond)) { \
if (guarantee_xerr_errsv == 0) { \
crash_or_trap(format_assert_message("Guarantee", cond) msg, ##args); \
} else { \
char guarantee_xerr_buf[250]; \
const char *errstr = errno_string_maybe_using_buffer(guarantee_xerr_errsv, guarantee_xerr_buf, sizeof(guarantee_xerr_buf)); \
crash_or_trap(format_assert_message("Guarantee", cond) " (errno %d - %s) " msg, guarantee_xerr_errsv, errstr, ##args); \
} \
} \
} while (0)
#define guarantee_err(cond, msg, args...) guarantee_xerr(cond, get_errno(), msg, ##args)
#define unreachable(msg, ...) crash("Unreachable code: " msg, ##__VA_ARGS__) // can't use crash_or_trap since code needs to depend on its noreturn property
#define not_implemented(msg, ...) crash_or_trap("Not implemented: " msg, ##__VA_ARGS__)
#ifdef NDEBUG
#define rassert(cond, msg...) ((void)(0))
#define rassert_err(cond, msg...) ((void)(0))
#else
#define rassert(cond, msg...) do { \
if (!(cond)) { \
crash_or_trap(format_assert_message("Assertion", cond) msg); \
} \
} while (0)
#define rassert_err(cond, msg, args...) do { \
int rassert_err_errsv = get_errno(); \
if (!(cond)) { \
if (rassert_err_errsv == 0) { \
crash_or_trap(format_assert_message("Assert", cond) msg); \
} else { \
char rassert_err_buf[250]; \
const char *errstr = errno_string_maybe_using_buffer(rassert_err_errsv, rassert_err_buf, sizeof(rassert_err_buf)); \
crash_or_trap(format_assert_message("Assert", cond) " (errno %d - %s) " msg, rassert_err_errsv, errstr, ##args); \
} \
} \
} while (0)
#endif
void install_generic_crash_handler();
void install_new_oom_handler();
// If you include errors.hpp before including a Boost library, then Boost assertion
// failures will be forwarded to the RethinkDB error mechanism.
#define BOOST_ENABLE_ASSERT_HANDLER
namespace boost {
void assertion_failed(char const * expr, char const * function, char const * file, long line); // NOLINT(runtime/int)
}
#define DISABLE_COPYING(T) \
T(const T&) = delete; \
T& operator=(const T&) = delete
/* Put these after functions to indicate what they throw. In release mode, they
turn into noops so that the compiler doesn't have to generate exception-checking
code everywhere. If you need to add an exception specification for compatibility
with e.g. a virtual method, don't use these, or your code won't compile in
release mode. */
#ifdef NDEBUG
#define THROWS_NOTHING
#define THROWS_ONLY(...)
#else
#define THROWS_NOTHING throw ()
#define THROWS_ONLY(...) throw (__VA_ARGS__)
#endif
// This is a workaround for old versions of boost causing a compilation error
#include <boost/version.hpp> // NOLINT(build/include_order)
#if (BOOST_VERSION >= 104200) && (BOOST_VERSION <= 104399)
#include <boost/config.hpp> // NOLINT(build/include_order)
#undef BOOST_HAS_RVALUE_REFS
#endif
#ifdef __GNUC__
#define GNUC_VERSION (__GNUC__ * 10000 + __GNUC_MINOR__ * 100 + __GNUC_PATCHLEVEL__)
#endif
/** RVALUE_THIS
*
* This macro is used to annotate methods that treat *this as an
* rvalue reference. On compilers that support it, it expands to &&
* and all uses of the method on non-rvlaue *this are reported as
* errors.
*
* The supported compilers are clang >= 2.9 and gcc >= 4.8.1
*
**/
#if defined(__clang__)
#if __has_extension(cxx_rvalue_references)
#define RVALUE_THIS &&
#else
#define RVALUE_THIS
#endif
#elif __GNUC__ > 4 || (__GNUC__ == 4 && \
(__GNUC_MINOR__ > 8 || (__GNUC_MINOR__ == 8 && \
__GNUC_PATCHLEVEL__ > 1)))
#define RVALUE_THIS &&
#else
#define RVALUE_THIS
#endif
#if defined(__clang__)
#if !__has_extension(cxx_override_control)
#define override
#define final
#endif
#elif GNUC_VERSION < 40700
#define override
#define final
#endif
#endif /* ERRORS_HPP_ */
<|endoftext|>
|
<commit_before>#include <iostream>
#include <vector>
#include <cmath>
#include <data.h>
#include <constants.h>
#include <mesh.h>
#include <initialconditions.h>
using namespace std;
extern vector<node> n;
extern vector<element> e;
extern vector<type1> tp1;
extern vector<type2> tp2;
extern vector<type3> tp3;
void W(int i)
{
tp1[i].W[0] = e[i].ro;
tp1[i].W[1] = e[i].ro * e[i].u;
tp1[i].W[2] = e[i].ro * e[i].v;
tp1[i].W[3] = e[i].ro * e[i].et;
}
void Fc1(int i)
{
double fenergyp, fenergym, fmassp, fmassm;
double ML,MR;
double VL, VR; //contravariant velocity of right state and left state
double cL, cR; //speed of sound
double roL, uL, vL, pL, etL;
double roR, uR, vR, pR, etR;
double vnx, vny;
double Fp[4], Fm[4];
roL = e[i].ro;
uL = e[i].u;
vL = e[i].v;
pL = e[i].p;
etL = e[i].et;
for(int d = 0; d < 4; d++)
{
roR = e[e[i].neigh[d]].ro;
uR = e[e[i].neigh[d]].u;
vR = e[e[i].neigh[d]].v;
pR = e[e[i].neigh[d]].p;
etR = e[e[i].neigh[d]].et;
vnx = e[i].vn[d].x;
vny = e[i].vn[d].y;
VL = vnx * uL + vny * vL;
VR = vnx * uR + vny * vR;
cL = sqrt(gama * pL / roL);
cR = sqrt(gama * pR / roR);
ML = VL / cL;
MR = VR / cR;
if(ML >= 1.)
{
Fp[0] = roL * VL;
Fp[1] = roL * uL * VL + vnx * pL;
Fp[2] = roL * vL * VL + vny * pL;
Fp[3] = roL * (etL + pL / roL) * VL;
}
else if(abs(ML) < 1)
{
fmassp = roL * cL * pow((ML + 1), 2) / 4.;
fenergyp = fmassp * ((pow(((gama - 1.) * VL + 2. * cL),2) / (2. * (pow(gama, 2) - 1.))) + (pow(uL, 2) + pow(vL, 2) - pow(VL, 2)) / 2.);
Fp[0] = fmassp;
Fp[1] = fmassp * (vnx * (-VL + 2. * cL) / gama + uL);
Fp[2] = fmassp * (vny * (-VL + 2. * cL) / gama + vL);
Fp[3] = fenergyp;
}
else
{
Fp[0] = 0;
Fp[1] = 0;
Fp[2] = 0;
Fp[3] = 0;
}
if(MR >= 1.)
{
Fm[0] = 0;
Fm[1] = 0;
Fm[2] = 0;
Fm[3] = 0;
}
else if(abs(MR) < 1)
{
fmassm = -roR * cR * pow((MR - 1), 2) / 4.;
fenergym = fmassm * ((pow(((gama - 1.) * VR - 2. * cR),2) / (2. * (pow(gama, 2) - 1.))) + (pow(uR, 2) + pow(vR, 2) - pow(VR, 2)) / 2.);
Fm[0] = fmassm;
Fm[1] = fmassm * (vnx * (-VR - 2. * cR) / gama + uR);
Fm[2] = fmassm * (vny * (-VR - 2. * cR) / gama + vR);
Fm[3] = fenergym;
}
else
{
Fm[0] = roR * VR;
Fm[1] = roR * uR * VR + vnx * pR;
Fm[2] = roR * vR * VR + vny * pR;
Fm[3] = roR * (etR + pR / roR) * VR;
}
for(int a = 0; a < 4; a++)
tp1[i].Fc[d][a] = Fp[a] + Fm[a];
}
}
void W3(int i, int t)
{
if(t == 0)
{
tp3[i].W[0][t] = e[i].roprev;
tp3[i].W[1][t] = e[i].roprev * e[i].uprev;
tp3[i].W[2][t] = e[i].roprev * e[i].vprev;
tp3[i].W[3][t] = e[i].roprev * e[i].etprev;
}
else if(t == 1)
{
tp3[i].W[0][t] = e[i].ro;
tp3[i].W[1][t] = e[i].ro * e[i].u;
tp3[i].W[2][t] = e[i].ro * e[i].v;
tp3[i].W[3][t] = e[i].ro * e[i].et;
}
else if(t == 2)
{
tp3[i].W[0][t] = e[i].ronew;
tp3[i].W[1][t] = e[i].ronew * e[i].unew;
tp3[i].W[2][t] = e[i].ronew * e[i].vnew;
tp3[i].W[3][t] = e[i].ronew * e[i].etnew;
}
}
void Fc1new(int i)
{
double fenergyp, fenergym, fmassp, fmassm;
double ML,MR;
double VL, VR; //contravariant velocity of right state and left state
double cL, cR; //speed of sound
double roL, uL, vL, pL, etL;
double roR, uR, vR, pR, etR;
double vnx, vny;
double Fp[4], Fm[4];
roL = e[i].ronew;
uL = e[i].unew;
vL = e[i].vnew;
pL = e[i].pnew;
etL = e[i].etnew;
for(int d = 0; d < 4; d++)
{
roR = e[e[i].neigh[d]].ro;
uR = e[e[i].neigh[d]].u;
vR = e[e[i].neigh[d]].v;
pR = e[e[i].neigh[d]].p;
etR = e[e[i].neigh[d]].et;
vnx = e[i].vn[d].x;
vny = e[i].vn[d].y;
VL = vnx * uL + vny * vL;
VR = vnx * uR + vny * vR;
cL = sqrt(gama * pL / roL);
cR = sqrt(gama * pR / roR);
ML = VL / cL;
MR = VR / cR;
if(ML >= 1.)
{
Fp[0] = roL * VL;
Fp[1] = roL * uL * VL + vnx * pL;
Fp[2] = roL * vL * VL + vny * pL;
Fp[3] = roL * (etL + pL / roL) * VL;
}
else if(abs(ML) < 1)
{
fmassp = roL * cL * pow((ML + 1), 2) / 4.;
fenergyp = fmassp * ((pow(((gama - 1.) * VL + 2. * cL),2) / (2. * (pow(gama, 2) - 1.))) + (pow(uL, 2) + pow(vL, 2) - pow(VL, 2)) / 2.);
Fp[0] = fmassp;
Fp[1] = fmassp * (vnx * (-VL + 2. * cL) / gama + uL);
Fp[2] = fmassp * (vny * (-VL + 2. * cL) / gama + vL);
Fp[3] = fenergyp;
}
else
{
Fp[0] = 0;
Fp[1] = 0;
Fp[2] = 0;
Fp[3] = 0;
}
if(MR >= 1.)
{
Fm[0] = 0;
Fm[1] = 0;
Fm[2] = 0;
Fm[3] = 0;
}
else if(abs(MR) < 1)
{
fmassm = -roR * cR * pow((MR - 1), 2) / 4.;
fenergym = fmassm * ((pow(((gama - 1.) * VR - 2. * cR),2) / (2. * (pow(gama, 2) - 1.))) + (pow(uR, 2) + pow(vR, 2) - pow(VR, 2)) / 2.);
Fm[0] = fmassm;
Fm[1] = fmassm * (vnx * (-VR - 2. * cR) / gama + uR);
Fm[2] = fmassm * (vny * (-VR - 2. * cR) / gama + vR);
Fm[3] = fenergym;
}
else
{
Fm[0] = roR * VR;
Fm[1] = roR * uR * VR + vnx * pR;
Fm[2] = roR * vR * VR + vny * pR;
Fm[3] = roR * (etR + pR / roR) * VR;
}
for(int a = 0; a < 4; a++)
tp1[i].Fc[d][a] = Fp[a] + Fm[a];
}
}
void Fc1new1(int i)
{
double fenergyp, fenergym, fmassp, fmassm;
double ML,MR;
double VL, VR; //contravariant velocity of right state and left state
double cL, cR; //speed of sound
double roL, uL, vL, pL, etL;
double roR, uR, vR, pR, etR;
double vnx, vny;
double Fp[4], Fm[4];
roL = e[i].ronew;
uL = e[i].unew;
vL = e[i].vnew;
pL = e[i].pnew;
etL = e[i].etnew;
for(int d = 0; d < 4; d++)
{
roR = e[e[i].neigh[d]].ronew;
uR = e[e[i].neigh[d]].unew;
vR = e[e[i].neigh[d]].vnew;
pR = e[e[i].neigh[d]].pnew;
etR = e[e[i].neigh[d]].etnew;
vnx = e[i].vn[d].x;
vny = e[i].vn[d].y;
VL = vnx * uL + vny * vL;
VR = vnx * uR + vny * vR;
cL = sqrt(gama * pL / roL);
cR = sqrt(gama * pR / roR);
ML = VL / cL;
MR = VR / cR;
if(ML >= 1.)
{
Fp[0] = roL * VL;
Fp[1] = roL * uL * VL + vnx * pL;
Fp[2] = roL * vL * VL + vny * pL;
Fp[3] = roL * (etL + pL / roL) * VL;
}
else if(abs(ML) < 1)
{
fmassp = roL * cL * pow((ML + 1), 2) / 4.;
fenergyp = fmassp * ((pow(((gama - 1.) * VL + 2. * cL),2) / (2. * (pow(gama, 2) - 1.))) + (pow(uL, 2) + pow(vL, 2) - pow(VL, 2)) / 2.);
Fp[0] = fmassp;
Fp[1] = fmassp * (vnx * (-VL + 2. * cL) / gama + uL);
Fp[2] = fmassp * (vny * (-VL + 2. * cL) / gama + vL);
Fp[3] = fenergyp;
}
else
{
Fp[0] = 0;
Fp[1] = 0;
Fp[2] = 0;
Fp[3] = 0;
}
if(MR >= 1.)
{
Fm[0] = 0;
Fm[1] = 0;
Fm[2] = 0;
Fm[3] = 0;
}
else if(abs(MR) < 1)
{
fmassm = -roR * cR * pow((MR - 1), 2) / 4.;
fenergym = fmassm * ((pow(((gama - 1.) * VR - 2. * cR),2) / (2. * (pow(gama, 2) - 1.))) + (pow(uR, 2) + pow(vR, 2) - pow(VR, 2)) / 2.);
Fm[0] = fmassm;
Fm[1] = fmassm * (vnx * (-VR - 2. * cR) / gama + uR);
Fm[2] = fmassm * (vny * (-VR - 2. * cR) / gama + vR);
Fm[3] = fenergym;
}
else
{
Fm[0] = roR * VR;
Fm[1] = roR * uR * VR + vnx * pR;
Fm[2] = roR * vR * VR + vny * pR;
Fm[3] = roR * (etR + pR / roR) * VR;
}
for(int a = 0; a < 4; a++)
tp1[i].Fc[d][a] = Fp[a] + Fm[a];
}
}
void Fv1(int i)
{
double ro, u, v, p, et, mu;
double vnx, vny;
double gradTx, gradTy, gradux, graduy, gradvx, gradvy, qx, qy;
double taoxx, taoxy, taoyy;
for(int d = 0; d < 4; d++)
{
vnx = e[i].vn[d].x;
vny = e[i].vn[d].y;
ro = (e[i].ro + e[e[i].neigh[d]].ro) / 2.;
u = (e[i].u + e[e[i].neigh[d]].u) / 2.;
v = (e[i].v + e[e[i].neigh[d]].v) / 2.;
p = (e[i].ro + e[e[i].neigh[d]].p) / 2.;
et = (e[i].et + e[e[i].neigh[d]].et) / 2.;
mu = (e[i].mu + e[e[i].neigh[d]].mu) / 2.;
gradux = (e[e[i].neigh[d]].u - e[i].u) / e[i].rm[d] * e[i].r[d].x / e[i].rm[d];
graduy = (e[e[i].neigh[d]].u - e[i].u) / e[i].rm[d] * e[i].r[d].y / e[i].rm[d];
gradvx = (e[e[i].neigh[d]].v - e[i].v) / e[i].rm[d] * e[i].r[d].x / e[i].rm[d];
gradvy = (e[e[i].neigh[d]].v - e[i].v) / e[i].rm[d] * e[i].r[d].y / e[i].rm[d];
gradTx = (e[e[i].neigh[d]].T - e[i].T) / e[i].rm[d] * e[i].r[d].x / e[i].rm[d];
gradTy = (e[e[i].neigh[d]].T - e[i].T) / e[i].rm[d] * e[i].r[d].y / e[i].rm[d];
taoxx = mu / Reinf * (4. / 3. * gradux - 2. / 3. * gradvy);
taoxy = mu / Reinf * (graduy + gradvx);
taoyy = mu / Reinf * (4. / 3. * gradvy - 2. / 3. * gradux);
qx = mu / (Reinf * Pr * (gama - 1.) * pow(Machinf,2)) * gradTx;
qy = mu / (Reinf * Pr * (gama - 1.) * pow(Machinf,2)) * gradTy;
tp2[i].Fv[d][0] = 0;
tp2[i].Fv[d][1] = vnx * taoxx + vny * taoxy;
tp2[i].Fv[d][2] = vnx * taoxy + vny * taoyy;
tp2[i].Fv[d][3] = vnx * (u * taoxx + v * taoxy + qx) + vny * (u * taoxy + v * taoyy + qy);
}
}
<commit_msg>Delete fluxes.cpp<commit_after><|endoftext|>
|
<commit_before>//*********************************************************
//GLFONT.CPP -- glFont routines
//Copyright (c) 1998 Brad Fish
//See glFont.txt for terms of use
//November 10, 1998
//*********************************************************
#include <stdio.h>
#include <malloc.h>
#include <string.h>
extern "C" {
#include <GL/gl.h>
#include <GL/glu.h>
}
#include "glfont.h"
//*********************************************************
//Variables
//*********************************************************
//Current font
GLFONT *glFont;
//*********************************************************
//Functions
//*********************************************************
int glFontCreate (GLFONT *Font, char *FileName, int Tex)
{
FILE *Input;
char *TexBytes;
int Num;
//Open font file
if ((Input = fopen(FileName, "rb")) == NULL)
return FALSE;
//Read glFont structure
fread(Font, sizeof(GLFONT), 1, Input);
//Save texture number
Font->Tex = Tex;
//Get number of characters
Num = Font->IntEnd - Font->IntStart + 1;
//Allocate memory for characters
if ((Font->Char = (GLFONTCHAR *)malloc(
sizeof(GLFONTCHAR) * Num)) == NULL)
return FALSE;
//Read glFont characters
fread(Font->Char, sizeof(GLFONTCHAR), Num, Input);
//Get texture size
Num = Font->TexWidth * Font->TexHeight * 2;
//Allocate memory for texture data
if ((TexBytes = (char *)malloc(Num)) == NULL)
return FALSE;
//Read texture data
fread(TexBytes, sizeof(char), Num, Input);
//Set texture attributes
glBindTexture(GL_TEXTURE_2D, Font->Tex);
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S,
GL_CLAMP);
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T,
GL_CLAMP);
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER,
GL_LINEAR);
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER,
GL_LINEAR);
glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE,
GL_MODULATE);
//Create texture
glTexImage2D(GL_TEXTURE_2D, 0, 2, Font->TexWidth,
Font->TexHeight, 0, GL_LUMINANCE_ALPHA,
GL_UNSIGNED_BYTE, (void *)TexBytes);
//Clean up
free(TexBytes);
fclose(Input);
//Return pointer to new font
return TRUE;
}
//*********************************************************
void glFontDestroy (GLFONT *Font)
{
//Free character memory
free(Font->Char);
}
//*********************************************************
void glFontBegin (GLFONT *Font)
{
//Save pointer to font structure
if (Font->Char != NULL)
glFont = Font;
else
glFont = NULL;
//Bind to font texture
glBindTexture(GL_TEXTURE_2D, Font->Tex);
}
//*********************************************************
void glFontEnd (void)
{
//Font no longer current
glFont = NULL;
}
//*********************************************************
void glFontTextOut (char *String, float x, float y,
float z)
{
int Length, i;
GLFONTCHAR *Char;
//Return if we don't have a valid glFont
if (glFont == NULL)
return;
//Get length of string
Length = strlen(String);
//Begin rendering quads
glBegin(GL_QUADS);
//Loop through characters
for (i = 0; i < Length; i++)
{
//Get pointer to glFont character
Char = &glFont->Char[(int)String[i] -
glFont->IntStart];
//Specify vertices and texture coordinates
glTexCoord2f(Char->tx1, Char->ty1);
glVertex3f(x, y, z);
glTexCoord2f(Char->tx1, Char->ty2);
glVertex3f(x, y - Char->dy, z);
glTexCoord2f(Char->tx2, Char->ty2);
glVertex3f(x + Char->dx, y - Char->dy, z);
glTexCoord2f(Char->tx2, Char->ty1);
glVertex3f(x + Char->dx, y, z);
//Move to next character
x += Char->dx;
}
//Stop rendering quads
glEnd();
}
int glFontTextSize( GLFONT *Font, char *String, float* width, float* height )
{
int Length, i;
GLFONTCHAR *Char;
float x = 0.0f;
float y = 0.0f;
//Return if we don't have a valid glFont
if (Font == NULL)
return 0;
//Get length of string
Length = strlen(String);
//Loop through characters
for (i = 0; i < Length; i++)
{
//Get pointer to glFont character
Char = &Font->Char[(int)String[i] -
Font->IntStart];
//Move to next character
x += Char->dx;
if(Char->dy > y)y = Char->dy;
}
*width = x;
*height = y;
return 1;
}
//*********************************************************
//End of file
<commit_msg>I made this compile on Visual Studio again.<commit_after>//*********************************************************
//GLFONT.CPP -- glFont routines
//Copyright (c) 1998 Brad Fish
//See glFont.txt for terms of use
//November 10, 1998
//*********************************************************
#ifdef WIN32
#include <windows.h>
#endif
#include <stdio.h>
#include <malloc.h>
#include <string.h>
extern "C" {
#include <GL/gl.h>
#ifdef WIN32
#include <GL/glu.h>
#else
#include <GL/glu.h>
#endif
}
#include "glfont.h"
//*********************************************************
//Variables
//*********************************************************
//Current font
GLFONT *glFont;
//*********************************************************
//Functions
//*********************************************************
int glFontCreate (GLFONT *Font, char *FileName, int Tex)
{
FILE *Input;
char *TexBytes;
int Num;
//Open font file
if ((Input = fopen(FileName, "rb")) == NULL)
return FALSE;
//Read glFont structure
fread(Font, sizeof(GLFONT), 1, Input);
//Save texture number
Font->Tex = Tex;
//Get number of characters
Num = Font->IntEnd - Font->IntStart + 1;
//Allocate memory for characters
if ((Font->Char = (GLFONTCHAR *)malloc(
sizeof(GLFONTCHAR) * Num)) == NULL)
return FALSE;
//Read glFont characters
fread(Font->Char, sizeof(GLFONTCHAR), Num, Input);
//Get texture size
Num = Font->TexWidth * Font->TexHeight * 2;
//Allocate memory for texture data
if ((TexBytes = (char *)malloc(Num)) == NULL)
return FALSE;
//Read texture data
fread(TexBytes, sizeof(char), Num, Input);
//Set texture attributes
glBindTexture(GL_TEXTURE_2D, Font->Tex);
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S,
GL_CLAMP);
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T,
GL_CLAMP);
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER,
GL_LINEAR);
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER,
GL_LINEAR);
glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE,
GL_MODULATE);
//Create texture
glTexImage2D(GL_TEXTURE_2D, 0, 2, Font->TexWidth,
Font->TexHeight, 0, GL_LUMINANCE_ALPHA,
GL_UNSIGNED_BYTE, (void *)TexBytes);
//Clean up
free(TexBytes);
fclose(Input);
//Return pointer to new font
return TRUE;
}
//*********************************************************
void glFontDestroy (GLFONT *Font)
{
//Free character memory
free(Font->Char);
}
//*********************************************************
void glFontBegin (GLFONT *Font)
{
//Save pointer to font structure
if (Font->Char != NULL)
glFont = Font;
else
glFont = NULL;
//Bind to font texture
glBindTexture(GL_TEXTURE_2D, Font->Tex);
}
//*********************************************************
void glFontEnd (void)
{
//Font no longer current
glFont = NULL;
}
//*********************************************************
void glFontTextOut (char *String, float x, float y,
float z)
{
int Length, i;
GLFONTCHAR *Char;
//Return if we don't have a valid glFont
if (glFont == NULL)
return;
//Get length of string
Length = strlen(String);
//Begin rendering quads
glBegin(GL_QUADS);
//Loop through characters
for (i = 0; i < Length; i++)
{
//Get pointer to glFont character
Char = &glFont->Char[(int)String[i] -
glFont->IntStart];
//Specify vertices and texture coordinates
glTexCoord2f(Char->tx1, Char->ty1);
glVertex3f(x, y, z);
glTexCoord2f(Char->tx1, Char->ty2);
glVertex3f(x, y - Char->dy, z);
glTexCoord2f(Char->tx2, Char->ty2);
glVertex3f(x + Char->dx, y - Char->dy, z);
glTexCoord2f(Char->tx2, Char->ty1);
glVertex3f(x + Char->dx, y, z);
//Move to next character
x += Char->dx;
}
//Stop rendering quads
glEnd();
}
int glFontTextSize( GLFONT *Font, char *String, float* width, float* height )
{
int Length, i;
GLFONTCHAR *Char;
float x = 0.0f;
float y = 0.0f;
//Return if we don't have a valid glFont
if (Font == NULL)
return 0;
//Get length of string
Length = strlen(String);
//Loop through characters
for (i = 0; i < Length; i++)
{
//Get pointer to glFont character
Char = &Font->Char[(int)String[i] -
Font->IntStart];
//Move to next character
x += Char->dx;
if(Char->dy > y)y = Char->dy;
}
*width = x;
*height = y;
return 1;
}
//*********************************************************
//End of file
<|endoftext|>
|
<commit_before>#include <ros/ros.h>
#include <serialport/serialport.h>
#define REPLY_SIZE 8
#define TIMEOUT 1000
char* itoa(int value, char* result, int base);
// This example opens the serial port and sends a request 'R' at 1Hz and waits for a reply.
int main(int argc, char** argv)
{
ros::init(argc, argv, "example_node");
ros::NodeHandle n;
cereal::CerealPort device;
char reply[REPLY_SIZE];
// Change the next line according to your port name and baud rate
try{ device.open("/dev/ttyAMA0", 38400); }
catch(cereal::Exception& e)
{
ROS_FATAL("Failed to open the serial port!!!");
ROS_BREAK();
}
ROS_INFO("The serial port is opened.");
ros::Rate r(1);
while(ros::ok())
{
// Send 'R' over the serial port
//const char send[] = "\x00\x25";
//or
const char send[] = {0x00,0x25};
device.write(send,2);
// Get the reply, the last value is the timeout in ms
try{ device.read(reply, REPLY_SIZE, TIMEOUT); }
catch(cereal::TimeoutException& e)
{
ROS_ERROR("Timeout!");
}
ROS_INFO("Got this reply: %i,%i,%i,%i,%i,%i,%i,%i", reply[0], reply[1], reply[2],reply[3], reply[4], reply[5], reply[6], reply[7]);
unsigned char speed_l;
speed_l=255;
const char send1[]={0x00,0x31,speed_l};
//send[]={0x00,0x31,255};
device.write(send1,3);
ros::spinOnce();
r.sleep();
}
}
char* itoa(int value, char* result, int base) {
// check that the base if valid
if (base < 2 || base > 36) { *result = '\0'; return result; }
char* ptr = result, *ptr1 = result, tmp_char;
int tmp_value;
do {
tmp_value = value;
value /= base;
*ptr++ = "zyxwvutsrqponmlkjihgfedcba9876543210123456789abcdefghijklmnopqrstuvwxyz" [35 + (tmp_value - value * base)];
} while ( value );
// Apply negative sign
if (tmp_value < 0) *ptr++ = '-';
*ptr-- = '\0';
while(ptr1 < ptr) {
tmp_char = *ptr;
*ptr--= *ptr1;
*ptr1++ = tmp_char;
}
return result;
}
<commit_msg>Update code<commit_after><|endoftext|>
|
<commit_before>/*
Copyright (c) 2015-2019, Robert J. Hansen <rjh@sixdemonbag.org>
Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted, provided that the above
copyright notice and this permission notice appear in all copies.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
#include <algorithm>
#include <boost/tokenizer.hpp>
#include <exception>
#include <iostream>
#include <sstream>
#include <vector>
#include "main.h"
using boost::char_separator;
using boost::tokenizer;
using boost::asio::ip::tcp;
using std::back_inserter;
using std::binary_search;
using std::exception;
using std::getline;
using std::pair;
using std::string;
using std::stringstream;
using std::to_string;
using std::transform;
using std::vector;
// defined in main.cc
extern const vector<pair64>& hashes;
namespace {
enum class Command {
Version = 0,
Bye = 1,
Status = 2,
Query = 3,
Upshift = 4,
Downshift = 5,
Unknown = 6
};
auto tokenize(const string& line) {
vector<string> rv;
char_separator<char> sep(" ");
tokenizer<char_separator<char>> tokens(line, sep);
for (const auto& t : tokens) {
rv.emplace_back(t);
}
return rv;
}
bool is_present_in_hashes(const string& hash) {
return binary_search(hashes.cbegin(), hashes.cend(), to_pair64(hash));
}
auto getCommand(const string& cmdstring) {
string localcmd = "";
transform(cmdstring.cbegin(), cmdstring.cend(), back_inserter(localcmd),
::toupper);
auto cmd = Command::Unknown;
if (localcmd == "VERSION:")
cmd = Command::Version;
else if (localcmd == "BYE")
cmd = Command::Bye;
else if (localcmd == "STATUS")
cmd = Command::Status;
else if (localcmd == "QUERY")
cmd = Command::Query;
else if (localcmd == "UPSHIFT")
cmd = Command::Upshift;
else if (localcmd == "DOWNSHIFT")
cmd = Command::Downshift;
return cmd;
}
} // namespace
void handle_client(tcp::iostream& stream) {
const string ipaddr = stream.socket().remote_endpoint().address().to_string();
unsigned long long queries = 0;
try {
while (stream) {
string line;
getline(stream, line);
if (line.size() == 0) return;
// trim leading/following whitespace
auto end_ws = line.find_last_not_of("\t\n\v\f\r ");
if (end_ws != string::npos) {
line.erase(end_ws + 1);
}
auto front_ws = line.find_first_not_of("\t\n\v\f\r ");
if (front_ws > 0) {
line.erase(0, front_ws);
}
auto commands = tokenize(line);
switch (getCommand(commands.at(0))) {
case Command::Version:
stream << "OK\r\n";
break;
case Command::Bye:
return;
case Command::Status:
stream << "NOT SUPPORTED\r\n";
break;
case Command::Query: {
stringstream rv;
rv << "OK ";
for (size_t idx = 1; idx < commands.size(); ++idx)
rv << (is_present_in_hashes(commands.at(idx)) ? "1" : "0");
rv << "\r\n";
queries += (commands.size() - 1);
stream << rv.str();
break;
}
case Command::Upshift:
stream << "NOT OK\r\n";
break;
case Command::Downshift:
stream << "NOT OK\r\n";
break;
case Command::Unknown:
stream << "NOT OK\r\n";
return;
}
}
} catch (std::exception& e) {
log(LogLevel::ALERT, string("Error: ") + e.what());
// swallow the exception: we'll close the connection
// automagically on exit
//
// fall-through here to function returb
}
stringstream status_msg;
status_msg << ipaddr << " closed session after " << queries << " queries";
log(LogLevel::ALERT, status_msg.str());
}
<commit_msg>Typo fix<commit_after>/*
Copyright (c) 2015-2019, Robert J. Hansen <rjh@sixdemonbag.org>
Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted, provided that the above
copyright notice and this permission notice appear in all copies.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
#include <algorithm>
#include <boost/tokenizer.hpp>
#include <exception>
#include <iostream>
#include <sstream>
#include <vector>
#include "main.h"
using boost::char_separator;
using boost::tokenizer;
using boost::asio::ip::tcp;
using std::back_inserter;
using std::binary_search;
using std::exception;
using std::getline;
using std::pair;
using std::string;
using std::stringstream;
using std::to_string;
using std::transform;
using std::vector;
// defined in main.cc
extern const vector<pair64>& hashes;
namespace {
enum class Command {
Version = 0,
Bye = 1,
Status = 2,
Query = 3,
Upshift = 4,
Downshift = 5,
Unknown = 6
};
auto tokenize(const string& line) {
vector<string> rv;
char_separator<char> sep(" ");
tokenizer<char_separator<char>> tokens(line, sep);
for (const auto& t : tokens) {
rv.emplace_back(t);
}
return rv;
}
bool is_present_in_hashes(const string& hash) {
return binary_search(hashes.cbegin(), hashes.cend(), to_pair64(hash));
}
auto getCommand(const string& cmdstring) {
string localcmd = "";
transform(cmdstring.cbegin(), cmdstring.cend(), back_inserter(localcmd),
::toupper);
auto cmd = Command::Unknown;
if (localcmd == "VERSION:")
cmd = Command::Version;
else if (localcmd == "BYE")
cmd = Command::Bye;
else if (localcmd == "STATUS")
cmd = Command::Status;
else if (localcmd == "QUERY")
cmd = Command::Query;
else if (localcmd == "UPSHIFT")
cmd = Command::Upshift;
else if (localcmd == "DOWNSHIFT")
cmd = Command::Downshift;
return cmd;
}
} // namespace
void handle_client(tcp::iostream& stream) {
const string ipaddr = stream.socket().remote_endpoint().address().to_string();
unsigned long long queries = 0;
try {
while (stream) {
string line;
getline(stream, line);
if (line.size() == 0) return;
// trim leading/following whitespace
auto end_ws = line.find_last_not_of("\t\n\v\f\r ");
if (end_ws != string::npos) {
line.erase(end_ws + 1);
}
auto front_ws = line.find_first_not_of("\t\n\v\f\r ");
if (front_ws > 0) {
line.erase(0, front_ws);
}
auto commands = tokenize(line);
switch (getCommand(commands.at(0))) {
case Command::Version:
stream << "OK\r\n";
break;
case Command::Bye:
return;
case Command::Status:
stream << "NOT SUPPORTED\r\n";
break;
case Command::Query: {
stringstream rv;
rv << "OK ";
for (size_t idx = 1; idx < commands.size(); ++idx)
rv << (is_present_in_hashes(commands.at(idx)) ? "1" : "0");
rv << "\r\n";
queries += (commands.size() - 1);
stream << rv.str();
break;
}
case Command::Upshift:
stream << "NOT OK\r\n";
break;
case Command::Downshift:
stream << "NOT OK\r\n";
break;
case Command::Unknown:
stream << "NOT OK\r\n";
return;
}
}
} catch (std::exception& e) {
log(LogLevel::ALERT, string("Error: ") + e.what());
// swallow the exception: we'll close the connection
// automagically on exit
//
// fall-through here to function return
}
stringstream status_msg;
status_msg << ipaddr << " closed session after " << queries << " queries";
log(LogLevel::ALERT, status_msg.str());
}
<|endoftext|>
|
<commit_before>// Copyright 2018 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// header and chunks writing
//
// Author: Skal (pascal.massimino@gmail.com)
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include "sjpegi.h"
using namespace sjpeg;
namespace sjpeg {
////////////////////////////////////////////////////////////////////////////////
// Headers
//
// NOTE(skal): all chunks start with a startcode '0xff??' (0xffd8 e.g),
// followed by the size of the payload *not counting the startcode*!
// That's why you often find these 'Reserve(data_size + 2)' below, the '+2'
// accounting for the 0xff?? startcode size.
void Encoder::WriteAPP0() { // SOI + APP0
const uint8_t kHeader0[] = {
0xff, 0xd8, // SOI
0xff, 0xe0, 0x00, 0x10, // APP0
0x4a, 0x46, 0x49, 0x46, 0x00, // 'JFIF'
0x01, 0x01, // v1.01
0x00, 0x00, 0x01, 0x00, 0x01, // aspect ratio = 1:1
0x00, 0x00 // thumbnail width/height
};
bw_.Reserve(sizeof(kHeader0));
bw_.PutBytes(kHeader0, sizeof(kHeader0));
}
bool Encoder::WriteAPPMarkers(const std::string& data) {
if (data.size() == 0) return true;
const size_t data_size = data.size();
bw_.Reserve(data_size);
bw_.PutBytes(reinterpret_cast<const uint8_t*>(data.data()), data.size());
return true;
}
bool Encoder::WriteEXIF(const std::string& data) {
if (data.size() == 0) return true;
const uint8_t kEXIF[] = "Exif\0";
const size_t kEXIF_len = 6; // includes the \0's
const size_t data_size = data.size() + kEXIF_len + 2;
if (data_size > 0xffff) return false;
bw_.Reserve(data_size);
bw_.PutByte(0xff);
bw_.PutByte(0xe1);
bw_.PutByte((data_size >> 8) & 0xff);
bw_.PutByte((data_size >> 0) & 0xff);
bw_.PutBytes(kEXIF, kEXIF_len);
bw_.PutBytes(reinterpret_cast<const uint8_t*>(data.data()), data.size());
return true;
}
bool Encoder::WriteICCP(const std::string& data) {
if (data.size() == 0) return true;
size_t data_size = data.size();
const uint8_t* ptr = reinterpret_cast<const uint8_t*>(data.data());
const uint8_t kICCP[] = "ICC_PROFILE";
const size_t kICCP_len = 12; // includes the \0
const size_t chunk_size_max = 0xffff - kICCP_len - 4;
size_t max_chunk = (data_size + chunk_size_max - 1) / chunk_size_max;
if (max_chunk >= 256) return false;
size_t seq = 1;
while (data_size > 0) {
size_t size = data_size;
if (size > chunk_size_max) size = chunk_size_max;
bw_.Reserve(size + kICCP_len + 4 + 2);
bw_.PutByte(0xff);
bw_.PutByte(0xe2);
bw_.PutByte(((size + kICCP_len + 4) >> 8) & 0xff);
bw_.PutByte(((size + kICCP_len + 4) >> 0) & 0xff);
bw_.PutBytes(kICCP, kICCP_len);
bw_.PutByte(seq & 0xff);
bw_.PutByte(max_chunk & 0xff);
bw_.PutBytes(ptr, size);
ptr += size;
data_size -= size;
seq += 1;
}
return true;
}
bool Encoder::WriteXMP(const std::string& data) {
if (data.size() == 0) return true;
const uint8_t kXMP[] = "http://ns.adobe.com/xap/1.0/";
const size_t kXMP_size = 29;
const size_t data_size = 2 + data.size() + kXMP_size;
if (data_size > 0xffff) return false; // error
bw_.Reserve(data_size + 2);
bw_.PutByte(0xff);
bw_.PutByte(0xe1);
bw_.PutByte((data_size >> 8) & 0xff);
bw_.PutByte((data_size >> 0) & 0xff);
bw_.PutBytes(kXMP, kXMP_size);
bw_.PutBytes(reinterpret_cast<const uint8_t*>(data.data()), data.size());
return true;
}
void Encoder::WriteDQT() {
const int data_size = 2 * 65 + 2;
const uint8_t kDQTHeader[] = { 0xff, 0xdb, 0x00, (uint8_t)data_size };
bw_.Reserve(data_size + 2);
bw_.PutBytes(kDQTHeader, sizeof(kDQTHeader));
for (int n = 0; n <= 1; ++n) {
bw_.PutByte(n);
const uint8_t* quant = quants_[n].quant_;
for (int i = 0; i < 64; ++i) {
bw_.PutByte(quant[kZigzag[i]]);
}
}
}
////////////////////////////////////////////////////////////////////////////////
#define DATA_16b(X) ((uint8_t)((X) >> 8)), ((uint8_t)((X) & 0xff))
void Encoder::WriteSOF() { // SOF
const int data_size = 8 + 3 * nb_comps_;
assert(data_size <= 255);
const uint8_t kHeader[] = {
0xff, 0xc0, DATA_16b(data_size), // SOF0 marker, size
0x08, // 8bits/components
DATA_16b(H_), DATA_16b(W_), // height, width
(uint8_t)nb_comps_ // number of components
};
bw_.Reserve(data_size + 2);
bw_.PutBytes(kHeader, sizeof(kHeader));
for (int c = 0; c < nb_comps_; ++c) {
bw_.PutByte(c + 1);
bw_.PutByte(block_dims_[c]);
bw_.PutByte(quant_idx_[c]);
}
}
void Encoder::WriteDHT() {
InitCodes(false);
const int nb_tables = (nb_comps_ == 1 ? 1 : 2);
for (int c = 0; c < nb_tables; ++c) { // luma, chroma
for (int type = 0; type <= 1; ++type) { // dc, ac
const HuffmanTable* const h = Huffman_tables_[type * 2 + c];
const int data_size = 3 + 16 + h->nb_syms_;
assert(data_size <= 255);
bw_.Reserve(data_size + 2);
bw_.PutByte(0xff);
bw_.PutByte(0xc4);
bw_.PutByte(0x00 /*data_size >> 8*/);
bw_.PutByte(data_size);
bw_.PutByte((type << 4) | c);
bw_.PutBytes(h->bits_, 16);
bw_.PutBytes(h->syms_, h->nb_syms_);
}
}
}
////////////////////////////////////////////////////////////////////////////////
void Encoder::WriteSOS() { // SOS
const int data_size = 6 + nb_comps_ * 2;
assert(data_size <= 255);
const uint8_t kHeader[] = {
0xff, 0xda, DATA_16b(data_size), (uint8_t)nb_comps_
};
bw_.Reserve(data_size + 2);
bw_.PutBytes(kHeader, sizeof(kHeader));
for (int c = 0; c < nb_comps_; ++c) {
bw_.PutByte(c + 1);
bw_.PutByte(quant_idx_[c] * 0x11);
}
bw_.PutByte(0x00); // Ss
bw_.PutByte(0x3f); // Se
bw_.PutByte(0x00); // Ah/Al
}
////////////////////////////////////////////////////////////////////////////////
void Encoder::WriteEOI() { // EOI
bw_.Flush();
// append EOI
bw_.Reserve(2);
bw_.PutByte(0xff);
bw_.PutByte(0xd9);
}
} // namespace sjpeg
<commit_msg>fix bug in data_size calculation for EXIF chunk<commit_after>// Copyright 2018 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// header and chunks writing
//
// Author: Skal (pascal.massimino@gmail.com)
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include "sjpegi.h"
using namespace sjpeg;
namespace sjpeg {
////////////////////////////////////////////////////////////////////////////////
// Headers
//
// NOTE(skal): all chunks start with a startcode '0xff??' (0xffd8 e.g),
// followed by the size of the payload *not counting the startcode*!
// That's why you often find these 'Reserve(data_size + 2)' below, the '+2'
// accounting for the 0xff?? startcode size.
void Encoder::WriteAPP0() { // SOI + APP0
const uint8_t kHeader0[] = {
0xff, 0xd8, // SOI
0xff, 0xe0, 0x00, 0x10, // APP0
0x4a, 0x46, 0x49, 0x46, 0x00, // 'JFIF'
0x01, 0x01, // v1.01
0x00, 0x00, 0x01, 0x00, 0x01, // aspect ratio = 1:1
0x00, 0x00 // thumbnail width/height
};
bw_.Reserve(sizeof(kHeader0));
bw_.PutBytes(kHeader0, sizeof(kHeader0));
}
bool Encoder::WriteAPPMarkers(const std::string& data) {
if (data.size() == 0) return true;
const size_t data_size = data.size();
bw_.Reserve(data_size);
bw_.PutBytes(reinterpret_cast<const uint8_t*>(data.data()), data.size());
return true;
}
bool Encoder::WriteEXIF(const std::string& data) {
if (data.size() == 0) return true;
const uint8_t kEXIF[] = "Exif\0";
const size_t kEXIF_len = 6; // includes the \0's
const size_t data_size = data.size() + kEXIF_len + 2;
if (data_size > 0xffff) return false;
bw_.Reserve(data_size + 2);
bw_.PutByte(0xff);
bw_.PutByte(0xe1);
bw_.PutByte((data_size >> 8) & 0xff);
bw_.PutByte((data_size >> 0) & 0xff);
bw_.PutBytes(kEXIF, kEXIF_len);
bw_.PutBytes(reinterpret_cast<const uint8_t*>(data.data()), data.size());
return true;
}
bool Encoder::WriteICCP(const std::string& data) {
if (data.size() == 0) return true;
size_t data_size = data.size();
const uint8_t* ptr = reinterpret_cast<const uint8_t*>(data.data());
const uint8_t kICCP[] = "ICC_PROFILE";
const size_t kICCP_len = 12; // includes the \0
const size_t chunk_size_max = 0xffff - kICCP_len - 4;
size_t max_chunk = (data_size + chunk_size_max - 1) / chunk_size_max;
if (max_chunk >= 256) return false;
size_t seq = 1;
while (data_size > 0) {
size_t size = data_size;
if (size > chunk_size_max) size = chunk_size_max;
bw_.Reserve(size + kICCP_len + 4 + 2);
bw_.PutByte(0xff);
bw_.PutByte(0xe2);
bw_.PutByte(((size + kICCP_len + 4) >> 8) & 0xff);
bw_.PutByte(((size + kICCP_len + 4) >> 0) & 0xff);
bw_.PutBytes(kICCP, kICCP_len);
bw_.PutByte(seq & 0xff);
bw_.PutByte(max_chunk & 0xff);
bw_.PutBytes(ptr, size);
ptr += size;
data_size -= size;
seq += 1;
}
return true;
}
bool Encoder::WriteXMP(const std::string& data) {
if (data.size() == 0) return true;
const uint8_t kXMP[] = "http://ns.adobe.com/xap/1.0/";
const size_t kXMP_size = 29;
const size_t data_size = 2 + data.size() + kXMP_size;
if (data_size > 0xffff) return false; // error
bw_.Reserve(data_size + 2);
bw_.PutByte(0xff);
bw_.PutByte(0xe1);
bw_.PutByte((data_size >> 8) & 0xff);
bw_.PutByte((data_size >> 0) & 0xff);
bw_.PutBytes(kXMP, kXMP_size);
bw_.PutBytes(reinterpret_cast<const uint8_t*>(data.data()), data.size());
return true;
}
void Encoder::WriteDQT() {
const size_t data_size = 2 * 65 + 2;
const uint8_t kDQTHeader[] = { 0xff, 0xdb, 0x00, (uint8_t)data_size };
bw_.Reserve(data_size + 2);
bw_.PutBytes(kDQTHeader, sizeof(kDQTHeader));
for (int n = 0; n <= 1; ++n) {
bw_.PutByte(n);
const uint8_t* quant = quants_[n].quant_;
for (int i = 0; i < 64; ++i) {
bw_.PutByte(quant[kZigzag[i]]);
}
}
}
////////////////////////////////////////////////////////////////////////////////
#define DATA_16b(X) ((uint8_t)((X) >> 8)), ((uint8_t)((X) & 0xff))
void Encoder::WriteSOF() { // SOF
const size_t data_size = 3 * nb_comps_ + 8;
assert(data_size <= 255);
const uint8_t kHeader[] = {
0xff, 0xc0, DATA_16b(data_size), // SOF0 marker, size
0x08, // 8bits/components
DATA_16b(H_), DATA_16b(W_), // height, width
(uint8_t)nb_comps_ // number of components
};
bw_.Reserve(data_size + 2);
bw_.PutBytes(kHeader, sizeof(kHeader));
for (int c = 0; c < nb_comps_; ++c) {
bw_.PutByte(c + 1);
bw_.PutByte(block_dims_[c]);
bw_.PutByte(quant_idx_[c]);
}
}
void Encoder::WriteDHT() {
InitCodes(false);
const int nb_tables = (nb_comps_ == 1 ? 1 : 2);
for (int c = 0; c < nb_tables; ++c) { // luma, chroma
for (int type = 0; type <= 1; ++type) { // dc, ac
const HuffmanTable* const h = Huffman_tables_[type * 2 + c];
const size_t data_size = 3 + 16 + h->nb_syms_;
assert(data_size <= 255);
bw_.Reserve(data_size + 2);
bw_.PutByte(0xff);
bw_.PutByte(0xc4);
bw_.PutByte(0x00 /*data_size >> 8*/);
bw_.PutByte(data_size);
bw_.PutByte((type << 4) | c);
bw_.PutBytes(h->bits_, 16);
bw_.PutBytes(h->syms_, h->nb_syms_);
}
}
}
////////////////////////////////////////////////////////////////////////////////
void Encoder::WriteSOS() { // SOS
const size_t data_size = 3 + nb_comps_ * 2 + 3;
assert(data_size <= 255);
const uint8_t kHeader[] = {
0xff, 0xda, DATA_16b(data_size), (uint8_t)nb_comps_
};
bw_.Reserve(data_size + 2);
bw_.PutBytes(kHeader, sizeof(kHeader));
for (int c = 0; c < nb_comps_; ++c) {
bw_.PutByte(c + 1);
bw_.PutByte(quant_idx_[c] * 0x11);
}
bw_.PutByte(0x00); // Ss
bw_.PutByte(0x3f); // Se
bw_.PutByte(0x00); // Ah/Al
}
////////////////////////////////////////////////////////////////////////////////
void Encoder::WriteEOI() { // EOI
bw_.Flush();
// append EOI
bw_.Reserve(2);
bw_.PutByte(0xff);
bw_.PutByte(0xd9);
}
} // namespace sjpeg
<|endoftext|>
|
<commit_before>/* IBM_PROLOG_BEGIN_TAG */
/* This is an automatically generated prolog. */
/* */
/* $Source: src/import/chips/p9/procedures/hwp/io/p9_io_xbus_image_build.C $ */
/* */
/* OpenPOWER HostBoot Project */
/* */
/* Contributors Listed Below - COPYRIGHT 2015,2019 */
/* [+] International Business Machines Corp. */
/* */
/* */
/* Licensed under the Apache License, Version 2.0 (the "License"); */
/* you may not use this file except in compliance with the License. */
/* You may obtain a copy of the License at */
/* */
/* http://www.apache.org/licenses/LICENSE-2.0 */
/* */
/* Unless required by applicable law or agreed to in writing, software */
/* distributed under the License is distributed on an "AS IS" BASIS, */
/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or */
/* implied. See the License for the specific language governing */
/* permissions and limitations under the License. */
/* */
/* IBM_PROLOG_END_TAG */
///
/// @file p9_io_xbus_image_build.C
/// @brief Implements HWP that builds the Hcode image in IO Xbus PPE Sram.
///----------------------------------------------------------------------------
/// *HWP HWP Owner : Chris Steffen <cwsteffen@us.ibm.com>
/// *HWP HPW Backup Owner : Gary Peterson <garyp@us.ibm.com>
/// *HWP FW Owner : Jamie Knight <rjknight@us.ibm.com>
/// *HWP Team : IO
/// *HWP Level : 3
/// *HWP Consumed by : FSP:HB
///----------------------------------------------------------------------------
//--------------------------------------------------------------------------
// Includes
//--------------------------------------------------------------------------
#include <p9_io_xbus_image_build.H>
#include "p9_xip_image.h"
//---------------------------------------------------------------------------
fapi2::ReturnCode extractPpeImgXbus(void* const iImagePtr, uint8_t*& oPpeImgPtr, uint32_t& oSize)
{
FAPI_IMP("Entering getXbusImageFromHwImage.");
P9XipSection ppeSection;
ppeSection.iv_offset = 0;
ppeSection.iv_size = 0;
FAPI_ASSERT(iImagePtr != NULL ,
fapi2::P9_IO_PPE_OBUS_IMG_PTR_ERROR().set_HW_IMG_PTR(iImagePtr),
"Bad pointer to HW Image.");
// Pulls the IO PPE Section from the HW/XIP Image
// XIP(Execution In Place) -- Points to Seeprom
FAPI_TRY(p9_xip_get_section(iImagePtr, P9_XIP_SECTION_HW_IOPPE, &ppeSection));
// Point to the I/O PPE Section in the HW/XIP Image
oPpeImgPtr = ppeSection.iv_offset + (uint8_t*)(iImagePtr);
// From the I/O Section, lets pull the IOO Nvlink Image.
FAPI_TRY(p9_xip_get_section(oPpeImgPtr, P9_XIP_SECTION_IOPPE_IOF, &ppeSection));
// Point to the IOO PPE Image of the I/O PPE Section
oPpeImgPtr = ppeSection.iv_offset + (uint8_t*)(oPpeImgPtr);
// Set the Size of the IOO Image
oSize = ppeSection.iv_size;
fapi_try_exit:
FAPI_IMP("Exiting getXbusImageFromHwImage.");
return fapi2::current_err;
}
//---------------------------------------------------------------------------
fapi2::ReturnCode scomWrite(CONST_PROC& iTgt, const uint64_t iAddr, const uint64_t iData)
{
fapi2::buffer<uint64_t> data64(iData);
// Xscom -- Scom from core in Hostboot mode
return fapi2::putScom(iTgt, iAddr, data64);
}
//---------------------------------------------------------------------------
fapi2::ReturnCode p9_io_xbus_image_build(CONST_PROC& iTgt, void* const iHwImagePtr)
{
FAPI_IMP("Entering p9_io_xbus_image_build.");
const uint64_t SRAM_BASE_ADDR = 0xFFFF000000000000ull;
const uint64_t AUTOINC_EN = 0x8000000000000000ull;
const uint64_t AUTOINC_DIS = 0x0000000000000000ull;
const uint64_t HARD_RESET = 0x6000000000000000ull; // xcr cmd=110
const uint64_t RESUME_FROM_HALT = 0x2000000000000000ull; // xcr cmd=010
// PPE Address
const uint64_t BASE_ADDR = 0x0000000006010840ull;
const uint64_t MEM_ARB_CSAR = 0x000000000000000Dull | BASE_ADDR; // Sram Address Reg
const uint64_t MEM_ARB_SCR = 0x000000000000000Aull | BASE_ADDR; // Sram Source Control Reg
const uint64_t MEM_ARB_CSDR = 0x000000000000000Eull | BASE_ADDR; // Sram Data Reg
const uint64_t XCR_NONE = 0x0000000000000010ull | BASE_ADDR; // External Control Reg
uint64_t data = 0;
uint8_t* pPpeImg = NULL;
uint32_t imgSize = 0;
// Get vector of xbus units from the processor
auto xbusUnits = iTgt.getChildren<fapi2::TARGET_TYPE_XBUS>();
// Make sure we have functional xbus units before we load the ppe
if(!xbusUnits.empty())
{
FAPI_TRY(extractPpeImgXbus(iHwImagePtr, pPpeImg, imgSize), "Extract PPE Image Failed.");
// PPE Reset
FAPI_TRY(scomWrite(iTgt, XCR_NONE, HARD_RESET), "Hard Reset Failed.");
// Set PPE Base Address
FAPI_TRY(scomWrite(iTgt, MEM_ARB_CSAR, SRAM_BASE_ADDR), "Set Base Address Failed.");
// Set PPE into Autoincrement Mode
FAPI_TRY(scomWrite(iTgt, MEM_ARB_SCR, AUTOINC_EN), "Auto-Increment Enable Failed.");
for(uint32_t i = 0; i < imgSize; i += 8)
{
data = (((uint64_t) * (pPpeImg + i + 0) << 56) & 0xFF00000000000000ull) |
(((uint64_t) * (pPpeImg + i + 1) << 48) & 0x00FF000000000000ull) |
(((uint64_t) * (pPpeImg + i + 2) << 40) & 0x0000FF0000000000ull) |
(((uint64_t) * (pPpeImg + i + 3) << 32) & 0x000000FF00000000ull) |
(((uint64_t) * (pPpeImg + i + 4) << 24) & 0x00000000FF000000ull) |
(((uint64_t) * (pPpeImg + i + 5) << 16) & 0x0000000000FF0000ull) |
(((uint64_t) * (pPpeImg + i + 6) << 8) & 0x000000000000FF00ull) |
(((uint64_t) * (pPpeImg + i + 7) << 0) & 0x00000000000000FFull);
// Write Data, as the address will be autoincremented.
FAPI_TRY(scomWrite(iTgt, MEM_ARB_CSDR, data), "Data Write Failed.");
}
// Disable Auto Increment
FAPI_TRY(scomWrite(iTgt, MEM_ARB_SCR, AUTOINC_DIS), "Auto-Increment Disable Failed.");
// PPE Reset
FAPI_TRY(scomWrite(iTgt, XCR_NONE, HARD_RESET), "Hard Reset Failed.");
// PPE Resume From Halt
FAPI_TRY(scomWrite(iTgt, XCR_NONE, RESUME_FROM_HALT), "Resume From Halt Failed.");
}
else
{
FAPI_INF("No functional xbus units found. Skipping Xbus PPE Load...");
}
fapi_try_exit:
FAPI_IMP("Exit p9_io_xbus_image_build.");
return fapi2::current_err;
}
<commit_msg>Alink Hot Repair Fix<commit_after>/* IBM_PROLOG_BEGIN_TAG */
/* This is an automatically generated prolog. */
/* */
/* $Source: src/import/chips/p9/procedures/hwp/io/p9_io_xbus_image_build.C $ */
/* */
/* OpenPOWER HostBoot Project */
/* */
/* Contributors Listed Below - COPYRIGHT 2015,2019 */
/* [+] International Business Machines Corp. */
/* */
/* */
/* Licensed under the Apache License, Version 2.0 (the "License"); */
/* you may not use this file except in compliance with the License. */
/* You may obtain a copy of the License at */
/* */
/* http://www.apache.org/licenses/LICENSE-2.0 */
/* */
/* Unless required by applicable law or agreed to in writing, software */
/* distributed under the License is distributed on an "AS IS" BASIS, */
/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or */
/* implied. See the License for the specific language governing */
/* permissions and limitations under the License. */
/* */
/* IBM_PROLOG_END_TAG */
///
/// @file p9_io_xbus_image_build.C
/// @brief Implements HWP that builds the Hcode image in IO Xbus PPE Sram.
///----------------------------------------------------------------------------
/// *HWP HWP Owner : Chris Steffen <cwsteffen@us.ibm.com>
/// *HWP HPW Backup Owner : Gary Peterson <garyp@us.ibm.com>
/// *HWP FW Owner : Jamie Knight <rjknight@us.ibm.com>
/// *HWP Team : IO
/// *HWP Level : 3
/// *HWP Consumed by : FSP:HB
///----------------------------------------------------------------------------
//--------------------------------------------------------------------------
// Includes
//--------------------------------------------------------------------------
#include <p9_io_xbus_image_build.H>
#include "p9_xip_image.h"
//---------------------------------------------------------------------------
fapi2::ReturnCode extractPpeImgXbus(void* const iImagePtr, uint8_t*& oPpeImgPtr, uint32_t& oSize)
{
FAPI_IMP("Entering getXbusImageFromHwImage.");
P9XipSection ppeSection;
ppeSection.iv_offset = 0;
ppeSection.iv_size = 0;
FAPI_ASSERT(iImagePtr != NULL ,
fapi2::P9_IO_PPE_OBUS_IMG_PTR_ERROR().set_HW_IMG_PTR(iImagePtr),
"Bad pointer to HW Image.");
// Pulls the IO PPE Section from the HW/XIP Image
// XIP(Execution In Place) -- Points to Seeprom
FAPI_TRY(p9_xip_get_section(iImagePtr, P9_XIP_SECTION_HW_IOPPE, &ppeSection));
// Point to the I/O PPE Section in the HW/XIP Image
oPpeImgPtr = ppeSection.iv_offset + (uint8_t*)(iImagePtr);
// From the I/O Section, lets pull the IOO Nvlink Image.
FAPI_TRY(p9_xip_get_section(oPpeImgPtr, P9_XIP_SECTION_IOPPE_IOF, &ppeSection));
// Point to the IOO PPE Image of the I/O PPE Section
oPpeImgPtr = ppeSection.iv_offset + (uint8_t*)(oPpeImgPtr);
// Set the Size of the IOO Image
oSize = ppeSection.iv_size;
fapi_try_exit:
FAPI_IMP("Exiting getXbusImageFromHwImage.");
return fapi2::current_err;
}
//---------------------------------------------------------------------------
fapi2::ReturnCode scomWrite(CONST_PROC& iTgt, const uint64_t iAddr, const uint64_t iData)
{
fapi2::buffer<uint64_t> data64(iData);
// Xscom -- Scom from core in Hostboot mode
return fapi2::putScom(iTgt, iAddr, data64);
}
//---------------------------------------------------------------------------
fapi2::ReturnCode p9_io_xbus_image_build(CONST_PROC& iTgt, void* const iHwImagePtr)
{
FAPI_IMP("Entering p9_io_xbus_image_build.");
/*
* Currently a NOP as we do not have a POR to use the xbus image.
*
const uint64_t SRAM_BASE_ADDR = 0xFFFF000000000000ull;
const uint64_t AUTOINC_EN = 0x8000000000000000ull;
const uint64_t AUTOINC_DIS = 0x0000000000000000ull;
const uint64_t HARD_RESET = 0x6000000000000000ull; // xcr cmd=110
const uint64_t RESUME_FROM_HALT = 0x2000000000000000ull; // xcr cmd=010
// PPE Address
const uint64_t BASE_ADDR = 0x0000000006010840ull;
const uint64_t MEM_ARB_CSAR = 0x000000000000000Dull | BASE_ADDR; // Sram Address Reg
const uint64_t MEM_ARB_SCR = 0x000000000000000Aull | BASE_ADDR; // Sram Source Control Reg
const uint64_t MEM_ARB_CSDR = 0x000000000000000Eull | BASE_ADDR; // Sram Data Reg
const uint64_t XCR_NONE = 0x0000000000000010ull | BASE_ADDR; // External Control Reg
uint64_t data = 0;
uint8_t* pPpeImg = NULL;
uint32_t imgSize = 0;
// Get vector of xbus units from the processor
auto xbusUnits = iTgt.getChildren<fapi2::TARGET_TYPE_XBUS>();
// Make sure we have functional xbus units before we load the ppe
if(!xbusUnits.empty())
{
FAPI_TRY(extractPpeImgXbus(iHwImagePtr, pPpeImg, imgSize), "Extract PPE Image Failed.");
// PPE Reset
FAPI_TRY(scomWrite(iTgt, XCR_NONE, HARD_RESET), "Hard Reset Failed.");
// Set PPE Base Address
FAPI_TRY(scomWrite(iTgt, MEM_ARB_CSAR, SRAM_BASE_ADDR), "Set Base Address Failed.");
// Set PPE into Autoincrement Mode
FAPI_TRY(scomWrite(iTgt, MEM_ARB_SCR, AUTOINC_EN), "Auto-Increment Enable Failed.");
for(uint32_t i = 0; i < imgSize; i += 8)
{
data = (((uint64_t) * (pPpeImg + i + 0) << 56) & 0xFF00000000000000ull) |
(((uint64_t) * (pPpeImg + i + 1) << 48) & 0x00FF000000000000ull) |
(((uint64_t) * (pPpeImg + i + 2) << 40) & 0x0000FF0000000000ull) |
(((uint64_t) * (pPpeImg + i + 3) << 32) & 0x000000FF00000000ull) |
(((uint64_t) * (pPpeImg + i + 4) << 24) & 0x00000000FF000000ull) |
(((uint64_t) * (pPpeImg + i + 5) << 16) & 0x0000000000FF0000ull) |
(((uint64_t) * (pPpeImg + i + 6) << 8) & 0x000000000000FF00ull) |
(((uint64_t) * (pPpeImg + i + 7) << 0) & 0x00000000000000FFull);
// Write Data, as the address will be autoincremented.
FAPI_TRY(scomWrite(iTgt, MEM_ARB_CSDR, data), "Data Write Failed.");
}
// Disable Auto Increment
FAPI_TRY(scomWrite(iTgt, MEM_ARB_SCR, AUTOINC_DIS), "Auto-Increment Disable Failed.");
// PPE Reset
FAPI_TRY(scomWrite(iTgt, XCR_NONE, HARD_RESET), "Hard Reset Failed.");
// PPE Resume From Halt
FAPI_TRY(scomWrite(iTgt, XCR_NONE, RESUME_FROM_HALT), "Resume From Halt Failed.");
}
else
{
FAPI_INF("No functional xbus units found. Skipping Xbus PPE Load...");
}
fapi_try_exit:
*/
FAPI_IMP("Exit p9_io_xbus_image_build.");
return fapi2::current_err;
}
<|endoftext|>
|
<commit_before>/* IBM_PROLOG_BEGIN_TAG */
/* This is an automatically generated prolog. */
/* */
/* $Source: src/import/chips/p9/procedures/hwp/perv/p9_sbe_chiplet_reset.H $ */
/* */
/* OpenPOWER HostBoot Project */
/* */
/* Contributors Listed Below - COPYRIGHT 2015,2019 */
/* [+] International Business Machines Corp. */
/* */
/* */
/* Licensed under the Apache License, Version 2.0 (the "License"); */
/* you may not use this file except in compliance with the License. */
/* You may obtain a copy of the License at */
/* */
/* http://www.apache.org/licenses/LICENSE-2.0 */
/* */
/* Unless required by applicable law or agreed to in writing, software */
/* distributed under the License is distributed on an "AS IS" BASIS, */
/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or */
/* implied. See the License for the specific language governing */
/* permissions and limitations under the License. */
/* */
/* IBM_PROLOG_END_TAG */
//------------------------------------------------------------------------------
/// @file p9_sbe_chiplet_reset.H
///
/// @brief Steps:-
/// 1) Identify Partical good chiplet and configure Multicasting register
/// 2) Similar way, Configure hang pulse counter for Nest/MC/OBus/XBus/PCIe
/// 3) Similar way, set fence for Nest and MC chiplet
/// 4) Similar way, Reset sys.config and OPCG setting for Nest and MC chiplet in sync mode
///
/// Done
//------------------------------------------------------------------------------
// *HWP HW Owner : Abhishek Agarwal <abagarw8@in.ibm.com>
// *HWP HW Backup Owner : Srinivas V. Naga <srinivan@in.ibm.com>
// *HWP FW Owner : Brian Silver <bsilver@us.ibm.com>
// *HWP Team : Perv
// *HWP Level : 2
// *HWP Consumed by : SBE
//------------------------------------------------------------------------------
#ifndef _P9_SBE_CHIPLET_RESET_H_
#define _P9_SBE_CHIPLET_RESET_H_
#include <fapi2.H>
namespace p9SbeChipletReset
{
enum P9_SBE_CHIPLET_RESET_Public_Constants
{
MCGR0_CNFG_SETTINGS = 0xE0001C0000000000ull,
MCGR1_CNFG_SETTINGS = 0xE4001C0000000000ull,
MCGR2_CNFG_SETTINGS = 0xE8001C0000000000ull,
MCGR3_CNFG_SETTINGS = 0xEC001C0000000000ull,
NET_CNTL0_HW_INIT_VALUE = 0x7C16222000000000ull,
HANG_PULSE_0X10 = 0x10,
HANG_PULSE_0X0F = 0x0F,
HANG_PULSE_0X06 = 0x06,
HANG_PULSE_0X17 = 0x17,
HANG_PULSE_0X18 = 0x18,
HANG_PULSE_0X22 = 0x22,
HANG_PULSE_0X13 = 0x13,
HANG_PULSE_0X03 = 0x03,
OPCG_ALIGN_SETTING = 0x5000000000003020ull,
INOP_ALIGN_SETTING_0X5 = 0x5,
OPCG_WAIT_CYCLE_0X020 = 0x020,
SCAN_RATIO_0X3 = 0x3,
SYNC_PULSE_DELAY_0X0 = 0X00,
SYNC_CONFIG_DEFAULT = 0X0000000000000000,
HANG_PULSE_0X00 = 0x00,
HANG_PULSE_0X01 = 0x01,
HANG_PULSE_0X04 = 0x04,
HANG_PULSE_0X1A = 0x1A,
NET_CNTL1_HW_INIT_VALUE = 0x7200000000000000ull,
MCGR2_CACHE_CNFG_SETTINGS = 0xF0001C0000000000ull,
MCGR3_CACHE_CNFG_SETTINGS = 0xF4001C0000000000ull,
MCGR4_CACHE_CNFG_SETTINGS = 0xF8001C0000000000ull,
REGIONS_EXCEPT_VITAL = 0x7FF,
SCAN_TYPES_EXCEPT_TIME_GPTR_REPR = 0xDCE,
SCAN_TYPES_TIME_GPTR_REPR = 0x230,
SCAN_RATIO_0X0 = 0x0,
SYNC_CONFIG_4TO1 = 0X0800000000000000,
HW_NS_DELAY = 200000, // unit is nano seconds
SIM_CYCLE_DELAY = 10000, // unit is cycles
HANG_PULSE_0X12 = 0x12,
HANG_PULSE_0X1C = 0x1C
};
}
typedef fapi2::ReturnCode (*p9_sbe_chiplet_reset_FP_t)(const
fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>&);
/// @brief Identify all good chiplets excluding EQ/EC
/// -- All chiplets will be reset and PLLs started
/// -- Partial bad - All nest Chiplets must be good, MC, IO can be partial bad
/// Setup multicast groups for all chiplets
/// -- Can't use the multicast for all non-nest chiplets
/// -- This is intended to be the eventual product setting
/// -- This includes the core/cache chiplets
/// For all good chiplets excluding EQ/EC
/// -- Setup Chiplet GP3 regs
/// -- Reset to default state
/// -- Set chiplet enable on all all good chiplets excluding EQ/EC
/// For all enabled chiplets excluding EQ/EC/Buses
/// -- Start vital clocks and release endpoint reset
/// -- PCB Slave error register Reset
///
///
/// @param[in] i_target_chip Reference to TARGET_TYPE_PROC_CHIP target
/// @return FAPI2_RC_SUCCESS if success, else error code.
extern "C"
{
fapi2::ReturnCode p9_sbe_chiplet_reset(const
fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>& i_target_chip);
}
#endif
<commit_msg>IPL updates -- IPL_flow_v180<commit_after>/* IBM_PROLOG_BEGIN_TAG */
/* This is an automatically generated prolog. */
/* */
/* $Source: src/import/chips/p9/procedures/hwp/perv/p9_sbe_chiplet_reset.H $ */
/* */
/* OpenPOWER HostBoot Project */
/* */
/* Contributors Listed Below - COPYRIGHT 2015,2019 */
/* [+] International Business Machines Corp. */
/* */
/* */
/* Licensed under the Apache License, Version 2.0 (the "License"); */
/* you may not use this file except in compliance with the License. */
/* You may obtain a copy of the License at */
/* */
/* http://www.apache.org/licenses/LICENSE-2.0 */
/* */
/* Unless required by applicable law or agreed to in writing, software */
/* distributed under the License is distributed on an "AS IS" BASIS, */
/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or */
/* implied. See the License for the specific language governing */
/* permissions and limitations under the License. */
/* */
/* IBM_PROLOG_END_TAG */
//------------------------------------------------------------------------------
/// @file p9_sbe_chiplet_reset.H
///
/// @brief Steps:-
/// 1) Identify Partical good chiplet and configure Multicasting register
/// 2) Similar way, Configure hang pulse counter for Nest/MC/OBus/XBus/PCIe
/// 3) Similar way, set fence for Nest and MC chiplet
/// 4) Similar way, Reset sys.config and OPCG setting for Nest and MC chiplet in sync mode
///
/// Done
//------------------------------------------------------------------------------
// *HWP HW Owner : Abhishek Agarwal <abagarw8@in.ibm.com>
// *HWP HW Backup Owner : Srinivas V. Naga <srinivan@in.ibm.com>
// *HWP FW Owner : Brian Silver <bsilver@us.ibm.com>
// *HWP Team : Perv
// *HWP Level : 2
// *HWP Consumed by : SBE
//------------------------------------------------------------------------------
#ifndef _P9_SBE_CHIPLET_RESET_H_
#define _P9_SBE_CHIPLET_RESET_H_
#include <fapi2.H>
namespace p9SbeChipletReset
{
enum P9_SBE_CHIPLET_RESET_Public_Constants
{
MCGR0_CNFG_SETTINGS = 0xE0001C0000000000ull,
MCGR1_CNFG_SETTINGS = 0xE4001C0000000000ull,
MCGR2_CNFG_SETTINGS = 0xE8001C0000000000ull,
MCGR3_CNFG_SETTINGS = 0xEC001C0000000000ull,
NET_CNTL0_HW_INIT_VALUE = 0x7C16222000000000ull,
HANG_PULSE_0X10 = 0x10,
HANG_PULSE_0X0F = 0x0F,
HANG_PULSE_0X06 = 0x06,
HANG_PULSE_0X17 = 0x17,
HANG_PULSE_0X18 = 0x18,
HANG_PULSE_0X22 = 0x22,
HANG_PULSE_0X13 = 0x13,
HANG_PULSE_0X03 = 0x03,
OPCG_ALIGN_SETTING = 0x5000000000003020ull,
INOP_ALIGN_SETTING_0X5 = 0x5,
OPCG_WAIT_CYCLE_0X020 = 0x020,
SCAN_RATIO_0X3 = 0x3,
SYNC_PULSE_DELAY_0X0 = 0X00,
SYNC_CONFIG_DEFAULT = 0X0000000000000000,
HANG_PULSE_0X00 = 0x00,
HANG_PULSE_0X01 = 0x01,
HANG_PULSE_0X04 = 0x04,
HANG_PULSE_0X1A = 0x1A,
NET_CNTL1_HW_INIT_VALUE = 0x7200000000000000ull,
MCGR2_CACHE_CNFG_SETTINGS = 0xF0001C0000000000ull,
MCGR3_CACHE_CNFG_SETTINGS = 0xF4001C0000000000ull,
MCGR4_CACHE_CNFG_SETTINGS = 0xF8001C0000000000ull,
REGIONS_EXCEPT_VITAL = 0x7FF,
SCAN_TYPES_EXCEPT_TIME_GPTR_REPR = 0xDCE,
SCAN_TYPES_TIME_GPTR_REPR = 0x230,
SCAN_RATIO_0X0 = 0x0,
SYNC_CONFIG_4TO1 = 0X0800000000000000,
HW_NS_DELAY = 200000, // unit is nano seconds
SIM_CYCLE_DELAY = 10000, // unit is cycles
HANG_PULSE_0X12 = 0x12,
HANG_PULSE_0X1C = 0x1C,
HANG_PULSE_0X05 = 0x05
};
}
typedef fapi2::ReturnCode (*p9_sbe_chiplet_reset_FP_t)(const
fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>&);
/// @brief Identify all good chiplets excluding EQ/EC
/// -- All chiplets will be reset and PLLs started
/// -- Partial bad - All nest Chiplets must be good, MC, IO can be partial bad
/// Setup multicast groups for all chiplets
/// -- Can't use the multicast for all non-nest chiplets
/// -- This is intended to be the eventual product setting
/// -- This includes the core/cache chiplets
/// For all good chiplets excluding EQ/EC
/// -- Setup Chiplet GP3 regs
/// -- Reset to default state
/// -- Set chiplet enable on all all good chiplets excluding EQ/EC
/// For all enabled chiplets excluding EQ/EC/Buses
/// -- Start vital clocks and release endpoint reset
/// -- PCB Slave error register Reset
///
///
/// @param[in] i_target_chip Reference to TARGET_TYPE_PROC_CHIP target
/// @return FAPI2_RC_SUCCESS if success, else error code.
extern "C"
{
fapi2::ReturnCode p9_sbe_chiplet_reset(const
fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>& i_target_chip);
}
#endif
<|endoftext|>
|
<commit_before>/*
http://portaudio.com/docs/v19-doxydocs/api_overview.html
*/
/* BEGIN Setup */
#include "jsaudio.h"
#include "helpers.h"
#include "stream.h"
/* Initialize stream and jsStreamCb as global */
LocalFunction jsStreamCb;
/* BEGIN Initialization, termination, and utility */
// http://portaudio.com/docs/v19-doxydocs/portaudio_8h.html#abed859482d156622d9332dff9b2d89da
NAN_METHOD(initialize) {
PaError err = Pa_Initialize();
if (err != paNoError) {
ThrowError(Pa_GetErrorText(err));
}
}
// http://portaudio.com/docs/v19-doxydocs/portaudio_8h.html#a0db317604e916e8bd6098e60e6237221
NAN_METHOD(terminate) {
PaError err = Pa_Terminate();
if (err != paNoError) {
ThrowError(Pa_GetErrorText(err));
}
}
// http://portaudio.com/docs/v19-doxydocs/portaudio_8h.html#a66da08bcf908e0849c62a6b47f50d7b4
NAN_METHOD(getVersion) {
info.GetReturnValue().Set(Pa_GetVersion());
}
/* BEGIN Host APIs */
// http://portaudio.com/docs/v19-doxydocs/portaudio_8h.html#a19dbdb7c8702e3f4bfc0cdb99dac3dd9
NAN_METHOD(getHostApiCount) {
info.GetReturnValue().Set(Pa_GetHostApiCount());
}
// http://portaudio.com/docs/v19-doxydocs/portaudio_8h.html#ae55c77f9b7e3f8eb301a6f1c0e2347ac
NAN_METHOD(getDefaultHostApi) {
info.GetReturnValue().Set(Pa_GetDefaultHostApi());
}
// http://portaudio.com/docs/v19-doxydocs/portaudio_8h.html#a7c650aede88ea553066bab9bbe97ea90
NAN_METHOD(getHostApiInfo) {
HandleScope scope;
int api = info[0].IsEmpty() ? Pa_GetDefaultHostApi() : info[0]->Uint32Value();
const PaHostApiInfo* hai = Pa_GetHostApiInfo(api);
LocalObject obj = New<Object>();
obj->Set(ToLocString("apiIndex"), New<Number>(api));
HostApiInfoToLocalObject(obj, hai);
info.GetReturnValue().Set(obj);
}
/* BEGIN Device APIs */
// http://portaudio.com/docs/v19-doxydocs/portaudio_8h.html#acfe4d3c5ec1a343f459981bfa2057f8d
NAN_METHOD(getDeviceCount) {
info.GetReturnValue().Set(Pa_GetDeviceCount());
}
// http://portaudio.com/docs/v19-doxydocs/portaudio_8h.html#abf9f2f82da95553d5adb929af670f74b
NAN_METHOD(getDefaultInputDevice) {
info.GetReturnValue().Set(Pa_GetDefaultInputDevice());
}
// http://portaudio.com/docs/v19-doxydocs/portaudio_8h.html#adc955dfab007624000695c48d4f876dc
NAN_METHOD(getDefaultOutputDevice) {
info.GetReturnValue().Set(Pa_GetDefaultOutputDevice());
}
// http://portaudio.com/docs/v19-doxydocs/portaudio_8h.html#ac7d8e091ffc1d1d4a035704660e117eb
NAN_METHOD(getDeviceInfo) {
HandleScope scope;
int dvc = info[0].IsEmpty()
? Pa_GetDefaultInputDevice()
: info[0]->Uint32Value();
const PaDeviceInfo* di = Pa_GetDeviceInfo(dvc);
LocalObject obj = New<Object>();
obj->Set(ToLocString("deviceIndex"), New<Number>(dvc));
DeviceInfoToLocalObject(obj, di);
info.GetReturnValue().Set(obj);
}
// http://portaudio.com/docs/v19-doxydocs/portaudio_8h.html#a443ad16338191af364e3be988014cbbe
NAN_METHOD(openStream) {
HandleScope scope;
PaError err;
// Get params objects
LocalObject obj = info[0]->ToObject();
JsPaStream* stream = ObjectWrap::Unwrap<JsPaStream>(ToLocObject(Get(obj, ToLocString("stream"))));
LocalObject objInput = ToLocObject(Get(obj, ToLocString("input")));
LocalObject objOutput = ToLocObject(Get(obj, ToLocString("output")));
PaStreamParameters paramsIn = LocObjToPaStreamParameters(objInput);
PaStreamParameters paramsOut = LocObjToPaStreamParameters(objOutput);
// Get stream options
double sampleRate = LocalizeDouble(Get(obj, ToLocString("sampleRate")));
unsigned long framesPerBuffer = LocalizeULong(
Get(obj, ToLocString("framesPerBuffer")));
PaStreamFlags streamFlags = static_cast<PaStreamFlags>(
Get(obj, ToLocString("streamFlags")).ToLocalChecked()->IntegerValue());
// Start stream
err = Pa_OpenStream(
stream->streamPtrRef(),
¶msIn,
¶msOut,
sampleRate,
framesPerBuffer,
streamFlags,
NULL,
NULL
);
if (err != paNoError) {
printf("%s\n", "OpenStream: ");
printf("%s\n", Pa_GetErrorText(err));
// ThrowError(Pa_GetErrorText(err));
}
// Testing that params are set right
info.GetReturnValue().Set(New<Number>(err));
}
/*
// http://portaudio.com/docs/v19-doxydocs/portaudio_8h.html#a0a12735ac191200f696a43b87667b714
NAN_METHOD(openDefaultStream) {
// ToDo: implement this
}
*/
//http://portaudio.com/docs/v19-doxydocs/portaudio_8h.html#a7432aadd26c40452da12fa99fc1a047b
NAN_METHOD(startStream) {
HandleScope scope;
PaError err;
// Get stream object
LocalObject obj = info[0]->ToObject();
JsPaStream* stream = ObjectWrap::Unwrap<JsPaStream>(info[0]->ToObject());
// Start stream
err = Pa_StartStream(stream->streamPtr());
if (err != paNoError) {
printf("%s\n", "StartStream: ");
printf("%s\n", Pa_GetErrorText(err));
// ThrowError(Pa_GetErrorText(err));
}
// Testing that params are set right
info.GetReturnValue().Set(New<Number>(err));
}
NAN_METHOD(getStreamWriteAvailable) {
HandleScope scope;
long retVal;
// Get stream object
LocalObject obj = info[0]->ToObject();
JsPaStream* stream = ObjectWrap::Unwrap<JsPaStream>(info[0]->ToObject());
// Start stream
retVal = Pa_GetStreamWriteAvailable(stream->streamPtr());
// Testing that params are set right
info.GetReturnValue().Set(New<Number>(retVal));
}
NAN_METHOD(getStreamReadAvailable) {
HandleScope scope;
long retVal;
// Get stream object
LocalObject obj = info[0]->ToObject();
JsPaStream* stream = ObjectWrap::Unwrap<JsPaStream>(info[0]->ToObject());
// Start stream
retVal = Pa_GetStreamReadAvailable(stream->streamPtr());
// Testing that params are set right
info.GetReturnValue().Set(New<Number>(retVal));
}
NAN_METHOD(writeStream) {
HandleScope scope;
long retVal;
// Get stream object
LocalObject obj = info[0]->ToObject();
JsPaStream* stream = ObjectWrap::Unwrap<JsPaStream>(info[0]->ToObject());
// Get the buffer data
TypedArrayContents<float> buf(info[1]);
unsigned long bufFrames = static_cast<unsigned long>(buf.length()) / 2;
// Start stream
retVal = Pa_WriteStream(stream->streamPtr(), *buf, bufFrames);
// Testing that params are set right
info.GetReturnValue().Set(New<Number>(retVal));
}
NAN_METHOD(readStream) {
HandleScope scope;
long retVal;
// Get stream object
LocalObject obj = info[0]->ToObject();
JsPaStream* stream = ObjectWrap::Unwrap<JsPaStream>(info[0]->ToObject());
// Get the buffer data
TypedArrayContents<float> buf(info[1]);
unsigned long bufFrames = static_cast<unsigned long>(buf.length()) / 2;
// Start stream
retVal = Pa_ReadStream(stream->streamPtr(), *buf, bufFrames);
// Testing that params are set right
info.GetReturnValue().Set(New<Number>(retVal));
}
<commit_msg>Added links to PortAudio docs<commit_after>/*
http://portaudio.com/docs/v19-doxydocs/api_overview.html
*/
/* BEGIN Setup */
#include "jsaudio.h"
#include "helpers.h"
#include "stream.h"
/* Initialize stream and jsStreamCb as global */
LocalFunction jsStreamCb;
/* BEGIN Initialization, termination, and utility */
// http://portaudio.com/docs/v19-doxydocs/portaudio_8h.html#abed859482d156622d9332dff9b2d89da
NAN_METHOD(initialize) {
PaError err = Pa_Initialize();
if (err != paNoError) {
ThrowError(Pa_GetErrorText(err));
}
}
// http://portaudio.com/docs/v19-doxydocs/portaudio_8h.html#a0db317604e916e8bd6098e60e6237221
NAN_METHOD(terminate) {
PaError err = Pa_Terminate();
if (err != paNoError) {
ThrowError(Pa_GetErrorText(err));
}
}
// http://portaudio.com/docs/v19-doxydocs/portaudio_8h.html#a66da08bcf908e0849c62a6b47f50d7b4
NAN_METHOD(getVersion) {
info.GetReturnValue().Set(Pa_GetVersion());
}
/* BEGIN Host APIs */
// http://portaudio.com/docs/v19-doxydocs/portaudio_8h.html#a19dbdb7c8702e3f4bfc0cdb99dac3dd9
NAN_METHOD(getHostApiCount) {
info.GetReturnValue().Set(Pa_GetHostApiCount());
}
// http://portaudio.com/docs/v19-doxydocs/portaudio_8h.html#ae55c77f9b7e3f8eb301a6f1c0e2347ac
NAN_METHOD(getDefaultHostApi) {
info.GetReturnValue().Set(Pa_GetDefaultHostApi());
}
// http://portaudio.com/docs/v19-doxydocs/portaudio_8h.html#a7c650aede88ea553066bab9bbe97ea90
NAN_METHOD(getHostApiInfo) {
HandleScope scope;
int api = info[0].IsEmpty() ? Pa_GetDefaultHostApi() : info[0]->Uint32Value();
const PaHostApiInfo* hai = Pa_GetHostApiInfo(api);
LocalObject obj = New<Object>();
obj->Set(ToLocString("apiIndex"), New<Number>(api));
HostApiInfoToLocalObject(obj, hai);
info.GetReturnValue().Set(obj);
}
/* BEGIN Device APIs */
// http://portaudio.com/docs/v19-doxydocs/portaudio_8h.html#acfe4d3c5ec1a343f459981bfa2057f8d
NAN_METHOD(getDeviceCount) {
info.GetReturnValue().Set(Pa_GetDeviceCount());
}
// http://portaudio.com/docs/v19-doxydocs/portaudio_8h.html#abf9f2f82da95553d5adb929af670f74b
NAN_METHOD(getDefaultInputDevice) {
info.GetReturnValue().Set(Pa_GetDefaultInputDevice());
}
// http://portaudio.com/docs/v19-doxydocs/portaudio_8h.html#adc955dfab007624000695c48d4f876dc
NAN_METHOD(getDefaultOutputDevice) {
info.GetReturnValue().Set(Pa_GetDefaultOutputDevice());
}
// http://portaudio.com/docs/v19-doxydocs/portaudio_8h.html#ac7d8e091ffc1d1d4a035704660e117eb
NAN_METHOD(getDeviceInfo) {
HandleScope scope;
int dvc = info[0].IsEmpty()
? Pa_GetDefaultInputDevice()
: info[0]->Uint32Value();
const PaDeviceInfo* di = Pa_GetDeviceInfo(dvc);
LocalObject obj = New<Object>();
obj->Set(ToLocString("deviceIndex"), New<Number>(dvc));
DeviceInfoToLocalObject(obj, di);
info.GetReturnValue().Set(obj);
}
// http://portaudio.com/docs/v19-doxydocs/portaudio_8h.html#a443ad16338191af364e3be988014cbbe
NAN_METHOD(openStream) {
HandleScope scope;
PaError err;
// Get params objects
LocalObject obj = info[0]->ToObject();
JsPaStream* stream = ObjectWrap::Unwrap<JsPaStream>(ToLocObject(Get(obj, ToLocString("stream"))));
LocalObject objInput = ToLocObject(Get(obj, ToLocString("input")));
LocalObject objOutput = ToLocObject(Get(obj, ToLocString("output")));
PaStreamParameters paramsIn = LocObjToPaStreamParameters(objInput);
PaStreamParameters paramsOut = LocObjToPaStreamParameters(objOutput);
// Get stream options
double sampleRate = LocalizeDouble(Get(obj, ToLocString("sampleRate")));
unsigned long framesPerBuffer = LocalizeULong(
Get(obj, ToLocString("framesPerBuffer")));
PaStreamFlags streamFlags = static_cast<PaStreamFlags>(
Get(obj, ToLocString("streamFlags")).ToLocalChecked()->IntegerValue());
// Start stream
err = Pa_OpenStream(
stream->streamPtrRef(),
¶msIn,
¶msOut,
sampleRate,
framesPerBuffer,
streamFlags,
NULL,
NULL
);
if (err != paNoError) {
printf("%s\n", "OpenStream: ");
printf("%s\n", Pa_GetErrorText(err));
// ThrowError(Pa_GetErrorText(err));
}
// Testing that params are set right
info.GetReturnValue().Set(New<Number>(err));
}
/*
// http://portaudio.com/docs/v19-doxydocs/portaudio_8h.html#a0a12735ac191200f696a43b87667b714
NAN_METHOD(openDefaultStream) {
// ToDo: implement this
}
*/
//http://portaudio.com/docs/v19-doxydocs/portaudio_8h.html#a7432aadd26c40452da12fa99fc1a047b
NAN_METHOD(startStream) {
HandleScope scope;
PaError err;
// Get stream object
LocalObject obj = info[0]->ToObject();
JsPaStream* stream = ObjectWrap::Unwrap<JsPaStream>(info[0]->ToObject());
// Start stream
err = Pa_StartStream(stream->streamPtr());
if (err != paNoError) {
printf("%s\n", "StartStream: ");
printf("%s\n", Pa_GetErrorText(err));
// ThrowError(Pa_GetErrorText(err));
}
// Testing that params are set right
info.GetReturnValue().Set(New<Number>(err));
}
//http://portaudio.com/docs/v19-doxydocs/portaudio_8h.html#a25595acf48733ec32045aa189c3caa61
NAN_METHOD(getStreamWriteAvailable) {
HandleScope scope;
long retVal;
// Get stream object
LocalObject obj = info[0]->ToObject();
JsPaStream* stream = ObjectWrap::Unwrap<JsPaStream>(info[0]->ToObject());
// Start stream
retVal = Pa_GetStreamWriteAvailable(stream->streamPtr());
// Testing that params are set right
info.GetReturnValue().Set(New<Number>(retVal));
}
//http://portaudio.com/docs/v19-doxydocs/portaudio_8h.html#ad04c33f045fa58d7b705b56b1fd3e816
NAN_METHOD(getStreamReadAvailable) {
HandleScope scope;
long retVal;
// Get stream object
LocalObject obj = info[0]->ToObject();
JsPaStream* stream = ObjectWrap::Unwrap<JsPaStream>(info[0]->ToObject());
// Start stream
retVal = Pa_GetStreamReadAvailable(stream->streamPtr());
// Testing that params are set right
info.GetReturnValue().Set(New<Number>(retVal));
}
//http://portaudio.com/docs/v19-doxydocs/portaudio_8h.html#a075a6efb503a728213bdae24347ed27d
NAN_METHOD(writeStream) {
HandleScope scope;
long retVal;
// Get stream object
LocalObject obj = info[0]->ToObject();
JsPaStream* stream = ObjectWrap::Unwrap<JsPaStream>(info[0]->ToObject());
// Get the buffer data
TypedArrayContents<float> buf(info[1]);
unsigned long bufFrames = static_cast<unsigned long>(buf.length()) / 2;
// Start stream
retVal = Pa_WriteStream(stream->streamPtr(), *buf, bufFrames);
// Testing that params are set right
info.GetReturnValue().Set(New<Number>(retVal));
}
//http://portaudio.com/docs/v19-doxydocs/portaudio_8h.html#a0b62d4b74b5d3d88368e9e4c0b8b2dc7
NAN_METHOD(readStream) {
HandleScope scope;
long retVal;
// Get stream object
LocalObject obj = info[0]->ToObject();
JsPaStream* stream = ObjectWrap::Unwrap<JsPaStream>(info[0]->ToObject());
// Get the buffer data
TypedArrayContents<float> buf(info[1]);
unsigned long bufFrames = static_cast<unsigned long>(buf.length()) / 2;
// Start stream
retVal = Pa_ReadStream(stream->streamPtr(), *buf, bufFrames);
// Testing that params are set right
info.GetReturnValue().Set(New<Number>(retVal));
}
<|endoftext|>
|
<commit_before>#include <node.h>
#include <v8.h>
#include "zmap-1.2.1/src/zopt.h"
#include "libzmap.h"
namespace libzmap {
using namespace node;
using namespace v8;
Handle<Value> LibZMAP(const Arguments& args) {
HandleScope scope;
Local<Function> callback;
Local<Object> obj;
if (args.Length() < 1) {
ThrowException(Exception::TypeError(String::New("Arguments invalid")));
return scope.Close(Undefined());
}
if (args[0]->IsFunction()) {
callback = Local<Function>::Cast(args[0]);
} else {
if (!args[1]->IsFunction()) {
ThrowException(Exception::TypeError(String::New("Function expected")));
return scope.Close(Undefined());
}
callback = Local<Function>::Cast(args[1]);
if (!args[0]->IsObject()) {
ThrowException(Exception::TypeError(String::New("Object expected")));
return scope.Close(Undefined());
}
}
if (args[0]->IsObject()) {
obj = args[0]->ToObject();
}
obj->Set(String::NewSymbol("x"),
String::New("wtf"));
/* Setup options */
/* Initialize scan */
return scope.Close(obj);
}
void Init (Handle<Object> exports) {
exports->Set(String::NewSymbol("zmap"),
FunctionTemplate::New(LibZMAP)->GetFunction());
}
extern "C" {
NODE_MODULE(zmap, Init)
}
} // namespace libzmap
<commit_msg>development Tue Sep 2 04:25:20 MDT 2014: Working on argument to option conversions<commit_after>#include <node.h>
#include <v8.h>
#include "zmap-1.2.1/src/zopt.h"
#include "libzmap.h"
namespace libzmap {
using namespace node;
using namespace v8;
Handle<Value> LibZMAP(const Arguments& args) {
HandleScope scope;
struct gengetopt_args_info argv;
struct cmdline_parser_params *params;
params = cmdline_parser_params_create();
params->initialize = 1;
params->override = 0;
params->check_required = 0;
int config_loaded = 0;
if (cmdline_parser_ext(args.Length(), args[0], &argv, params) != 0) {
ThrowException(Exception::TypeError(String::New("cmdline_parser_ext met")));
//exit(EXIT_SUCCESS);
}
Local<Function> callback;
Local<Object> obj;
if (args.Length() < 1) {
ThrowException(Exception::TypeError(String::New("Arguments invalid")));
return scope.Close(Undefined());
}
if (args[0]->IsFunction()) {
callback = Local<Function>::Cast(args[0]);
} else {
if (!args[1]->IsFunction()) {
ThrowException(Exception::TypeError(String::New("Function expected")));
return scope.Close(Undefined());
}
callback = Local<Function>::Cast(args[1]);
if (!args[0]->IsObject()) {
ThrowException(Exception::TypeError(String::New("Object expected")));
return scope.Close(Undefined());
}
}
if (args[0]->IsObject()) {
obj = args[0]->ToObject();
}
return scope.Close(obj);
}
void Init (Handle<Object> exports) {
exports->Set(String::NewSymbol("zmap"),
FunctionTemplate::New(LibZMAP)->GetFunction());
}
extern "C" {
NODE_MODULE(zmap, Init)
}
} // namespace libzmap
<|endoftext|>
|
<commit_before>#include <tinyxml2.h>
#include "mud.h"
#include "living.h"
#include "event.h"
#include "delayedEvent.h"
#include "world.h"
Living::Living()
{
events.RegisterEvent("HeartBeat", new DelayedEvent(LIVING_PULSE,0));
_position = POSITION_STANDING;
_gender = Gender::Neuter;
}
void Living::EnterGame()
{
}
void Living::LeaveGame()
{
}
void Living::Update()
{
events.CallEvent("HeartBeat", NULL, (void*)this);
}
bool Living::IsLiving() const
{
return true;
}
Gender Living::GetGender() const
{
return _gender;
}
void Living::SetGender(Gender gender)
{
_gender = gender;
}
unsigned int Living::GetPosition() const
{
return _position;
}
void Living::SetPosition(unsigned int pos)
{
_position = pos;
}
bool Living::AddAttribute(Attribute* attr)
{
_attributes.push_back(attr);
return true;
}
void Living::FindAttribute(int apply, int id, std::vector<Attribute*> &results)
{
for (Attribute* attr: _attributes)
{
if (attr->GetApply() == apply && attr->GetId() == id)
{
results.push_back(attr);
}
}
}
void Living::FindAttribute(int type, std::vector<Attribute*>& results)
{
for (Attribute* attr:_attributes)
{
if (attr->GetType() == type)
{
results.push_back(attr);
}
}
}
void Living::Serialize(tinyxml2::XMLElement* root)
{
tinyxml2::XMLDocument* doc = root->GetDocument();
tinyxml2::XMLElement* node = doc->NewElement("living");
node->SetAttribute("gender", (int)_gender);
Entity::Serialize(node);
root->InsertEndChild(node);
}
void Living::Deserialize(tinyxml2::XMLElement* root)
{
_gender = (Gender)root->IntAttribute("gender");
Entity::Deserialize(root->FirstChildElement("entity"));
}
<commit_msg>fixed uninitialized members.<commit_after>#include <tinyxml2.h>
#include "mud.h"
#include "living.h"
#include "event.h"
#include "delayedEvent.h"
#include "world.h"
Living::Living()
{
events.RegisterEvent("HeartBeat", new DelayedEvent(LIVING_PULSE,0));
_position = POSITION_STANDING;
_gender = Gender::Neuter;
_following = nullptr;
}
void Living::EnterGame()
{
}
void Living::LeaveGame()
{
}
void Living::Update()
{
events.CallEvent("HeartBeat", NULL, (void*)this);
}
bool Living::IsLiving() const
{
return true;
}
Gender Living::GetGender() const
{
return _gender;
}
void Living::SetGender(Gender gender)
{
_gender = gender;
}
unsigned int Living::GetPosition() const
{
return _position;
}
void Living::SetPosition(unsigned int pos)
{
_position = pos;
}
bool Living::AddAttribute(Attribute* attr)
{
_attributes.push_back(attr);
return true;
}
void Living::FindAttribute(int apply, int id, std::vector<Attribute*> &results)
{
for (Attribute* attr: _attributes)
{
if (attr->GetApply() == apply && attr->GetId() == id)
{
results.push_back(attr);
}
}
}
void Living::FindAttribute(int type, std::vector<Attribute*>& results)
{
for (Attribute* attr:_attributes)
{
if (attr->GetType() == type)
{
results.push_back(attr);
}
}
}
void Living::Serialize(tinyxml2::XMLElement* root)
{
tinyxml2::XMLDocument* doc = root->GetDocument();
tinyxml2::XMLElement* node = doc->NewElement("living");
node->SetAttribute("gender", (int)_gender);
Entity::Serialize(node);
root->InsertEndChild(node);
}
void Living::Deserialize(tinyxml2::XMLElement* root)
{
_gender = (Gender)root->IntAttribute("gender");
Entity::Deserialize(root->FirstChildElement("entity"));
}
<|endoftext|>
|
<commit_before>#include "parser.h"
int priority[128];
bool rightassoc[128];
const std::vector<std::pair<token_type, std::string> > splitExpression(const std::string &expr)
{
priority[int('+')] = 0;
priority[int('-')] = 0;
priority[int('*')] = 1;
priority[int('/')] = 1;
priority[int('%')] = 1;
priority[int('^')] = 2;
priority[int('\\')] = 3;
priority[int('=')] = -1;
rightassoc[int('^')] = true;
rightassoc[int('\\')] = true;
std::string func, num, poly;
std::vector<std::pair<token_type, std::string> > ans;
token_type last = TOKEN_LEFTPAR;
bool skip_next_matrix = false;
for(char i : expr + ' ')
{
if(('A' <= i && i <= 'Z') || i == '_')
{
if(func.size())
ans.push_back({TOKEN_FUNC, func});
if(num.size())
ans.push_back({TOKEN_NUMBER, num});
num = func = "";
if(last == TOKEN_MATRIX || last == TOKEN_NUMBER || last == TOKEN_RIGHTPAR)
ans.push_back({TOKEN_OP, "*"});
ans.push_back({TOKEN_MATRIX, std::string() + i});
if(skip_next_matrix)
last = TOKEN_LEFTPAR;
else
last = TOKEN_MATRIX;
skip_next_matrix = false;
}
else if(i == '+' || i == '*' || i == '^' || i == '(' || i == ')' || i == '=' || i == '/' || i == '%')
{
if(i == '/' && poly.size())
{
poly.push_back('/');
continue;
}
if(func.size())
ans.push_back({TOKEN_FUNC, func});
if(num.size())
ans.push_back({TOKEN_NUMBER, num});
num = func = "";
if(i == '(')
{
if(last == TOKEN_MATRIX || last == TOKEN_NUMBER || last == TOKEN_RIGHTPAR)
ans.push_back({TOKEN_OP, "*"});
ans.push_back({TOKEN_LEFTPAR, ""});
}
else if(i == ')')
ans.push_back({TOKEN_RIGHTPAR, ""});
else
ans.push_back({TOKEN_OP, std::string() + i});
last = ans.back().first;
}
else if(i == '-')
{
if(poly.size())
{
poly.push_back('-');
continue;
}
if(func.size())
ans.push_back({TOKEN_FUNC, func});
if(num.size())
ans.push_back({TOKEN_NUMBER, num});
num = func = "";
if(last == TOKEN_LEFTPAR || last == TOKEN_OP || last == TOKEN_COMMA)
{
ans.push_back({TOKEN_OP, "\\"}); // unary
}
else
{
ans.push_back({TOKEN_OP, "-"});
}
last = TOKEN_OP;
}
else if(('0' <= i && i <= '9') || i == '.')
{
if(poly.size())
{
poly.push_back(i);
continue;
}
if(func.size())
ans.push_back({TOKEN_FUNC, func});
func = "";
num.push_back(i);
last = TOKEN_NUMBER;
}
else if('a' <= i && i <= 'z')
{
if(num.size())
ans.push_back({TOKEN_NUMBER, num});
num = "";
if(last == TOKEN_MATRIX || last == TOKEN_NUMBER || last == TOKEN_RIGHTPAR)
ans.push_back({TOKEN_OP, "*"});
func.push_back(i);
last = TOKEN_FUNC;
}
else if(i == ',')
{
if(func.size())
ans.push_back({TOKEN_FUNC, func});
if(num.size())
ans.push_back({TOKEN_NUMBER, num});
num = func = "";
ans.push_back({TOKEN_COMMA, ""});
last = TOKEN_COMMA;
}
else if(i == '$')
{
if(func.size())
ans.push_back({TOKEN_FUNC, func});
if(num.size())
ans.push_back({TOKEN_NUMBER, num});
num = func = "";
if(last == TOKEN_MATRIX || last == TOKEN_NUMBER || last == TOKEN_RIGHTPAR)
ans.push_back({TOKEN_OP, "*"});
ans.push_back({TOKEN_DOLLAR, ""});
last = TOKEN_DOLLAR;
}
else if(i == '"' || i == '\'')
{
if(poly.size())
{
if(poly[0] != i)
{
ans.clear();
return ans;
}
ans.push_back({TOKEN_POLY, poly});
poly = "";
last = TOKEN_POLY;
}
else
{
poly = i;
num = func = "";
}
}
else
{
if(i == ' ' && poly.size())
{
poly.push_back(i);
continue;
}
if(func.size())
{
ans.push_back({TOKEN_FUNC, func});
if(func == "let")
skip_next_matrix = true;
}
if(num.size())
ans.push_back({TOKEN_NUMBER, num});
num = func = "";
}
}
return ans;
}
<commit_msg>Более естественная расстановка умнежений<commit_after>#include "parser.h"
int priority[128];
bool rightassoc[128];
const std::vector<std::pair<token_type, std::string> > splitExpression(const std::string &expr)
{
priority[int('+')] = 0;
priority[int('-')] = 0;
priority[int('*')] = 1;
priority[int('/')] = 1;
priority[int('%')] = 1;
priority[int('^')] = 2;
priority[int('\\')] = 3;
priority[int('=')] = -1;
rightassoc[int('^')] = true;
rightassoc[int('\\')] = true;
std::string func, num, poly;
std::vector<std::pair<token_type, std::string> > ans;
token_type last = TOKEN_LEFTPAR;
bool skip_next_matrix = false;
for(char i : expr + ' ')
{
if(('A' <= i && i <= 'Z') || i == '_')
{
if(func.size())
ans.push_back({TOKEN_FUNC, func});
if(num.size())
ans.push_back({TOKEN_NUMBER, num});
num = func = "";
if(last == TOKEN_MATRIX || last == TOKEN_NUMBER || last == TOKEN_RIGHTPAR || last == TOKEN_POLY)
ans.push_back({TOKEN_OP, "*"});
ans.push_back({TOKEN_MATRIX, std::string() + i});
if(skip_next_matrix)
last = TOKEN_LEFTPAR;
else
last = TOKEN_MATRIX;
skip_next_matrix = false;
}
else if(i == '+' || i == '*' || i == '^' || i == '(' || i == ')' || i == '=' || i == '/' || i == '%')
{
if(i == '/' && poly.size())
{
poly.push_back('/');
continue;
}
if(func.size())
ans.push_back({TOKEN_FUNC, func});
if(num.size())
ans.push_back({TOKEN_NUMBER, num});
num = func = "";
if(i == '(')
{
if(last == TOKEN_MATRIX || last == TOKEN_NUMBER || last == TOKEN_RIGHTPAR || last == TOKEN_POLY)
ans.push_back({TOKEN_OP, "*"});
ans.push_back({TOKEN_LEFTPAR, ""});
}
else if(i == ')')
ans.push_back({TOKEN_RIGHTPAR, ""});
else
ans.push_back({TOKEN_OP, std::string() + i});
last = ans.back().first;
}
else if(i == '-')
{
if(poly.size())
{
poly.push_back('-');
continue;
}
if(func.size())
ans.push_back({TOKEN_FUNC, func});
if(num.size())
ans.push_back({TOKEN_NUMBER, num});
num = func = "";
if(last == TOKEN_LEFTPAR || last == TOKEN_OP || last == TOKEN_COMMA)
{
ans.push_back({TOKEN_OP, "\\"}); // unary
}
else
{
ans.push_back({TOKEN_OP, "-"});
}
last = TOKEN_OP;
}
else if(('0' <= i && i <= '9') || i == '.')
{
if(poly.size())
{
poly.push_back(i);
continue;
}
if(func.size())
ans.push_back({TOKEN_FUNC, func});
func = "";
num.push_back(i);
last = TOKEN_NUMBER;
}
else if('a' <= i && i <= 'z')
{
if(num.size())
ans.push_back({TOKEN_NUMBER, num});
num = "";
if(last == TOKEN_MATRIX || last == TOKEN_NUMBER || last == TOKEN_RIGHTPAR || last == TOKEN_POLY)
ans.push_back({TOKEN_OP, "*"});
func.push_back(i);
last = TOKEN_FUNC;
}
else if(i == ',')
{
if(func.size())
ans.push_back({TOKEN_FUNC, func});
if(num.size())
ans.push_back({TOKEN_NUMBER, num});
num = func = "";
ans.push_back({TOKEN_COMMA, ""});
last = TOKEN_COMMA;
}
else if(i == '$')
{
if(func.size())
ans.push_back({TOKEN_FUNC, func});
if(num.size())
ans.push_back({TOKEN_NUMBER, num});
num = func = "";
if(last == TOKEN_MATRIX || last == TOKEN_NUMBER || last == TOKEN_RIGHTPAR || last == TOKEN_POLY)
ans.push_back({TOKEN_OP, "*"});
ans.push_back({TOKEN_DOLLAR, ""});
last = TOKEN_DOLLAR;
}
else if(i == '"' || i == '\'')
{
if(poly.size())
{
if(poly[0] != i)
{
ans.clear();
return ans;
}
ans.push_back({TOKEN_POLY, poly});
poly = "";
last = TOKEN_POLY;
}
else
{
if(func.size())
ans.push_back({TOKEN_FUNC, func});
if(num.size())
ans.push_back({TOKEN_NUMBER, num});
if(last == TOKEN_MATRIX || last == TOKEN_NUMBER || last == TOKEN_RIGHTPAR || last == TOKEN_POLY)
ans.push_back({TOKEN_OP, "*"});
poly = i;
num = func = "";
}
}
else
{
if(i == ' ' && poly.size())
{
poly.push_back(i);
continue;
}
if(func.size())
{
ans.push_back({TOKEN_FUNC, func});
if(func == "let")
skip_next_matrix = true;
}
if(num.size())
ans.push_back({TOKEN_NUMBER, num});
num = func = "";
}
}
return ans;
}
<|endoftext|>
|
<commit_before>#include "parser.hpp"
//////////////
// Includes //
#include <istream>
#include <string>
#include <vector>
#include <tuple>
#include "parsestream.hpp"
#include "streamutils.hpp"
#include "json.hpp"
//////////
// Code //
// Creating a parse exception.
ParseException::ParseException(std::string type) {
this->type = type;
}
// Returning a string to refer to this exception.
const char* ParseException::what() const throw() {
return ("Failed to parse a " + this->type + " piece of JSON.").c_str();
}
//// Trying to specifically parse out a JSON object.
//JValue parseJSONObject(ParseStream& ps) throw(ParseException) {
//throw ParseException("JObject");
//}
//// Trying to specifically parse out a JSON array.
//JValue parseJSONArray(ParseStream& ps) throw(ParseException) {
//if (str[0] == '[' && str[str.size() - 1] == ']') {
//std::string useStr = str.substr(1, str.size() - 2);
//if (useStr.compare("") == 0)
//return JValue();
//std::vector<JValue> jValues;
//std::tuple<std::string, std::string> tup;
//for (tup = untilChar(useStr, ','); std::get<0>(tup).compare("") != 0; tup = untilChar(std::get<1>(tup), ','))
//jValues.push_back(parseJSON(stripWhitespace(std::get<0>(tup))));
//return JValue(jValues);
//}
//throw ParseException("parseJSONArray");
//}
// Trying to specifically parse out a JSON array.
JValue parseJSONArray(ParseStream& ps) throw(ParseException) {
consumeWhitespace(ps);
if (ps.consume() == '[') {
std::vector<JValue> values;
while (true) {
consumeWhitespace(ps);
values.push_back(parseJSON(ps));
consumeWhitespace(ps);
char c = ps.consume();
if (c == ']')
break;
else if (c != ',')
throw ParseException("parseJSONArray");
}
return JValue(values);
}
throw ParseException("parseJSONArray");
}
// Trying to specifically parse out a JSON number.
JValue parseJSONNumber(ParseStream& ps) throw(ParseException) {
consumeWhitespace(ps);
std::string str;
bool first = true;
while (!ps.eof() && !isDelimiter(ps.peek())) {
char c = ps.consume();
if (first && c == '-') {
str.push_back(c);
first = false;
} else if (('0' <= c && c <= '9') || c == '.')
str.push_back(c);
else
throw ParseException("parseJSONNumber");
}
return JValue(stod(str));
}
// Trying to specifically parse out a JSON string.
JValue parseJSONString(ParseStream& ps) throw(ParseException) {
consumeWhitespace(ps);
if (ps.peek() == '"') {
ps.consume();
std::string str;
while (ps.peek() != '"') {
char c = ps.consume();
if (c == '\n')
throw ParseException("parseJSONString");
if (c == '\\') {
char c2 = ps.consume();
switch (c2) {
case '"':
str.push_back('"');
break;
case '\\':
str.push_back('\\');
break;
case '/':
str.push_back('/');
case 'b':
str.push_back('\b');
break;
case 'f':
str.push_back('\f');
break;
case 't':
str.push_back('\t');
break;
case 'r':
str.push_back('\r');
break;
case 'n':
str.push_back('\n');
break;
default:
throw ParseException("parseJSONString");
break;
}
} else
str.push_back(c);
}
ps.consume();
return JValue(str);
}
throw ParseException("parseJSONString");
}
// Trying to specifically parse out a JSON boolean.
JValue parseJSONBool(ParseStream& ps) throw(ParseException) {
consumeWhitespace(ps);
std::string str;
while (!ps.eof() && !isDelimiter(ps.peek()))
str.push_back(ps.consume());
if (str.compare("true") == 0)
return JValue(true);
else if (str.compare("false") == 0)
return JValue(false);
throw ParseException("JSONBool");
}
// Trying to specifically parse out the null JSON value.
JValue parseJSONNull(ParseStream& ps) throw(ParseException) {
consumeWhitespace(ps);
std::string str;
while (!ps.eof() && !isDelimiter(ps.peek()))
str.push_back(ps.consume());
if (str.compare("null") == 0)
return JValue();
throw ParseException("parseJSONNull");
}
// Attempting to perform a parse - and then backing up on an error.
JValue attemptParse(ParseStream& ps, JValue (*parseFn)(ParseStream&)) throw(ParseException) {
int sl = ps.getLoc();
try { return parseFn(ps); }
catch (const ParseException& e) {
ps.back(ps.getLoc() - sl);
throw e;
}
}
// Parsing out a block of JSON from a ParseStream.
JValue parseJSON(ParseStream& ps) throw(ParseException) {
std::vector<JValue (*)(ParseStream&)> fns;
fns.push_back(&parseJSONArray);
fns.push_back(&parseJSONNumber);
fns.push_back(&parseJSONString);
fns.push_back(&parseJSONBool);
fns.push_back(&parseJSONNull);
for (auto it = fns.begin(); it != fns.end(); it++) {
try { return attemptParse(ps, *it); }
catch (const ParseException& e) { }
}
throw ParseException("parseJSON");
}
// Parsing out a block of JSON from a string.
JValue parseJSON(const std::string& str) throw(ParseException) {
ParseStream ps(str);
return parseJSON(ps);
}
// Parsing out a block of JSON from an istream.
JValue parseJSON(std::istream& stream) throw(ParseException) {
std::string line, all;
while (!stream.eof()) {
std::getline(stream, line);
all += line;
}
return parseJSON(all);
}
<commit_msg>Removed the old parseJSONArray function.<commit_after>#include "parser.hpp"
//////////////
// Includes //
#include <istream>
#include <string>
#include <vector>
#include <tuple>
#include "parsestream.hpp"
#include "streamutils.hpp"
#include "json.hpp"
//////////
// Code //
// Creating a parse exception.
ParseException::ParseException(std::string type) {
this->type = type;
}
// Returning a string to refer to this exception.
const char* ParseException::what() const throw() {
return ("Failed to parse a " + this->type + " piece of JSON.").c_str();
}
// Trying to specifically parse out a JSON object.
JValue parseJSONObject(ParseStream& ps) throw(ParseException) {
throw ParseException("JObject");
}
// Trying to specifically parse out a JSON array.
JValue parseJSONArray(ParseStream& ps) throw(ParseException) {
consumeWhitespace(ps);
if (ps.consume() == '[') {
std::vector<JValue> values;
while (true) {
consumeWhitespace(ps);
values.push_back(parseJSON(ps));
consumeWhitespace(ps);
char c = ps.consume();
if (c == ']')
break;
else if (c != ',')
throw ParseException("parseJSONArray");
}
return JValue(values);
}
throw ParseException("parseJSONArray");
}
// Trying to specifically parse out a JSON number.
JValue parseJSONNumber(ParseStream& ps) throw(ParseException) {
consumeWhitespace(ps);
std::string str;
bool first = true;
while (!ps.eof() && !isDelimiter(ps.peek())) {
char c = ps.consume();
if (first && c == '-') {
str.push_back(c);
first = false;
} else if (('0' <= c && c <= '9') || c == '.')
str.push_back(c);
else
throw ParseException("parseJSONNumber");
}
return JValue(stod(str));
}
// Trying to specifically parse out a JSON string.
JValue parseJSONString(ParseStream& ps) throw(ParseException) {
consumeWhitespace(ps);
if (ps.peek() == '"') {
ps.consume();
std::string str;
while (ps.peek() != '"') {
char c = ps.consume();
if (c == '\n')
throw ParseException("parseJSONString");
if (c == '\\') {
char c2 = ps.consume();
switch (c2) {
case '"':
str.push_back('"');
break;
case '\\':
str.push_back('\\');
break;
case '/':
str.push_back('/');
case 'b':
str.push_back('\b');
break;
case 'f':
str.push_back('\f');
break;
case 't':
str.push_back('\t');
break;
case 'r':
str.push_back('\r');
break;
case 'n':
str.push_back('\n');
break;
default:
throw ParseException("parseJSONString");
break;
}
} else
str.push_back(c);
}
ps.consume();
return JValue(str);
}
throw ParseException("parseJSONString");
}
// Trying to specifically parse out a JSON boolean.
JValue parseJSONBool(ParseStream& ps) throw(ParseException) {
consumeWhitespace(ps);
std::string str;
while (!ps.eof() && !isDelimiter(ps.peek()))
str.push_back(ps.consume());
if (str.compare("true") == 0)
return JValue(true);
else if (str.compare("false") == 0)
return JValue(false);
throw ParseException("JSONBool");
}
// Trying to specifically parse out the null JSON value.
JValue parseJSONNull(ParseStream& ps) throw(ParseException) {
consumeWhitespace(ps);
std::string str;
while (!ps.eof() && !isDelimiter(ps.peek()))
str.push_back(ps.consume());
if (str.compare("null") == 0)
return JValue();
throw ParseException("parseJSONNull");
}
// Attempting to perform a parse - and then backing up on an error.
JValue attemptParse(ParseStream& ps, JValue (*parseFn)(ParseStream&)) throw(ParseException) {
int sl = ps.getLoc();
try { return parseFn(ps); }
catch (const ParseException& e) {
ps.back(ps.getLoc() - sl);
throw e;
}
}
// Parsing out a block of JSON from a ParseStream.
JValue parseJSON(ParseStream& ps) throw(ParseException) {
std::vector<JValue (*)(ParseStream&)> fns;
fns.push_back(&parseJSONObject);
fns.push_back(&parseJSONArray);
fns.push_back(&parseJSONNumber);
fns.push_back(&parseJSONString);
fns.push_back(&parseJSONBool);
fns.push_back(&parseJSONNull);
for (auto it = fns.begin(); it != fns.end(); it++) {
try { return attemptParse(ps, *it); }
catch (const ParseException& e) { }
}
throw ParseException("parseJSON");
}
// Parsing out a block of JSON from a string.
JValue parseJSON(const std::string& str) throw(ParseException) {
ParseStream ps(str);
return parseJSON(ps);
}
// Parsing out a block of JSON from an istream.
JValue parseJSON(std::istream& stream) throw(ParseException) {
std::string line, all;
while (!stream.eof()) {
std::getline(stream, line);
all += line;
}
return parseJSON(all);
}
<|endoftext|>
|
<commit_before>/******************************
** Tsunagari Tile Engine **
** player.cpp **
** Copyright 2011 OmegaSDG **
******************************/
#include <Gosu/Audio.hpp>
#include <Gosu/Input.hpp>
#include "area.h"
#include "entity.h"
#include "player.h"
#include "world.h"
#include "window.h"
Player::Player(Resourcer* rc, Area* area)
: Entity(rc, area)
{
}
void Player::moveByTile(coord_t delta)
{
bool changed = false;
// TODO: use double array of directions
// would make diagonals easier to handle
if (delta.x > 0) {
setPhase("right");
changed = true;
}
else if (delta.x < 0) {
setPhase("left");
changed = true;
}
else if (delta.y > 0) {
setPhase("down");
changed = true;
}
else if (delta.y < 0) {
setPhase("up");
changed = true;
}
// Redraw the player if we change graphics.
if (changed)
redraw = true;
// Left CTRL allows changing facing, but disallows movement.
GameWindow* w = GameWindow::getWindow();
if (w->input().down(Gosu::kbLeftControl))
return;
// Try to actually move.
coord_t newCoord = getCoordsByTile();
newCoord.x += delta.x;
newCoord.y += delta.y;
newCoord.z += delta.z;
Area::Tile* dest = area->getTile(newCoord);
if ((dest->flags & Area::player_nowalk) != 0 ||
(dest->type->flags & Area::player_nowalk) != 0) {
// The tile we're trying to move onto is set as player_nowalk.
// Stop here.
return;
}
Entity::moveByTile(delta);
}
void Player::postMove()
{
SampleRef step_sound = getSound("step");
if (step_sound)
step_sound->play(1, 1, 0);
coord_t coord = getCoordsByTile();
Area::Tile* dest = area->getTile(coord);
Area::Door* door = dest->door;
if (door)
World::getWorld()->loadArea(door->area, door->coord);
}
<commit_msg>change access to door, realizing its a scoped_ptr<commit_after>/******************************
** Tsunagari Tile Engine **
** player.cpp **
** Copyright 2011 OmegaSDG **
******************************/
#include <Gosu/Audio.hpp>
#include <Gosu/Input.hpp>
#include "area.h"
#include "entity.h"
#include "player.h"
#include "world.h"
#include "window.h"
Player::Player(Resourcer* rc, Area* area)
: Entity(rc, area)
{
}
void Player::moveByTile(coord_t delta)
{
bool changed = false;
// TODO: use double array of directions
// would make diagonals easier to handle
if (delta.x > 0) {
setPhase("right");
changed = true;
}
else if (delta.x < 0) {
setPhase("left");
changed = true;
}
else if (delta.y > 0) {
setPhase("down");
changed = true;
}
else if (delta.y < 0) {
setPhase("up");
changed = true;
}
// Redraw the player if we change graphics.
if (changed)
redraw = true;
// Left CTRL allows changing facing, but disallows movement.
GameWindow* w = GameWindow::getWindow();
if (w->input().down(Gosu::kbLeftControl))
return;
// Try to actually move.
coord_t newCoord = getCoordsByTile();
newCoord.x += delta.x;
newCoord.y += delta.y;
newCoord.z += delta.z;
Area::Tile* dest = area->getTile(newCoord);
if ((dest->flags & Area::player_nowalk) != 0 ||
(dest->type->flags & Area::player_nowalk) != 0) {
// The tile we're trying to move onto is set as player_nowalk.
// Stop here.
return;
}
Entity::moveByTile(delta);
}
void Player::postMove()
{
SampleRef step_sound = getSound("step");
if (step_sound)
step_sound->play(1, 1, 0);
coord_t coord = getCoordsByTile();
Area::Tile* dest = area->getTile(coord);
Area::Door* door = dest->door.get();
if (door)
World::getWorld()->loadArea(door->area, door->coord);
}
<|endoftext|>
|
<commit_before>#include "player.h"
Player::Player()
{
}
Player::Player(Level* lev)
{
moveVector = sf::Vector2f(0,0);
position = lev->getPlayerStart();
// std::cout << "pos: " << position.x << "," << position.y << "\n";
// initPlayer();
movementSpeed = 8;
level = lev;
collectedScrews = 0;
// orientation = DIRECTION_LEFT;
// s = SoundHandler::getSoundHandler();
// shooting = false;
// reload_time = 40;
// shoot_threshold = 0;
// leben = 100.0f;
roboto_bold.loadFromFile("assets/Roboto-Bold.ttf");
tex_player.loadFromFile("assets/robot_ani.png");
ani = new Animation();
ani->setSpriteSheet(tex_player);
ani->addFrame(sf::IntRect(0, 0, 80, 80));
ani->addFrame(sf::IntRect(80, 0, 80, 80));
animatedSprite = new AnimatedSprite(sf::seconds(0.2), true, false);
}
void Player::move()
{
sf::Vector2f mV = moveVector*movementSpeed;
//std::cout << "move\n" << mV.x << " " <<mV.y<<"\n";
// Bounding box of the player(after the move)
sf::FloatRect* player_box = new sf::FloatRect(position + mV,sf::Vector2f(ROBOTSIZE,ROBOTSIZE));
//check if hit exit
if(level->isExit(position + mV,player_box))
{
resetLevel(new Level(level->getNextLevel()));
std::cout << "Exit\n";
}
//check for wall Collisions
mV = level->wallCollision(position,player_box,mV);
// Update the player location
sf::Vector2f new_location(position + mV);
//std::cout << "pos: " << position.x << "," << position.y << "\n";
//std::cout << "move\n" << mV.x << " " <<mV.y<<"\n";
// Check if new position is inside the game area
if(new_location.x >= 0
&& new_location.x + ROBOTSIZE <= level->getBounds().x
&& new_location.y >= 0
&& new_location.y + ROBOTSIZE <= level->getBounds().y)
{
// std::cout<< collision << "\n";
position = new_location; // Update location
}
collectedScrews += level->screwCollision(position,player_box);
animatedSprite->update(sf::seconds(0.02));
animatedSprite->setPosition(position);
}
void Player::setMovementDirection(int direction)
{
switch(direction)
{
case DIRECTION_LEFT:
moveVector = sf::Vector2f(-1,0);
break;
case DIRECTION_LEFT_UP:
moveVector = sf::Vector2f(-1,-1);
break;
case DIRECTION_LEFT_DOWN:
moveVector = sf::Vector2f(-1,1);
break;
case DIRECTION_RIGHT:
moveVector = sf::Vector2f(1,0);
break;
case DIRECTION_RIGHT_UP:
moveVector = sf::Vector2f(1,-1);
break;
case DIRECTION_RIGHT_DOWN:
moveVector = sf::Vector2f(1,1);
break;
case DIRECTION_UP:
moveVector = sf::Vector2f(0,-1);
break;
case DIRECTION_DOWN:
moveVector = sf::Vector2f(0,1);
break;
default:
//moveVector = sf::Vector2f(0,0);
break;
}
}
sf::Vector2f Player::getPosition()
{
return position;
}
void Player::onDeath()
{
}
void Player::resetLevel(Level* level)
{
*this->level = *level;
position = level->getPlayerStart();
}
void Player::draw(sf::RenderTarget& target,sf::RenderStates states)const
{
/*sf::Sprite sprite_playeVr;
sprite_player.setTexture(tex_player);
sprite_player.setPosition(position);
target.draw(sprite_player);*/
sf::Time t = sf::seconds(0.2);
animatedSprite->play(*ani);
target.draw(*animatedSprite);
//draw stats
std::stringstream str;
str << collectedScrews << " Schrauben gesammelt\n";
sf::Text stats;
stats.setFont(roboto_bold);
stats.setString(str.str());
stats.setCharacterSize(30);
stats.setPosition(position - sf::Vector2f(600,350));
target.draw(stats);
}
<commit_msg>bugfix<commit_after>#include "player.h"
Player::Player()
{
}
Player::Player(Level* lev)
{
moveVector = sf::Vector2f(0,0);
position = lev->getPlayerStart();
// std::cout << "pos: " << position.x << "," << position.y << "\n";
// initPlayer();
movementSpeed = 8;
level = lev;
collectedScrews = 0;
// orientation = DIRECTION_LEFT;
// s = SoundHandler::getSoundHandler();
// shooting = false;
// reload_time = 40;
// shoot_threshold = 0;
// leben = 100.0f;
roboto_bold.loadFromFile("assets/Roboto-Bold.ttf");
tex_player.loadFromFile("assets/robot_ani.png");
ani = new Animation();
ani->setSpriteSheet(tex_player);
ani->addFrame(sf::IntRect(0, 0, 80, 80));
ani->addFrame(sf::IntRect(80, 0, 80, 80));
animatedSprite = new AnimatedSprite(sf::seconds(0.2), true, false);
}
void Player::move()
{
sf::Vector2f mV = moveVector*movementSpeed;
//std::cout << "move\n" << mV.x << " " <<mV.y<<"\n";
// Bounding box of the player(after the move)
sf::FloatRect* player_box = new sf::FloatRect(position + mV,sf::Vector2f(ROBOTSIZE,ROBOTSIZE));
//check if hit exit
if(level->isExit(position + mV,player_box))
{
resetLevel(new Level(level->getNextLevel()));
std::cout << "Exit\n";
}
//check for wall Collisions
mV = level->wallCollision(position,player_box,mV);
// Update the player location
sf::Vector2f new_location(position + mV);
//std::cout << "pos: " << position.x << "," << position.y << "\n";
//std::cout << "move\n" << mV.x << " " <<mV.y<<"\n";
// Check if new position is inside the game area
if(new_location.x >= 0
&& new_location.x + ROBOTSIZE <= level->getBounds().x
&& new_location.y >= 0
&& new_location.y + ROBOTSIZE <= level->getBounds().y)
{
// std::cout<< collision << "\n";
position = new_location; // Update location
}
collectedScrews += level->screwCollision(position,player_box);
animatedSprite->update(sf::seconds(0.02));
animatedSprite->setPosition(position);
}
void Player::setMovementDirection(int direction)
{
switch(direction)
{
case DIRECTION_LEFT:
moveVector = sf::Vector2f(-1,0);
break;
case DIRECTION_LEFT_UP:
moveVector = sf::Vector2f(-1,-1);
break;
case DIRECTION_LEFT_DOWN:
moveVector = sf::Vector2f(-1,1);
break;
case DIRECTION_RIGHT:
moveVector = sf::Vector2f(1,0);
break;
case DIRECTION_RIGHT_UP:
moveVector = sf::Vector2f(1,-1);
break;
case DIRECTION_RIGHT_DOWN:
moveVector = sf::Vector2f(1,1);
break;
case DIRECTION_UP:
moveVector = sf::Vector2f(0,-1);
break;
case DIRECTION_DOWN:
moveVector = sf::Vector2f(0,1);
break;
default:
moveVector = sf::Vector2f(0,0);
break;
}
}
sf::Vector2f Player::getPosition()
{
return position;
}
void Player::onDeath()
{
}
void Player::resetLevel(Level* level)
{
*this->level = *level;
position = level->getPlayerStart();
}
void Player::draw(sf::RenderTarget& target,sf::RenderStates states)const
{
/*sf::Sprite sprite_playeVr;
sprite_player.setTexture(tex_player);
sprite_player.setPosition(position);
target.draw(sprite_player);*/
sf::Time t = sf::seconds(0.2);
animatedSprite->play(*ani);
target.draw(*animatedSprite);
//draw stats
std::stringstream str;
str << collectedScrews << " Schrauben gesammelt\n";
sf::Text stats;
stats.setFont(roboto_bold);
stats.setString(str.str());
stats.setCharacterSize(30);
stats.setPosition(position - sf::Vector2f(600,350));
target.draw(stats);
}
<|endoftext|>
|
<commit_before>// Copyright (c) 2011-2015 Zeex
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
// 2. Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
#include <functional>
#include <sstream>
#include <string>
#include <subhook.h>
#ifdef _WIN32
#include <windows.h>
#else
#include <stdio.h>
#endif
#include "amxerror.h"
#include "amxpathfinder.h"
#include "crashdetecthandler.h"
#include "fileutils.h"
#include "logprintf.h"
#include "natives.h"
#include "os.h"
#include "plugincommon.h"
#include "pluginversion.h"
#include "stringutils.h"
namespace {
subhook::Hook amx_exec_hook;
// Path to the last loaded AMX file. This is used to make a connection between
// *.amx files and their corresponding AMX instances.
std::string last_amx_path;
// Stores paths to loaded AMX files and is able to find a path by a pointer to
// an AMX instance.
AMXPathFinder amx_path_finder;
#ifdef _WIN32
subhook::Hook create_file_hook;
HANDLE
WINAPI
CreateFileHookA(
_In_ LPCSTR lpFileName,
_In_ DWORD dwDesiredAccess,
_In_ DWORD dwShareMode,
_In_opt_ LPSECURITY_ATTRIBUTES lpSecurityAttributes,
_In_ DWORD dwCreationDisposition,
_In_ DWORD dwFlagsAndAttributes,
_In_opt_ HANDLE hTemplateFile)
{
subhook::ScopedHookRemove _(&create_file_hook);
std::string file_ext(fileutils::GetExtenstion(lpFileName));
if (stringutils::ToLower(file_ext) == "amx") {
last_amx_path = lpFileName;
}
return CreateFileA(
lpFileName,
dwDesiredAccess,
dwShareMode,
lpSecurityAttributes,
dwCreationDisposition,
dwFlagsAndAttributes,
hTemplateFile);
}
#else
subhook::Hook fopen_hook;
FILE *FopenHook(const char *filename, const char *mode) {
subhook::ScopedHookRemove _(&fopen_hook);
std::string file_ext(fileutils::GetExtenstion(filename));
if (stringutils::ToLower(file_ext) == "amx") {
last_amx_path = filename;
}
return fopen(filename, mode);
}
#endif
int AMXAPI AmxDebug(AMX *amx) {
return CrashDetectHandler::GetHandler(amx)->HandleAMXDebug();
}
int AMXAPI AmxCallback(AMX *amx, cell index, cell *result, cell *params) {
CrashDetectHandler *handler = CrashDetectHandler::GetHandler(amx);
return handler->HandleAMXCallback(index, result, params);
}
int AMXAPI AmxExec(AMX *amx, cell *retval, int index) {
if (amx->flags & AMX_FLAG_BROWSE) {
return amx_Exec(amx, retval, index);
}
return CrashDetectHandler::GetHandler(amx)->HandleAMXExec(retval, index);
}
void AMXAPI AmxExecError(AMX *amx, cell index, cell *retval, int error) {
CrashDetectHandler *handler = CrashDetectHandler::GetHandler(amx);
handler->HandleAMXExecError(index, retval, error);
}
} // anonymous namespace
PLUGIN_EXPORT unsigned int PLUGIN_CALL Supports() {
return SUPPORTS_VERSION | SUPPORTS_AMX_NATIVES;
}
PLUGIN_EXPORT bool PLUGIN_CALL Load(void **ppData) {
void **exports = reinterpret_cast<void**>(ppData[PLUGIN_DATA_AMX_EXPORTS]);
::logprintf = (logprintf_t)ppData[PLUGIN_DATA_LOGPRINTF];
void *amx_Exec_ptr = exports[PLUGIN_AMX_EXPORT_Exec];
void *amx_Exec_sub = subhook::Hook::ReadDst(amx_Exec_ptr);
if (amx_Exec_sub == 0) {
amx_exec_hook.Install(amx_Exec_ptr, (void*)AmxExec);
} else {
std::string module =
fileutils::GetFileName(os::GetModuleName(amx_Exec_sub));
if (!module.empty()) {
logprintf(" CrashDetect must be loaded before '%s'", module.c_str());
}
return false;
}
#if _WIN32
create_file_hook.Install((void*)CreateFileA, (void*)CreateFileHookA);
#else
fopen_hook.Install((void*)fopen, (void*)FopenHook);
#endif
amx_path_finder.AddSearchPath("gamemodes");
amx_path_finder.AddSearchPath("filterscripts");
const char *amx_path_var = getenv("AMX_PATH");
if (amx_path_var != 0) {
stringutils::SplitString(
amx_path_var,
fileutils::kNativePathListSepChar,
std::bind1st(std::mem_fun(&AMXPathFinder::AddSearchPath),
&amx_path_finder));
}
os::SetCrashHandler(CrashDetectHandler::OnCrash);
os::SetInterruptHandler(CrashDetectHandler::OnInterrupt);
logprintf(" CrashDetect plugin " PROJECT_VERSION_STRING);
return true;
}
PLUGIN_EXPORT int PLUGIN_CALL AmxLoad(AMX *amx) {
if (last_amx_path.length() != 0) {
amx_path_finder.AddKnownFile(amx, last_amx_path);
}
CrashDetectHandler *handler = CrashDetectHandler::CreateHandler(amx);
handler->set_amx_path_finder(&amx_path_finder);
handler->Load();
amx_SetDebugHook(amx, AmxDebug);
amx_SetCallback(amx, AmxCallback);
amx_SetExecErrorHandler(amx, AmxExecError);
RegisterNatives(amx);
return AMX_ERR_NONE;
}
PLUGIN_EXPORT int PLUGIN_CALL AmxUnload(AMX *amx) {
CrashDetectHandler::GetHandler(amx)->Unload();
CrashDetectHandler::DestroyHandler(amx);
return AMX_ERR_NONE;
}
<commit_msg>Add null handler check in amx_Exec() hook<commit_after>// Copyright (c) 2011-2015 Zeex
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
// 2. Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
#include <functional>
#include <sstream>
#include <string>
#include <subhook.h>
#ifdef _WIN32
#include <windows.h>
#else
#include <stdio.h>
#endif
#include "amxerror.h"
#include "amxpathfinder.h"
#include "crashdetecthandler.h"
#include "fileutils.h"
#include "logprintf.h"
#include "natives.h"
#include "os.h"
#include "plugincommon.h"
#include "pluginversion.h"
#include "stringutils.h"
namespace {
subhook::Hook amx_exec_hook;
// Path to the last loaded AMX file. This is used to make a connection between
// *.amx files and their corresponding AMX instances.
std::string last_amx_path;
// Stores paths to loaded AMX files and is able to find a path by a pointer to
// an AMX instance.
AMXPathFinder amx_path_finder;
#ifdef _WIN32
subhook::Hook create_file_hook;
HANDLE
WINAPI
CreateFileHookA(
_In_ LPCSTR lpFileName,
_In_ DWORD dwDesiredAccess,
_In_ DWORD dwShareMode,
_In_opt_ LPSECURITY_ATTRIBUTES lpSecurityAttributes,
_In_ DWORD dwCreationDisposition,
_In_ DWORD dwFlagsAndAttributes,
_In_opt_ HANDLE hTemplateFile)
{
subhook::ScopedHookRemove _(&create_file_hook);
std::string file_ext(fileutils::GetExtenstion(lpFileName));
if (stringutils::ToLower(file_ext) == "amx") {
last_amx_path = lpFileName;
}
return CreateFileA(
lpFileName,
dwDesiredAccess,
dwShareMode,
lpSecurityAttributes,
dwCreationDisposition,
dwFlagsAndAttributes,
hTemplateFile);
}
#else
subhook::Hook fopen_hook;
FILE *FopenHook(const char *filename, const char *mode) {
subhook::ScopedHookRemove _(&fopen_hook);
std::string file_ext(fileutils::GetExtenstion(filename));
if (stringutils::ToLower(file_ext) == "amx") {
last_amx_path = filename;
}
return fopen(filename, mode);
}
#endif
int AMXAPI AmxDebug(AMX *amx) {
return CrashDetectHandler::GetHandler(amx)->HandleAMXDebug();
}
int AMXAPI AmxCallback(AMX *amx, cell index, cell *result, cell *params) {
CrashDetectHandler *handler = CrashDetectHandler::GetHandler(amx);
return handler->HandleAMXCallback(index, result, params);
}
int AMXAPI AmxExec(AMX *amx, cell *retval, int index) {
if (amx->flags & AMX_FLAG_BROWSE) {
return amx_Exec(amx, retval, index);
}
CrashDetectHandler *handler = CrashDetectHandler::GetHandler(amx);
if (handler == 0) {
return amx_Exec(amx, retval, index);
}
return handler->HandleAMXExec(retval, index);
}
void AMXAPI AmxExecError(AMX *amx, cell index, cell *retval, int error) {
CrashDetectHandler *handler = CrashDetectHandler::GetHandler(amx);
handler->HandleAMXExecError(index, retval, error);
}
} // anonymous namespace
PLUGIN_EXPORT unsigned int PLUGIN_CALL Supports() {
return SUPPORTS_VERSION | SUPPORTS_AMX_NATIVES;
}
PLUGIN_EXPORT bool PLUGIN_CALL Load(void **ppData) {
void **exports = reinterpret_cast<void**>(ppData[PLUGIN_DATA_AMX_EXPORTS]);
::logprintf = (logprintf_t)ppData[PLUGIN_DATA_LOGPRINTF];
void *amx_Exec_ptr = exports[PLUGIN_AMX_EXPORT_Exec];
void *amx_Exec_sub = subhook::Hook::ReadDst(amx_Exec_ptr);
if (amx_Exec_sub == 0) {
amx_exec_hook.Install(amx_Exec_ptr, (void*)AmxExec);
} else {
std::string module =
fileutils::GetFileName(os::GetModuleName(amx_Exec_sub));
if (!module.empty()) {
logprintf(" CrashDetect must be loaded before '%s'", module.c_str());
}
return false;
}
#if _WIN32
create_file_hook.Install((void*)CreateFileA, (void*)CreateFileHookA);
#else
fopen_hook.Install((void*)fopen, (void*)FopenHook);
#endif
amx_path_finder.AddSearchPath("gamemodes");
amx_path_finder.AddSearchPath("filterscripts");
const char *amx_path_var = getenv("AMX_PATH");
if (amx_path_var != 0) {
stringutils::SplitString(
amx_path_var,
fileutils::kNativePathListSepChar,
std::bind1st(std::mem_fun(&AMXPathFinder::AddSearchPath),
&amx_path_finder));
}
os::SetCrashHandler(CrashDetectHandler::OnCrash);
os::SetInterruptHandler(CrashDetectHandler::OnInterrupt);
logprintf(" CrashDetect plugin " PROJECT_VERSION_STRING);
return true;
}
PLUGIN_EXPORT int PLUGIN_CALL AmxLoad(AMX *amx) {
if (last_amx_path.length() != 0) {
amx_path_finder.AddKnownFile(amx, last_amx_path);
}
CrashDetectHandler *handler = CrashDetectHandler::CreateHandler(amx);
handler->set_amx_path_finder(&amx_path_finder);
handler->Load();
amx_SetDebugHook(amx, AmxDebug);
amx_SetCallback(amx, AmxCallback);
amx_SetExecErrorHandler(amx, AmxExecError);
RegisterNatives(amx);
return AMX_ERR_NONE;
}
PLUGIN_EXPORT int PLUGIN_CALL AmxUnload(AMX *amx) {
CrashDetectHandler::GetHandler(amx)->Unload();
CrashDetectHandler::DestroyHandler(amx);
return AMX_ERR_NONE;
}
<|endoftext|>
|
<commit_before>#include <uv.h>
#include <windows.h>
#include <stdio.h>
#include <tchar.h>
#include <strsafe.h>
#include "pm.h"
#include "constants.h"
#define MAX_THREAD_WINDOW_NAME 64
HWND handle;
DWORD threadId;
HANDLE threadHandle;
HANDLE notifyEvent;
char *notify_msg;
bool isRunning = false;
DWORD WINAPI ListenerThread( LPVOID lpParam );
void NotifyAsync(uv_work_t* req);
void NotifyFinished(uv_work_t* req);
void NotifyAsync(uv_work_t* req)
{
WaitForSingleObject(notifyEvent, INFINITE);
}
void NotifyFinished(uv_work_t* req)
{
if (isRunning)
{
Notify(notify_msg);
}
uv_queue_work(uv_default_loop(), req, NotifyAsync, (uv_after_work_cb)NotifyFinished);
}
static long FAR PASCAL WindowProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
{
if(message == WM_POWERBROADCAST)
{
// printf("%d\n", wParam);
if (wParam == PBT_APMRESUMESUSPEND)
{
// printf("wake\n");
notify_msg = (char *)WAKE_NOTIFY;
SetEvent(notifyEvent);
}
if (wParam == PBT_APMRESUMEAUTOMATIC)
{
// printf("waking\n");
// strcpy(notify_msg, "waking");
// SetEvent(notifyEvent);
}
if (wParam == PBT_APMSUSPEND)
{
// printf("sleeping\n");
notify_msg = (char *)SLEEP_NOTIFY;
SetEvent(notifyEvent);
}
if (wParam == PBT_APMPOWERSTATUSCHANGE)
{
// printf("PBT_APMPOWERSTATUSCHANGE\n");
// SetEvent(notifyEvent);
}
//Do something
return TRUE;
}
else
return DefWindowProc(hWnd, message, wParam, lParam);
}
DWORD WINAPI ListenerThread( LPVOID lpParam )
{
char className[MAX_THREAD_WINDOW_NAME];
_snprintf(className, MAX_THREAD_WINDOW_NAME, "ListnerThreadPmNotify_%d", GetCurrentThreadId());
WNDCLASS wc = {0};
// Set up and register window class
wc.lpfnWndProc = (WNDPROC)WindowProc;
wc.lpszClassName = className;
RegisterClass(&wc);
HWND hWin = CreateWindow(className, className, 0, 0, 0, 0, 0, NULL, NULL, NULL, 0);
BOOL bRet;
MSG msg;
while( (bRet = GetMessage( &msg, hWin, 0, 0 )) != 0)
{
if (bRet == -1)
{
// handle the error and possibly exit
}
else
{
TranslateMessage(&msg);
DispatchMessage(&msg);
}
}
return 0;
}
void Start()
{
isRunning = true;
}
void Stop()
{
isRunning = false;
}
void InitPM()
{
notifyEvent = CreateEvent(NULL, false /* auto-reset event */, false /* non-signalled state */, "");
threadHandle = CreateThread(
NULL, // default security attributes
0, // use default stack size
ListenerThread, // thread function name
NULL, // argument to thread function
0, // use default creation flags
&threadId);
uv_work_t* req = new uv_work_t();
uv_queue_work(uv_default_loop(), req, NotifyAsync, (uv_after_work_cb)NotifyFinished);
Start();
}<commit_msg>Remove compiler warnings<commit_after>#include <uv.h>
#include <windows.h>
#include <stdio.h>
#include <tchar.h>
#include <strsafe.h>
#include "pm.h"
#include "constants.h"
#define MAX_THREAD_WINDOW_NAME 64
HWND handle;
DWORD threadId;
HANDLE threadHandle;
HANDLE notifyEvent;
char *notify_msg;
bool isRunning = false;
DWORD WINAPI ListenerThread( LPVOID lpParam );
void NotifyAsync(uv_work_t* req);
void NotifyFinished(uv_work_t* req);
void NotifyAsync(uv_work_t* req)
{
WaitForSingleObject(notifyEvent, INFINITE);
}
void NotifyFinished(uv_work_t* req)
{
if (isRunning)
{
Notify(notify_msg);
}
uv_queue_work(uv_default_loop(), req, NotifyAsync, (uv_after_work_cb)NotifyFinished);
}
static LRESULT FAR PASCAL WindowProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
{
if(message == WM_POWERBROADCAST)
{
// printf("%d\n", wParam);
if (wParam == PBT_APMRESUMESUSPEND)
{
// printf("wake\n");
notify_msg = (char *)WAKE_NOTIFY;
SetEvent(notifyEvent);
}
if (wParam == PBT_APMRESUMEAUTOMATIC)
{
// printf("waking\n");
// strcpy(notify_msg, "waking");
// SetEvent(notifyEvent);
}
if (wParam == PBT_APMSUSPEND)
{
// printf("sleeping\n");
notify_msg = (char *)SLEEP_NOTIFY;
SetEvent(notifyEvent);
}
if (wParam == PBT_APMPOWERSTATUSCHANGE)
{
// printf("PBT_APMPOWERSTATUSCHANGE\n");
// SetEvent(notifyEvent);
}
//Do something
return TRUE;
}
else
return DefWindowProc(hWnd, message, wParam, lParam);
}
DWORD WINAPI ListenerThread( LPVOID lpParam )
{
char className[MAX_THREAD_WINDOW_NAME];
_snprintf_s(className, MAX_THREAD_WINDOW_NAME, "ListnerThreadPmNotify_%d", GetCurrentThreadId());
WNDCLASS wc = {0};
// Set up and register window class
wc.lpfnWndProc = (WNDPROC)WindowProc;
wc.lpszClassName = className;
RegisterClass(&wc);
HWND hWin = CreateWindow(className, className, 0, 0, 0, 0, 0, NULL, NULL, NULL, 0);
BOOL bRet;
MSG msg;
while( (bRet = GetMessage( &msg, hWin, 0, 0 )) != 0)
{
if (bRet == -1)
{
// handle the error and possibly exit
}
else
{
TranslateMessage(&msg);
DispatchMessage(&msg);
}
}
return 0;
}
void Start()
{
isRunning = true;
}
void Stop()
{
isRunning = false;
}
void InitPM()
{
notifyEvent = CreateEvent(NULL, false /* auto-reset event */, false /* non-signalled state */, "");
threadHandle = CreateThread(
NULL, // default security attributes
0, // use default stack size
ListenerThread, // thread function name
NULL, // argument to thread function
0, // use default creation flags
&threadId);
uv_work_t* req = new uv_work_t();
uv_queue_work(uv_default_loop(), req, NotifyAsync, (uv_after_work_cb)NotifyFinished);
Start();
}<|endoftext|>
|
<commit_before>#include <bitcoin/poller.hpp>
#include <bitcoin/utility/logger.hpp>
namespace libbitcoin {
using std::placeholders::_1;
using std::placeholders::_2;
poller::poller(async_service& service, blockchain& chain)
: strand_(service.get_service()), chain_(chain)
{
}
void poller::query(channel_ptr node)
{
fetch_block_locator(chain_,
std::bind(&poller::initial_ask_blocks,
this, _1, _2, node));
}
void poller::monitor(channel_ptr node)
{
node->subscribe_inventory(
strand_.wrap(std::bind(&poller::receive_inv,
this, _1, _2, node)));
node->subscribe_block(
std::bind(&poller::receive_block,
this, _1, _2, node));
}
void poller::initial_ask_blocks(const std::error_code& ec,
const message::block_locator& locator, channel_ptr node)
{
if (ec)
{
log_error(log_domain::poller)
<< "Fetching initial block locator: " << ec.message();
return;
}
strand_.dispatch(std::bind(&poller::ask_blocks,
this, ec, locator, null_hash, node));
}
void handle_send_packet(const std::error_code& ec)
{
if (ec)
log_error(log_domain::poller)
<< "Send problem: " << ec.message();
}
void poller::receive_inv(const std::error_code& ec,
const message::inventory& packet, channel_ptr node)
{
if (ec)
{
log_error(log_domain::poller)
<< "Received bad inventory: " << ec.message();
return;
}
// Filter out only block inventories
message::get_data getdata;
for (const message::inventory_vector& ivv: packet.inventories)
{
if (ivv.type != message::inventory_type::block)
continue;
// Already got this block
if (ivv.hash == last_block_hash_)
continue;
getdata.inventories.push_back(ivv);
}
if (!getdata.inventories.empty())
{
last_block_hash_ = getdata.inventories.back().hash;
node->send(getdata, handle_send_packet);
}
node->subscribe_inventory(
strand_.wrap(std::bind(&poller::receive_inv,
this, _1, _2, node)));
}
void poller::receive_block(const std::error_code& ec,
const message::block& blk, channel_ptr node)
{
if (ec)
{
log_error(log_domain::poller)
<< "Received bad block: " << ec.message();
return;
}
chain_.store(blk,
std::bind(&poller::handle_store,
this, _1, _2, hash_block_header(blk), node));
node->subscribe_block(
std::bind(&poller::receive_block,
this, _1, _2, node));
}
void poller::handle_store(const std::error_code& ec, block_info info,
const hash_digest& block_hash, channel_ptr node)
{
// We need orphan blocks so we can do the next getblocks round
if (ec && info.status != block_status::orphan)
{
log_error(log_domain::poller)
<< "Storing block " << pretty_hex(block_hash)
<< ": " << ec.message();
return;
}
switch (info.status)
{
case block_status::orphan:
// TODO: Make more efficient by storing block hash
// and next time do not download orphan block again.
// Remember to remove from list once block is no longer orphan
fetch_block_locator(chain_,
strand_.wrap(std::bind(&poller::ask_blocks,
this, _1, _2, block_hash, node)));
break;
case block_status::rejected:
log_error(log_domain::poller)
<< "Rejected block " << pretty_hex(block_hash);
break;
case block_status::confirmed:
log_info(log_domain::poller)
<< "Block #" << info.depth << " " << pretty_hex(block_hash);
break;
}
}
void poller::ask_blocks(const std::error_code& ec,
const message::block_locator& locator,
const hash_digest& hash_stop, channel_ptr node)
{
if (ec)
{
log_error(log_domain::poller)
<< "Ask for blocks: " << ec.message();
return;
}
if (last_hash_end_ == locator.front())
{
log_debug(log_domain::poller) << "Skipping duplicate ask blocks: "
<< pretty_hex(locator.front());
return;
}
message::get_blocks packet;
packet.start_hashes = locator;
packet.hash_stop = hash_stop;
node->send(packet, std::bind(&handle_send_packet, _1));
last_hash_end_ = locator.front();
}
} // namespace libbitcoin
<commit_msg>unitialised variable.<commit_after>#include <bitcoin/poller.hpp>
#include <bitcoin/utility/logger.hpp>
namespace libbitcoin {
using std::placeholders::_1;
using std::placeholders::_2;
poller::poller(async_service& service, blockchain& chain)
: strand_(service.get_service()), chain_(chain), last_hash_end_(null_hash)
{
}
void poller::query(channel_ptr node)
{
fetch_block_locator(chain_,
std::bind(&poller::initial_ask_blocks,
this, _1, _2, node));
}
void poller::monitor(channel_ptr node)
{
node->subscribe_inventory(
strand_.wrap(std::bind(&poller::receive_inv,
this, _1, _2, node)));
node->subscribe_block(
std::bind(&poller::receive_block,
this, _1, _2, node));
}
void poller::initial_ask_blocks(const std::error_code& ec,
const message::block_locator& locator, channel_ptr node)
{
if (ec)
{
log_error(log_domain::poller)
<< "Fetching initial block locator: " << ec.message();
return;
}
strand_.dispatch(std::bind(&poller::ask_blocks,
this, ec, locator, null_hash, node));
}
void handle_send_packet(const std::error_code& ec)
{
if (ec)
log_error(log_domain::poller)
<< "Send problem: " << ec.message();
}
void poller::receive_inv(const std::error_code& ec,
const message::inventory& packet, channel_ptr node)
{
if (ec)
{
log_error(log_domain::poller)
<< "Received bad inventory: " << ec.message();
return;
}
// Filter out only block inventories
message::get_data getdata;
for (const message::inventory_vector& ivv: packet.inventories)
{
if (ivv.type != message::inventory_type::block)
continue;
// Already got this block
if (ivv.hash == last_block_hash_)
continue;
getdata.inventories.push_back(ivv);
}
if (!getdata.inventories.empty())
{
last_block_hash_ = getdata.inventories.back().hash;
node->send(getdata, handle_send_packet);
}
node->subscribe_inventory(
strand_.wrap(std::bind(&poller::receive_inv,
this, _1, _2, node)));
}
void poller::receive_block(const std::error_code& ec,
const message::block& blk, channel_ptr node)
{
if (ec)
{
log_error(log_domain::poller)
<< "Received bad block: " << ec.message();
return;
}
chain_.store(blk,
std::bind(&poller::handle_store,
this, _1, _2, hash_block_header(blk), node));
node->subscribe_block(
std::bind(&poller::receive_block,
this, _1, _2, node));
}
void poller::handle_store(const std::error_code& ec, block_info info,
const hash_digest& block_hash, channel_ptr node)
{
// We need orphan blocks so we can do the next getblocks round
if (ec && info.status != block_status::orphan)
{
log_error(log_domain::poller)
<< "Storing block " << pretty_hex(block_hash)
<< ": " << ec.message();
return;
}
switch (info.status)
{
case block_status::orphan:
// TODO: Make more efficient by storing block hash
// and next time do not download orphan block again.
// Remember to remove from list once block is no longer orphan
fetch_block_locator(chain_,
strand_.wrap(std::bind(&poller::ask_blocks,
this, _1, _2, block_hash, node)));
break;
case block_status::rejected:
log_error(log_domain::poller)
<< "Rejected block " << pretty_hex(block_hash);
break;
case block_status::confirmed:
log_info(log_domain::poller)
<< "Block #" << info.depth << " " << pretty_hex(block_hash);
break;
}
}
void poller::ask_blocks(const std::error_code& ec,
const message::block_locator& locator,
const hash_digest& hash_stop, channel_ptr node)
{
if (ec)
{
log_error(log_domain::poller)
<< "Ask for blocks: " << ec.message();
return;
}
if (last_hash_end_ == locator.front())
{
log_debug(log_domain::poller) << "Skipping duplicate ask blocks: "
<< pretty_hex(locator.front());
return;
}
message::get_blocks packet;
packet.start_hashes = locator;
packet.hash_stop = hash_stop;
node->send(packet, std::bind(&handle_send_packet, _1));
last_hash_end_ = locator.front();
}
} // namespace libbitcoin
<|endoftext|>
|
<commit_before>/* -*- Mode: C++; indent-tabs-mode: nil; c-basic-offset: 4; tab-width: 4 -*- */
#include <pybind11/pybind11.h>
#include <pybind11/stl.h>
#include <pybind11/functional.h>
#include <vector>
PYBIND11_DECLARE_HOLDER_TYPE(T, std::shared_ptr<T>)
#include "client.h"
using namespace echolib;
namespace py = pybind11;
typedef function<void(string)> MessageCallback;
class PySubscriber : public Subscriber, public std::enable_shared_from_this<PySubscriber> {
public:
PySubscriber(SharedClient client, const string &alias, const string &type, function<void(MessageReader)> callback) : Subscriber(client, alias, type), callback(callback) {
}
virtual void on_message(SharedMessage message) {
MessageReader reader(message);
py::gil_scoped_acquire gil; // acquire GIL lock
callback(reader);
}
private:
function<void(MessageReader)> callback;
};
class PyWatcher : public Watcher {
public:
using Watcher::Watcher;
virtual void on_event(SharedDictionary command) {
PYBIND11_OVERLOAD_PURE(
void,
Subscriber,
on_event,
command
);
}
};
PYBIND11_PLUGIN(pyecho) {
py::init_threading();
py::module m("pyecho", "Echo IPC library");
py::class_<Client, std::shared_ptr<Client> >(m, "Client")
.def(py::init<string>())
.def("disconnect", &Client::disconnect, "Disconnect the client")
.def("wait", [](Client& c, long timeout) {
py::gil_scoped_release gil; // release GIL lock
return c.wait(timeout);
}, "Wait for more messages")
.def("isConnected", &Client::is_connected, "Check if the client is connected");
py::class_<PySubscriber, std::shared_ptr<PySubscriber> >(m, "Subscriber")
.def(py::init<SharedClient, string, string, function<void(MessageReader)> >())
.def("subscribe", [](PySubscriber &a) {
py::gil_scoped_release gil; // release GIL lock
return a.subscribe();
}, "Start receiving")
.def("unsubscribe", [](PySubscriber &a) {
py::gil_scoped_release gil; // release GIL lock
return a.unsubscribe();
}, "Stop receiving");
py::class_<PyWatcher, std::shared_ptr<PyWatcher> >(m, "Watcher")
.def(py::init<SharedClient, string>())
.def("subscribe", [](PyWatcher &a) {
py::gil_scoped_release gil; // release GIL lock
return a.watch();
}, "Start receiving")
.def("unsubscribe", [](PyWatcher &a) {
py::gil_scoped_release gil; // release GIL lock
return a.unwatch();
}, "Stop watching");
py::class_<Publisher, std::shared_ptr<Publisher> >(m, "Publisher")
.def(py::init<SharedClient, string, string>())
.def("send", [](Publisher &p, uchar* data, int size) {
py::gil_scoped_release gil; // release GIL lock
return p.send_message(data, size);
} , "Send a raw buffer")
.def("send", [](Publisher &p, MessageWriter& message) {
py::gil_scoped_release gil; // release GIL lock
return p.send_message(message);
}, "Send a writer");
py::class_<BufferedMessage, std::shared_ptr<Message> >(m, "BufferedMessage")
.def(py::init<int, uchar*, int, bool>())
.def(py::init<int, MessageWriter>())
.def("getChannel", &BufferedMessage::get_channel, "Get channel");
py::class_<MessageReader>(m, "MessageReader")
.def("readInt", &MessageReader::read_integer, "Read an integer")
.def("readLong", &MessageReader::read_long, "Read a long")
.def("readChar", &MessageReader::read_char, "Read a char")
.def("readFloat", &MessageReader::read_float, "Read a float")
.def("readDouble", &MessageReader::read_double, "Read a double")
.def("readString", &MessageReader::read_string, "Read a string");
py::class_<MessageWriter>(m, "MessageWriter")
.def(py::init<ssize_t>(), py::arg("size") = 0)
.def("writeInt", &MessageWriter::write_integer, "Write an integer")
.def("writeLong", &MessageWriter::write_long, "Write a long")
.def("writeChar", &MessageWriter::write_char, "Write a char")
.def("writeFloat", &MessageWriter::write_float, "Write a float")
.def("writeDouble", &MessageWriter::write_double, "Write a double")
.def("writeString", &MessageWriter::write_string, "Write a string");
return m.ptr();
}
<commit_msg>Updating python bindings.<commit_after>/* -*- Mode: C++; indent-tabs-mode: nil; c-basic-offset: 4; tab-width: 4 -*- */
#define WITH_THREAD
#include <pybind11/pybind11.h>
#include <pybind11/stl.h>
#include <pybind11/functional.h>
#include <vector>
PYBIND11_DECLARE_HOLDER_TYPE(T, std::shared_ptr<T>)
#include "client.h"
using namespace echolib;
namespace py = pybind11;
typedef function<void(string)> MessageCallback;
class PySubscriber : public Subscriber, public std::enable_shared_from_this<PySubscriber> {
public:
PySubscriber(SharedClient client, const string &alias, const string &type, function<void(MessageReader)> callback) : Subscriber(client, alias, type), callback(callback) {
}
virtual void on_message(SharedMessage message) {
MessageReader reader(message);
py::gil_scoped_acquire gil; // acquire GIL lock
callback(reader);
}
using Subscriber::subscribe;
using Subscriber::unsubscribe;
private:
function<void(MessageReader)> callback;
};
class PyWatcher : public Watcher {
public:
using Watcher::Watcher;
void on_event(SharedDictionary command) override {
PYBIND11_OVERLOAD_PURE(
void,
Watcher,
on_event,
command
);
}
};
PYBIND11_PLUGIN(pyecho) {
py::module m("pyecho", "Echo IPC library Python bindings");
py::class_<Client, std::shared_ptr<Client> >(m, "Client")
.def(py::init<string>())
.def("disconnect", &Client::disconnect, "Disconnect the client")
.def("wait", [](Client& c, long timeout) {
py::gil_scoped_release gil; // release GIL lock
return c.wait(timeout);
}, "Wait for more messages")
.def("isConnected", &Client::is_connected, "Check if the client is connected");
py::class_<Subscriber, PySubscriber, std::shared_ptr<Subscriber> >(m, "Subscriber")
.def(py::init<SharedClient, string, string, function<void(MessageReader)> >())
.def("subscribe", [](PySubscriber &a) {
py::gil_scoped_release gil; // release GIL lock
return a.subscribe();
}, "Start receiving")
.def("unsubscribe", [](PySubscriber &a) {
py::gil_scoped_release gil; // release GIL lock
return a.unsubscribe();
}, "Stop receiving");
py::class_<Watcher, PyWatcher, std::shared_ptr<Watcher> >(m, "Watcher")
.def(py::init<SharedClient, string>())
.def("subscribe", [](PyWatcher &a) {
py::gil_scoped_release gil; // release GIL lock
return a.watch();
}, "Start receiving")
.def("unsubscribe", [](PyWatcher &a) {
py::gil_scoped_release gil; // release GIL lock
return a.unwatch();
}, "Stop watching");
py::class_<Publisher, std::shared_ptr<Publisher> >(m, "Publisher")
.def(py::init<SharedClient, string, string>())
.def("send", [](Publisher &p, uchar* data, int size) {
py::gil_scoped_release gil; // release GIL lock
return p.send_message(data, size);
} , "Send a raw buffer")
.def("send", [](Publisher &p, MessageWriter& message) {
py::gil_scoped_release gil; // release GIL lock
return p.send_message(message);
}, "Send a writer");
py::class_<BufferedMessage, std::shared_ptr<BufferedMessage> >(m, "BufferedMessage")
.def(py::init<int, uchar*, int, bool>())
.def(py::init<int, MessageWriter>())
.def("getChannel", &BufferedMessage::get_channel, "Get channel");
py::class_<MessageReader>(m, "MessageReader")
.def("readInt", &MessageReader::read_integer, "Read an integer")
.def("readLong", &MessageReader::read_long, "Read a long")
.def("readChar", &MessageReader::read_char, "Read a char")
.def("readFloat", &MessageReader::read_float, "Read a float")
.def("readDouble", &MessageReader::read_double, "Read a double")
.def("readString", &MessageReader::read_string, "Read a string");
py::class_<MessageWriter>(m, "MessageWriter")
.def(py::init<ssize_t>(), py::arg("size") = 0)
.def("writeInt", &MessageWriter::write_integer, "Write an integer")
.def("writeLong", &MessageWriter::write_long, "Write a long")
.def("writeChar", &MessageWriter::write_char, "Write a char")
.def("writeFloat", &MessageWriter::write_float, "Write a float")
.def("writeDouble", &MessageWriter::write_double, "Write a double")
.def("writeString", &MessageWriter::write_string, "Write a string");
return m.ptr();
}
<|endoftext|>
|
<commit_before>//
// This file is part of the Marble Virtual Globe.
//
// This program is free software licensed under the GNU LGPL. You can
// find a copy of this license in LICENSE.txt in the top directory of
// the source code.
//
// Copyright 2006-2007 Torsten Rahn <tackat@kde.org>
// Copyright 2007 Inge Wallin <ingwa@kde.org>
//
#include <QtGui/QApplication>
#include <QtCore/QFile>
#include <QtCore/QDir>
#include <QtCore/QLocale>
#include <QtCore/QSettings>
#include <QtCore/QTranslator>
#include "QtMainWindow.h"
#include "MarbleDirs.h"
#include "MarbleDebug.h"
#include "MarbleTest.h"
#ifdef STATIC_BUILD
#include <QtCore/QtPlugin>
Q_IMPORT_PLUGIN(qjpeg)
Q_IMPORT_PLUGIN(qsvg)
#endif
#ifdef Q_OS_MACX
//for getting app bundle path
#include <ApplicationServices/ApplicationServices.h>
#endif
using namespace Marble;
int main(int argc, char *argv[])
{
// The GraphicsSystem needs to be set before the instantiation of the
// QApplication. Therefore we need to parse the current setting
// in this unusual place :-/
QSettings * graphicsSettings = new QSettings("kde.org", "Marble Desktop Globe");
QString graphicsString = graphicsSettings->value("View/graphicsSystem", "native").toString();
delete graphicsSettings;
QApplication::setGraphicsSystem( graphicsString );
QApplication app(argc, argv);
// Widget translation
QString lang = QLocale::system().name().section('_', 0, 0);
QTranslator translator;
translator.load( "marble-" + lang, MarbleDirs::path(QString("lang") ) );
app.installTranslator(&translator);
// For non static builds on mac and win
// we need to be sure we can find the qt image
// plugins. In mac be sure to look in the
// application bundle...
#ifdef Q_WS_WIN
QApplication::addLibraryPath( QApplication::applicationDirPath()
+ QDir::separator() + "plugins" );
#endif
#ifdef Q_OS_MACX
QApplication::instance()->setAttribute(Qt::AA_DontShowIconsInMenus);
qDebug("Adding qt image plugins to plugin search path...");
CFURLRef myBundleRef = CFBundleCopyBundleURL(CFBundleGetMainBundle());
CFStringRef myMacPath = CFURLCopyFileSystemPath(myBundleRef, kCFURLPOSIXPathStyle);
const char *mypPathPtr = CFStringGetCStringPtr(myMacPath,CFStringGetSystemEncoding());
CFRelease(myBundleRef);
CFRelease(myMacPath);
QString myPath(mypPathPtr);
// if we are not in a bundle assume that the app is built
// as a non bundle app and that image plugins will be
// in system Qt frameworks. If the app is a bundle
// lets try to set the qt plugin search path...
if (myPath.contains(".app"))
{
myPath += "/Contents/plugins";
QApplication::addLibraryPath( myPath );
qDebug( "Added %s to plugin search path", qPrintable( myPath ) );
}
#endif
QString marbleDataPath;
int dataPathIndex=0;
MarbleGlobal::Profiles profiles = MarbleGlobal::detectProfiles();
QStringList args = QApplication::arguments();
for ( int i = 1; i < args.count(); ++i ) {
const QString arg = args.at(i);
if ( arg == "--debug-info" )
{
MarbleDebug::enable = true;
}
else if ( arg.startsWith( "--marbledatapath=", Qt::CaseInsensitive ) )
{
marbleDataPath = args.at(i).mid(17);
}
else if ( arg.compare( "--marbledatapath", Qt::CaseInsensitive ) == 0 ) {
dataPathIndex = i + 1;
marbleDataPath = args.value( dataPathIndex );
++i;
}
else if ( arg == "--smallscreen" ) {
profiles |= MarbleGlobal::SmallScreen;
}
else if ( arg == "--nosmallscreen" ) {
profiles &= ~MarbleGlobal::SmallScreen;
}
else if ( arg == "--highresolution" ) {
profiles |= MarbleGlobal::HighResolution;
}
else if ( arg == "--nohighresolution" ) {
profiles &= ~MarbleGlobal::HighResolution;
}
}
MarbleGlobal::getInstance()->setProfiles( profiles );
MainWindow *window = new MainWindow( marbleDataPath );
window->setAttribute( Qt::WA_DeleteOnClose, true );
MarbleTest *marbleTest = new MarbleTest( window->marbleWidget() );
// window->marbleWidget()->rotateTo( 0, 0, -90 );
// window->show();
for ( int i = 1; i < args.count(); ++i ) {
const QString arg = args.at(i);
if ( arg == "--timedemo" )
{
window->resize(900, 640);
marbleTest->timeDemo();
return 0;
}
else if( arg == "--gpsdemo" ) {
window->resize( 900, 640 );
marbleTest->gpsDemo();
return 0;
}
else if( arg == "--fps" ) {
window->marbleControl()->marbleWidget()->setShowFrameRate( true );
}
else if( arg == "--enableCurrentLocation" )
{
window->marbleControl()->setCurrentLocationTabShown(true);
}
else if( arg == "--enableFileView" )
{
window->marbleControl()->setFileViewTabShown(true);
}
else if ( arg == "--tile-id" )
{
window->marbleControl()->marbleWidget()->setShowTileId(true);
}
else if ( i != dataPathIndex && QFile::exists( arg ) )
( window->marbleControl() )->addGeoDataFile( arg );
}
delete marbleTest;
return app.exec();
}
<commit_msg>Initialize measurement system in the qt application. Fixes wrong distance unit being shown in the mapscale float item and the toolbar. Note that you need to remove a previous View/distanceUnit config entry for this to take effect.<commit_after>//
// This file is part of the Marble Virtual Globe.
//
// This program is free software licensed under the GNU LGPL. You can
// find a copy of this license in LICENSE.txt in the top directory of
// the source code.
//
// Copyright 2006-2007 Torsten Rahn <tackat@kde.org>
// Copyright 2007 Inge Wallin <ingwa@kde.org>
//
#include <QtGui/QApplication>
#include <QtCore/QFile>
#include <QtCore/QDir>
#include <QtCore/QLocale>
#include <QtCore/QSettings>
#include <QtCore/QTranslator>
#include "QtMainWindow.h"
#include "MarbleDirs.h"
#include "MarbleDebug.h"
#include "MarbleTest.h"
#include "MarbleLocale.h"
#ifdef STATIC_BUILD
#include <QtCore/QtPlugin>
Q_IMPORT_PLUGIN(qjpeg)
Q_IMPORT_PLUGIN(qsvg)
#endif
#ifdef Q_OS_MACX
//for getting app bundle path
#include <ApplicationServices/ApplicationServices.h>
#endif
using namespace Marble;
int main(int argc, char *argv[])
{
// The GraphicsSystem needs to be set before the instantiation of the
// QApplication. Therefore we need to parse the current setting
// in this unusual place :-/
QSettings * graphicsSettings = new QSettings("kde.org", "Marble Desktop Globe");
QString graphicsString = graphicsSettings->value("View/graphicsSystem", "native").toString();
delete graphicsSettings;
QApplication::setGraphicsSystem( graphicsString );
QApplication app(argc, argv);
// Widget translation
QString lang = QLocale::system().name().section('_', 0, 0);
QTranslator translator;
translator.load( "marble-" + lang, MarbleDirs::path(QString("lang") ) );
app.installTranslator(&translator);
// For non static builds on mac and win
// we need to be sure we can find the qt image
// plugins. In mac be sure to look in the
// application bundle...
#ifdef Q_WS_WIN
QApplication::addLibraryPath( QApplication::applicationDirPath()
+ QDir::separator() + "plugins" );
#endif
#ifdef Q_OS_MACX
QApplication::instance()->setAttribute(Qt::AA_DontShowIconsInMenus);
qDebug("Adding qt image plugins to plugin search path...");
CFURLRef myBundleRef = CFBundleCopyBundleURL(CFBundleGetMainBundle());
CFStringRef myMacPath = CFURLCopyFileSystemPath(myBundleRef, kCFURLPOSIXPathStyle);
const char *mypPathPtr = CFStringGetCStringPtr(myMacPath,CFStringGetSystemEncoding());
CFRelease(myBundleRef);
CFRelease(myMacPath);
QString myPath(mypPathPtr);
// if we are not in a bundle assume that the app is built
// as a non bundle app and that image plugins will be
// in system Qt frameworks. If the app is a bundle
// lets try to set the qt plugin search path...
if (myPath.contains(".app"))
{
myPath += "/Contents/plugins";
QApplication::addLibraryPath( myPath );
qDebug( "Added %s to plugin search path", qPrintable( myPath ) );
}
#endif
QString marbleDataPath;
int dataPathIndex=0;
MarbleGlobal::Profiles profiles = MarbleGlobal::detectProfiles();
QStringList args = QApplication::arguments();
for ( int i = 1; i < args.count(); ++i ) {
const QString arg = args.at(i);
if ( arg == "--debug-info" )
{
MarbleDebug::enable = true;
}
else if ( arg.startsWith( "--marbledatapath=", Qt::CaseInsensitive ) )
{
marbleDataPath = args.at(i).mid(17);
}
else if ( arg.compare( "--marbledatapath", Qt::CaseInsensitive ) == 0 ) {
dataPathIndex = i + 1;
marbleDataPath = args.value( dataPathIndex );
++i;
}
else if ( arg == "--smallscreen" ) {
profiles |= MarbleGlobal::SmallScreen;
}
else if ( arg == "--nosmallscreen" ) {
profiles &= ~MarbleGlobal::SmallScreen;
}
else if ( arg == "--highresolution" ) {
profiles |= MarbleGlobal::HighResolution;
}
else if ( arg == "--nohighresolution" ) {
profiles &= ~MarbleGlobal::HighResolution;
}
}
MarbleGlobal::getInstance()->setProfiles( profiles );
QLocale::MeasurementSystem const measurement = QLocale::system().measurementSystem();
Marble::MeasureSystem const marbleMeasurement = measurement == QLocale::ImperialSystem ? Marble::Imperial : Marble::Metric;
MarbleGlobal::getInstance()->locale()->setMeasureSystem( marbleMeasurement );
MainWindow *window = new MainWindow( marbleDataPath );
window->setAttribute( Qt::WA_DeleteOnClose, true );
MarbleTest *marbleTest = new MarbleTest( window->marbleWidget() );
// window->marbleWidget()->rotateTo( 0, 0, -90 );
// window->show();
for ( int i = 1; i < args.count(); ++i ) {
const QString arg = args.at(i);
if ( arg == "--timedemo" )
{
window->resize(900, 640);
marbleTest->timeDemo();
return 0;
}
else if( arg == "--gpsdemo" ) {
window->resize( 900, 640 );
marbleTest->gpsDemo();
return 0;
}
else if( arg == "--fps" ) {
window->marbleControl()->marbleWidget()->setShowFrameRate( true );
}
else if( arg == "--enableCurrentLocation" )
{
window->marbleControl()->setCurrentLocationTabShown(true);
}
else if( arg == "--enableFileView" )
{
window->marbleControl()->setFileViewTabShown(true);
}
else if ( arg == "--tile-id" )
{
window->marbleControl()->marbleWidget()->setShowTileId(true);
}
else if ( i != dataPathIndex && QFile::exists( arg ) )
( window->marbleControl() )->addGeoDataFile( arg );
}
delete marbleTest;
return app.exec();
}
<|endoftext|>
|
<commit_before>/*!
* \file report.cxx
* \brief Program entry and command line parsing for MP3Report.
*
* Copyright (c) 2013 Falko Schmidt <kaethorn@gmail.com>
*
* Distributed under the MIT License (MIT) (See accompanying file LICENSE.txt
* or copy at http://opensource.org/licenses/MIT)
*/
#include <boost/program_options.hpp>
namespace po = boost::program_options;
#include <iostream>
#include <iterator>
#include <map>
using namespace std;
#include "report_config.hxx"
#include "reporter.hxx"
int main (int argc, char *argv[]) {
string reportType, directory, outputPath;
po::options_description desc("Allowed options");
desc.add_options()
("help,h", "Produce this help message")
("version,v", "Print version string")
("report-type,r", po::value<string>(&reportType)->default_value("plain"),
"Report type (html_list, html_collapsible, csv, plain)")
("output-path,o", po::value<string>(&outputPath),
"File to write the report to (fallback: stdout)")
("directory", po::value<string>(&directory)->required(), "Working directory")
;
po::positional_options_description p;
p.add("directory", -1);
po::variables_map vm;
po::store(po::command_line_parser(argc, argv).options(desc).positional(p).run(), vm);
if (vm.count("help")) {
cout << desc << endl;
return 0;
}
if (vm.count("version")) {
cout << argv[0] << " version " << MP3REPORT_VERSION_MAJOR << "." << MP3REPORT_VERSION_MINOR << endl;
return 0;
}
try {
po::notify(vm);
} catch ( const boost::program_options::error& e ) {
cerr << e.what() << endl;
return 1;
}
if (vm["report-type"].as<string>() != "html_list" &&
vm["report-type"].as<string>() != "html_collapsible" &&
vm["report-type"].as<string>() != "csv" &&
vm["report-type"].as<string>() != "plain") {
cerr << "invalid report type (should be one of html_list, html_collapsible, csv or plain)" << endl;
return 1;
}
Reporter reporter(&directory, &reportType, &outputPath);
reporter.run();
return 0;
}
<commit_msg>use basename for argv[0] in version output.<commit_after>/*!
* \file report.cxx
* \brief Program entry and command line parsing for MP3Report.
*
* Copyright (c) 2013 Falko Schmidt <kaethorn@gmail.com>
*
* Distributed under the MIT License (MIT) (See accompanying file LICENSE.txt
* or copy at http://opensource.org/licenses/MIT)
*/
#include <boost/program_options.hpp>
#include <boost/filesystem.hpp>
namespace po = boost::program_options;
#include <iostream>
#include <iterator>
#include <map>
using namespace std;
#include "report_config.hxx"
#include "reporter.hxx"
int main (int argc, char *argv[]) {
string reportType, directory, outputPath;
po::options_description desc("Allowed options");
desc.add_options()
("help,h", "Produce this help message")
("version,v", "Print version string")
("report-type,r", po::value<string>(&reportType)->default_value("plain"),
"Report type (html_list, html_collapsible, csv, plain)")
("output-path,o", po::value<string>(&outputPath),
"File to write the report to (fallback: stdout)")
("directory", po::value<string>(&directory)->required(), "Working directory")
;
po::positional_options_description p;
p.add("directory", -1);
po::variables_map vm;
po::store(po::command_line_parser(argc, argv).options(desc).positional(p).run(), vm);
if (vm.count("help")) {
cout << desc << endl;
return 0;
}
if (vm.count("version")) {
cout << boost::filesystem::basename(argv[0]) << " version " <<
MP3REPORT_VERSION_MAJOR << "." << MP3REPORT_VERSION_MINOR << endl;
return 0;
}
try {
po::notify(vm);
} catch ( const boost::program_options::error& e ) {
cerr << e.what() << endl;
return 1;
}
if (vm["report-type"].as<string>() != "html_list" &&
vm["report-type"].as<string>() != "html_collapsible" &&
vm["report-type"].as<string>() != "csv" &&
vm["report-type"].as<string>() != "plain") {
cerr << "invalid report type (should be one of html_list, html_collapsible, csv or plain)" << endl;
return 1;
}
Reporter reporter(&directory, &reportType, &outputPath);
reporter.run();
return 0;
}
<|endoftext|>
|
<commit_before>// Copyright (c) 2009-2012 Bitcoin Developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "net.h"
#include "bitcoinrpc.h"
#include "alert.h"
#include "wallet.h"
#include "db.h"
#include "walletdb.h"
using namespace json_spirit;
using namespace std;
extern std::string NeuralRequest(std::string MyNeuralRequest);
extern bool RequestSupermajorityNeuralData();
std::string GetCurrentNeuralNetworkSupermajorityHash(double& out_popularity);
extern void GatherNeuralHashes();
extern bool AsyncNeuralRequest(std::string command_name,std::string cpid,int NodeLimit);
Value getconnectioncount(const Array& params, bool fHelp)
{
if (fHelp || params.size() != 0)
throw runtime_error(
"getconnectioncount\n"
"Returns the number of connections to other nodes.");
LOCK(cs_vNodes);
return (int)vNodes.size();
}
std::string NeuralRequest(std::string MyNeuralRequest)
{
// Find a Neural Network Node that is free
LOCK(cs_vNodes);
BOOST_FOREACH(CNode* pNode, vNodes)
{
if (Contains(pNode->strSubVer,"1999"))
{
//printf("Node is a neural participant \r\n");
std::string reqid = "reqid";
pNode->PushMessage("neural", MyNeuralRequest, reqid);
if (fDebug3) printf(" PUSH ");
}
}
return "";
}
void GatherNeuralHashes()
{
// Find a Neural Network Node that is free
LOCK(cs_vNodes);
BOOST_FOREACH(CNode* pNode, vNodes)
{
if (Contains(pNode->strSubVer,"1999"))
{
std::string reqid = "reqid";
std::string command_name="neural_hash";
pNode->PushMessage("neural", command_name, reqid);
if (fDebug10) printf(" Pushed ");
}
}
}
bool RequestSupermajorityNeuralData()
{
LOCK(cs_vNodes);
double dCurrentPopularity = 0;
std::string sCurrentNeuralSupermajorityHash = GetCurrentNeuralNetworkSupermajorityHash(dCurrentPopularity);
std::string reqid = DefaultWalletAddress();
BOOST_FOREACH(CNode* pNode, vNodes)
{
if (!pNode->NeuralHash.empty() && !sCurrentNeuralSupermajorityHash.empty() && pNode->NeuralHash == sCurrentNeuralSupermajorityHash)
{
std::string command_name="neural_data";
pNode->PushMessage("neural", command_name, reqid);
return true;
}
}
return false;
}
Value addnode(const Array& params, bool fHelp)
{
string strCommand;
if (params.size() == 2)
strCommand = params[1].get_str();
if (fHelp || params.size() != 2 ||
(strCommand != "onetry" && strCommand != "add" && strCommand != "remove"))
throw runtime_error(
"addnode <node> <add|remove|onetry>\n"
"Attempts add or remove <node> from the addnode list or try a connection to <node> once.");
string strNode = params[0].get_str();
if (strCommand == "onetry")
{
CAddress addr;
ConnectNode(addr, strNode.c_str());
return Value::null;
}
LOCK(cs_vAddedNodes);
vector<string>::iterator it = vAddedNodes.begin();
for(; it != vAddedNodes.end(); it++)
if (strNode == *it)
break;
if (strCommand == "add")
{
if (it != vAddedNodes.end())
throw JSONRPCError(-23, "Error: Node already added");
vAddedNodes.push_back(strNode);
}
else if(strCommand == "remove")
{
if (it == vAddedNodes.end())
throw JSONRPCError(-24, "Error: Node has not been added.");
vAddedNodes.erase(it);
}
return Value::null;
}
Value getaddednodeinfo(const Array& params, bool fHelp)
{
if (fHelp || params.size() < 1 || params.size() > 2)
throw runtime_error(
"getaddednodeinfo <dns> [node]\n"
"Returns information about the given added node, or all added nodes\n"
"(note that onetry addnodes are not listed here)\n"
"If dns is false, only a list of added nodes will be provided,\n"
"otherwise connected information will also be available.");
bool fDns = params[0].get_bool();
list<string> laddedNodes(0);
if (params.size() == 1)
{
LOCK(cs_vAddedNodes);
BOOST_FOREACH(string& strAddNode, vAddedNodes)
laddedNodes.push_back(strAddNode);
}
else
{
string strNode = params[1].get_str();
LOCK(cs_vAddedNodes);
BOOST_FOREACH(string& strAddNode, vAddedNodes)
if (strAddNode == strNode)
{
laddedNodes.push_back(strAddNode);
break;
}
if (laddedNodes.size() == 0)
throw JSONRPCError(-24, "Error: Node has not been added.");
}
if (!fDns)
{
Object ret;
BOOST_FOREACH(string& strAddNode, laddedNodes)
ret.push_back(Pair("addednode", strAddNode));
return ret;
}
Array ret;
list<pair<string, vector<CService> > > laddedAddreses(0);
BOOST_FOREACH(string& strAddNode, laddedNodes)
{
vector<CService> vservNode(0);
if(Lookup(strAddNode.c_str(), vservNode, GetDefaultPort(), fNameLookup, 0))
laddedAddreses.push_back(make_pair(strAddNode, vservNode));
else
{
Object obj;
obj.push_back(Pair("addednode", strAddNode));
obj.push_back(Pair("connected", false));
Array addresses;
obj.push_back(Pair("addresses", addresses));
}
}
LOCK(cs_vNodes);
for (list<pair<string, vector<CService> > >::iterator it = laddedAddreses.begin(); it != laddedAddreses.end(); it++)
{
Object obj;
obj.push_back(Pair("addednode", it->first));
Array addresses;
bool fConnected = false;
BOOST_FOREACH(CService& addrNode, it->second)
{
bool fFound = false;
Object node;
node.push_back(Pair("address", addrNode.ToString()));
BOOST_FOREACH(CNode* pnode, vNodes)
if (pnode->addr == addrNode)
{
fFound = true;
fConnected = true;
node.push_back(Pair("connected", pnode->fInbound ? "inbound" : "outbound"));
break;
}
if (!fFound)
node.push_back(Pair("connected", "false"));
addresses.push_back(node);
}
obj.push_back(Pair("connected", fConnected));
obj.push_back(Pair("addresses", addresses));
ret.push_back(obj);
}
return ret;
}
bool AsyncNeuralRequest(std::string command_name,std::string cpid,int NodeLimit)
{
// Find a Neural Network Node that is free
LOCK(cs_vNodes);
int iContactCount = 0;
msNeuralResponse="";
BOOST_FOREACH(CNode* pNode, vNodes)
{
if (Contains(pNode->strSubVer,"1999"))
{
std::string reqid = cpid;
pNode->PushMessage("neural", command_name, reqid);
//if (fDebug3) printf("Requested command %s \r\n",command_name.c_str());
iContactCount++;
if (iContactCount >= NodeLimit) return true;
}
}
if (iContactCount==0)
{
printf("No neural network nodes online.");
return false;
}
return true;
}
Value ping(const Array& params, bool fHelp)
{
if (fHelp || params.size() != 0)
throw runtime_error(
"ping\n"
"Requests that a ping be sent to all other nodes, to measure ping time.\n"
"Results provided in getpeerinfo, pingtime and pingwait fields are decimal seconds.\n"
"Ping command is handled in queue with all other commands, so it measures processing backlog, not just network ping.");
// Request that each node send a ping during next message processing pass
LOCK(cs_vNodes);
BOOST_FOREACH(CNode* pNode, vNodes) {
pNode->fPingQueued = true;
}
return Value::null;
}
static void CopyNodeStats(std::vector<CNodeStats>& vstats)
{
vstats.clear();
LOCK(cs_vNodes);
vstats.reserve(vNodes.size());
BOOST_FOREACH(CNode* pnode, vNodes) {
CNodeStats stats;
pnode->copyStats(stats);
vstats.push_back(stats);
}
}
Value getpeerinfo(const Array& params, bool fHelp)
{
if (fHelp || params.size() != 0)
throw runtime_error(
"getpeerinfo\n"
"Returns data about each connected network node.");
vector<CNodeStats> vstats;
CopyNodeStats(vstats);
Array ret;
GatherNeuralHashes();
BOOST_FOREACH(const CNodeStats& stats, vstats) {
Object obj;
obj.push_back(Pair("addr", stats.addrName));
if (!(stats.addrLocal.empty()))
obj.push_back(Pair("addrlocal", stats.addrLocal));
obj.push_back(Pair("services", strprintf("%08" PRIx64, stats.nServices)));
obj.push_back(Pair("lastsend", stats.nLastSend));
obj.push_back(Pair("lastrecv", stats.nLastRecv));
obj.push_back(Pair("conntime", stats.nTimeConnected));
obj.push_back(Pair("pingtime", stats.dPingTime));
if (stats.dPingWait > 0.0)
obj.push_back(Pair("pingwait", stats.dPingWait));
obj.push_back(Pair("version", stats.nVersion));
obj.push_back(Pair("subver", stats.strSubVer));
obj.push_back(Pair("inbound", stats.fInbound));
obj.push_back(Pair("startingheight", stats.nStartingHeight));
obj.push_back(Pair("nTrust", stats.nTrust));
obj.push_back(Pair("banscore", stats.nMisbehavior));
bool bNeural = false;
bNeural = Contains(stats.strSubVer, "1999");
obj.push_back(Pair("Neural Network", bNeural));
if (bNeural)
{
obj.push_back(Pair("Neural Hash", stats.NeuralHash));
obj.push_back(Pair("Neural Participant", IsNeuralNodeParticipant(stats.sGRCAddress, GetAdjustedTime())));
}
ret.push_back(obj);
}
return ret;
}
Value getnettotals(const Array& params, bool fHelp)
{
if (fHelp || params.size() > 0)
throw runtime_error(
"getnettotals\n"
"Returns information about network traffic, including bytes in, bytes out,\n"
"and current time.");
Object obj;
obj.push_back(Pair("totalbytesrecv", CNode::GetTotalBytesRecv()));
obj.push_back(Pair("totalbytessent", CNode::GetTotalBytesSent()));
obj.push_back(Pair("timemillis", GetTimeMillis()));
return obj;
}
// ppcoin: send alert.
// There is a known deadlock situation with ThreadMessageHandler
// ThreadMessageHandler: holds cs_vSend and acquiring cs_main in SendMessages()
// ThreadRPCServer: holds cs_main and acquiring cs_vSend in alert.RelayTo()/PushMessage()/BeginMessage()
Value sendalert(const Array& params, bool fHelp)
{
if (fHelp || params.size() < 6)
throw runtime_error(
"sendalert <message> <privatekey> <minver> <maxver> <priority> <id> [cancelupto]\n"
"<message> is the alert text message\n"
"<privatekey> is hex string of alert master private key\n"
"<minver> is the minimum applicable internal client version\n"
"<maxver> is the maximum applicable internal client version\n"
"<priority> is integer priority number\n"
"<id> is the alert id\n"
"[cancelupto] cancels all alert id's up to this number\n"
"Returns true or false.");
CAlert alert;
CKey key;
alert.strStatusBar = params[0].get_str();
alert.nMinVer = params[2].get_int();
alert.nMaxVer = params[3].get_int();
alert.nPriority = params[4].get_int();
alert.nID = params[5].get_int();
if (params.size() > 6)
alert.nCancel = params[6].get_int();
alert.nVersion = PROTOCOL_VERSION;
alert.nRelayUntil = GetAdjustedTime() + 365*24*60*60;
alert.nExpiration = GetAdjustedTime() + 365*24*60*60;
CDataStream sMsg(SER_NETWORK, PROTOCOL_VERSION);
sMsg << (CUnsignedAlert)alert;
alert.vchMsg = vector<unsigned char>(sMsg.begin(), sMsg.end());
vector<unsigned char> vchPrivKey = ParseHex(params[1].get_str());
key.SetPrivKey(CPrivKey(vchPrivKey.begin(), vchPrivKey.end())); // if key is not correct openssl may crash
if (!key.Sign(Hash(alert.vchMsg.begin(), alert.vchMsg.end()), alert.vchSig))
throw runtime_error(
"Unable to sign alert, check private key?\n");
if(!alert.ProcessAlert())
throw runtime_error(
"Failed to process alert.\n");
// Relay alert
{
LOCK(cs_vNodes);
BOOST_FOREACH(CNode* pnode, vNodes)
alert.RelayTo(pnode);
}
Object result;
result.push_back(Pair("strStatusBar", alert.strStatusBar));
result.push_back(Pair("nVersion", alert.nVersion));
result.push_back(Pair("nMinVer", alert.nMinVer));
result.push_back(Pair("nMaxVer", alert.nMaxVer));
result.push_back(Pair("nPriority", alert.nPriority));
result.push_back(Pair("nID", alert.nID));
if (alert.nCancel > 0)
result.push_back(Pair("nCancel", alert.nCancel));
return result;
}
<commit_msg>boost_foreach change in rpcnet.cpp<commit_after>// Copyright (c) 2009-2012 Bitcoin Developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "net.h"
#include "bitcoinrpc.h"
#include "alert.h"
#include "wallet.h"
#include "db.h"
#include "walletdb.h"
using namespace json_spirit;
using namespace std;
extern std::string NeuralRequest(std::string MyNeuralRequest);
extern bool RequestSupermajorityNeuralData();
std::string GetCurrentNeuralNetworkSupermajorityHash(double& out_popularity);
extern void GatherNeuralHashes();
extern bool AsyncNeuralRequest(std::string command_name,std::string cpid,int NodeLimit);
Value getconnectioncount(const Array& params, bool fHelp)
{
if (fHelp || params.size() != 0)
throw runtime_error(
"getconnectioncount\n"
"Returns the number of connections to other nodes.");
LOCK(cs_vNodes);
return (int)vNodes.size();
}
std::string NeuralRequest(std::string MyNeuralRequest)
{
// Find a Neural Network Node that is free
LOCK(cs_vNodes);
for (auto const& pNode : vNodes)
{
if (Contains(pNode->strSubVer,"1999"))
{
//printf("Node is a neural participant \r\n");
std::string reqid = "reqid";
pNode->PushMessage("neural", MyNeuralRequest, reqid);
if (fDebug3) printf(" PUSH ");
}
}
return "";
}
void GatherNeuralHashes()
{
// Find a Neural Network Node that is free
LOCK(cs_vNodes);
for (auto const& pNode : vNodes)
{
if (Contains(pNode->strSubVer,"1999"))
{
std::string reqid = "reqid";
std::string command_name="neural_hash";
pNode->PushMessage("neural", command_name, reqid);
if (fDebug10) printf(" Pushed ");
}
}
}
bool RequestSupermajorityNeuralData()
{
LOCK(cs_vNodes);
double dCurrentPopularity = 0;
std::string sCurrentNeuralSupermajorityHash = GetCurrentNeuralNetworkSupermajorityHash(dCurrentPopularity);
std::string reqid = DefaultWalletAddress();
for (auto const& pNode : vNodes)
{
if (!pNode->NeuralHash.empty() && !sCurrentNeuralSupermajorityHash.empty() && pNode->NeuralHash == sCurrentNeuralSupermajorityHash)
{
std::string command_name="neural_data";
pNode->PushMessage("neural", command_name, reqid);
return true;
}
}
return false;
}
Value addnode(const Array& params, bool fHelp)
{
string strCommand;
if (params.size() == 2)
strCommand = params[1].get_str();
if (fHelp || params.size() != 2 ||
(strCommand != "onetry" && strCommand != "add" && strCommand != "remove"))
throw runtime_error(
"addnode <node> <add|remove|onetry>\n"
"Attempts add or remove <node> from the addnode list or try a connection to <node> once.");
string strNode = params[0].get_str();
if (strCommand == "onetry")
{
CAddress addr;
ConnectNode(addr, strNode.c_str());
return Value::null;
}
LOCK(cs_vAddedNodes);
vector<string>::iterator it = vAddedNodes.begin();
for(; it != vAddedNodes.end(); it++)
if (strNode == *it)
break;
if (strCommand == "add")
{
if (it != vAddedNodes.end())
throw JSONRPCError(-23, "Error: Node already added");
vAddedNodes.push_back(strNode);
}
else if(strCommand == "remove")
{
if (it == vAddedNodes.end())
throw JSONRPCError(-24, "Error: Node has not been added.");
vAddedNodes.erase(it);
}
return Value::null;
}
Value getaddednodeinfo(const Array& params, bool fHelp)
{
if (fHelp || params.size() < 1 || params.size() > 2)
throw runtime_error(
"getaddednodeinfo <dns> [node]\n"
"Returns information about the given added node, or all added nodes\n"
"(note that onetry addnodes are not listed here)\n"
"If dns is false, only a list of added nodes will be provided,\n"
"otherwise connected information will also be available.");
bool fDns = params[0].get_bool();
list<string> laddedNodes(0);
if (params.size() == 1)
{
LOCK(cs_vAddedNodes);
for (auto const& strAddNode : vAddedNodes)
laddedNodes.push_back(strAddNode);
}
else
{
string strNode = params[1].get_str();
LOCK(cs_vAddedNodes);
for (auto const& strAddNode : vAddedNodes)
if (strAddNode == strNode)
{
laddedNodes.push_back(strAddNode);
break;
}
if (laddedNodes.size() == 0)
throw JSONRPCError(-24, "Error: Node has not been added.");
}
if (!fDns)
{
Object ret;
for (auto const& strAddNode : laddedNodes)
ret.push_back(Pair("addednode", strAddNode));
return ret;
}
Array ret;
list<pair<string, vector<CService> > > laddedAddreses(0);
for (auto const& strAddNode : laddedNodes)
{
vector<CService> vservNode(0);
if(Lookup(strAddNode.c_str(), vservNode, GetDefaultPort(), fNameLookup, 0))
laddedAddreses.push_back(make_pair(strAddNode, vservNode));
else
{
Object obj;
obj.push_back(Pair("addednode", strAddNode));
obj.push_back(Pair("connected", false));
Array addresses;
obj.push_back(Pair("addresses", addresses));
}
}
LOCK(cs_vNodes);
for (list<pair<string, vector<CService> > >::iterator it = laddedAddreses.begin(); it != laddedAddreses.end(); it++)
{
Object obj;
obj.push_back(Pair("addednode", it->first));
Array addresses;
bool fConnected = false;
for (auto const& addrNode : it->second)
{
bool fFound = false;
Object node;
node.push_back(Pair("address", addrNode.ToString()));
for (auto const& pnode : vNodes)
if (pnode->addr == addrNode)
{
fFound = true;
fConnected = true;
node.push_back(Pair("connected", pnode->fInbound ? "inbound" : "outbound"));
break;
}
if (!fFound)
node.push_back(Pair("connected", "false"));
addresses.push_back(node);
}
obj.push_back(Pair("connected", fConnected));
obj.push_back(Pair("addresses", addresses));
ret.push_back(obj);
}
return ret;
}
bool AsyncNeuralRequest(std::string command_name,std::string cpid,int NodeLimit)
{
// Find a Neural Network Node that is free
LOCK(cs_vNodes);
int iContactCount = 0;
msNeuralResponse="";
for (auto const& pNode : vNodes)
{
if (Contains(pNode->strSubVer,"1999"))
{
std::string reqid = cpid;
pNode->PushMessage("neural", command_name, reqid);
//if (fDebug3) printf("Requested command %s \r\n",command_name.c_str());
iContactCount++;
if (iContactCount >= NodeLimit) return true;
}
}
if (iContactCount==0)
{
printf("No neural network nodes online.");
return false;
}
return true;
}
Value ping(const Array& params, bool fHelp)
{
if (fHelp || params.size() != 0)
throw runtime_error(
"ping\n"
"Requests that a ping be sent to all other nodes, to measure ping time.\n"
"Results provided in getpeerinfo, pingtime and pingwait fields are decimal seconds.\n"
"Ping command is handled in queue with all other commands, so it measures processing backlog, not just network ping.");
// Request that each node send a ping during next message processing pass
LOCK(cs_vNodes);
for (auto const& pNode : vNodes) {
pNode->fPingQueued = true;
}
return Value::null;
}
static void CopyNodeStats(std::vector<CNodeStats>& vstats)
{
vstats.clear();
LOCK(cs_vNodes);
vstats.reserve(vNodes.size());
for (auto const& pnode : vNodes) {
CNodeStats stats;
pnode->copyStats(stats);
vstats.push_back(stats);
}
}
Value getpeerinfo(const Array& params, bool fHelp)
{
if (fHelp || params.size() != 0)
throw runtime_error(
"getpeerinfo\n"
"Returns data about each connected network node.");
vector<CNodeStats> vstats;
CopyNodeStats(vstats);
Array ret;
GatherNeuralHashes();
for (auto const& stats : vstats) {
Object obj;
obj.push_back(Pair("addr", stats.addrName));
if (!(stats.addrLocal.empty()))
obj.push_back(Pair("addrlocal", stats.addrLocal));
obj.push_back(Pair("services", strprintf("%08" PRIx64, stats.nServices)));
obj.push_back(Pair("lastsend", stats.nLastSend));
obj.push_back(Pair("lastrecv", stats.nLastRecv));
obj.push_back(Pair("conntime", stats.nTimeConnected));
obj.push_back(Pair("pingtime", stats.dPingTime));
if (stats.dPingWait > 0.0)
obj.push_back(Pair("pingwait", stats.dPingWait));
obj.push_back(Pair("version", stats.nVersion));
obj.push_back(Pair("subver", stats.strSubVer));
obj.push_back(Pair("inbound", stats.fInbound));
obj.push_back(Pair("startingheight", stats.nStartingHeight));
obj.push_back(Pair("nTrust", stats.nTrust));
obj.push_back(Pair("banscore", stats.nMisbehavior));
bool bNeural = false;
bNeural = Contains(stats.strSubVer, "1999");
obj.push_back(Pair("Neural Network", bNeural));
if (bNeural)
{
obj.push_back(Pair("Neural Hash", stats.NeuralHash));
obj.push_back(Pair("Neural Participant", IsNeuralNodeParticipant(stats.sGRCAddress, GetAdjustedTime())));
}
ret.push_back(obj);
}
return ret;
}
Value getnettotals(const Array& params, bool fHelp)
{
if (fHelp || params.size() > 0)
throw runtime_error(
"getnettotals\n"
"Returns information about network traffic, including bytes in, bytes out,\n"
"and current time.");
Object obj;
obj.push_back(Pair("totalbytesrecv", CNode::GetTotalBytesRecv()));
obj.push_back(Pair("totalbytessent", CNode::GetTotalBytesSent()));
obj.push_back(Pair("timemillis", GetTimeMillis()));
return obj;
}
// ppcoin: send alert.
// There is a known deadlock situation with ThreadMessageHandler
// ThreadMessageHandler: holds cs_vSend and acquiring cs_main in SendMessages()
// ThreadRPCServer: holds cs_main and acquiring cs_vSend in alert.RelayTo()/PushMessage()/BeginMessage()
Value sendalert(const Array& params, bool fHelp)
{
if (fHelp || params.size() < 6)
throw runtime_error(
"sendalert <message> <privatekey> <minver> <maxver> <priority> <id> [cancelupto]\n"
"<message> is the alert text message\n"
"<privatekey> is hex string of alert master private key\n"
"<minver> is the minimum applicable internal client version\n"
"<maxver> is the maximum applicable internal client version\n"
"<priority> is integer priority number\n"
"<id> is the alert id\n"
"[cancelupto] cancels all alert id's up to this number\n"
"Returns true or false.");
CAlert alert;
CKey key;
alert.strStatusBar = params[0].get_str();
alert.nMinVer = params[2].get_int();
alert.nMaxVer = params[3].get_int();
alert.nPriority = params[4].get_int();
alert.nID = params[5].get_int();
if (params.size() > 6)
alert.nCancel = params[6].get_int();
alert.nVersion = PROTOCOL_VERSION;
alert.nRelayUntil = GetAdjustedTime() + 365*24*60*60;
alert.nExpiration = GetAdjustedTime() + 365*24*60*60;
CDataStream sMsg(SER_NETWORK, PROTOCOL_VERSION);
sMsg << (CUnsignedAlert)alert;
alert.vchMsg = vector<unsigned char>(sMsg.begin(), sMsg.end());
vector<unsigned char> vchPrivKey = ParseHex(params[1].get_str());
key.SetPrivKey(CPrivKey(vchPrivKey.begin(), vchPrivKey.end())); // if key is not correct openssl may crash
if (!key.Sign(Hash(alert.vchMsg.begin(), alert.vchMsg.end()), alert.vchSig))
throw runtime_error(
"Unable to sign alert, check private key?\n");
if(!alert.ProcessAlert())
throw runtime_error(
"Failed to process alert.\n");
// Relay alert
{
LOCK(cs_vNodes);
for (auto const& pnode : vNodes)
alert.RelayTo(pnode);
}
Object result;
result.push_back(Pair("strStatusBar", alert.strStatusBar));
result.push_back(Pair("nVersion", alert.nVersion));
result.push_back(Pair("nMinVer", alert.nMinVer));
result.push_back(Pair("nMaxVer", alert.nMaxVer));
result.push_back(Pair("nPriority", alert.nPriority));
result.push_back(Pair("nID", alert.nID));
if (alert.nCancel > 0)
result.push_back(Pair("nCancel", alert.nCancel));
return result;
}
<|endoftext|>
|
<commit_before>#include "scanner.hh"
#include <cctype>
using namespace std;
/*
Spidermonkey's tokenize function has the following control flow structure:
retry:
switch (c) {
case ...:
goto badchar
badchar:
default:
}
out:
error:
*/
boost::optional<boost::variant<Token, Decimal> >
Scanner::getToken() {
for (;;) {
Token token;
if (tokStream.eof()) {
return boost::optional<boost::variant<Token, Decimal> >();
}
int c = tokStream.get();
auto initialKind = FirstCharKind(firstCharKinds[c]);
// Cases:
// 1. Single character token
if (initialKind <= OneChar_Max) {
return boost::optional<boost::variant<Token, Decimal> >(Token());
}
// 2. Whitespace
if (isspace(tokStream.get())) continue;
// 3. Identifier
for (;;) {
c = tokStream.get();
}
// 4. Decimal
if (isASCIIDecimal(c)) {
while (isASCIIDecimal(c)) {
c = tokStream.get();
if (c == '.') {
do {
c = tokStream.get();
} while (isASCIIDecimal(c));
}
if (c == 'e' || c == 'E') {
c = tokStream.get();
if (c == '+' || c == '-')
c = tokStream.get();
if (!isASCIIDecimal(c)) {
std::cerr << "error: malformed decimal" << std::endl;
return boost::optional<boost::variant<Token, Decimal> >();
}
do {
c = tokStream.get();
} while (isASCIIDecimal(c));
}
}
}
// 5. String or Template String
// 6. EOL
// 7. Hex, octal, binary
// 8. Operators
switch (c) {
case '.':
c = tokStream.get();
if (isASCIIDecimal(c)) {
return boost::optional<boost::variant<Token, Decimal> >(Decimal(tokStream.tellg()));
}
if (c == '.' && tokStream.get() == '.') {
token.type = TOK_TRIPLEDOT;
return boost::optional<boost::variant<Token, Decimal> >(token);
}
case '=':
c = tokStream.get();
if (c == '=') {
if (tokStream.get() == '=') token.type = TOK_STRICTEQ;
else token.type = TOK_EQ;
} else if (c == '>') {
token.type = TOK_ARROW;
} else {
token.type = TOK_ASSIGN;
}
return boost::optional<boost::variant<Token, Decimal> >(token);
}
}
}
<commit_msg>scaffolding<commit_after>#include "scanner.hh"
#include <cctype>
using namespace std;
/*
Spidermonkey's tokenize function has the following control flow structure:
retry:
switch (c) {
case ...:
goto badchar
badchar:
default:
}
out:
error:
*/
boost::optional<boost::variant<Token, Decimal> >
Scanner::getToken() {
for (;;) {
Token token;
if (tokStream.eof()) {
return boost::optional<boost::variant<Token, Decimal> >();
}
int c = tokStream.get();
auto initialKind = FirstCharKind(firstCharKinds[c]);
// Cases:
// 1. Single character token
if (initialKind <= OneChar_Max) {
return boost::optional<boost::variant<Token, Decimal> >(Token());
}
// 2. Whitespace
if (isspace(tokStream.get())) continue;
// 3. Identifier
for (;;) {
c = tokStream.get();
}
// 4. Decimal
if (isASCIIDecimal(c)) {
while (isASCIIDecimal(c)) {
c = tokStream.get();
if (c == '.') {
do {
c = tokStream.get();
} while (isASCIIDecimal(c));
}
if (c == 'e' || c == 'E') {
c = tokStream.get();
if (c == '+' || c == '-')
c = tokStream.get();
if (!isASCIIDecimal(c)) {
std::cerr << "error: malformed decimal" << std::endl;
return boost::optional<boost::variant<Token, Decimal> >();
}
do {
c = tokStream.get();
} while (isASCIIDecimal(c));
}
}
}
// 5. String or Template String
if (initialKind == String) {
}
// 6. EOL
// 7. Hex, octal, binary
if (initialKind == BasePrefix) {
c = tokStream.get();
if (c == 'x' || c == 'X') {
} else if (c == 'b' || c == 'B') {
} else if (c == 'o' || c == 'O') {
} else if (isASCIIDecimal(c)) {
} else {
}
}
// 8. Operators
switch (c) {
case '.':
c = tokStream.get();
if (isASCIIDecimal(c)) {
return boost::optional<boost::variant<Token, Decimal> >(Decimal(tokStream.tellg()));
}
if (c == '.' && tokStream.get() == '.') {
token.type = TOK_TRIPLEDOT;
return boost::optional<boost::variant<Token, Decimal> >(token);
}
case '=':
c = tokStream.get();
if (c == '=') {
if (tokStream.get() == '=') token.type = TOK_STRICTEQ;
else token.type = TOK_EQ;
} else if (c == '>') {
token.type = TOK_ARROW;
} else {
token.type = TOK_ASSIGN;
}
return boost::optional<boost::variant<Token, Decimal> >(token);
}
}
}
<|endoftext|>
|
<commit_before>#include <algorithm>
#include "base/common.h"
#include "base/task.h"
static double english_frequencies[26] = {
0.08167, 0.01492, 0.02782, 0.04253, 0.12702, 0.02228, 0.02015,
0.06094, 0.06966, 0.00153, 0.00772, 0.04025, 0.02406, 0.06749,
0.07507, 0.01929, 0.00095, 0.05987, 0.06327, 0.09056, 0.02758,
0.00978, 0.02360, 0.00150, 0.01974, 0.00074};
double ScoreData(const std::vector<uint8_t>& input) {
double frequences[256] = {0.0};
for (uint8_t element : input) {
frequences[element] += 1;
}
for (double& f : frequences) {
f /= input.size();
}
double score = 0.0;
for (int i = 0; i < 256; ++i) {
if ('A' <= i && i <= 'Z') {
score += std::abs(frequences[i] - english_frequencies[i - 'A']);
} else if ('a' <= i && i <= 'z') {
score += std::abs(frequences[i] - english_frequencies[i - 'a']);
} else {
score += frequences[i];
}
}
return score;
}
std::vector<uint8_t> XorWithSingleByte(const std::vector<uint8_t>& input,
uint8_t xor_byte) {
std::vector<uint8_t> result(input.size());
for (size_t i = 0; i < input.size(); ++i) {
result[i] = input[i] ^ xor_byte;
}
return result;
}
uint8_t DetectSingleCharXor(const std::vector<uint8_t>& input) {
int best_i = -1;
double best_score = std::numeric_limits<double>::infinity();
// From the task we know that we are looking for all lowercase letters.
for (int i = 'a'; i <= 'z'; ++i) {
double score = ScoreData(XorWithSingleByte(input, i));
if (score < best_score) {
best_score = score;
best_i = i;
}
}
return best_i;
}
std::vector<uint8_t> RepeatingKeyXor(const std::vector<uint8_t>& input,
const std::vector<uint8_t>& key) {
std::vector<uint8_t> result(input.size());
int key_index = 0;
for (size_t i = 0; i < input.size(); ++i) {
result[i] = input[i] ^ key[key_index];
key_index = (key_index + 1) % key.size();
}
return result;
}
std::vector<uint8_t> GetEqualDistanceBytes(const std::vector<uint8_t>& data,
int start, int step) {
std::vector<uint8_t> result;
result.reserve((data.size() - start) / step);
for (size_t i = start; i < data.size(); i += step) {
result.push_back(data[i]);
}
return result;
}
#include <iostream>
TASK(59) {
auto codes = Split(ReadFileIntoString("data/059_cipher.txt"), ',');
std::vector<uint8_t> cipher(codes.size());
std::transform(codes.begin(), codes.end(), cipher.begin(),
[](const std::string& s) { return std::stoi(s); });
std::vector<uint8_t> key(3);
for (int i = 0; i < 3; ++i) {
auto transposed_data = GetEqualDistanceBytes(cipher, i, 3);
key[i] = DetectSingleCharXor(transposed_data);
}
auto decoded_data = RepeatingKeyXor(cipher, key);
return std::accumulate(decoded_data.begin(), decoded_data.end(), 0);
}
<commit_msg>Remove unnecessary include<commit_after>#include <algorithm>
#include "base/common.h"
#include "base/task.h"
static double english_frequencies[26] = {
0.08167, 0.01492, 0.02782, 0.04253, 0.12702, 0.02228, 0.02015,
0.06094, 0.06966, 0.00153, 0.00772, 0.04025, 0.02406, 0.06749,
0.07507, 0.01929, 0.00095, 0.05987, 0.06327, 0.09056, 0.02758,
0.00978, 0.02360, 0.00150, 0.01974, 0.00074};
double ScoreData(const std::vector<uint8_t>& input) {
double frequences[256] = {0.0};
for (uint8_t element : input) {
frequences[element] += 1;
}
for (double& f : frequences) {
f /= input.size();
}
double score = 0.0;
for (int i = 0; i < 256; ++i) {
if ('A' <= i && i <= 'Z') {
score += std::abs(frequences[i] - english_frequencies[i - 'A']);
} else if ('a' <= i && i <= 'z') {
score += std::abs(frequences[i] - english_frequencies[i - 'a']);
} else {
score += frequences[i];
}
}
return score;
}
std::vector<uint8_t> XorWithSingleByte(const std::vector<uint8_t>& input,
uint8_t xor_byte) {
std::vector<uint8_t> result(input.size());
for (size_t i = 0; i < input.size(); ++i) {
result[i] = input[i] ^ xor_byte;
}
return result;
}
uint8_t DetectSingleCharXor(const std::vector<uint8_t>& input) {
int best_i = -1;
double best_score = std::numeric_limits<double>::infinity();
// From the task we know that we are looking for all lowercase letters.
for (int i = 'a'; i <= 'z'; ++i) {
double score = ScoreData(XorWithSingleByte(input, i));
if (score < best_score) {
best_score = score;
best_i = i;
}
}
return best_i;
}
std::vector<uint8_t> RepeatingKeyXor(const std::vector<uint8_t>& input,
const std::vector<uint8_t>& key) {
std::vector<uint8_t> result(input.size());
int key_index = 0;
for (size_t i = 0; i < input.size(); ++i) {
result[i] = input[i] ^ key[key_index];
key_index = (key_index + 1) % key.size();
}
return result;
}
std::vector<uint8_t> GetEqualDistanceBytes(const std::vector<uint8_t>& data,
int start, int step) {
std::vector<uint8_t> result;
result.reserve((data.size() - start) / step);
for (size_t i = start; i < data.size(); i += step) {
result.push_back(data[i]);
}
return result;
}
TASK(59) {
auto codes = Split(ReadFileIntoString("data/059_cipher.txt"), ',');
std::vector<uint8_t> cipher(codes.size());
std::transform(codes.begin(), codes.end(), cipher.begin(),
[](const std::string& s) { return std::stoi(s); });
std::vector<uint8_t> key(3);
for (int i = 0; i < 3; ++i) {
auto transposed_data = GetEqualDistanceBytes(cipher, i, 3);
key[i] = DetectSingleCharXor(transposed_data);
}
auto decoded_data = RepeatingKeyXor(cipher, key);
return std::accumulate(decoded_data.begin(), decoded_data.end(), 0);
}
<|endoftext|>
|
<commit_before>//===------------------------- thread.cpp----------------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is dual licensed under the MIT and the University of Illinois Open
// Source Licenses. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "__config"
#ifndef _LIBCPP_HAS_NO_THREADS
#include "thread"
#include "exception"
#include "vector"
#include "future"
#include "limits"
#include <sys/types.h>
#if defined(__unix__) || (defined(__APPLE__) && defined(__MACH__))
# include <sys/param.h>
# if defined(BSD)
# include <sys/sysctl.h>
# endif // defined(BSD)
#endif // defined(__unix__) || (defined(__APPLE__) && defined(__MACH__))
#if defined(__unix__) || (defined(__APPLE__) && defined(__MACH__)) || defined(__CloudABI__) || defined(__Fuchsia__)
# include <unistd.h>
#endif // defined(__unix__) || (defined(__APPLE__) && defined(__MACH__)) || defined(__CloudABI__) || defined(__Fuchsia__)
#if defined(__NetBSD__)
#pragma weak pthread_create // Do not create libpthread dependency
#endif
#if defined(_LIBCPP_WIN32API)
#include <windows.h>
#endif
_LIBCPP_BEGIN_NAMESPACE_STD
thread::~thread()
{
if (!__libcpp_thread_isnull(&__t_))
terminate();
}
void
thread::join()
{
int ec = EINVAL;
if (!__libcpp_thread_isnull(&__t_))
{
ec = __libcpp_thread_join(&__t_);
if (ec == 0)
__t_ = _LIBCPP_NULL_THREAD;
}
if (ec)
__throw_system_error(ec, "thread::join failed");
}
void
thread::detach()
{
int ec = EINVAL;
if (!__libcpp_thread_isnull(&__t_))
{
ec = __libcpp_thread_detach(&__t_);
if (ec == 0)
__t_ = _LIBCPP_NULL_THREAD;
}
if (ec)
__throw_system_error(ec, "thread::detach failed");
}
unsigned
thread::hardware_concurrency() _NOEXCEPT
{
#if defined(CTL_HW) && defined(HW_NCPU)
unsigned n;
int mib[2] = {CTL_HW, HW_NCPU};
std::size_t s = sizeof(n);
sysctl(mib, 2, &n, &s, 0, 0);
return n;
#elif defined(_SC_NPROCESSORS_ONLN)
long result = sysconf(_SC_NPROCESSORS_ONLN);
// sysconf returns -1 if the name is invalid, the option does not exist or
// does not have a definite limit.
// if sysconf returns some other negative number, we have no idea
// what is going on. Default to something safe.
if (result < 0)
return 0;
return static_cast<unsigned>(result);
#elif defined(_LIBCPP_WIN32API)
SYSTEM_INFO info;
GetSystemInfo(&info);
return info.dwNumberOfProcessors;
#else // defined(CTL_HW) && defined(HW_NCPU)
// TODO: grovel through /proc or check cpuid on x86 and similar
// instructions on other architectures.
# if defined(_LIBCPP_WARNING)
_LIBCPP_WARNING("hardware_concurrency not yet implemented")
# else
# warning hardware_concurrency not yet implemented
# endif
return 0; // Means not computable [thread.thread.static]
#endif // defined(CTL_HW) && defined(HW_NCPU)
}
namespace this_thread
{
void
sleep_for(const chrono::nanoseconds& ns)
{
if (ns > chrono::nanoseconds::zero())
{
__libcpp_thread_sleep_for(ns);
}
}
} // this_thread
__thread_specific_ptr<__thread_struct>&
__thread_local_data()
{
static __thread_specific_ptr<__thread_struct> __p;
return __p;
}
// __thread_struct_imp
template <class T>
class _LIBCPP_HIDDEN __hidden_allocator
{
public:
typedef T value_type;
T* allocate(size_t __n)
{return static_cast<T*>(::operator new(__n * sizeof(T)));}
void deallocate(T* __p, size_t) {::operator delete(static_cast<void*>(__p));}
size_t max_size() const {return size_t(~0) / sizeof(T);}
};
class _LIBCPP_HIDDEN __thread_struct_imp
{
typedef vector<__assoc_sub_state*,
__hidden_allocator<__assoc_sub_state*> > _AsyncStates;
typedef vector<pair<condition_variable*, mutex*>,
__hidden_allocator<pair<condition_variable*, mutex*> > > _Notify;
_AsyncStates async_states_;
_Notify notify_;
__thread_struct_imp(const __thread_struct_imp&);
__thread_struct_imp& operator=(const __thread_struct_imp&);
public:
__thread_struct_imp() {}
~__thread_struct_imp();
void notify_all_at_thread_exit(condition_variable* cv, mutex* m);
void __make_ready_at_thread_exit(__assoc_sub_state* __s);
};
__thread_struct_imp::~__thread_struct_imp()
{
for (_Notify::iterator i = notify_.begin(), e = notify_.end();
i != e; ++i)
{
i->second->unlock();
i->first->notify_all();
}
for (_AsyncStates::iterator i = async_states_.begin(), e = async_states_.end();
i != e; ++i)
{
(*i)->__make_ready();
(*i)->__release_shared();
}
}
void
__thread_struct_imp::notify_all_at_thread_exit(condition_variable* cv, mutex* m)
{
notify_.push_back(pair<condition_variable*, mutex*>(cv, m));
}
void
__thread_struct_imp::__make_ready_at_thread_exit(__assoc_sub_state* __s)
{
async_states_.push_back(__s);
__s->__add_shared();
}
// __thread_struct
__thread_struct::__thread_struct()
: __p_(new __thread_struct_imp)
{
}
__thread_struct::~__thread_struct()
{
delete __p_;
}
void
__thread_struct::notify_all_at_thread_exit(condition_variable* cv, mutex* m)
{
__p_->notify_all_at_thread_exit(cv, m);
}
void
__thread_struct::__make_ready_at_thread_exit(__assoc_sub_state* __s)
{
__p_->__make_ready_at_thread_exit(__s);
}
_LIBCPP_END_NAMESPACE_STD
#endif // !_LIBCPP_HAS_NO_THREADS
<commit_msg>[libcxx] GNU/Hurd uses BSD-based interfaces, but does not (and won't) provide <sys/sysctl.h><commit_after>//===------------------------- thread.cpp----------------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is dual licensed under the MIT and the University of Illinois Open
// Source Licenses. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "__config"
#ifndef _LIBCPP_HAS_NO_THREADS
#include "thread"
#include "exception"
#include "vector"
#include "future"
#include "limits"
#include <sys/types.h>
#if defined(__unix__) || (defined(__APPLE__) && defined(__MACH__))
# include <sys/param.h>
# if defined(__FreeBSD__) || defined(__NetBSD__) || defined(__OpenBSD__) || defined(__DragonFly__) || defined(__APPLE__)
# include <sys/sysctl.h>
# endif
#endif // defined(__unix__) || (defined(__APPLE__) && defined(__MACH__))
#if defined(__unix__) || (defined(__APPLE__) && defined(__MACH__)) || defined(__CloudABI__) || defined(__Fuchsia__)
# include <unistd.h>
#endif // defined(__unix__) || (defined(__APPLE__) && defined(__MACH__)) || defined(__CloudABI__) || defined(__Fuchsia__)
#if defined(__NetBSD__)
#pragma weak pthread_create // Do not create libpthread dependency
#endif
#if defined(_LIBCPP_WIN32API)
#include <windows.h>
#endif
_LIBCPP_BEGIN_NAMESPACE_STD
thread::~thread()
{
if (!__libcpp_thread_isnull(&__t_))
terminate();
}
void
thread::join()
{
int ec = EINVAL;
if (!__libcpp_thread_isnull(&__t_))
{
ec = __libcpp_thread_join(&__t_);
if (ec == 0)
__t_ = _LIBCPP_NULL_THREAD;
}
if (ec)
__throw_system_error(ec, "thread::join failed");
}
void
thread::detach()
{
int ec = EINVAL;
if (!__libcpp_thread_isnull(&__t_))
{
ec = __libcpp_thread_detach(&__t_);
if (ec == 0)
__t_ = _LIBCPP_NULL_THREAD;
}
if (ec)
__throw_system_error(ec, "thread::detach failed");
}
unsigned
thread::hardware_concurrency() _NOEXCEPT
{
#if defined(CTL_HW) && defined(HW_NCPU)
unsigned n;
int mib[2] = {CTL_HW, HW_NCPU};
std::size_t s = sizeof(n);
sysctl(mib, 2, &n, &s, 0, 0);
return n;
#elif defined(_SC_NPROCESSORS_ONLN)
long result = sysconf(_SC_NPROCESSORS_ONLN);
// sysconf returns -1 if the name is invalid, the option does not exist or
// does not have a definite limit.
// if sysconf returns some other negative number, we have no idea
// what is going on. Default to something safe.
if (result < 0)
return 0;
return static_cast<unsigned>(result);
#elif defined(_LIBCPP_WIN32API)
SYSTEM_INFO info;
GetSystemInfo(&info);
return info.dwNumberOfProcessors;
#else // defined(CTL_HW) && defined(HW_NCPU)
// TODO: grovel through /proc or check cpuid on x86 and similar
// instructions on other architectures.
# if defined(_LIBCPP_WARNING)
_LIBCPP_WARNING("hardware_concurrency not yet implemented")
# else
# warning hardware_concurrency not yet implemented
# endif
return 0; // Means not computable [thread.thread.static]
#endif // defined(CTL_HW) && defined(HW_NCPU)
}
namespace this_thread
{
void
sleep_for(const chrono::nanoseconds& ns)
{
if (ns > chrono::nanoseconds::zero())
{
__libcpp_thread_sleep_for(ns);
}
}
} // this_thread
__thread_specific_ptr<__thread_struct>&
__thread_local_data()
{
static __thread_specific_ptr<__thread_struct> __p;
return __p;
}
// __thread_struct_imp
template <class T>
class _LIBCPP_HIDDEN __hidden_allocator
{
public:
typedef T value_type;
T* allocate(size_t __n)
{return static_cast<T*>(::operator new(__n * sizeof(T)));}
void deallocate(T* __p, size_t) {::operator delete(static_cast<void*>(__p));}
size_t max_size() const {return size_t(~0) / sizeof(T);}
};
class _LIBCPP_HIDDEN __thread_struct_imp
{
typedef vector<__assoc_sub_state*,
__hidden_allocator<__assoc_sub_state*> > _AsyncStates;
typedef vector<pair<condition_variable*, mutex*>,
__hidden_allocator<pair<condition_variable*, mutex*> > > _Notify;
_AsyncStates async_states_;
_Notify notify_;
__thread_struct_imp(const __thread_struct_imp&);
__thread_struct_imp& operator=(const __thread_struct_imp&);
public:
__thread_struct_imp() {}
~__thread_struct_imp();
void notify_all_at_thread_exit(condition_variable* cv, mutex* m);
void __make_ready_at_thread_exit(__assoc_sub_state* __s);
};
__thread_struct_imp::~__thread_struct_imp()
{
for (_Notify::iterator i = notify_.begin(), e = notify_.end();
i != e; ++i)
{
i->second->unlock();
i->first->notify_all();
}
for (_AsyncStates::iterator i = async_states_.begin(), e = async_states_.end();
i != e; ++i)
{
(*i)->__make_ready();
(*i)->__release_shared();
}
}
void
__thread_struct_imp::notify_all_at_thread_exit(condition_variable* cv, mutex* m)
{
notify_.push_back(pair<condition_variable*, mutex*>(cv, m));
}
void
__thread_struct_imp::__make_ready_at_thread_exit(__assoc_sub_state* __s)
{
async_states_.push_back(__s);
__s->__add_shared();
}
// __thread_struct
__thread_struct::__thread_struct()
: __p_(new __thread_struct_imp)
{
}
__thread_struct::~__thread_struct()
{
delete __p_;
}
void
__thread_struct::notify_all_at_thread_exit(condition_variable* cv, mutex* m)
{
__p_->notify_all_at_thread_exit(cv, m);
}
void
__thread_struct::__make_ready_at_thread_exit(__assoc_sub_state* __s)
{
__p_->__make_ready_at_thread_exit(__s);
}
_LIBCPP_END_NAMESPACE_STD
#endif // !_LIBCPP_HAS_NO_THREADS
<|endoftext|>
|
<commit_before>// Copyright (c) 2011 Zeex
//
// 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 <sampgdk/config.h>
#include <sampgdk/export.h>
#include <sampgdk/samp.h>
#include <set>
#include <vector>
#include "timers.h"
std::vector<Timer*> Timer::timers_;
Timer::Timer(int interval, bool repeat, TimerHandler hander, void *param)
: interval_(interval)
, repeating_(repeat)
, handler_(hander)
, param_(param)
, startTime_(GetServerTickCount())
{
}
Timer::~Timer() {
}
void Timer::Fire(int elapsedTime) {
size_t timerid = 0;
while (timerid < timers_.size()) {
if (timers_[timerid] == this) {
break;
}
}
handler_(timerid, param_);
if (repeating_) {
startTime_ = GetServerTickCount() - (elapsedTime - interval_);
}
}
int Timer::CreateTimer(int interval, bool repeat, TimerHandler handler, void *param) {
Timer *timer = new Timer(interval, repeat, handler, param);
size_t timerid = 0;
while (timerid < timers_.size()) {
if (timers_[timerid] == 0) {
timers_[timerid] = timer;
break;
}
}
if (timerid == timers_.size()) {
timers_.push_back(timer);
}
return timerid;
}
bool Timer::DestroyTimer(int timerid) {
if (timerid < 0 || timerid >= static_cast<int>(timers_.size())) {
return false;
}
Timer *timer = timers_[timerid];
delete timer;
if (timerid == timers_.size()) {
timers_.pop_back();
} else {
timers_[timerid] = 0;
}
return true;
}
void Timer::ProcessTimers() {
int time = GetServerTickCount();
for (size_t i = 0; i < timers_.size(); ++i) {
Timer *timer = timers_[i];
int elapsedTime = time - timer->GetStartTime();
if (elapsedTime >= timer->GetInterval()) {
timer->Fire(elapsedTime);
if (!timer->IsRepeating()) {
DestroyTimer(i);
}
}
}
}
SAMPGDK_EXPORT void SAMPGDK_CALL sampgdk_process_timers() {
Timer::ProcessTimers();
}
SAMPGDK_EXPORT int SAMPGDK_CALL CreateTimer(int interval, bool repeat, TimerHandler handler, void *param) {
return Timer::CreateTimer(interval, repeat, handler, param);
}
SAMPGDK_EXPORT bool SAMPGDK_CALL DestroyTimer(int timerid) {
return Timer::DestroyTimer(timerid);
}
<commit_msg>Fix infinite loop in CreateTimer and Timer::Fire<commit_after>// Copyright (c) 2011 Zeex
//
// 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 <sampgdk/config.h>
#include <sampgdk/export.h>
#include <sampgdk/samp.h>
#include <set>
#include <vector>
#include "timers.h"
std::vector<Timer*> Timer::timers_;
Timer::Timer(int interval, bool repeat, TimerHandler hander, void *param)
: interval_(interval)
, repeating_(repeat)
, handler_(hander)
, param_(param)
, startTime_(GetServerTickCount())
{
}
Timer::~Timer() {
}
void Timer::Fire(int elapsedTime) {
size_t timerid = 0;
while (timerid < timers_.size()) {
if (timers_[timerid] == this) {
break;
}
++timerid;
}
handler_(timerid, param_);
if (repeating_) {
startTime_ = GetServerTickCount() - (elapsedTime - interval_);
}
}
int Timer::CreateTimer(int interval, bool repeat, TimerHandler handler, void *param) {
Timer *timer = new Timer(interval, repeat, handler, param);
size_t timerid = 0;
while (timerid < timers_.size()) {
if (timers_[timerid] == 0) {
timers_[timerid] = timer;
break;
}
++timerid;
}
if (timerid == timers_.size()) {
timers_.push_back(timer);
}
return timerid;
}
bool Timer::DestroyTimer(int timerid) {
if (timerid < 0 || timerid >= static_cast<int>(timers_.size())) {
return false;
}
Timer *timer = timers_[timerid];
delete timer;
if (timerid == timers_.size()) {
timers_.pop_back();
} else {
timers_[timerid] = 0;
}
return true;
}
void Timer::ProcessTimers() {
int time = GetServerTickCount();
for (size_t i = 0; i < timers_.size(); ++i) {
Timer *timer = timers_[i];
int elapsedTime = time - timer->GetStartTime();
if (elapsedTime >= timer->GetInterval()) {
timer->Fire(elapsedTime);
if (!timer->IsRepeating()) {
DestroyTimer(i);
}
}
}
}
SAMPGDK_EXPORT void SAMPGDK_CALL sampgdk_process_timers() {
Timer::ProcessTimers();
}
SAMPGDK_EXPORT int SAMPGDK_CALL CreateTimer(int interval, bool repeat, TimerHandler handler, void *param) {
return Timer::CreateTimer(interval, repeat, handler, param);
}
SAMPGDK_EXPORT bool SAMPGDK_CALL DestroyTimer(int timerid) {
return Timer::DestroyTimer(timerid);
}
<|endoftext|>
|
<commit_before>#include "arc_utilities/timing.hpp"
#include <iostream>
#include <cassert>
#include <algorithm>
#include <cstdio>
using namespace arc_utilities;
double GlobalStopwatch(const StopwatchControl control)
{
static Stopwatch global_stopwatch;
return global_stopwatch(control);
}
Profiler* Profiler::m_instance = NULL;
Profiler* Profiler::getInstance()
{
if (m_instance == NULL)
{
m_instance = new Profiler();
}
return m_instance;
}
void Profiler::reset_and_preallocate(size_t num_names, size_t num_events)
{
Profiler* monitor = getInstance();
monitor->data.clear();
monitor->prealloc_buffer.resize(num_names);
for (size_t i=0; i<num_names; i++)
{
monitor->prealloc_buffer[i].reserve(num_events);
}
}
void Profiler::reset(std::string name)
{
Profiler* m = getInstance();
if(m->data.find(name) != m->data.end())
{
m->data[name].resize(0);
startTimer(name);
}
}
void Profiler::addData(std::string name, double datum)
{
Profiler* m = getInstance();
if (m->data.find(name) == m->data.end())
{
m->data[name] = std::vector<double>();
if (m->prealloc_buffer.size() > 0)
{
m->data[name].swap(m->prealloc_buffer.back());
m->prealloc_buffer.pop_back();
}
}
m->data[name].push_back(datum);
}
void Profiler::startTimer(std::string timer_name)
{
Profiler* m = getInstance();
if (m->timers.find(timer_name) == m->timers.end())
{
m->timers[timer_name] = Stopwatch();
}
m->timers[timer_name](RESET);
}
double Profiler::record(std::string timer_name)
{
Profiler* m = getInstance();
if (m->timers.find(timer_name) == m->timers.end())
{
std::cout << "Attempting to record timer \""<< timer_name <<
"\" before timer started\n";
assert(false);
}
double time_elapsed = m->timers[timer_name]();
m->addData(timer_name, time_elapsed);
return time_elapsed;
}
std::vector<double> Profiler::getData(std::string name)
{
Profiler* m = getInstance();
return m->data[name];
}
void Profiler::printSingleSummary(std::string name)
{
Profiler* m = getInstance();
std::string box = std::string(2+name.length(), '=');
std::cout << " ." << box << ". " << "\n";
std::cout << "|| " << name << " || Summary :\n";
std::cout << " '" << box << "' " << "\n";
if (m->data.find(name) == m->data.end())
{
std::cout << name << " never called\n\n";
return;
}
std::vector<double> data = m->getData(name);
size_t n = data.size();
double sum = 0;
for(auto& num : data)
{
sum += num;
}
std::cout << "total time : " << sum << " s\n";
std::cout << "called " << n << " times\n";
std::cout << "min time : " << *std::min_element(data.begin(), data.end()) << "s\n";
std::cout << "max time : " << *std::max_element(data.begin(), data.end()) << "s\n";
std::cout << "average : " << sum/(double)n << "s\n";
std::cout << "\n";
}
void Profiler::printGroupSummary(const std::vector<std::string> &names)
{
Profiler* m = getInstance();
std::cout << " .=======================. \n";
std::cout << "|| Profile Summary ||\n";
std::cout << " '=======================' \n";
std::size_t label_len = max_element(names.begin(), names.end(),
[] (const std::string &a, const std::string &b)
{return a.length() < b.length();}) -> length() + 2;
label_len = std::max(label_len, (size_t)8);
const std::string label_format = ("%-" + std::to_string(label_len) + "s");
printf(label_format.c_str(), "Label");
printf("%16s", "tot time (s)");
printf("%16s", "num_calls");
printf("%16s", "avg time (s)");
printf("\n");
std::string seperator = std::string(label_len-2, '~') + " " + std::string(12, '.')
+ " " + std::string(9, '~') + " " + std::string(12, '.');
for(const auto& name: names)
{
if(name.find("~~~~~")==0)
{
printf("%s\n", seperator.c_str());
continue;
}
printf(label_format.c_str(), name.c_str());
double tot_time = 0.0;
double avg_time = 0.0;
size_t num_calls = 0;
if(m->data.find(name) != m->data.end())
{
std::vector<double> &data = m->data[name];
tot_time = 0;
for(auto& val : data)
{
tot_time += val;
}
num_calls = data.size();
avg_time = tot_time/(double)num_calls;
}
printf(" %15f %15ld %15f\n", tot_time, num_calls, avg_time);
}
}
void Profiler::writeGroupSummary(const std::string &filename,
const std::vector<std::string> &names)
{
FILE * outfile;
outfile = std::fopen(filename.c_str(), "a");
Profiler* m = getInstance();
// std::cout << " .=======================. \n";
// std::cout << "|| Profile Summary ||\n";
// std::cout << " '=======================' \n";
std::size_t label_len = max_element(names.begin(), names.end(),
[] (const std::string &a, const std::string &b)
{return a.length() < b.length();}) -> length() + 2;
label_len = std::max(label_len, (size_t)8);
const std::string label_format = ("%-" + std::to_string(label_len) + "s");
fprintf(outfile, label_format.c_str(), "Label");
fprintf(outfile, "%16s", "tot time (s)");
fprintf(outfile, "%16s", "num_calls");
fprintf(outfile, "%16s", "avg time (s)");
fprintf(outfile, "\n");
std::string seperator = std::string(label_len-2, '~') + " " + std::string(12, '.')
+ " " + std::string(9, '~') + " " + std::string(12, '.');
for(const auto& name: names)
{
if(name.find("~~~~~")==0)
{
fprintf(outfile, "%s\n", seperator.c_str());
continue;
}
fprintf(outfile, label_format.c_str(), name.c_str());
double tot_time = 0.0;
double avg_time = 0.0;
size_t num_calls = 0;
if(m->data.find(name) != m->data.end())
{
std::vector<double> &data = m->data[name];
tot_time = 0;
for(auto& val : data)
{
tot_time += val;
}
num_calls = data.size();
avg_time = tot_time/(double)num_calls;
}
fprintf(outfile, " %15f %15ld %15f\n", tot_time, num_calls, avg_time);
}
std::fclose(outfile);
}
<commit_msg>Create file if it does not exist<commit_after>#include "arc_utilities/timing.hpp"
#include <iostream>
#include <cassert>
#include <algorithm>
#include <cstdio>
using namespace arc_utilities;
double GlobalStopwatch(const StopwatchControl control)
{
static Stopwatch global_stopwatch;
return global_stopwatch(control);
}
Profiler* Profiler::m_instance = NULL;
Profiler* Profiler::getInstance()
{
if (m_instance == NULL)
{
m_instance = new Profiler();
}
return m_instance;
}
void Profiler::reset_and_preallocate(size_t num_names, size_t num_events)
{
Profiler* monitor = getInstance();
monitor->data.clear();
monitor->prealloc_buffer.resize(num_names);
for (size_t i=0; i<num_names; i++)
{
monitor->prealloc_buffer[i].reserve(num_events);
}
}
void Profiler::reset(std::string name)
{
Profiler* m = getInstance();
if(m->data.find(name) != m->data.end())
{
m->data[name].resize(0);
startTimer(name);
}
}
void Profiler::addData(std::string name, double datum)
{
Profiler* m = getInstance();
if (m->data.find(name) == m->data.end())
{
m->data[name] = std::vector<double>();
if (m->prealloc_buffer.size() > 0)
{
m->data[name].swap(m->prealloc_buffer.back());
m->prealloc_buffer.pop_back();
}
}
m->data[name].push_back(datum);
}
void Profiler::startTimer(std::string timer_name)
{
Profiler* m = getInstance();
if (m->timers.find(timer_name) == m->timers.end())
{
m->timers[timer_name] = Stopwatch();
}
m->timers[timer_name](RESET);
}
double Profiler::record(std::string timer_name)
{
Profiler* m = getInstance();
if (m->timers.find(timer_name) == m->timers.end())
{
std::cout << "Attempting to record timer \""<< timer_name <<
"\" before timer started\n";
assert(false);
}
double time_elapsed = m->timers[timer_name]();
m->addData(timer_name, time_elapsed);
return time_elapsed;
}
std::vector<double> Profiler::getData(std::string name)
{
Profiler* m = getInstance();
return m->data[name];
}
void Profiler::printSingleSummary(std::string name)
{
Profiler* m = getInstance();
std::string box = std::string(2+name.length(), '=');
std::cout << " ." << box << ". " << "\n";
std::cout << "|| " << name << " || Summary :\n";
std::cout << " '" << box << "' " << "\n";
if (m->data.find(name) == m->data.end())
{
std::cout << name << " never called\n\n";
return;
}
std::vector<double> data = m->getData(name);
size_t n = data.size();
double sum = 0;
for(auto& num : data)
{
sum += num;
}
std::cout << "total time : " << sum << " s\n";
std::cout << "called " << n << " times\n";
std::cout << "min time : " << *std::min_element(data.begin(), data.end()) << "s\n";
std::cout << "max time : " << *std::max_element(data.begin(), data.end()) << "s\n";
std::cout << "average : " << sum/(double)n << "s\n";
std::cout << "\n";
}
void Profiler::printGroupSummary(const std::vector<std::string> &names)
{
Profiler* m = getInstance();
std::cout << " .=======================. \n";
std::cout << "|| Profile Summary ||\n";
std::cout << " '=======================' \n";
std::size_t label_len = max_element(names.begin(), names.end(),
[] (const std::string &a, const std::string &b)
{return a.length() < b.length();}) -> length() + 2;
label_len = std::max(label_len, (size_t)8);
const std::string label_format = ("%-" + std::to_string(label_len) + "s");
printf(label_format.c_str(), "Label");
printf("%16s", "tot time (s)");
printf("%16s", "num_calls");
printf("%16s", "avg time (s)");
printf("\n");
std::string seperator = std::string(label_len-2, '~') + " " + std::string(12, '.')
+ " " + std::string(9, '~') + " " + std::string(12, '.');
for(const auto& name: names)
{
if(name.find("~~~~~")==0)
{
printf("%s\n", seperator.c_str());
continue;
}
printf(label_format.c_str(), name.c_str());
double tot_time = 0.0;
double avg_time = 0.0;
size_t num_calls = 0;
if(m->data.find(name) != m->data.end())
{
std::vector<double> &data = m->data[name];
tot_time = 0;
for(auto& val : data)
{
tot_time += val;
}
num_calls = data.size();
avg_time = tot_time/(double)num_calls;
}
printf(" %15f %15ld %15f\n", tot_time, num_calls, avg_time);
}
}
void Profiler::writeGroupSummary(const std::string &filename,
const std::vector<std::string> &names)
{
FILE * outfile;
outfile = std::fopen(filename.c_str(), "a+");
Profiler* m = getInstance();
// std::cout << " .=======================. \n";
// std::cout << "|| Profile Summary ||\n";
// std::cout << " '=======================' \n";
std::size_t label_len = max_element(names.begin(), names.end(),
[] (const std::string &a, const std::string &b)
{return a.length() < b.length();}) -> length() + 2;
label_len = std::max(label_len, (size_t)8);
const std::string label_format = ("%-" + std::to_string(label_len) + "s");
fprintf(outfile, label_format.c_str(), "Label");
fprintf(outfile, "%16s", "tot time (s)");
fprintf(outfile, "%16s", "num_calls");
fprintf(outfile, "%16s", "avg time (s)");
fprintf(outfile, "\n");
std::string seperator = std::string(label_len-2, '~') + " " + std::string(12, '.')
+ " " + std::string(9, '~') + " " + std::string(12, '.');
for(const auto& name: names)
{
if(name.find("~~~~~")==0)
{
fprintf(outfile, "%s\n", seperator.c_str());
continue;
}
fprintf(outfile, label_format.c_str(), name.c_str());
double tot_time = 0.0;
double avg_time = 0.0;
size_t num_calls = 0;
if(m->data.find(name) != m->data.end())
{
std::vector<double> &data = m->data[name];
tot_time = 0;
for(auto& val : data)
{
tot_time += val;
}
num_calls = data.size();
avg_time = tot_time/(double)num_calls;
}
fprintf(outfile, " %15f %15ld %15f\n", tot_time, num_calls, avg_time);
}
std::fclose(outfile);
}
<|endoftext|>
|
<commit_before>#include "vision.hpp"
#include "operators.hpp"
#include <QTemporaryFile>
#include <iomanip>
#include <iostream>
#include <sstream>
vision::vision (QStatusBar& statusbar, augmentation_widget& augmentation, QObject* parent)
: QObject (parent)
, _movement3d_average (1)
, _failed_frames_counter (0)
, _debug_mode (0)
, _augmentation (augmentation)
, _cam (new QCamera (QCamera::BackFace))
, _video_player (NULL)
, _acquisition (this)
, _operators ()
, _statusbar (statusbar) {
_cam->setViewfinder (&_acquisition);
connect (&_acquisition, SIGNAL (frameAvailable (const QVideoFrame&)), this,
SLOT (frame_callback (const QVideoFrame&)));
_cam->start ();
}
void vision::set_debug_mode (const int mode) {
_debug_mode = mode;
}
int vision::debug_mode () {
return _debug_mode;
}
void vision::set_input (const QCameraInfo& cameraInfo) {
if (_video_player != NULL) {
delete _video_player;
}
_video_player = NULL;
if (_cam != NULL) {
delete _cam;
}
_cam = new QCamera (cameraInfo);
_cam->setViewfinder (&_acquisition);
_cam->start ();
if (_cam->status () != QCamera::ActiveStatus) {
_statusbar.showMessage (QString ("camera status %1").arg (_cam->status ()), 2000);
}
}
void vision::set_input (const QString& resource_path) {
QFile resource_file (resource_path);
if (resource_file.exists ()) {
auto temp_file = QTemporaryFile::createNativeFile (resource_file);
QString fs_path = temp_file->fileName ();
if (!fs_path.isEmpty ()) {
if (_cam != NULL) {
delete _cam;
}
_cam = NULL;
if (_video_player != NULL) {
delete _video_player;
}
_video_player = new QMediaPlayer ();
_video_player->setVideoOutput (&_acquisition);
_video_player->setMedia (QUrl::fromLocalFile (fs_path));
_video_player->play ();
}
}
}
void vision::set_paused (bool paused) {
if (paused) {
disconnect (&_acquisition, SIGNAL (frameAvailable (const QVideoFrame&)),
this, SLOT (frame_callback (const QVideoFrame&)));
} else {
connect (&_acquisition, SIGNAL (frameAvailable (const QVideoFrame&)),
this, SLOT (frame_callback (const QVideoFrame&)));
}
}
void set_focus () {
; // TODO: add focus implementation
}
void vision::set_reference () {
_markers_mutex.lock ();
_reference = _markers;
_markers_mutex.unlock ();
}
void vision::frame_callback (const QVideoFrame& const_buffer) {
bool status = true;
image_t image;
if (const_buffer.isValid ()) {
// copy image into cpu memory
QVideoFrame frame (const_buffer);
if (frame.map (QAbstractVideoBuffer::ReadOnly)) {
image.data = (uint8_t*)malloc (frame.mappedBytes ());
memcpy (image.data, frame.bits (), frame.mappedBytes ());
if (frame.pixelFormat () == QVideoFrame::Format_RGB24) {
image.format = RGB24;
image.width = frame.width ();
image.height = frame.height ();
} else if (frame.pixelFormat () == QVideoFrame::Format_YUV420P) {
image.format = YUV;
image.width = frame.width ();
image.height = frame.height ();
} else {
_statusbar.showMessage (
QString ("unsuported format %1").arg (frame.pixelFormat ()), 2000);
}
} else {
status = false;
}
frame.unmap ();
}
if (status) {
if (_debug_mode == 0) {
_augmentation.setBackground (image);
_augmentation.update ();
}
// start image processing
_operators.preprocessing (image);
if (_debug_mode == 1) {
_augmentation.setBackground (image);
_augmentation.update ();
}
_operators.segmentation (image);
if (_debug_mode == 2) {
_augmentation.setBackground (image);
_augmentation.update ();
}
_markers_mutex.lock ();
_markers.clear ();
_operators.extraction (image, _markers);
if (_debug_mode == 3) {
_augmentation.setBackground (image);
_augmentation.update ();
}
movement3d movement;
_operators.classification (_reference, _markers, movement); // classify
_markers_mutex.unlock ();
movement = _movement3d_average.average (movement);
_augmentation.setScale (movement.scale ());
translation_t translation = movement.translation ();
movement.translation (
{ movement.translation_delta_to_absolute (translation.x, image.width, -1, 1),
movement.translation_delta_to_absolute (translation.y, image.height, -1, 1) });
_augmentation.setXPosition (movement.translation ().x);
_augmentation.setYPosition (movement.translation ().y);
_augmentation.setYRotation (movement.yaw ());
_augmentation.setZRotation (movement.roll ());
_augmentation.setXRotation ((movement.pitch ()) - 90);
std::cout << movement << std::endl;
std::stringstream stream;
stream << std::setprecision (2);
// stream << "T(" << movement.translation ().x << ","
// << movement.translation ().y << ") ";
stream << "S: " << movement.scale () << " ";
stream << "yaw: " << movement.yaw () << " ";
stream << "pitch: " << movement.pitch () << " ";
stream << "roll: " << movement.roll () << std::endl;
_statusbar.showMessage (stream.str ().c_str ());
QImage debug_image ((const unsigned char*)image.data, image.width,
image.height, QImage::Format_Grayscale8);
debug_image.save ("debug_image.png");
delete image.data;
}
}
<commit_msg>fix error handling when not enough markers are found<commit_after>#include "vision.hpp"
#include "operators.hpp"
#include <QTemporaryFile>
#include <iomanip>
#include <iostream>
#include <sstream>
vision::vision (QStatusBar& statusbar, augmentation_widget& augmentation, QObject* parent)
: QObject (parent)
, _movement3d_average (1)
, _failed_frames_counter (0)
, _debug_mode (0)
, _augmentation (augmentation)
, _cam (new QCamera (QCamera::BackFace))
, _video_player (NULL)
, _acquisition (this)
, _operators ()
, _statusbar (statusbar) {
_cam->setViewfinder (&_acquisition);
connect (&_acquisition, SIGNAL (frameAvailable (const QVideoFrame&)), this,
SLOT (frame_callback (const QVideoFrame&)));
_cam->start ();
}
void vision::set_debug_mode (const int mode) {
_debug_mode = mode;
}
int vision::debug_mode () {
return _debug_mode;
}
void vision::set_input (const QCameraInfo& cameraInfo) {
if (_video_player != NULL) {
delete _video_player;
}
_video_player = NULL;
if (_cam != NULL) {
delete _cam;
}
_cam = new QCamera (cameraInfo);
_cam->setViewfinder (&_acquisition);
_cam->start ();
if (_cam->status () != QCamera::ActiveStatus) {
_statusbar.showMessage (QString ("camera status %1").arg (_cam->status ()), 2000);
}
}
void vision::set_input (const QString& resource_path) {
QFile resource_file (resource_path);
if (resource_file.exists ()) {
auto temp_file = QTemporaryFile::createNativeFile (resource_file);
QString fs_path = temp_file->fileName ();
if (!fs_path.isEmpty ()) {
if (_cam != NULL) {
delete _cam;
}
_cam = NULL;
if (_video_player != NULL) {
delete _video_player;
}
_video_player = new QMediaPlayer ();
_video_player->setVideoOutput (&_acquisition);
_video_player->setMedia (QUrl::fromLocalFile (fs_path));
_video_player->play ();
}
}
}
void vision::set_paused (bool paused) {
if (paused) {
disconnect (&_acquisition, SIGNAL (frameAvailable (const QVideoFrame&)),
this, SLOT (frame_callback (const QVideoFrame&)));
} else {
connect (&_acquisition, SIGNAL (frameAvailable (const QVideoFrame&)),
this, SLOT (frame_callback (const QVideoFrame&)));
}
}
void set_focus () {
; // TODO: add focus implementation
}
void vision::set_reference () {
_markers_mutex.lock ();
_reference = _markers;
_markers_mutex.unlock ();
}
void vision::frame_callback (const QVideoFrame& const_buffer) {
bool status = true;
image_t image;
if (const_buffer.isValid ()) {
// copy image into cpu memory
QVideoFrame frame (const_buffer);
if (frame.map (QAbstractVideoBuffer::ReadOnly)) {
image.data = (uint8_t*)malloc (frame.mappedBytes ());
memcpy (image.data, frame.bits (), frame.mappedBytes ());
if (frame.pixelFormat () == QVideoFrame::Format_RGB24) {
image.format = RGB24;
image.width = frame.width ();
image.height = frame.height ();
} else if (frame.pixelFormat () == QVideoFrame::Format_YUV420P) {
image.format = YUV;
image.width = frame.width ();
image.height = frame.height ();
} else {
_statusbar.showMessage (
QString ("unsuported format %1").arg (frame.pixelFormat ()), 2000);
}
} else {
status = false;
}
frame.unmap ();
}
if (status) {
if (_debug_mode == 0) {
_augmentation.setBackground (image);
_augmentation.update ();
}
// start image processing
_operators.preprocessing (image);
if (_debug_mode == 1) {
_augmentation.setBackground (image);
_augmentation.update ();
}
_operators.segmentation (image);
if (_debug_mode == 2) {
_augmentation.setBackground (image);
_augmentation.update ();
}
_markers_mutex.lock ();
_markers.clear ();
_operators.extraction (image, _markers);
if (_debug_mode == 3) {
_augmentation.setBackground (image);
_augmentation.update ();
}
movement3d movement;
bool clasified = _operators.classification (_reference, _markers, movement); // classify
if (clasified) {
_markers_mutex.unlock ();
movement = _movement3d_average.average (movement);
_augmentation.setScale (movement.scale ());
translation_t translation = movement.translation ();
movement.translation (
{ movement.translation_delta_to_absolute (translation.x, image.width, -1, 1),
movement.translation_delta_to_absolute (translation.y, image.height, -1, 1) });
_augmentation.setXPosition (movement.translation ().x);
_augmentation.setYPosition (movement.translation ().y);
_augmentation.setYRotation (movement.yaw ());
_augmentation.setZRotation (movement.roll ());
_augmentation.setXRotation ((movement.pitch ()) - 90);
std::cout << movement << std::endl;
std::stringstream stream;
stream << std::setprecision (2);
// stream << "T(" << movement.translation ().x << ","
// << movement.translation ().y << ") ";
stream << "S: " << movement.scale () << " ";
stream << "yaw: " << movement.yaw () << " ";
stream << "pitch: " << movement.pitch () << " ";
stream << "roll: " << movement.roll () << std::endl;
_statusbar.showMessage (stream.str ().c_str ());
} else {
_statusbar.showMessage ("No markers! You idiot...");
}
QImage debug_image ((const unsigned char*)image.data, image.width,
image.height, QImage::Format_Grayscale8);
debug_image.save ("debug_image.png");
delete image.data;
}
}
<|endoftext|>
|
<commit_before>/*!
* @file window.cpp
*
* @brief Window class source file
*/
#include <algorithm>
#include "window.hpp"
#include "spoa/spoa.hpp"
namespace racon {
std::shared_ptr<Window> createWindow(uint64_t id, uint32_t rank, WindowType type,
const char* backbone, uint32_t backbone_length, const char* quality,
uint32_t quality_length) {
if (backbone_length == 0 || backbone_length != quality_length) {
fprintf(stderr, "[racon::createWindow] error: "
"empty backbone sequence/unequal quality length!\n");
exit(1);
}
return std::shared_ptr<Window>(new Window(id, rank, type, backbone,
backbone_length, quality, quality_length));
}
Window::Window(uint64_t id, uint32_t rank, WindowType type, const char* backbone,
uint32_t backbone_length, const char* quality, uint32_t quality_length)
: id_(id), rank_(rank), type_(type), consensus_(), sequences_(),
qualities_(), positions_() {
sequences_.emplace_back(backbone, backbone_length);
qualities_.emplace_back(quality, quality_length);
positions_.emplace_back(0, 0);
}
Window::~Window() {
}
void Window::add_layer(const char* sequence, uint32_t sequence_length,
const char* quality, uint32_t quality_length, uint32_t begin, uint32_t end) {
if (quality != nullptr && sequence_length != quality_length) {
fprintf(stderr, "[racon::Window::add_layer] error: "
"unequal quality size!\n");
exit(1);
}
if (begin >= end || begin > sequences_.front().second || end > sequences_.front().second) {
fprintf(stderr, "[racon::Window::add_layer] error: "
"layer begin and end positions are invalid!\n");
exit(1);
}
sequences_.emplace_back(sequence, sequence_length);
qualities_.emplace_back(quality, quality_length);
positions_.emplace_back(begin, end);
}
bool Window::generate_consensus(std::shared_ptr<spoa::AlignmentEngine> alignment_engine) {
if (sequences_.size() < 3) {
consensus_ = std::string(sequences_.front().first, sequences_.front().second);
return false;
}
auto graph = spoa::createGraph();
graph->add_alignment(spoa::Alignment(), sequences_.front().first,
sequences_.front().second, qualities_.front().first,
qualities_.front().second);
std::vector<uint32_t> rank;
rank.reserve(sequences_.size());
for (uint32_t i = 0; i < sequences_.size(); ++i) {
rank.emplace_back(i);
}
std::sort(rank.begin() + 1, rank.end(), [&](uint32_t lhs, uint32_t rhs) {
return positions_[lhs].first < positions_[rhs].first; });
uint32_t offset = 0.01 * sequences_.front().second;
for (uint32_t i = 1; i < sequences_.size(); ++i) {
//uint32_t i = rank[j];
spoa::Alignment alignment;
//if (positions_[i].first < offset && positions_[i].second >
// sequences_.front().second - offset) {
alignment = alignment_engine->align_sequence_with_graph(
sequences_[i].first, sequences_[i].second, graph);
//} else {
// std::vector<int32_t> mapping;
// auto subgraph = graph->subgraph(positions_[i].first,
// positions_[i].second, mapping);
// alignment = alignment_engine->align_sequence_with_graph(
// sequences_[i].first, sequences_[i].second, subgraph);
// subgraph->update_alignment(alignment, mapping);
//}
if (qualities_[i].first == nullptr) {
graph->add_alignment(alignment, sequences_[i].first,
sequences_[i].second);
} else {
graph->add_alignment(alignment, sequences_[i].first,
sequences_[i].second, qualities_[i].first,
qualities_[i].second);
}
}
std::vector<uint32_t> coverages;
consensus_ = graph->generate_consensus(coverages);
if (type_ == WindowType::kTGS) {
uint32_t average_coverage = (sequences_.size() - 1) / 2;
int32_t begin = 0, end = consensus_.size() - 1;
for (; begin < static_cast<int32_t>(consensus_.size()); ++begin) {
if (coverages[begin] >= average_coverage) {
break;
}
}
for (; end >= 0; --end) {
if (coverages[end] >= average_coverage) {
break;
}
}
if (begin >= end) {
fprintf(stderr, "[racon::Window::generate_consensus] warning: "
"contig %lu might be chimeric in window %u!\n", id_, rank_);
} else {
//consensus_ = consensus_.substr(begin, end - begin + 1);
}
}
return true;
}
}
<commit_msg>undid commenting out of line<commit_after>/*!
* @file window.cpp
*
* @brief Window class source file
*/
#include <algorithm>
#include "window.hpp"
#include "spoa/spoa.hpp"
namespace racon {
std::shared_ptr<Window> createWindow(uint64_t id, uint32_t rank, WindowType type,
const char* backbone, uint32_t backbone_length, const char* quality,
uint32_t quality_length) {
if (backbone_length == 0 || backbone_length != quality_length) {
fprintf(stderr, "[racon::createWindow] error: "
"empty backbone sequence/unequal quality length!\n");
exit(1);
}
return std::shared_ptr<Window>(new Window(id, rank, type, backbone,
backbone_length, quality, quality_length));
}
Window::Window(uint64_t id, uint32_t rank, WindowType type, const char* backbone,
uint32_t backbone_length, const char* quality, uint32_t quality_length)
: id_(id), rank_(rank), type_(type), consensus_(), sequences_(),
qualities_(), positions_() {
sequences_.emplace_back(backbone, backbone_length);
qualities_.emplace_back(quality, quality_length);
positions_.emplace_back(0, 0);
}
Window::~Window() {
}
void Window::add_layer(const char* sequence, uint32_t sequence_length,
const char* quality, uint32_t quality_length, uint32_t begin, uint32_t end) {
if (quality != nullptr && sequence_length != quality_length) {
fprintf(stderr, "[racon::Window::add_layer] error: "
"unequal quality size!\n");
exit(1);
}
if (begin >= end || begin > sequences_.front().second || end > sequences_.front().second) {
fprintf(stderr, "[racon::Window::add_layer] error: "
"layer begin and end positions are invalid!\n");
exit(1);
}
sequences_.emplace_back(sequence, sequence_length);
qualities_.emplace_back(quality, quality_length);
positions_.emplace_back(begin, end);
}
bool Window::generate_consensus(std::shared_ptr<spoa::AlignmentEngine> alignment_engine) {
if (sequences_.size() < 3) {
consensus_ = std::string(sequences_.front().first, sequences_.front().second);
return false;
}
auto graph = spoa::createGraph();
graph->add_alignment(spoa::Alignment(), sequences_.front().first,
sequences_.front().second, qualities_.front().first,
qualities_.front().second);
std::vector<uint32_t> rank;
rank.reserve(sequences_.size());
for (uint32_t i = 0; i < sequences_.size(); ++i) {
rank.emplace_back(i);
}
std::sort(rank.begin() + 1, rank.end(), [&](uint32_t lhs, uint32_t rhs) {
return positions_[lhs].first < positions_[rhs].first; });
uint32_t offset = 0.01 * sequences_.front().second;
for (uint32_t i = 1; i < sequences_.size(); ++i) {
//uint32_t i = rank[j];
spoa::Alignment alignment;
//if (positions_[i].first < offset && positions_[i].second >
// sequences_.front().second - offset) {
alignment = alignment_engine->align_sequence_with_graph(
sequences_[i].first, sequences_[i].second, graph);
//} else {
// std::vector<int32_t> mapping;
// auto subgraph = graph->subgraph(positions_[i].first,
// positions_[i].second, mapping);
// alignment = alignment_engine->align_sequence_with_graph(
// sequences_[i].first, sequences_[i].second, subgraph);
// subgraph->update_alignment(alignment, mapping);
//}
if (qualities_[i].first == nullptr) {
graph->add_alignment(alignment, sequences_[i].first,
sequences_[i].second);
} else {
graph->add_alignment(alignment, sequences_[i].first,
sequences_[i].second, qualities_[i].first,
qualities_[i].second);
}
}
std::vector<uint32_t> coverages;
consensus_ = graph->generate_consensus(coverages);
if (type_ == WindowType::kTGS) {
uint32_t average_coverage = (sequences_.size() - 1) / 2;
int32_t begin = 0, end = consensus_.size() - 1;
for (; begin < static_cast<int32_t>(consensus_.size()); ++begin) {
if (coverages[begin] >= average_coverage) {
break;
}
}
for (; end >= 0; --end) {
if (coverages[end] >= average_coverage) {
break;
}
}
if (begin >= end) {
fprintf(stderr, "[racon::Window::generate_consensus] warning: "
"contig %lu might be chimeric in window %u!\n", id_, rank_);
} else {
consensus_ = consensus_.substr(begin, end - begin + 1);
}
}
return true;
}
}
<|endoftext|>
|
<commit_before>/*********************************
** Tsunagari Tile Engine **
** window.cpp **
** Copyright 2011-2012 OmegaSDG **
*********************************/
#include <Gosu/Graphics.hpp> // for Gosu::Graphics
#include <Gosu/Timing.hpp>
#include <Gosu/Utility.hpp>
#include "config.h"
#include "resourcer.h"
#include "world.h"
#include "window.h"
static GameWindow* globalWindow = NULL;
const GameWindow& GameWindow::getWindow()
{
return *globalWindow;
}
GameWindow::GameWindow(ClientValues* conf)
: Gosu::Window((unsigned)conf->windowSize.x,
(unsigned)conf->windowSize.y, conf->fullscreen),
lastTime((int)Gosu::milliseconds()),
now(lastTime),
currentSecond(now/1000),
conf(conf)
{
globalWindow = this;
}
GameWindow::~GameWindow()
{
}
bool GameWindow::init(char** argv)
{
rc.reset(new Resourcer(this, conf));
world.reset(new World(this, rc.get(), conf));
return rc->init(argv) && world->init();
}
int GameWindow::width() const
{
return (int)graphics().width();
}
int GameWindow::height() const
{
return (int)graphics().height();
}
void GameWindow::buttonDown(const Gosu::Button btn)
{
now = (int)Gosu::milliseconds();
if (btn == Gosu::kbEscape)
close();
else {
if (keystates.find(btn) == keystates.end()) {
keystate& state = keystates[btn];
state.since = now;
state.initiallyResolved = false;
state.consecutive = false;
// We process the initial buttonDown here so that it
// gets handled even if we receive a buttonUp before an
// update.
world->buttonDown(btn);
}
}
}
void GameWindow::buttonUp(const Gosu::Button btn)
{
keystates.erase(btn);
world->buttonUp(btn);
}
void GameWindow::draw()
{
world->draw();
}
bool GameWindow::needsRedraw() const
{
return world->needsRedraw();
}
void GameWindow::update()
{
calculateDt();
if (conf->moveMode == TURN)
handleKeyboardInput();
world->update(dt);
// Run once per second.
if (now/1000 > currentSecond) {
currentSecond = now/1000;
rc->garbageCollect();
}
}
int GameWindow::time() const
{
return now;
}
void GameWindow::calculateDt()
{
now = (int)Gosu::milliseconds();
dt = now - lastTime;
lastTime = now;
}
void GameWindow::handleKeyboardInput()
{
std::map<Gosu::Button, keystate>::iterator it;
// Persistent input handling code
for (it = keystates.begin(); it != keystates.end(); it++) {
Gosu::Button btn = it->first;
keystate& state = it->second;
// If there is PERSIST_DELAY_CONSECUTIVE milliseconds of latency
// between when a button is depressed and when we first look at
// it here, we'll incorrectly try to fire off a second round of
// input.
// This can happen if an intermediary function blocks the thread
// for a while.
if (!state.initiallyResolved) {
state.initiallyResolved = true;
continue;
}
int delay = state.consecutive ?
ROGUELIKE_PERSIST_DELAY_CONSECUTIVE : ROGUELIKE_PERSIST_DELAY_INIT;
if (now >= state.since + delay) {
state.since = now;
world->buttonDown(btn);
state.consecutive = true;
}
}
}
<commit_msg>fix Gosu's faux fullscreen aspect ratio<commit_after>/*********************************
** Tsunagari Tile Engine **
** window.cpp **
** Copyright 2011-2012 OmegaSDG **
*********************************/
#include <Gosu/Graphics.hpp> // for Gosu::Graphics
#include <Gosu/Timing.hpp>
#include <Gosu/Utility.hpp>
#include "config.h"
#include "resourcer.h"
#include "world.h"
#include "window.h"
static GameWindow* globalWindow = NULL;
const GameWindow& GameWindow::getWindow()
{
return *globalWindow;
}
GameWindow::GameWindow(ClientValues* conf)
// Gosu emulates the requested screen resolution on fullscreen,
// but this breaks our aspect ratio-correcting letterbox.
// Ergo we just make a window the size of the screen.
: Gosu::Window(
conf->fullscreen ? Gosu::screenWidth() :
(unsigned)conf->windowSize.x,
conf->fullscreen ? Gosu::screenHeight() :
(unsigned)conf->windowSize.y,
conf->fullscreen
),
lastTime((int)Gosu::milliseconds()),
now(lastTime),
currentSecond(now/1000),
conf(conf)
{
globalWindow = this;
}
GameWindow::~GameWindow()
{
}
bool GameWindow::init(char** argv)
{
rc.reset(new Resourcer(this, conf));
world.reset(new World(this, rc.get(), conf));
return rc->init(argv) && world->init();
}
int GameWindow::width() const
{
return (int)graphics().width();
}
int GameWindow::height() const
{
return (int)graphics().height();
}
void GameWindow::buttonDown(const Gosu::Button btn)
{
now = (int)Gosu::milliseconds();
if (btn == Gosu::kbEscape)
close();
else {
if (keystates.find(btn) == keystates.end()) {
keystate& state = keystates[btn];
state.since = now;
state.initiallyResolved = false;
state.consecutive = false;
// We process the initial buttonDown here so that it
// gets handled even if we receive a buttonUp before an
// update.
world->buttonDown(btn);
}
}
}
void GameWindow::buttonUp(const Gosu::Button btn)
{
keystates.erase(btn);
world->buttonUp(btn);
}
void GameWindow::draw()
{
world->draw();
}
bool GameWindow::needsRedraw() const
{
return world->needsRedraw();
}
void GameWindow::update()
{
calculateDt();
if (conf->moveMode == TURN)
handleKeyboardInput();
world->update(dt);
// Run once per second.
if (now/1000 > currentSecond) {
currentSecond = now/1000;
rc->garbageCollect();
}
}
int GameWindow::time() const
{
return now;
}
void GameWindow::calculateDt()
{
now = (int)Gosu::milliseconds();
dt = now - lastTime;
lastTime = now;
}
void GameWindow::handleKeyboardInput()
{
std::map<Gosu::Button, keystate>::iterator it;
// Persistent input handling code
for (it = keystates.begin(); it != keystates.end(); it++) {
Gosu::Button btn = it->first;
keystate& state = it->second;
// If there is PERSIST_DELAY_CONSECUTIVE milliseconds of latency
// between when a button is depressed and when we first look at
// it here, we'll incorrectly try to fire off a second round of
// input.
// This can happen if an intermediary function blocks the thread
// for a while.
if (!state.initiallyResolved) {
state.initiallyResolved = true;
continue;
}
int delay = state.consecutive ?
ROGUELIKE_PERSIST_DELAY_CONSECUTIVE : ROGUELIKE_PERSIST_DELAY_INIT;
if (now >= state.since + delay) {
state.since = now;
world->buttonDown(btn);
state.consecutive = true;
}
}
}
<|endoftext|>
|
<commit_before>// This file is a part of the OpenSurgSim project.
// Copyright 2013, SimQuest Solutions Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "SurgSim/Devices/LabJack/LabJackDevice.h"
#include "SurgSim/Devices/LabJack/LabJackScaffold.h"
#include "SurgSim/Framework/Log.h"
namespace SurgSim
{
namespace Device
{
LabJackDevice::LabJackDevice(const std::string& uniqueName) :
SurgSim::Input::CommonDevice(uniqueName, LabJackScaffold::buildDeviceInputData()),
m_model(LabJack::MODEL_SEARCH),
m_connection(LabJack::CONNECTION_SEARCH),
m_address(""),
m_timerBase(LabJack::TIMERBASE_DEFAULT),
m_timerClockDivisor(1),
m_timerCounterPinOffset(0),
m_threadRate(1000.0),
m_analogInputResolution(0),
m_analogInputSettling(0)
{
}
LabJackDevice::~LabJackDevice()
{
if (isInitialized())
{
finalize();
}
}
bool LabJackDevice::initialize()
{
SURGSIM_ASSERT(!isInitialized()) << "LabJackDevice already initialized.";
if (getDigitalOutputs().size() > 0)
{
SURGSIM_ASSERT(hasOutputProducer()) << "LabJackDevice named " << getName() <<
" has digital output channels. An output producer is required, call setOutputProducer.";
}
if (getAnalogOutputs().size() > 0)
{
SURGSIM_ASSERT(hasOutputProducer()) << "LabJackDevice named " << getName() <<
" has analog output channels. An output producer is required, call setOutputProducer.";
}
if (getTimers().size() > 0)
{
SURGSIM_ASSERT(hasOutputProducer()) << "LabJackDevice named " << getName() <<
" has timers. An output producer is required, call setOutputProducer.";
}
std::shared_ptr<LabJackScaffold> scaffold = LabJackScaffold::getOrCreateSharedInstance();
SURGSIM_ASSERT(scaffold) << "LabJackDevice failed to get a LabJackScaffold.";
bool found = false;
// registerDevice will set this object's type and/or connection, if they are currently set to SEARCH.
if (scaffold->registerDevice(this))
{
m_scaffold = std::move(scaffold);
SURGSIM_LOG_INFO(m_scaffold->getLogger()) << "Device " << getName() << ": Initialized.";
found = true;
}
return found;
}
bool LabJackDevice::finalize()
{
SURGSIM_ASSERT(isInitialized()) << "LabJackDevice has not been initialized before finalize.";
SURGSIM_LOG_INFO(m_scaffold->getLogger()) << "Device " << getName() << ": " << "Finalizing.";
const bool ok = m_scaffold->unregisterDevice(this);
m_scaffold.reset();
return ok;
}
bool LabJackDevice::isInitialized() const
{
return (m_scaffold != nullptr);
}
void LabJackDevice::setModel(LabJack::Model model)
{
SURGSIM_ASSERT(!isInitialized()) << "LabJackDevice's model cannot be set after it is initialized.";
m_model = model;
}
LabJack::Model LabJackDevice::getModel() const
{
return m_model;
}
void LabJackDevice::setConnection(LabJack::Connection connection)
{
SURGSIM_ASSERT(!isInitialized()) << "LabJackDevice's connection cannot be set after it is initialized.";
m_connection = connection;
}
LabJack::Connection LabJackDevice::getConnection() const
{
return m_connection;
}
void LabJackDevice::setAddress(std::string address)
{
SURGSIM_ASSERT(!isInitialized()) << "LabJackDevice's address cannot be set after it is initialized.";
m_address = address;
}
const std::string& LabJackDevice::getAddress() const
{
return m_address;
}
void LabJackDevice::enableDigitalInput(int channel)
{
SURGSIM_ASSERT(!isInitialized()) << "Digital input cannot be enabled for a LabJackDevice after it is initialized.";
m_digitalInputChannels.insert(channel);
}
const std::unordered_set<int>& LabJackDevice::getDigitalInputs() const
{
return m_digitalInputChannels;
}
void LabJackDevice::enableDigitalOutput(int channel)
{
SURGSIM_ASSERT(!isInitialized()) << "Digital output cannot be enabled for a LabJackDevice after it is initialized.";
m_digitalOutputChannels.insert(channel);
}
const std::unordered_set<int>& LabJackDevice::getDigitalOutputs() const
{
return m_digitalOutputChannels;
}
void LabJackDevice::setTimerBase(LabJack::TimerBase base)
{
SURGSIM_ASSERT(!isInitialized()) << "LabJackDevice's timer base cannot be set after it is initialized.";
m_timerBase = base;
}
LabJack::TimerBase LabJackDevice::getTimerBase() const
{
return m_timerBase;
}
void LabJackDevice::setTimerClockDivisor(int divisor)
{
SURGSIM_ASSERT(!isInitialized()) << "LabJackDevice's timer clock divisor cannot be set after it is initialized.";
m_timerClockDivisor = divisor;
}
int LabJackDevice::getTimerClockDivisor() const
{
return m_timerClockDivisor;
}
void LabJackDevice::setTimerCounterPinOffset(int offset)
{
SURGSIM_ASSERT(!isInitialized()) <<
"LabJackDevice's timer/counter pin offset cannot be set after it is initialized.";
m_timerCounterPinOffset = offset;
}
int LabJackDevice::getTimerCounterPinOffset() const
{
return m_timerCounterPinOffset;
}
void LabJackDevice::enableTimer(int index, LabJack::TimerMode mode)
{
SURGSIM_ASSERT(!isInitialized()) << "Timers cannot be enabled for a LabJackDevice after it is initialized.";
m_timers[index] = mode;
}
const std::unordered_map<int, LabJack::TimerMode>& LabJackDevice::getTimers() const
{
return m_timers;
}
void LabJackDevice::setMaximumUpdateRate(double rate)
{
SURGSIM_ASSERT(!isInitialized()) <<
"LabJackDevice's maximum update rate cannot be set after it is initialized.";
m_threadRate = rate;
}
double LabJackDevice::getMaximumUpdateRate() const
{
return m_threadRate;
}
void LabJackDevice::enableAnalogInput(int positiveChannel, LabJack::Range range, int negativeChannel)
{
SURGSIM_ASSERT(!isInitialized()) <<
"Analog inputs cannot be enabled for a LabJackDevice after it is initialized.";
LabJack::RangeAndOptionalNegativeChannel rangeAndOptionalNegativeChannel = {range,
SurgSim::DataStructures::OptionalValue<int>(negativeChannel)};
m_analogInputs[positiveChannel] = std::move(rangeAndOptionalNegativeChannel);
}
void LabJackDevice::enableAnalogInput(int channel, LabJack::Range range)
{
SURGSIM_ASSERT(!isInitialized()) <<
"Analog inputs cannot be enabled for a LabJackDevice after it is initialized.";
LabJack::RangeAndOptionalNegativeChannel rangeAndOptionalNegativeChannel = {range,
SurgSim::DataStructures::OptionalValue<int>()};
m_analogInputs[channel] = std::move(rangeAndOptionalNegativeChannel);
}
const std::unordered_map<int, LabJack::RangeAndOptionalNegativeChannel>& LabJackDevice::getAnalogInputs() const
{
return m_analogInputs;
}
void LabJackDevice::enableAnalogOutput(int channel)
{
SURGSIM_ASSERT(!isInitialized()) << "Analog outputs cannot be enabled for a LabJackDevice after it is initialized.";
m_analogOutputChannels.insert(channel);
}
const std::unordered_set<int>& LabJackDevice::getAnalogOutputs() const
{
return m_analogOutputChannels;
}
void LabJackDevice::setAnalogInputResolution(int resolution)
{
SURGSIM_ASSERT(!isInitialized()) <<
"Analog input resolution cannot be set for a LabJackDevice after it is initialized.";
m_analogInputResolution = resolution;
}
int LabJackDevice::getAnalogInputResolution() const
{
return m_analogInputResolution;
}
void LabJackDevice::setAnalogInputSettling(int settling)
{
SURGSIM_ASSERT(!isInitialized()) <<
"Analog input settling time cannot be set for a LabJackDevice after it is initialized.";
m_analogInputSettling = settling;
}
int LabJackDevice::getAnalogInputSettling() const
{
return m_analogInputSettling;
}
}; // namespace Device
}; // namespace SurgSim
<commit_msg>LabJackDevice logs to Warning if it has outputs but no OutputProducer. Inputs will work fine, so it does not assert. No longer checks for timers, which can work without output data.<commit_after>// This file is a part of the OpenSurgSim project.
// Copyright 2013, SimQuest Solutions Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "SurgSim/Devices/LabJack/LabJackDevice.h"
#include "SurgSim/Devices/LabJack/LabJackScaffold.h"
#include "SurgSim/Framework/Log.h"
namespace SurgSim
{
namespace Device
{
LabJackDevice::LabJackDevice(const std::string& uniqueName) :
SurgSim::Input::CommonDevice(uniqueName, LabJackScaffold::buildDeviceInputData()),
m_model(LabJack::MODEL_SEARCH),
m_connection(LabJack::CONNECTION_SEARCH),
m_address(""),
m_timerBase(LabJack::TIMERBASE_DEFAULT),
m_timerClockDivisor(1),
m_timerCounterPinOffset(0),
m_threadRate(1000.0),
m_analogInputResolution(0),
m_analogInputSettling(0)
{
}
LabJackDevice::~LabJackDevice()
{
if (isInitialized())
{
finalize();
}
}
bool LabJackDevice::initialize()
{
SURGSIM_ASSERT(!isInitialized()) << "LabJackDevice already initialized.";
std::shared_ptr<LabJackScaffold> scaffold = LabJackScaffold::getOrCreateSharedInstance();
SURGSIM_ASSERT(scaffold) << "LabJackDevice failed to get a LabJackScaffold.";
if (getDigitalOutputs().size() > 0)
{
SURGSIM_LOG_IF(!hasOutputProducer(), scaffold->getLogger(), WARNING) << "LabJackDevice named " << getName() <<
" has digital output channels but no output producer to provide the output data. Call setOutputProducer.";
}
if (getAnalogOutputs().size() > 0)
{
SURGSIM_LOG_IF(!hasOutputProducer(), scaffold->getLogger(), WARNING) << "LabJackDevice named " << getName() <<
" has analog output channels but no output producer to provide the output data. Call setOutputProducer.";
}
bool found = false;
// registerDevice will set this object's type and/or connection, if they are currently set to SEARCH.
if (scaffold->registerDevice(this))
{
m_scaffold = std::move(scaffold);
SURGSIM_LOG_INFO(m_scaffold->getLogger()) << "Device " << getName() << ": Initialized.";
found = true;
}
return found;
}
bool LabJackDevice::finalize()
{
SURGSIM_ASSERT(isInitialized()) << "LabJackDevice has not been initialized before finalize.";
SURGSIM_LOG_INFO(m_scaffold->getLogger()) << "Device " << getName() << ": " << "Finalizing.";
const bool ok = m_scaffold->unregisterDevice(this);
m_scaffold.reset();
return ok;
}
bool LabJackDevice::isInitialized() const
{
return (m_scaffold != nullptr);
}
void LabJackDevice::setModel(LabJack::Model model)
{
SURGSIM_ASSERT(!isInitialized()) << "LabJackDevice's model cannot be set after it is initialized.";
m_model = model;
}
LabJack::Model LabJackDevice::getModel() const
{
return m_model;
}
void LabJackDevice::setConnection(LabJack::Connection connection)
{
SURGSIM_ASSERT(!isInitialized()) << "LabJackDevice's connection cannot be set after it is initialized.";
m_connection = connection;
}
LabJack::Connection LabJackDevice::getConnection() const
{
return m_connection;
}
void LabJackDevice::setAddress(std::string address)
{
SURGSIM_ASSERT(!isInitialized()) << "LabJackDevice's address cannot be set after it is initialized.";
m_address = address;
}
const std::string& LabJackDevice::getAddress() const
{
return m_address;
}
void LabJackDevice::enableDigitalInput(int channel)
{
SURGSIM_ASSERT(!isInitialized()) << "Digital input cannot be enabled for a LabJackDevice after it is initialized.";
m_digitalInputChannels.insert(channel);
}
const std::unordered_set<int>& LabJackDevice::getDigitalInputs() const
{
return m_digitalInputChannels;
}
void LabJackDevice::enableDigitalOutput(int channel)
{
SURGSIM_ASSERT(!isInitialized()) << "Digital output cannot be enabled for a LabJackDevice after it is initialized.";
m_digitalOutputChannels.insert(channel);
}
const std::unordered_set<int>& LabJackDevice::getDigitalOutputs() const
{
return m_digitalOutputChannels;
}
void LabJackDevice::setTimerBase(LabJack::TimerBase base)
{
SURGSIM_ASSERT(!isInitialized()) << "LabJackDevice's timer base cannot be set after it is initialized.";
m_timerBase = base;
}
LabJack::TimerBase LabJackDevice::getTimerBase() const
{
return m_timerBase;
}
void LabJackDevice::setTimerClockDivisor(int divisor)
{
SURGSIM_ASSERT(!isInitialized()) << "LabJackDevice's timer clock divisor cannot be set after it is initialized.";
m_timerClockDivisor = divisor;
}
int LabJackDevice::getTimerClockDivisor() const
{
return m_timerClockDivisor;
}
void LabJackDevice::setTimerCounterPinOffset(int offset)
{
SURGSIM_ASSERT(!isInitialized()) <<
"LabJackDevice's timer/counter pin offset cannot be set after it is initialized.";
m_timerCounterPinOffset = offset;
}
int LabJackDevice::getTimerCounterPinOffset() const
{
return m_timerCounterPinOffset;
}
void LabJackDevice::enableTimer(int index, LabJack::TimerMode mode)
{
SURGSIM_ASSERT(!isInitialized()) << "Timers cannot be enabled for a LabJackDevice after it is initialized.";
m_timers[index] = mode;
}
const std::unordered_map<int, LabJack::TimerMode>& LabJackDevice::getTimers() const
{
return m_timers;
}
void LabJackDevice::setMaximumUpdateRate(double rate)
{
SURGSIM_ASSERT(!isInitialized()) <<
"LabJackDevice's maximum update rate cannot be set after it is initialized.";
m_threadRate = rate;
}
double LabJackDevice::getMaximumUpdateRate() const
{
return m_threadRate;
}
void LabJackDevice::enableAnalogInput(int positiveChannel, LabJack::Range range, int negativeChannel)
{
SURGSIM_ASSERT(!isInitialized()) <<
"Analog inputs cannot be enabled for a LabJackDevice after it is initialized.";
LabJack::RangeAndOptionalNegativeChannel rangeAndOptionalNegativeChannel = {range,
SurgSim::DataStructures::OptionalValue<int>(negativeChannel)};
m_analogInputs[positiveChannel] = std::move(rangeAndOptionalNegativeChannel);
}
void LabJackDevice::enableAnalogInput(int channel, LabJack::Range range)
{
SURGSIM_ASSERT(!isInitialized()) <<
"Analog inputs cannot be enabled for a LabJackDevice after it is initialized.";
LabJack::RangeAndOptionalNegativeChannel rangeAndOptionalNegativeChannel = {range,
SurgSim::DataStructures::OptionalValue<int>()};
m_analogInputs[channel] = std::move(rangeAndOptionalNegativeChannel);
}
const std::unordered_map<int, LabJack::RangeAndOptionalNegativeChannel>& LabJackDevice::getAnalogInputs() const
{
return m_analogInputs;
}
void LabJackDevice::enableAnalogOutput(int channel)
{
SURGSIM_ASSERT(!isInitialized()) << "Analog outputs cannot be enabled for a LabJackDevice after it is initialized.";
m_analogOutputChannels.insert(channel);
}
const std::unordered_set<int>& LabJackDevice::getAnalogOutputs() const
{
return m_analogOutputChannels;
}
void LabJackDevice::setAnalogInputResolution(int resolution)
{
SURGSIM_ASSERT(!isInitialized()) <<
"Analog input resolution cannot be set for a LabJackDevice after it is initialized.";
m_analogInputResolution = resolution;
}
int LabJackDevice::getAnalogInputResolution() const
{
return m_analogInputResolution;
}
void LabJackDevice::setAnalogInputSettling(int settling)
{
SURGSIM_ASSERT(!isInitialized()) <<
"Analog input settling time cannot be set for a LabJackDevice after it is initialized.";
m_analogInputSettling = settling;
}
int LabJackDevice::getAnalogInputSettling() const
{
return m_analogInputSettling;
}
}; // namespace Device
}; // namespace SurgSim
<|endoftext|>
|
<commit_before>// This file is a part of the OpenSurgSim project.
// Copyright 2013, SimQuest Solutions Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "SurgSim/Devices/Phantom/PhantomDevice.h"
#include <iostream>
#include <iomanip>
#include <HD/hd.h>
#include <SurgSim/Math/Vector.h>
#include <SurgSim/Math/Matrix.h>
#include <SurgSim/Math/RigidTransform.h>
#include <SurgSim/Framework/Log.h>
#include <SurgSim/Devices/Phantom/PhantomManager.h>
#include <SurgSim/DataStructures/DataGroup.h>
#include <SurgSim/DataStructures/DataGroupBuilder.h>
using SurgSim::Math::Vector3d;
using SurgSim::Math::Matrix44d;
using SurgSim::Math::Matrix33d;
using SurgSim::Math::RigidTransform3d;
using SurgSim::DataStructures::DataGroup;
using SurgSim::DataStructures::DataGroupBuilder;
namespace SurgSim
{
namespace Device
{
struct PhantomDevice::State
{
/// Initialize the state.
State() : hHD(HD_INVALID_HANDLE)
{
for (int i = 0; i < 3; ++i)
{
positionBuffer[i] = 0;
}
for (int i = 0; i < 16; ++i)
{
transformBuffer[i] = (i % 5) ? 0 : 1; // initialize to identity matrix
}
buttonsBuffer = 0;
for (int i = 0; i < 3; ++i)
{
forceBuffer[i] = 0;
}
}
/// The device handle.
HHD hHD;
/// The raw position read from the device.
double positionBuffer[3];
/// The raw pose transform read from the device.
double transformBuffer[16];
/// The raw button state read from the device.
int buttonsBuffer;
/// The raw force to be written to the device.
double forceBuffer[3];
};
PhantomDevice::PhantomDevice(const PhantomManager& manager, const std::string& uniqueName,
const std::string& initializationName) :
SurgSim::Input::CommonDevice(uniqueName, buildInputData()),
m_logger(manager.getLogger()),
m_initializationName(initializationName),
m_messageLabel("Device " + uniqueName + ": "),
m_state(new State)
{
}
PhantomDevice::~PhantomDevice()
{
finalize(); // it's OK if we finalized already
}
bool PhantomDevice::initialize()
{
HHD hHD = HD_INVALID_HANDLE;
if (m_initializationName.length() > 0)
{
hHD = hdInitDevice(m_initializationName.c_str());
}
else
{
hHD = hdInitDevice(HD_DEFAULT_DEVICE);
}
if (checkForFatalError("Failed to initialize"))
{
// HDAPI error message already logged
SURGSIM_LOG_INFO(m_logger) << std::endl <<
" OpenHaptics device name: '" << m_initializationName << "'" << std::endl;
return false;
}
else if (hHD == HD_INVALID_HANDLE)
{
SURGSIM_LOG_SEVERE(m_logger) << m_messageLabel << "Failed to initialize" << std::endl <<
" Error details: unknown (HDAPI returned an invalid handle)" << std::endl <<
" OpenHaptics device name: '" << m_initializationName << "'" << std::endl;
return false;
}
// Enable forces.
hdMakeCurrentDevice(hHD);
hdEnable(HD_FORCE_OUTPUT);
checkForFatalError("Couldn't enable forces");
m_state->hHD = hHD;
SURGSIM_LOG_INFO(m_logger) << m_messageLabel << "Initialized." << std::endl <<
" OpenHaptics device name: '" << m_initializationName << "'" << std::endl;
return true;
}
bool PhantomDevice::finalize()
{
HHD hHD = m_state->hHD;
if (hHD == HD_INVALID_HANDLE)
{
return false;
}
SURGSIM_LOG_DEBUG(m_logger) << m_messageLabel << "Finalizing.";
hdDisableDevice(hHD);
m_state->hHD = HD_INVALID_HANDLE;
return true;
}
bool PhantomDevice::update()
{
// TODO(bert): this code should cache the access indices.
{
// Use Eigen::Map to make the raw HDAPI output values look like Eigen data types
Eigen::Map<Vector3d> force(m_state->forceBuffer);
Vector3d forceValue;
if (getOutputData().isValid() && getOutputData().vectors().get("force", forceValue))
{
force = forceValue;
}
else
{
force.setZero();
}
}
hdBeginFrame(m_state->hHD);
// Receive the current device position (in millimeters!), pose transform, and button state bitmap.
hdGetDoublev(HD_CURRENT_POSITION, m_state->positionBuffer);
hdGetDoublev(HD_CURRENT_TRANSFORM, m_state->transformBuffer);
hdGetIntegerv(HD_CURRENT_BUTTONS, &(m_state->buttonsBuffer));
// Set the force command (in newtons).
hdSetDoublev(HD_CURRENT_FORCE, m_state->forceBuffer);
//hdSetDoublev(HD_CURRENT_TORQUE, m_state->torqueBuffer);
hdEndFrame(m_state->hHD);
bool fatalError = checkForFatalError("Error in device update");
{
// Use Eigen::Map to make the raw HDAPI output values look like Eigen data types
Eigen::Map<Vector3d> position(m_state->positionBuffer);
Eigen::Map<Eigen::Matrix<double, 4, 4, Eigen::ColMajor>> transform(m_state->transformBuffer);
RigidTransform3d pose;
pose.linear() = transform.block<3,3>(0,0);
pose.translation() = position * 0.001; // convert from millimeters to meters!
getInputData().poses().put("pose", pose);
getInputData().booleans().put("button0", (m_state->buttonsBuffer & HD_DEVICE_BUTTON_1) != 0);
getInputData().booleans().put("button1", (m_state->buttonsBuffer & HD_DEVICE_BUTTON_2) != 0);
getInputData().booleans().put("button2", (m_state->buttonsBuffer & HD_DEVICE_BUTTON_3) != 0);
getInputData().booleans().put("button3", (m_state->buttonsBuffer & HD_DEVICE_BUTTON_4) != 0);
}
return !fatalError;
}
DataGroup PhantomDevice::buildInputData()
{
DataGroupBuilder builder;
builder.addPose("pose");
builder.addBoolean("button0");
builder.addBoolean("button1");
builder.addBoolean("button2");
builder.addBoolean("button3");
return builder.createData();
}
bool PhantomDevice::checkForFatalError(const char* message)
{
return checkForFatalError(m_logger, m_messageLabel.c_str(), message);
}
bool PhantomDevice::checkForFatalError(const std::shared_ptr<SurgSim::Framework::Logger>& logger,
const char* prefix, const char* message)
{
HDErrorInfo error = hdGetError();
if (error.errorCode == HD_SUCCESS)
{
return false;
}
// The HD API maintains an error stack, so in theory there could be more than one error pending.
// We do head recursion to get them all in the correct order.
bool anotherFatalError = checkForFatalError(logger, prefix, message);
bool isFatal = ((error.errorCode != HD_WARM_MOTORS) &&
(error.errorCode != HD_EXCEEDED_MAX_FORCE) &&
(error.errorCode != HD_EXCEEDED_MAX_FORCE_IMPULSE) &&
(error.errorCode != HD_EXCEEDED_MAX_VELOCITY) &&
(error.errorCode != HD_FORCE_ERROR));
SURGSIM_LOG_SEVERE(logger) << prefix << message << std::endl <<
" Error text: '" << hdGetErrorString(error.errorCode) << "'" << std::endl <<
" Error code: 0x" << std::hex << std::setw(4) << std::setfill('0') << error.errorCode <<
" (internal: " << std::dec << error.internalErrorCode << ")" << std::endl;
return (isFatal || anotherFatalError);
}
}; // namespace Device
}; // namespace SurgSim
<commit_msg>Fix the Phantom device build after get/set changes.<commit_after>// This file is a part of the OpenSurgSim project.
// Copyright 2013, SimQuest Solutions Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "SurgSim/Devices/Phantom/PhantomDevice.h"
#include <iostream>
#include <iomanip>
#include <HD/hd.h>
#include <SurgSim/Math/Vector.h>
#include <SurgSim/Math/Matrix.h>
#include <SurgSim/Math/RigidTransform.h>
#include <SurgSim/Framework/Log.h>
#include <SurgSim/Devices/Phantom/PhantomManager.h>
#include <SurgSim/DataStructures/DataGroup.h>
#include <SurgSim/DataStructures/DataGroupBuilder.h>
using SurgSim::Math::Vector3d;
using SurgSim::Math::Matrix44d;
using SurgSim::Math::Matrix33d;
using SurgSim::Math::RigidTransform3d;
using SurgSim::DataStructures::DataGroup;
using SurgSim::DataStructures::DataGroupBuilder;
namespace SurgSim
{
namespace Device
{
struct PhantomDevice::State
{
/// Initialize the state.
State() : hHD(HD_INVALID_HANDLE)
{
for (int i = 0; i < 3; ++i)
{
positionBuffer[i] = 0;
}
for (int i = 0; i < 16; ++i)
{
transformBuffer[i] = (i % 5) ? 0 : 1; // initialize to identity matrix
}
buttonsBuffer = 0;
for (int i = 0; i < 3; ++i)
{
forceBuffer[i] = 0;
}
}
/// The device handle.
HHD hHD;
/// The raw position read from the device.
double positionBuffer[3];
/// The raw pose transform read from the device.
double transformBuffer[16];
/// The raw button state read from the device.
int buttonsBuffer;
/// The raw force to be written to the device.
double forceBuffer[3];
};
PhantomDevice::PhantomDevice(const PhantomManager& manager, const std::string& uniqueName,
const std::string& initializationName) :
SurgSim::Input::CommonDevice(uniqueName, buildInputData()),
m_logger(manager.getLogger()),
m_initializationName(initializationName),
m_messageLabel("Device " + uniqueName + ": "),
m_state(new State)
{
}
PhantomDevice::~PhantomDevice()
{
finalize(); // it's OK if we finalized already
}
bool PhantomDevice::initialize()
{
HHD hHD = HD_INVALID_HANDLE;
if (m_initializationName.length() > 0)
{
hHD = hdInitDevice(m_initializationName.c_str());
}
else
{
hHD = hdInitDevice(HD_DEFAULT_DEVICE);
}
if (checkForFatalError("Failed to initialize"))
{
// HDAPI error message already logged
SURGSIM_LOG_INFO(m_logger) << std::endl <<
" OpenHaptics device name: '" << m_initializationName << "'" << std::endl;
return false;
}
else if (hHD == HD_INVALID_HANDLE)
{
SURGSIM_LOG_SEVERE(m_logger) << m_messageLabel << "Failed to initialize" << std::endl <<
" Error details: unknown (HDAPI returned an invalid handle)" << std::endl <<
" OpenHaptics device name: '" << m_initializationName << "'" << std::endl;
return false;
}
// Enable forces.
hdMakeCurrentDevice(hHD);
hdEnable(HD_FORCE_OUTPUT);
checkForFatalError("Couldn't enable forces");
m_state->hHD = hHD;
SURGSIM_LOG_INFO(m_logger) << m_messageLabel << "Initialized." << std::endl <<
" OpenHaptics device name: '" << m_initializationName << "'" << std::endl;
return true;
}
bool PhantomDevice::finalize()
{
HHD hHD = m_state->hHD;
if (hHD == HD_INVALID_HANDLE)
{
return false;
}
SURGSIM_LOG_DEBUG(m_logger) << m_messageLabel << "Finalizing.";
hdDisableDevice(hHD);
m_state->hHD = HD_INVALID_HANDLE;
return true;
}
bool PhantomDevice::update()
{
// TODO(bert): this code should cache the access indices.
{
// Use Eigen::Map to make the raw HDAPI output values look like Eigen data types
Eigen::Map<Vector3d> force(m_state->forceBuffer);
Vector3d forceValue;
if (getOutputData().isValid() && getOutputData().vectors().get("force", &forceValue))
{
force = forceValue;
}
else
{
force.setZero();
}
}
hdBeginFrame(m_state->hHD);
// Receive the current device position (in millimeters!), pose transform, and button state bitmap.
hdGetDoublev(HD_CURRENT_POSITION, m_state->positionBuffer);
hdGetDoublev(HD_CURRENT_TRANSFORM, m_state->transformBuffer);
hdGetIntegerv(HD_CURRENT_BUTTONS, &(m_state->buttonsBuffer));
// Set the force command (in newtons).
hdSetDoublev(HD_CURRENT_FORCE, m_state->forceBuffer);
//hdSetDoublev(HD_CURRENT_TORQUE, m_state->torqueBuffer);
hdEndFrame(m_state->hHD);
bool fatalError = checkForFatalError("Error in device update");
{
// Use Eigen::Map to make the raw HDAPI output values look like Eigen data types
Eigen::Map<Vector3d> position(m_state->positionBuffer);
Eigen::Map<Eigen::Matrix<double, 4, 4, Eigen::ColMajor>> transform(m_state->transformBuffer);
RigidTransform3d pose;
pose.linear() = transform.block<3,3>(0,0);
pose.translation() = position * 0.001; // convert from millimeters to meters!
getInputData().poses().set("pose", pose);
getInputData().booleans().set("button0", (m_state->buttonsBuffer & HD_DEVICE_BUTTON_1) != 0);
getInputData().booleans().set("button1", (m_state->buttonsBuffer & HD_DEVICE_BUTTON_2) != 0);
getInputData().booleans().set("button2", (m_state->buttonsBuffer & HD_DEVICE_BUTTON_3) != 0);
getInputData().booleans().set("button3", (m_state->buttonsBuffer & HD_DEVICE_BUTTON_4) != 0);
}
return !fatalError;
}
DataGroup PhantomDevice::buildInputData()
{
DataGroupBuilder builder;
builder.addPose("pose");
builder.addBoolean("button0");
builder.addBoolean("button1");
builder.addBoolean("button2");
builder.addBoolean("button3");
return builder.createData();
}
bool PhantomDevice::checkForFatalError(const char* message)
{
return checkForFatalError(m_logger, m_messageLabel.c_str(), message);
}
bool PhantomDevice::checkForFatalError(const std::shared_ptr<SurgSim::Framework::Logger>& logger,
const char* prefix, const char* message)
{
HDErrorInfo error = hdGetError();
if (error.errorCode == HD_SUCCESS)
{
return false;
}
// The HD API maintains an error stack, so in theory there could be more than one error pending.
// We do head recursion to get them all in the correct order.
bool anotherFatalError = checkForFatalError(logger, prefix, message);
bool isFatal = ((error.errorCode != HD_WARM_MOTORS) &&
(error.errorCode != HD_EXCEEDED_MAX_FORCE) &&
(error.errorCode != HD_EXCEEDED_MAX_FORCE_IMPULSE) &&
(error.errorCode != HD_EXCEEDED_MAX_VELOCITY) &&
(error.errorCode != HD_FORCE_ERROR));
SURGSIM_LOG_SEVERE(logger) << prefix << message << std::endl <<
" Error text: '" << hdGetErrorString(error.errorCode) << "'" << std::endl <<
" Error code: 0x" << std::hex << std::setw(4) << std::setfill('0') << error.errorCode <<
" (internal: " << std::dec << error.internalErrorCode << ")" << std::endl;
return (isFatal || anotherFatalError);
}
}; // namespace Device
}; // namespace SurgSim
<|endoftext|>
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.