text
stringlengths 54
60.6k
|
|---|
<commit_before>#include "omnicore_pending.h"
#include "mastercore.h"
#include "mastercore_log.h"
#include "uint256.h"
#include "json/json_spirit_value.h"
#include "json/json_spirit_writer_template.h"
#include <string>
using json_spirit::Object;
using json_spirit::Pair;
using json_spirit::Value;
using json_spirit::write_string;
using namespace mastercore;
/**
* Adds a transaction to the pending map using supplied parameters
*/
void PendingAdd(const uint256& txid, const std::string& sendingAddress, const std::string& refAddress, uint16_t type, uint32_t propertyId, int64_t amount, uint32_t propertyIdDesired, int64_t amountDesired, int64_t action)
{
Object txobj;
std::string amountStr, amountDStr;
bool divisible;
bool divisibleDesired;
txobj.push_back(Pair("txid", txid.GetHex()));
txobj.push_back(Pair("sendingaddress", sendingAddress));
if (!refAddress.empty()) txobj.push_back(Pair("referenceaddress", refAddress));
txobj.push_back(Pair("confirmations", 0));
txobj.push_back(Pair("type", c_strMasterProtocolTXType(type)));
switch (type) {
case MSC_TYPE_SIMPLE_SEND:
txobj.push_back(Pair("propertyid", (uint64_t)propertyId));
divisible = isPropertyDivisible(propertyId);
txobj.push_back(Pair("divisible", divisible));
if (divisible) { amountStr = FormatDivisibleMP(amount); } else { amountStr = FormatIndivisibleMP(amount); }
txobj.push_back(Pair("amount", amountStr));
break;
case MSC_TYPE_SEND_TO_OWNERS:
txobj.push_back(Pair("propertyid", (uint64_t)propertyId));
divisible = isPropertyDivisible(propertyId);
txobj.push_back(Pair("divisible", divisible));
if (divisible) { amountStr = FormatDivisibleMP(amount); } else { amountStr = FormatIndivisibleMP(amount); }
txobj.push_back(Pair("amount", amountStr));
break;
case MSC_TYPE_TRADE_OFFER:
amountStr = FormatDivisibleMP(amount); // both amount for sale (either TMSC or MSC) and BTC desired are always divisible
amountDStr = FormatDivisibleMP(amountDesired);
txobj.push_back(Pair("amountoffered", amountStr));
txobj.push_back(Pair("propertyidoffered", (uint64_t)propertyId));
txobj.push_back(Pair("btcamountdesired", amountDStr));
txobj.push_back(Pair("action", action));
break;
case MSC_TYPE_METADEX:
divisible = isPropertyDivisible(propertyId);
divisibleDesired = isPropertyDivisible(propertyIdDesired);
if (divisible) { amountStr = FormatDivisibleMP(amount); } else { amountStr = FormatIndivisibleMP(amount); }
if (divisibleDesired) { amountDStr = FormatDivisibleMP(amountDesired); } else { amountDStr = FormatIndivisibleMP(amountDesired); }
txobj.push_back(Pair("amountoffered", amountStr));
txobj.push_back(Pair("propertyidoffered", (uint64_t)propertyId));
txobj.push_back(Pair("propertyidofferedisdivisible", divisible));
txobj.push_back(Pair("amountdesired", amountDStr));
txobj.push_back(Pair("propertyiddesired", (uint64_t)propertyIdDesired));
txobj.push_back(Pair("propertyiddesiredisdivisible", divisibleDesired));
txobj.push_back(Pair("action", action));
break;
}
std::string txDesc = write_string(Value(txobj), false);
CMPPending pending;
if (msc_debug_pending) file_log("%s(%s,%s,%s,%d,%u,%ld,%u,%ld,%d,%s)\n", __FUNCTION__, txid.GetHex(), sendingAddress, refAddress,
type, propertyId, amount, propertyIdDesired, amountDesired, action, txDesc);
if (update_tally_map(sendingAddress, propertyId, -amount, PENDING)) {
pending.src = sendingAddress;
pending.amount = amount;
pending.prop = propertyId;
pending.desc = txDesc;
pending.type = type;
my_pending.insert(std::make_pair(txid, pending));
}
}
/**
* Deletes a transaction from the pending map and credits the amount back to the pending tally for the address
*
* NOTE: this is currently called for every bitcoin transaction prior to running through the parser
*/
void PendingDelete(const uint256& txid)
{
PendingMap::iterator it = my_pending.find(txid);
if (it != my_pending.end()) {
CMPPending *p_pending = &(it->second);
int64_t src_amount = getMPbalance(p_pending->src, p_pending->prop, PENDING);
if (msc_debug_pending) file_log("%s(%s): amount=%d\n", __FUNCTION__, txid.GetHex(), src_amount);
if (src_amount) update_tally_map(p_pending->src, p_pending->prop, p_pending->amount, PENDING);
my_pending.erase(it);
}
}
<commit_msg>PENDING: Use json_spirit to format tx description for pending object<commit_after>#include "omnicore_pending.h"
#include "mastercore.h"
#include "mastercore_log.h"
#include "uint256.h"
#include "json/json_spirit_value.h"
#include "json/json_spirit_writer_template.h"
#include <string>
using json_spirit::Object;
using json_spirit::Pair;
using json_spirit::Value;
using json_spirit::write_string;
using namespace mastercore;
/**
* Adds a transaction to the pending map using supplied parameters
*/
void PendingAdd(const uint256& txid, const std::string& sendingAddress, const std::string& refAddress, uint16_t type, uint32_t propertyId, int64_t amount, uint32_t propertyIdDesired, int64_t amountDesired, int64_t action)
{
Object txobj;
std::string amountStr, amountDStr;
bool divisible;
bool divisibleDesired;
txobj.push_back(Pair("txid", txid.GetHex()));
txobj.push_back(Pair("sendingaddress", sendingAddress));
if (!refAddress.empty()) txobj.push_back(Pair("referenceaddress", refAddress));
txobj.push_back(Pair("confirmations", 0));
txobj.push_back(Pair("type", c_strMasterProtocolTXType(type)));
switch (type) {
case MSC_TYPE_SIMPLE_SEND:
txobj.push_back(Pair("propertyid", (uint64_t)propertyId));
divisible = isPropertyDivisible(propertyId);
txobj.push_back(Pair("divisible", divisible));
if (divisible) { amountStr = FormatDivisibleMP(amount); } else { amountStr = FormatIndivisibleMP(amount); }
txobj.push_back(Pair("amount", amountStr));
break;
case MSC_TYPE_SEND_TO_OWNERS:
txobj.push_back(Pair("propertyid", (uint64_t)propertyId));
divisible = isPropertyDivisible(propertyId);
txobj.push_back(Pair("divisible", divisible));
if (divisible) { amountStr = FormatDivisibleMP(amount); } else { amountStr = FormatIndivisibleMP(amount); }
txobj.push_back(Pair("amount", amountStr));
break;
case MSC_TYPE_TRADE_OFFER:
amountStr = FormatDivisibleMP(amount); // both amount for sale (either TMSC or MSC) and BTC desired are always divisible
amountDStr = FormatDivisibleMP(amountDesired);
txobj.push_back(Pair("amountoffered", amountStr));
txobj.push_back(Pair("propertyidoffered", (uint64_t)propertyId));
txobj.push_back(Pair("btcamountdesired", amountDStr));
txobj.push_back(Pair("action", action));
break;
case MSC_TYPE_METADEX:
divisible = isPropertyDivisible(propertyId);
divisibleDesired = isPropertyDivisible(propertyIdDesired);
if (divisible) { amountStr = FormatDivisibleMP(amount); } else { amountStr = FormatIndivisibleMP(amount); }
if (divisibleDesired) { amountDStr = FormatDivisibleMP(amountDesired); } else { amountDStr = FormatIndivisibleMP(amountDesired); }
txobj.push_back(Pair("amountoffered", amountStr));
txobj.push_back(Pair("propertyidoffered", (uint64_t)propertyId));
txobj.push_back(Pair("propertyidofferedisdivisible", divisible));
txobj.push_back(Pair("amountdesired", amountDStr));
txobj.push_back(Pair("propertyiddesired", (uint64_t)propertyIdDesired));
txobj.push_back(Pair("propertyiddesiredisdivisible", divisibleDesired));
txobj.push_back(Pair("action", action));
break;
}
std::string txDesc = write_string(Value(txobj), true);
CMPPending pending;
if (msc_debug_pending) file_log("%s(%s,%s,%s,%d,%u,%ld,%u,%ld,%d,%s)\n", __FUNCTION__, txid.GetHex(), sendingAddress, refAddress,
type, propertyId, amount, propertyIdDesired, amountDesired, action, txDesc);
if (update_tally_map(sendingAddress, propertyId, -amount, PENDING)) {
pending.src = sendingAddress;
pending.amount = amount;
pending.prop = propertyId;
pending.desc = txDesc;
pending.type = type;
my_pending.insert(std::make_pair(txid, pending));
}
}
/**
* Deletes a transaction from the pending map and credits the amount back to the pending tally for the address
*
* NOTE: this is currently called for every bitcoin transaction prior to running through the parser
*/
void PendingDelete(const uint256& txid)
{
PendingMap::iterator it = my_pending.find(txid);
if (it != my_pending.end()) {
CMPPending *p_pending = &(it->second);
int64_t src_amount = getMPbalance(p_pending->src, p_pending->prop, PENDING);
if (msc_debug_pending) file_log("%s(%s): amount=%d\n", __FUNCTION__, txid.GetHex(), src_amount);
if (src_amount) update_tally_map(p_pending->src, p_pending->prop, p_pending->amount, PENDING);
my_pending.erase(it);
}
}
<|endoftext|>
|
<commit_before>///
/// ssd - small {starter, system, supervision} daemon
///
/// small, personal and (distributed future) systemd/upstart/launchd
/// daemon
///
/// usage:
/// ssd -- start local daemon
/// ssd status -- show services status
/// ssd enable NAME command -- start service NAME
/// ssd disable NAME command -- add persitent service
///
#include <tinfra/tstring.h>
#include <tinfra/fmt.h>
#include <vector>
#include <string>
#include <map>
#include <iostream>
#include <tinfra/subprocess.h> // we actually manage subprocesses
// of this type
#include <tinfra/cli.h>
#include <tinfra/logger.h>
#include <tinfra/os_common.h>
#include <signal.h>
template <typename T>
class event_emitter {
using callback_t = std::function<void(T const&)>;
using listeners_t = std::vector<callback_t>;
listeners_t listeners;
public:
event_emitter& add_listener(callback_t callback) {
listeners.push_back(std::move(callback));
return *this;
}
event_emitter& remove_listener(callback_t callback) {
auto it = std::find(listeners.begin(), listeners.end(), callback);
if( it != listeners.end() ) {
listeners.erase(it);
}
return *this;
}
void emit(T const& value) {
for(auto const& c: this->listeners ) {
c(value);
}
}
};
/*
template <typename T>
class async_event_emitter: public event_emitter {
void emit(T value) {
for(auto c: this->listeners ) {
async([c,value] {
c(value);
});
}
}
};
*/
///
/// generic stuff
///
using tinfra::tstring;
using tinfra::log_info;
using tinfra::tsprintf;
template <typename... T>
void log(tinfra::tstring const& fmt, T&&... args) {
tinfra::log_info(tinfra::tsprintf(fmt, args...));
}
//
// timer_manager
//
/*
class timer_manager {
using tinfra::time_stamp;
std::priority_queue<time_stamp> times;
};
*/
using std::shared_ptr;
using std::string;
using std::vector;
using std::map;
using std::unique_ptr;
struct process_exit_result {
int exit_status;
int signal_number;
};
struct runtime_process_entry {
int pid = -1;
unique_ptr<tinfra::subprocess> sp;
bool running = false;
bool terminate_sent = false;
//unique_ptr<process_exit_result> exit_result;
// valid for exited processes
// event_emitter<process_exit_result> exit_event;
};
struct process_entry {
string name;
vector<string> command;
string working_dir;
shared_ptr<runtime_process_entry> re;
};
struct runtime_state {
map<int, shared_ptr<runtime_process_entry>> running;
vector<process_entry> entries;
};
void process_exited_processes(runtime_state& rts)
{
while( true ) {
int status;
int pid = ::waitpid(-1, &status, WNOHANG);
if( pid == 0 || pid == -1 ) {
// TBD: error in case of -1
return;
}
auto pei = rts.running.find(pid);
if( pei == rts.running.end() ) {
log("ignoring unknown process exit, pid=%s", pid);
continue;
}
process_exit_result per;
per.exit_status = 1;
per.signal_number = 0;
if( WIFSIGNALED(status) ) {
per.signal_number = WTERMSIG(status);
}
if( WIFEXITED(status) ) {
per.exit_status = WEXITSTATUS(status);
}
log("exited, pid=%s, ec=%s, s=%s", pid, per.exit_status, per.signal_number);
// pei->second->exit_event.emit(per);
// pei->second->exit_result.reset(new process_exit_result(per));
pei->second->running = false;
rts.running.erase(pei);
}
}
void start_outstanding_processes(runtime_state& rts)
{
for(auto& pe: rts.entries ) {
if( pe.re && pe.re->running ) {
continue;
}
log("[%s] not running, checking when to start", pe.name);
log("[%s] starting", pe.name);
// TBD, calculate start jitter & restart interval
pe.re.reset( new runtime_process_entry );
pe.re->running = false;
pe.re->sp.reset( tinfra::create_subprocess() );
if( pe.working_dir != "" ) {
pe.re->sp->set_working_dir(pe.working_dir);
}
pe.re->sp->start(pe.command);
pe.re->pid = pe.re->sp->get_native_handle();
rts.running[pe.re->pid] = pe.re;
log("[%s] started, pid=%s", pe.name, pe.re->pid);
pe.re->running = true;
}
}
void graceful_terminate_processes(runtime_state& rts)
{
for(auto& rpei: rts.running ) {
runtime_process_entry& rpe = *(rpei.second.get());
if( ! rpe.terminate_sent ) {
log("graceful_terminate_processes, terminating, pid=%s", rpe.pid);
rpe.terminate_sent = true;
rpe.sp->terminate();
}
// TBD, after some timeout send kill!
}
}
//
// SIGCHLD
//
sig_atomic_t some_children_exited = 0;
static void sigchld_handler(int, siginfo_t *, void *)
{
std::cerr << "sigchld\n";
// log("sigchld");
some_children_exited = 1;
}
void install_sigchld_handler()
{
struct sigaction act;
memset (&act, '\0', sizeof(act));
act.sa_sigaction = sigchld_handler;
act.sa_flags = SA_SIGINFO;
int r = sigaction(SIGCHLD, &act, (struct sigaction*)0);
if( r == -1) {
TINFRA_LOG_ERROR(tinfra::tsprintf("unable to install signal(%i) handler: %s", SIGCHLD, tinfra::errno_to_string(errno)));
}
}
//
// SIGTERM & SIGINT
//
sig_atomic_t terminate_requested = 0;
static void sigterm_handler(int signo, siginfo_t *, void *)
{
// log("sigterm (%s)", signo);
std::cerr << "sigerm\n";
terminate_requested = 1;
}
void install_sigterm_handler()
{
struct sigaction act;
memset (&act, '\0', sizeof(act));
act.sa_sigaction = sigterm_handler;
act.sa_flags = SA_SIGINFO;
int r = sigaction(SIGTERM, &act, (struct sigaction*)0);
if( r == -1) {
TINFRA_LOG_ERROR(tinfra::tsprintf("unable to install signal(%i) handler: %s", SIGTERM, tinfra::errno_to_string(errno)));
}
int r2 = sigaction(SIGINT, &act, (struct sigaction*)0);
if( r2 == -1) {
TINFRA_LOG_ERROR(tinfra::tsprintf("unable to install signal(%i) handler: %s", SIGINT, tinfra::errno_to_string(errno)));
}
}
//
// loop
//
void loop(runtime_state& rts)
{
sigset_t mask;
sigset_t old_mask;
sigemptyset(&mask);
sigaddset(&mask, SIGCHLD);
sigaddset(&mask, SIGTERM);
sigaddset(&mask, SIGINT);
sigprocmask(SIG_BLOCK, &mask, &old_mask);
start_outstanding_processes(rts);
do {
if( terminate_requested && rts.running.size() == 0 ) {
break;
}
if( !some_children_exited ) {
sigsuspend(&old_mask);
}
if( some_children_exited ) {
some_children_exited = 0;
process_exited_processes(rts);
}
if( terminate_requested ) {
graceful_terminate_processes(rts);
} else {
start_outstanding_processes(rts);
}
} while( true );
sigprocmask(SIG_UNBLOCK, &mask, NULL);
log("all done, exiting");
}
extern void maybe_initialize_syslog_logging();
extern void maybe_daemonize();
int ssd_main(tstring const& program_name, std::vector<tinfra::tstring>& args)
{
maybe_initialize_syslog_logging();
maybe_daemonize();
runtime_state rts;
// TBD, read config
{
process_entry pe;
pe.name = "p1";
pe.command = vector<string> { "sleep", "5" };
rts.entries.push_back(pe);
}
{
process_entry pe;
pe.name = "p2";
pe.command = vector<string> { "sleep", "2" };
rts.entries.push_back(pe);
}
{
process_entry pe;
pe.name = "p3";
pe.command = vector<string> { "sleep", "3" };
rts.entries.push_back(pe);
}
install_sigchld_handler();
install_sigterm_handler();
loop(rts);
return 0;
}
int main(int argc, char** argv)
{
return tinfra::cli_main(argc, argv, ssd_main);
}
<commit_msg>main loop logic cleanup<commit_after>///
/// ssd - small {starter, system, supervision} daemon
///
/// small, personal and (distributed future) systemd/upstart/launchd
/// daemon
///
/// usage:
/// ssd -- start local daemon
/// ssd status -- show services status
/// ssd enable NAME command -- start service NAME
/// ssd disable NAME command -- add persitent service
///
#include <tinfra/tstring.h>
#include <tinfra/fmt.h>
#include <vector>
#include <string>
#include <map>
#include <iostream>
#include <tinfra/subprocess.h> // we actually manage subprocesses
// of this type
#include <tinfra/cli.h>
#include <tinfra/logger.h>
#include <tinfra/os_common.h>
#include <signal.h>
template <typename T>
class event_emitter {
using callback_t = std::function<void(T const&)>;
using listeners_t = std::vector<callback_t>;
listeners_t listeners;
public:
event_emitter& add_listener(callback_t callback) {
listeners.push_back(std::move(callback));
return *this;
}
event_emitter& remove_listener(callback_t callback) {
auto it = std::find(listeners.begin(), listeners.end(), callback);
if( it != listeners.end() ) {
listeners.erase(it);
}
return *this;
}
void emit(T const& value) {
for(auto const& c: this->listeners ) {
c(value);
}
}
};
/*
template <typename T>
class async_event_emitter: public event_emitter {
void emit(T value) {
for(auto c: this->listeners ) {
async([c,value] {
c(value);
});
}
}
};
*/
///
/// generic stuff
///
using tinfra::tstring;
using tinfra::log_info;
using tinfra::tsprintf;
template <typename... T>
void log(tinfra::tstring const& fmt, T&&... args) {
tinfra::log_info(tinfra::tsprintf(fmt, args...));
}
//
// timer_manager
//
/*
class timer_manager {
using tinfra::time_stamp;
std::priority_queue<time_stamp> times;
};
*/
using std::shared_ptr;
using std::string;
using std::vector;
using std::map;
using std::unique_ptr;
struct process_exit_result {
int exit_status;
int signal_number;
};
struct runtime_process_entry {
int pid = -1;
unique_ptr<tinfra::subprocess> sp;
bool running = false;
bool terminate_sent = false;
//unique_ptr<process_exit_result> exit_result;
// valid for exited processes
// event_emitter<process_exit_result> exit_event;
};
struct process_entry {
string name;
vector<string> command;
string working_dir;
shared_ptr<runtime_process_entry> re;
};
struct runtime_state {
map<int, shared_ptr<runtime_process_entry>> running;
vector<process_entry> entries;
};
void process_exited_processes(runtime_state& rts)
{
while( true ) {
int status;
int pid = ::waitpid(-1, &status, WNOHANG);
if( pid == 0 || pid == -1 ) {
// TBD: error in case of -1
return;
}
auto pei = rts.running.find(pid);
if( pei == rts.running.end() ) {
log("ignoring unknown process exit, pid=%s", pid);
continue;
}
process_exit_result per;
per.exit_status = 1;
per.signal_number = 0;
if( WIFSIGNALED(status) ) {
per.signal_number = WTERMSIG(status);
}
if( WIFEXITED(status) ) {
per.exit_status = WEXITSTATUS(status);
}
log("exited, pid=%s, ec=%s, s=%s", pid, per.exit_status, per.signal_number);
// pei->second->exit_event.emit(per);
// pei->second->exit_result.reset(new process_exit_result(per));
pei->second->running = false;
rts.running.erase(pei);
}
}
void start_outstanding_processes(runtime_state& rts)
{
for(auto& pe: rts.entries ) {
if( pe.re && pe.re->running ) {
continue;
}
log("[%s] not running, checking when to start", pe.name);
log("[%s] starting", pe.name);
// TBD, calculate start jitter & restart interval
pe.re.reset( new runtime_process_entry );
pe.re->running = false;
pe.re->sp.reset( tinfra::create_subprocess() );
if( pe.working_dir != "" ) {
pe.re->sp->set_working_dir(pe.working_dir);
}
pe.re->sp->start(pe.command);
pe.re->pid = pe.re->sp->get_native_handle();
rts.running[pe.re->pid] = pe.re;
log("[%s] started, pid=%s", pe.name, pe.re->pid);
pe.re->running = true;
}
}
void graceful_terminate_processes(runtime_state& rts)
{
for(auto& rpei: rts.running ) {
runtime_process_entry& rpe = *(rpei.second.get());
if( ! rpe.terminate_sent ) {
log("graceful_terminate_processes, terminating, pid=%s", rpe.pid);
rpe.terminate_sent = true;
rpe.sp->terminate();
}
// TBD, after some timeout send kill!
}
}
//
// SIGCHLD
//
sig_atomic_t some_children_exited = 0;
static void sigchld_handler(int, siginfo_t *, void *)
{
std::cerr << "sigchld\n";
// log("sigchld");
some_children_exited = 1;
}
void install_sigchld_handler()
{
struct sigaction act;
memset (&act, '\0', sizeof(act));
act.sa_sigaction = sigchld_handler;
act.sa_flags = SA_SIGINFO;
int r = sigaction(SIGCHLD, &act, (struct sigaction*)0);
if( r == -1) {
TINFRA_LOG_ERROR(tinfra::tsprintf("unable to install signal(%i) handler: %s", SIGCHLD, tinfra::errno_to_string(errno)));
}
}
//
// SIGTERM & SIGINT
//
sig_atomic_t terminate_requested = 0;
static void sigterm_handler(int signo, siginfo_t *, void *)
{
// log("sigterm (%s)", signo);
std::cerr << "sigerm\n";
terminate_requested = 1;
}
void install_sigterm_handler()
{
struct sigaction act;
memset (&act, '\0', sizeof(act));
act.sa_sigaction = sigterm_handler;
act.sa_flags = SA_SIGINFO;
int r = sigaction(SIGTERM, &act, (struct sigaction*)0);
if( r == -1) {
TINFRA_LOG_ERROR(tinfra::tsprintf("unable to install signal(%i) handler: %s", SIGTERM, tinfra::errno_to_string(errno)));
}
int r2 = sigaction(SIGINT, &act, (struct sigaction*)0);
if( r2 == -1) {
TINFRA_LOG_ERROR(tinfra::tsprintf("unable to install signal(%i) handler: %s", SIGINT, tinfra::errno_to_string(errno)));
}
}
//
// loop
//
void loop(runtime_state& rts)
{
sigset_t mask;
sigset_t old_mask;
sigemptyset(&mask);
sigaddset(&mask, SIGCHLD);
sigaddset(&mask, SIGTERM);
sigaddset(&mask, SIGINT);
sigprocmask(SIG_BLOCK, &mask, &old_mask);
start_outstanding_processes(rts);
while( true ) {
// maybe terminate ?
if( terminate_requested ) {
if( rts.running.size() == 0 ) {
break;
}
graceful_terminate_processes(rts);
}
// maybe start unstarted things
if( !terminate_requested ) {
start_outstanding_processes(rts);
}
// process exit signals
if ( some_children_exited ) {
some_children_exited = 0;
process_exited_processes(rts);
continue;
}
// wait for next events
sigsuspend(&old_mask);
}
sigprocmask(SIG_UNBLOCK, &mask, NULL);
log("all done, exiting");
}
extern void maybe_initialize_syslog_logging();
extern void maybe_daemonize();
int ssd_main(tstring const& program_name, std::vector<tinfra::tstring>& args)
{
maybe_initialize_syslog_logging();
maybe_daemonize();
runtime_state rts;
// TBD, read config
{
process_entry pe;
pe.name = "p1";
pe.command = vector<string> { "sleep", "5" };
rts.entries.push_back(pe);
}
{
process_entry pe;
pe.name = "p2";
pe.command = vector<string> { "sleep", "2" };
rts.entries.push_back(pe);
}
{
process_entry pe;
pe.name = "p3";
pe.command = vector<string> { "sleep", "3" };
rts.entries.push_back(pe);
}
install_sigchld_handler();
install_sigterm_handler();
loop(rts);
return 0;
}
int main(int argc, char** argv)
{
return tinfra::cli_main(argc, argv, ssd_main);
}
<|endoftext|>
|
<commit_before>
#include "config.h"
// boost
#include <boost/filesystem.hpp>
// dune-common
#include <dune/common/exceptions.hh>
#include <dune/common/mpihelper.hh>
#include <dune/common/timer.hh>
// dune-grid-multiscale
#include <dune/grid/multiscale/provider/cube.hh>
// dune-stuff
#include <dune/stuff/common/parameter/tree.hh>
#include <dune/stuff/common/logging.hh>
#include <dune/stuff/grid/boundaryinfo.hh>
// dune-detailed-solvers
#include <dune/detailed/solvers/stationary/linear/elliptic/model/default.hh>
//#include <dune/detailed/solvers/stationary/linear/elliptic/model/spe10.hh>
#include <dune/detailed/solvers/stationary/linear/elliptic/multiscale/semicontinuousgalerkin/dune-detailed-discretizations.hh>
#ifdef POLORDER
const int polOrder = POLORDER;
#else
const int polOrder = 1;
#endif
const std::string id = "semicontinuous_ddd_multiscale_solver";
/**
\brief Creates a parameter file if it does not exist.
Nothing is done if the file already exists. If not, a parameter file will be created with all neccessary
keys and values.
\param[in] filename
(Relative) path to the file.
**/
void ensureParamFile(std::string filename)
{
// only write param file if there is none
if (!boost::filesystem::exists(filename)) {
std::ofstream file;
file.open(filename);
file << "[grid.multiscale.provider.cube]" << std::endl;
file << "level = 4" << std::endl;
file << "boundaryId = 7" << std::endl; // a cube from the factory gets the boundary ids 1 to 4 ind 2d and 1 to 6 in 3d (hopefully)
file << "partitions.0 = 2" << std::endl;
file << "partitions.1 = 2" << std::endl;
file << "partitions.2 = 2" << std::endl;
file << "filename = " << id << "_msGrid" << std::endl;
file << "[detailed.solvers.stationary.linear.elliptic.model.default]" << std::endl;
file << "diffusion.order = 0" << std::endl;
file << "diffusion.variable = x" << std::endl;
file << "diffusion.expression.0 = 1.0" << std::endl;
file << "diffusion.expression.1 = 1.0" << std::endl;
file << "diffusion.expression.2 = 1.0" << std::endl;
file << "force.order = 0" << std::endl;
file << "force.variable = x" << std::endl;
file << "force.expression.0 = 1.0" << std::endl;
file << "force.expression.1 = 1.0" << std::endl;
file << "force.expression.2 = 1.0" << std::endl;
file << "dirichlet.order = 0" << std::endl;
file << "dirichlet.variable = x" << std::endl;
file << "dirichlet.expression.0 = x[0]" << std::endl;
file << "dirichlet.expression.1 = 1.0" << std::endl;
file << "dirichlet.expression.2 = 1.0" << std::endl;
file << "[detailed.solvers.stationary.linear.elliptic.multiscale.semicontinuousgalerkin]" << std::endl;
file << "discretization.penaltyFactor = 10.0" << std::endl;
file << "solve.type = eigen.bicgstab.incompletelut" << std::endl;
file << "solve.maxIter = 5000" << std::endl;
file << "solve.precision = 1e-12" << std::endl;
file << "visualize.filename = " << id << "_solution" << std::endl;
file << "visualize.name = solution" << std::endl;
file.close();
} // only write param file if there is none
} // void ensureParamFile()
int main(int argc, char** argv)
{
try {
// mpi
Dune::MPIHelper::instance(argc, argv);
// parameter
const std::string filename = id + ".param";
ensureParamFile(filename);
Dune::ParameterTree paramTree = Dune::Stuff::Common::Parameter::Tree::init(argc, argv, filename);
// logger
Dune::Stuff::Common::Logger().create(Dune::Stuff::Common::LOG_INFO |
Dune::Stuff::Common::LOG_CONSOLE |
Dune::Stuff::Common::LOG_DEBUG);
// Dune::Stuff::Common::LogStream& info = Dune::Stuff::Common::Logger().info();
std::ostream& info = std::cout;
Dune::Stuff::Common::LogStream& debug = Dune::Stuff::Common::Logger().debug();
// timer
Dune::Timer timer;
// grid
info << "setting up grid: " << std::endl;
debug.suspend();
typedef Dune::grid::Multiscale::Provider::Cube<> GridProviderType;
Dune::Stuff::Common::Parameter::Tree::assertSub(paramTree, GridProviderType::id, id);
const GridProviderType gridProvider(paramTree.sub(GridProviderType::id));
typedef GridProviderType::MsGridType MsGridType;
const Dune::shared_ptr< const MsGridType > msGrid = gridProvider.msGridPtr();
info << " took " << timer.elapsed()
<< " sec (has " << gridProvider.grid().size(0) << " elements, "
<< msGrid->size() << " subdomains)" << std::endl;
info << "visualizing grid... " << std::flush;
timer.reset();
msGrid->visualize(paramTree.sub(GridProviderType::id).get("filename", id + "_msGrid"));
info << "done (took " << timer.elapsed() << " sek)" << std::endl;
debug.resume();
// model
info << "setting up model... " << std::flush;
debug.suspend();
// timer.reset();
const unsigned int DUNE_UNUSED(dimDomain) = GridProviderType::dim;
const unsigned int DUNE_UNUSED(dimRange) = 1;
typedef GridProviderType::CoordinateType::value_type DomainFieldType;
typedef DomainFieldType RangeFieldType;
typedef Dune::Detailed::Solvers::Stationary::Linear::Elliptic::Model::Default< DomainFieldType, dimDomain, RangeFieldType, dimRange > ModelType;
Dune::Stuff::Common::Parameter::Tree::assertSub(paramTree, ModelType::id, id);
const Dune::shared_ptr< const ModelType > model(new ModelType(paramTree.sub(ModelType::id)));
typedef Dune::Stuff::Grid::BoundaryInfo::AllDirichlet BoundaryInfoType;
const Dune::shared_ptr< const BoundaryInfoType > boundaryInfo(new BoundaryInfoType());
info << "done (took " << timer.elapsed() << " sec)" << std::endl;
debug.resume();
// solver
info << "initializing solver:" << std::endl;
// debug.suspend();
// timer.reset();
typedef Dune::Detailed::Solvers::Stationary::Linear::Elliptic::Multiscale::SemicontinuousGalerkin::DuneDetailedDiscretizations<
ModelType,
MsGridType,
BoundaryInfoType,
polOrder > SolverType;
Dune::Stuff::Common::Parameter::Tree::assertSub(paramTree, SolverType::id, id);
SolverType solver(model, msGrid, boundaryInfo, paramTree.sub(SolverType::id));
solver.init(" ", std::cout);
// debug.resume();
// info << "done (took " << timer.elapsed() << " sec)" << std::endl;
// info << "solving:" << std::endl;
// debug.suspend();
// timer.reset();
// typedef SolverType::LocalVectorType LocalDofVectorType;
// std::vector< Dune::shared_ptr< LocalDofVectorType > > solution = solver.createVector();
// solver.solve(solution, paramTree.sub(SolverType::id).sub("solve"), " ", std::cout);
// debug.resume();
// info << "done (took " << timer.elapsed() << " sec)" << std::endl;
// info << "postprocessing..." << std::endl;
// debug.suspend();
// timer.reset();
// solver.visualize(solution,
// paramTree.sub(SolverType::id).sub("visualize").get("filename", id + "_solution"),
// paramTree.sub(SolverType::id).sub("visualize").get("name", "solution"),
// " ",
// std::cout);
// debug.resume();
// info << "done (took " << timer.elapsed() << " sec)" << std::endl;
// if we came that far we can as well be happy about it
return 0;
} catch(Dune::Exception& e) {
std::cerr << "Dune reported error: " << e.what() << std::endl;
} catch(std::exception& e) {
std::cerr << e.what() << std::endl;
} catch( ... ) {
std::cerr << "Unknown exception thrown!" << std::endl;
} // try
} // main
<commit_msg>[examples...elliptic.multiscale...] adapted to new solver<commit_after>
#include "config.h"
// boost
#include <boost/filesystem.hpp>
// dune-common
#include <dune/common/exceptions.hh>
#include <dune/common/mpihelper.hh>
#include <dune/common/timer.hh>
// dune-grid-multiscale
#include <dune/grid/multiscale/provider/cube.hh>
// dune-stuff
#include <dune/stuff/common/parameter/tree.hh>
#include <dune/stuff/common/logging.hh>
#include <dune/stuff/grid/boundaryinfo.hh>
// dune-detailed-solvers
#include <dune/detailed/solvers/stationary/linear/elliptic/model/default.hh>
//#include <dune/detailed/solvers/stationary/linear/elliptic/model/spe10.hh>
#include <dune/detailed/solvers/stationary/linear/elliptic/multiscale/semicontinuousgalerkin/dune-detailed-discretizations.hh>
#ifdef POLORDER
const int polOrder = POLORDER;
#else
const int polOrder = 1;
#endif
const std::string id = "semicontinuous_ddd_multiscale_solver";
/**
\brief Creates a parameter file if it does not exist.
Nothing is done if the file already exists. If not, a parameter file will be created with all neccessary
keys and values.
\param[in] filename
(Relative) path to the file.
**/
void ensureParamFile(std::string filename)
{
// only write param file if there is none
if (!boost::filesystem::exists(filename)) {
std::ofstream file;
file.open(filename);
file << "[grid.multiscale.provider.cube]" << std::endl;
file << "level = 4" << std::endl;
file << "boundaryId = 7" << std::endl; // a cube from the factory gets the boundary ids 1 to 4 ind 2d and 1 to 6 in 3d (hopefully)
file << "partitions.0 = 2" << std::endl;
file << "partitions.1 = 2" << std::endl;
file << "partitions.2 = 2" << std::endl;
file << "filename = " << id << "_msGrid" << std::endl;
file << "[detailed.solvers.stationary.linear.elliptic.model.default]" << std::endl;
file << "diffusion.order = 0" << std::endl;
file << "diffusion.variable = x" << std::endl;
file << "diffusion.expression.0 = 1.0" << std::endl;
file << "diffusion.expression.1 = 1.0" << std::endl;
file << "diffusion.expression.2 = 1.0" << std::endl;
file << "force.order = 0" << std::endl;
file << "force.variable = x" << std::endl;
file << "force.expression.0 = 1.0" << std::endl;
file << "force.expression.1 = 1.0" << std::endl;
file << "force.expression.2 = 1.0" << std::endl;
file << "dirichlet.order = 0" << std::endl;
file << "dirichlet.variable = x" << std::endl;
file << "dirichlet.expression.0 = x[0]" << std::endl;
file << "dirichlet.expression.1 = 1.0" << std::endl;
file << "dirichlet.expression.2 = 1.0" << std::endl;
file << "[detailed.solvers.stationary.linear.elliptic.multiscale.semicontinuousgalerkin]" << std::endl;
file << "discretization.penaltyFactor = 10.0" << std::endl;
file << "solve.type = eigen.bicgstab.incompletelut" << std::endl;
file << "solve.maxIter = 5000" << std::endl;
file << "solve.precision = 1e-12" << std::endl;
file << "visualize.filename = " << id << "_solution" << std::endl;
file << "visualize.name = solution" << std::endl;
file.close();
} // only write param file if there is none
} // void ensureParamFile()
int main(int argc, char** argv)
{
try {
// mpi
Dune::MPIHelper::instance(argc, argv);
// parameter
const std::string filename = id + ".param";
ensureParamFile(filename);
Dune::ParameterTree paramTree = Dune::Stuff::Common::Parameter::Tree::init(argc, argv, filename);
// logger
Dune::Stuff::Common::Logger().create(Dune::Stuff::Common::LOG_INFO |
Dune::Stuff::Common::LOG_CONSOLE |
Dune::Stuff::Common::LOG_DEBUG);
// Dune::Stuff::Common::LogStream& info = Dune::Stuff::Common::Logger().info();
std::ostream& info = std::cout;
Dune::Stuff::Common::LogStream& debug = Dune::Stuff::Common::Logger().debug();
// timer
Dune::Timer timer;
// grid
info << "setting up grid: " << std::endl;
debug.suspend();
typedef Dune::grid::Multiscale::Provider::Cube<> GridProviderType;
Dune::Stuff::Common::Parameter::Tree::assertSub(paramTree, GridProviderType::id, id);
const GridProviderType gridProvider(paramTree.sub(GridProviderType::id));
typedef GridProviderType::MsGridType MsGridType;
const Dune::shared_ptr< const MsGridType > msGrid = gridProvider.msGridPtr();
info << " took " << timer.elapsed()
<< " sec (has " << gridProvider.grid().size(0) << " elements, "
<< msGrid->size() << " subdomains)" << std::endl;
debug.resume();
info << "visualizing grid... " << std::flush;
timer.reset();
debug.suspend();
msGrid->visualize(paramTree.sub(GridProviderType::id).get("filename", id + "_msGrid"));
info << "done (took " << timer.elapsed() << " sek)" << std::endl;
debug.resume();
// model
info << "setting up model... " << std::flush;
debug.suspend();
timer.reset();
const unsigned int DUNE_UNUSED(dimDomain) = GridProviderType::dim;
const unsigned int DUNE_UNUSED(dimRange) = 1;
typedef GridProviderType::CoordinateType::value_type DomainFieldType;
typedef DomainFieldType RangeFieldType;
typedef Dune::Detailed::Solvers::Stationary::Linear::Elliptic::Model::Default< DomainFieldType, dimDomain, RangeFieldType, dimRange > ModelType;
Dune::Stuff::Common::Parameter::Tree::assertSub(paramTree, ModelType::id, id);
const Dune::shared_ptr< const ModelType > model(new ModelType(paramTree.sub(ModelType::id)));
typedef Dune::Stuff::Grid::BoundaryInfo::AllDirichlet BoundaryInfoType;
const Dune::shared_ptr< const BoundaryInfoType > boundaryInfo(new BoundaryInfoType());
info << "done (took " << timer.elapsed() << " sec)" << std::endl;
debug.resume();
// solver
info << "initializing solver";
// info << ":" << std::endl;
info << "... " << std::flush;
debug.suspend();
timer.reset();
typedef Dune::Detailed::Solvers::Stationary::Linear::Elliptic::Multiscale::SemicontinuousGalerkin::DuneDetailedDiscretizations<
ModelType,
MsGridType,
BoundaryInfoType,
polOrder > SolverType;
Dune::Stuff::Common::Parameter::Tree::assertSub(paramTree, SolverType::id, id);
SolverType solver(model, msGrid, boundaryInfo, paramTree.sub(SolverType::id));
solver.init(" ", debug);
debug.resume();
info << "done (took " << timer.elapsed() << " sec)" << std::endl;
info << "solving";
// info << ":" << std::endl;
info << "... " << std::flush;
debug.suspend();
timer.reset();
typedef SolverType::VectorBackendType VectorType;
Dune::shared_ptr< std::vector< VectorType > > solution = solver.createVector();
solver.solve(*solution, paramTree.sub(SolverType::id).sub("solve"), " ", debug);
debug.resume();
info << "done (took " << timer.elapsed() << " sec)" << std::endl;
info << "postprocessing";
info << ":" << std::endl;
// info << "... " << std::flush;
// debug.suspend();
// timer.reset();
solver.visualize(*solution,
paramTree.sub(SolverType::id).sub("visualize").get("filename", id + "_solution"),
paramTree.sub(SolverType::id).sub("visualize").get("name", "solution"),
" ",
std::cout);
// debug.resume();
// info << "done (took " << timer.elapsed() << " sec)" << std::endl;
// if we came that far we can as well be happy about it
return 0;
} catch(Dune::Exception& e) {
std::cerr << "Dune reported error: " << e.what() << std::endl;
} catch(std::exception& e) {
std::cerr << e.what() << std::endl;
} catch( ... ) {
std::cerr << "Unknown exception thrown!" << std::endl;
} // try
} // main
<|endoftext|>
|
<commit_before>#ifndef ITER_STARMAP_H_
#define ITER_STARMAP_H_
#include "iterbase.hpp"
#include <utility>
#include <iterator>
#include <type_traits>
#include <array>
#include <cassert>
#include <memory>
namespace iter {
// starmap with a container<T> where T is one of tuple, pair, array
template <typename Func, typename Container>
class StarMapper {
private:
Func func;
Container container;
using StarIterDeref =
std::remove_reference_t<decltype(call_with_tuple(func,
std::declval<iterator_deref<Container>>()))>;
public:
StarMapper(Func f, Container&& c)
: func(std::forward<Func>(f)),
container(std::forward<Container>(c))
{ }
class Iterator
: public std::iterator<std::input_iterator_tag, StarIterDeref>
{
private:
Func *func;
iterator_type<Container> sub_iter;
public:
Iterator(Func& f, iterator_type<Container>&& iter)
: func(&f),
sub_iter(std::move(iter))
{ }
bool operator!=(const Iterator& other) const {
return this->sub_iter != other.sub_iter;
}
bool operator==(const Iterator& other) const {
return !(*this != other);
}
Iterator& operator++() {
++this->sub_iter;
return *this;
}
Iterator operator++(int) {
auto ret = *this;
++*this;
return ret;
}
decltype(auto) operator*() {
return call_with_tuple(*this->func, *this->sub_iter);
}
};
Iterator begin() {
return {this->func, std::begin(this->container)};
}
Iterator end() {
return {this->func, std::end(this->container)};
}
};
template <typename Func, typename Container>
StarMapper<Func, Container> starmap_helper(
Func func, Container&& container, std::false_type) {
return {std::forward<Func>(func), std::forward<Container>(container)};
}
// starmap for a tuple or pair of tuples or pairs
template <typename Func, typename TupType, std::size_t... Is>
class TupleStarMapper {
private:
Func func;
TupType tup;
private:
static_assert(sizeof...(Is)
== std::tuple_size<std::decay_t<TupType>>::value,
"tuple size doesn't match size of Is");
template <std::size_t Idx>
static decltype(auto) get_and_call_with_tuple(Func& f, TupType &t){
return call_with_tuple(f, std::get<Idx>(t));
}
using ResultType = decltype(get_and_call_with_tuple<0>(func, tup));
using CallerFunc = ResultType (*)(Func&, TupType&);
constexpr static std::array<CallerFunc, sizeof...(Is)> callers{{
get_and_call_with_tuple<Is>...}};
using TraitsValue = std::remove_reference_t<ResultType>;
public:
TupleStarMapper(Func f, TupType t)
: func(std::forward<Func>(f)),
tup(std::forward<TupType>(t))
{ }
class Iterator
: public std::iterator<std::input_iterator_tag, TraitsValue>
{
private:
Func& func;
TupType& tup;
std::size_t index;
public:
Iterator(Func& f, TupType& t, std::size_t i)
: func{f},
tup{t},
index{i}
{ }
decltype(auto) operator*() {
return callers[this->index](this->func, this->tup);
}
Iterator& operator++() {
++this->index;
return *this;
}
Iterator operator++(int) {
auto ret = *this;
++*this;
return ret;
}
bool operator!=(const Iterator& other) const {
return this->index != other.index;
}
bool operator==(const Iterator& other) const {
return !(*this != other);
}
};
Iterator begin() {
return {this->func, this->tup, 0};
}
Iterator end() {
return {this->func, this->tup, sizeof...(Is)};
}
};
template <typename Func, typename TupType, std::size_t... Is>
constexpr std::array<
typename TupleStarMapper<Func, TupType, Is...>::CallerFunc,
sizeof...(Is)>
TupleStarMapper<Func, TupType, Is...>::callers;
template <typename Func, typename TupType, std::size_t... Is>
TupleStarMapper<Func, TupType, Is...> starmap_helper_impl(
Func func, TupType&& tup, std::index_sequence<Is...>)
{
return {std::forward<Func>(func), std::forward<TupType>(tup)};
}
template <typename Func, typename TupType>
auto starmap_helper(
Func func, TupType&& tup, std::true_type) {
return starmap_helper_impl(
std::forward<Func>(func),
std::forward<TupType>(tup),
std::make_index_sequence<
std::tuple_size<std::decay_t<TupType>>::value>{});
}
// "tag dispatch" to differentiate between normal containers and
// tuple-like containers, things that work with std::get
template <typename T, typename =void>
struct is_tuple_like : public std::false_type { };
template <typename T>
struct is_tuple_like<T, decltype(std::get<0>(std::declval<T>()), void())>
: public std::true_type { };
template <typename Func, typename Seq>
auto starmap(Func func, Seq&& sequence) {
return starmap_helper(
std::forward<Func>(func),
std::forward<Seq>(sequence),
is_tuple_like<Seq>{});
}
}
#endif
<commit_msg>replaces references with pointers in starmap iter<commit_after>#ifndef ITER_STARMAP_H_
#define ITER_STARMAP_H_
#include "iterbase.hpp"
#include <utility>
#include <iterator>
#include <type_traits>
#include <array>
#include <cassert>
#include <memory>
namespace iter {
// starmap with a container<T> where T is one of tuple, pair, array
template <typename Func, typename Container>
class StarMapper {
private:
Func func;
Container container;
using StarIterDeref =
std::remove_reference_t<decltype(call_with_tuple(func,
std::declval<iterator_deref<Container>>()))>;
public:
StarMapper(Func f, Container&& c)
: func(std::forward<Func>(f)),
container(std::forward<Container>(c))
{ }
class Iterator
: public std::iterator<std::input_iterator_tag, StarIterDeref>
{
private:
Func *func;
iterator_type<Container> sub_iter;
public:
Iterator(Func& f, iterator_type<Container>&& iter)
: func(&f),
sub_iter(std::move(iter))
{ }
bool operator!=(const Iterator& other) const {
return this->sub_iter != other.sub_iter;
}
bool operator==(const Iterator& other) const {
return !(*this != other);
}
Iterator& operator++() {
++this->sub_iter;
return *this;
}
Iterator operator++(int) {
auto ret = *this;
++*this;
return ret;
}
decltype(auto) operator*() {
return call_with_tuple(*this->func, *this->sub_iter);
}
};
Iterator begin() {
return {this->func, std::begin(this->container)};
}
Iterator end() {
return {this->func, std::end(this->container)};
}
};
template <typename Func, typename Container>
StarMapper<Func, Container> starmap_helper(
Func func, Container&& container, std::false_type) {
return {std::forward<Func>(func), std::forward<Container>(container)};
}
// starmap for a tuple or pair of tuples or pairs
template <typename Func, typename TupType, std::size_t... Is>
class TupleStarMapper {
private:
Func func;
TupType tup;
private:
static_assert(sizeof...(Is)
== std::tuple_size<std::decay_t<TupType>>::value,
"tuple size doesn't match size of Is");
template <std::size_t Idx>
static decltype(auto) get_and_call_with_tuple(Func& f, TupType &t){
return call_with_tuple(f, std::get<Idx>(t));
}
using ResultType = decltype(get_and_call_with_tuple<0>(func, tup));
using CallerFunc = ResultType (*)(Func&, TupType&);
constexpr static std::array<CallerFunc, sizeof...(Is)> callers{{
get_and_call_with_tuple<Is>...}};
using TraitsValue = std::remove_reference_t<ResultType>;
public:
TupleStarMapper(Func f, TupType t)
: func(std::forward<Func>(f)),
tup(std::forward<TupType>(t))
{ }
class Iterator
: public std::iterator<std::input_iterator_tag, TraitsValue>
{
private:
Func *func;
std::remove_reference_t<TupType> *tup;
std::size_t index;
public:
Iterator(Func& f, TupType& t, std::size_t i)
: func{&f},
tup{&t},
index{i}
{ }
decltype(auto) operator*() {
return callers[this->index](*this->func, *this->tup);
}
Iterator& operator++() {
++this->index;
return *this;
}
Iterator operator++(int) {
auto ret = *this;
++*this;
return ret;
}
bool operator!=(const Iterator& other) const {
return this->index != other.index;
}
bool operator==(const Iterator& other) const {
return !(*this != other);
}
};
Iterator begin() {
return {this->func, this->tup, 0};
}
Iterator end() {
return {this->func, this->tup, sizeof...(Is)};
}
};
template <typename Func, typename TupType, std::size_t... Is>
constexpr std::array<
typename TupleStarMapper<Func, TupType, Is...>::CallerFunc,
sizeof...(Is)>
TupleStarMapper<Func, TupType, Is...>::callers;
template <typename Func, typename TupType, std::size_t... Is>
TupleStarMapper<Func, TupType, Is...> starmap_helper_impl(
Func func, TupType&& tup, std::index_sequence<Is...>)
{
return {std::forward<Func>(func), std::forward<TupType>(tup)};
}
template <typename Func, typename TupType>
auto starmap_helper(
Func func, TupType&& tup, std::true_type) {
return starmap_helper_impl(
std::forward<Func>(func),
std::forward<TupType>(tup),
std::make_index_sequence<
std::tuple_size<std::decay_t<TupType>>::value>{});
}
// "tag dispatch" to differentiate between normal containers and
// tuple-like containers, things that work with std::get
template <typename T, typename =void>
struct is_tuple_like : public std::false_type { };
template <typename T>
struct is_tuple_like<T, decltype(std::get<0>(std::declval<T>()), void())>
: public std::true_type { };
template <typename Func, typename Seq>
auto starmap(Func func, Seq&& sequence) {
return starmap_helper(
std::forward<Func>(func),
std::forward<Seq>(sequence),
is_tuple_like<Seq>{});
}
}
#endif
<|endoftext|>
|
<commit_before>#include "benchmark_framework.hpp"
#include "benchmark_provider.hpp"
#include "../coding/file_container.hpp"
#include "../std/fstream.hpp"
#include "../platform/settings.hpp"
#include "../version/version.hpp"
template <class T> class DoGetBenchmarks
{
set<string> m_processed;
vector<T> & m_benchmarks;
Platform & m_pl;
public:
DoGetBenchmarks(vector<T> & benchmarks)
: m_benchmarks(benchmarks), m_pl(GetPlatform())
{
}
void operator() (vector<string> const & v)
{
if (v[0][0] == '#')
return;
T b;
b.m_name = v[1];
m2::RectD r;
if (m_processed.insert(v[0]).second)
{
try
{
feature::DataHeader header;
header.Load(FilesContainerR(m_pl.GetReader(v[0])).GetReader(HEADER_FILE_TAG));
r = header.GetBounds();
}
catch (RootException const & e)
{
LOG(LINFO, ("Cannot add ", v[0], " file to benchmark: ", e.what()));
return;
}
}
int lastScale;
if (v.size() > 3)
{
double x0, y0, x1, y1;
strings::to_double(v[2], x0);
strings::to_double(v[3], y0);
strings::to_double(v[4], x1);
strings::to_double(v[5], y1);
r = m2::RectD(x0, y0, x1, y1);
strings::to_int(v[6], lastScale);
}
else
strings::to_int(v[2], lastScale);
ASSERT ( r != m2::RectD::GetEmptyRect(), (r) );
b.m_provider.reset(new BenchmarkRectProvider(scales::GetScaleLevel(r), r, lastScale));
m_benchmarks.push_back(b);
}
};
template <class ToDo>
void ForEachBenchmarkRecord(ToDo & toDo)
{
Platform & pl = GetPlatform();
string buffer;
try
{
string configPath;
Settings::Get("BenchmarkConfig", configPath);
ReaderPtr<Reader>(pl.GetReader(configPath)).ReadAsString(buffer);
}
catch (RootException const & e)
{
LOG(LERROR, ("Error reading benchmarks: ", e.what()));
return;
}
istringstream stream(buffer);
string line;
while (stream.good())
{
getline(stream, line);
vector<string> parts;
strings::SimpleTokenizer it(line, " ");
while (it)
{
parts.push_back(*it);
++it;
}
if (!parts.empty())
toDo(parts);
}
}
struct MapsCollector
{
vector<string> m_maps;
void operator() (vector<string> const & v)
{
if (!v[0].empty())
if (v[0][0] == '#')
return;
m_maps.push_back(v[0]);
}
};
void BenchmarkFramework::ReAddLocalMaps()
{
// remove all previously added maps in framework constructor
Platform::FilesList files;
Framework::GetLocalMaps(files);
for_each(files.begin(), files.end(),
bind(&BenchmarkFramework::RemoveMap, this, _1));
// add only maps needed for benchmarks
MapsCollector collector;
ForEachBenchmarkRecord(collector);
for_each(collector.m_maps.begin(), collector.m_maps.end(),
bind(&BenchmarkFramework::AddMap, this, _1));
}
BenchmarkFramework::BenchmarkFramework()
: m_paintDuration(0),
m_maxDuration(0),
m_isBenchmarkFinished(false),
m_isBenchmarkInitialized(false)
{
m_startTime = my::FormatCurrentTime();
Framework::m_informationDisplay.enableBenchmarkInfo(true);
ReAddLocalMaps();
}
void BenchmarkFramework::BenchmarkCommandFinished()
{
double duration = m_paintDuration;
if (duration > m_maxDuration)
{
m_maxDuration = duration;
m_maxDurationRect = m_curBenchmarkRect;
Framework::m_informationDisplay.addBenchmarkInfo("maxDurationRect: ", m_maxDurationRect, m_maxDuration);
}
BenchmarkResult res;
res.m_name = m_benchmarks[m_curBenchmark].m_name;
res.m_rect = m_curBenchmarkRect;
res.m_time = duration;
m_benchmarkResults.push_back(res);
if (m_benchmarkResults.size() > 100)
SaveBenchmarkResults();
m_paintDuration = 0;
if (!m_isBenchmarkFinished)
NextBenchmarkCommand();
}
void BenchmarkFramework::SaveBenchmarkResults()
{
string resultsPath;
Settings::Get("BenchmarkResults", resultsPath);
LOG(LINFO, (resultsPath));
ofstream fout(GetPlatform().WritablePathForFile(resultsPath).c_str(), ios::app);
for (size_t i = 0; i < m_benchmarkResults.size(); ++i)
{
fout << GetPlatform().DeviceName() << " "
<< VERSION_STRING << " "
<< m_startTime << " "
<< m_benchmarkResults[i].m_name << " "
<< m_benchmarkResults[i].m_rect.minX() << " "
<< m_benchmarkResults[i].m_rect.minY() << " "
<< m_benchmarkResults[i].m_rect.maxX() << " "
<< m_benchmarkResults[i].m_rect.maxY() << " "
<< m_benchmarkResults[i].m_time << endl;
}
m_benchmarkResults.clear();
}
void BenchmarkFramework::SendBenchmarkResults()
{
// ofstream fout(GetPlatform().WritablePathForFile("benchmarks/results.txt").c_str(), ios::app);
// fout << "[COMPLETED]";
// fout.close();
/// send to server for adding to statistics graphics
/// and delete results file
}
void BenchmarkFramework::MarkBenchmarkResultsEnd()
{
string resultsPath;
Settings::Get("BenchmarkResults", resultsPath);
LOG(LINFO, (resultsPath));
ofstream fout(GetPlatform().WritablePathForFile(resultsPath).c_str(), ios::app);
fout << "END " << m_startTime << endl;
}
void BenchmarkFramework::MarkBenchmarkResultsStart()
{
string resultsPath;
Settings::Get("BenchmarkResults", resultsPath);
LOG(LINFO, (resultsPath));
ofstream fout(GetPlatform().WritablePathForFile(resultsPath).c_str(), ios::app);
fout << "START " << m_startTime << endl;
}
void BenchmarkFramework::NextBenchmarkCommand()
{
if ((m_benchmarks[m_curBenchmark].m_provider->hasRect()) || (++m_curBenchmark < m_benchmarks.size()))
{
m_curBenchmarkRect = m_benchmarks[m_curBenchmark].m_provider->nextRect();
Framework::m_navigator.SetFromRect(m2::AnyRectD(m_curBenchmarkRect));
Framework::Invalidate();
}
else
{
static bool isFirstTime = true;
if (isFirstTime)
{
m_isBenchmarkFinished = true;
isFirstTime = false;
SaveBenchmarkResults();
MarkBenchmarkResultsEnd();
SendBenchmarkResults();
LOG(LINFO, ("Bechmarks took ", m_benchmarksTimer.ElapsedSeconds(), " seconds to complete"));
}
}
}
void BenchmarkFramework::InitBenchmark()
{
DoGetBenchmarks<Benchmark> doGet(m_benchmarks);
ForEachBenchmarkRecord(doGet);
m_curBenchmark = 0;
//base_type::m_renderPolicy->addAfterFrame(bind(&this_type::BenchmarkCommandFinished, this));
m_benchmarksTimer.Reset();
MarkBenchmarkResultsStart();
NextBenchmarkCommand();
Framework::Invalidate();
}
void BenchmarkFramework::OnSize(int w, int h)
{
Framework::OnSize(w, h);
if (!m_isBenchmarkInitialized)
{
m_isBenchmarkInitialized = true;
InitBenchmark();
}
}
void BenchmarkFramework::DoPaint(shared_ptr<PaintEvent> const & e)
{
double s = m_benchmarksTimer.ElapsedSeconds();
Framework::DoPaint(e);
m_paintDuration += m_benchmarksTimer.ElapsedSeconds() - s;
if (!m_isBenchmarkFinished)
BenchmarkCommandFinished();
}
<commit_msg>fixed errors in settings curBenchmarkRect<commit_after>#include "benchmark_framework.hpp"
#include "benchmark_provider.hpp"
#include "../coding/file_container.hpp"
#include "../std/fstream.hpp"
#include "../platform/settings.hpp"
#include "../version/version.hpp"
template <class T> class DoGetBenchmarks
{
set<string> m_processed;
vector<T> & m_benchmarks;
Navigator & m_navigator;
Platform & m_pl;
public:
DoGetBenchmarks(vector<T> & benchmarks, Navigator & navigator)
: m_benchmarks(benchmarks), m_navigator(navigator), m_pl(GetPlatform())
{
}
void operator() (vector<string> const & v)
{
if (v[0][0] == '#')
return;
T b;
b.m_name = v[1];
m2::RectD r;
if (m_processed.insert(v[0]).second)
{
try
{
feature::DataHeader header;
header.Load(FilesContainerR(m_pl.GetReader(v[0])).GetReader(HEADER_FILE_TAG));
r = header.GetBounds();
}
catch (RootException const & e)
{
LOG(LINFO, ("Cannot add ", v[0], " file to benchmark: ", e.what()));
return;
}
}
int lastScale;
if (v.size() > 3)
{
double x0, y0, x1, y1;
strings::to_double(v[2], x0);
strings::to_double(v[3], y0);
strings::to_double(v[4], x1);
strings::to_double(v[5], y1);
r = m2::RectD(x0, y0, x1, y1);
strings::to_int(v[6], lastScale);
}
else
strings::to_int(v[2], lastScale);
ASSERT ( r != m2::RectD::GetEmptyRect(), (r) );
m_navigator.SetFromRect(m2::AnyRectD(r));
r = m_navigator.Screen().GlobalRect().GetGlobalRect();
b.m_provider.reset(new BenchmarkRectProvider(scales::GetScaleLevel(r), r, lastScale));
m_benchmarks.push_back(b);
}
};
template <class ToDo>
void ForEachBenchmarkRecord(ToDo & toDo)
{
Platform & pl = GetPlatform();
string buffer;
try
{
string configPath;
Settings::Get("BenchmarkConfig", configPath);
ReaderPtr<Reader>(pl.GetReader(configPath)).ReadAsString(buffer);
}
catch (RootException const & e)
{
LOG(LERROR, ("Error reading benchmarks: ", e.what()));
return;
}
istringstream stream(buffer);
string line;
while (stream.good())
{
getline(stream, line);
vector<string> parts;
strings::SimpleTokenizer it(line, " ");
while (it)
{
parts.push_back(*it);
++it;
}
if (!parts.empty())
toDo(parts);
}
}
struct MapsCollector
{
vector<string> m_maps;
void operator() (vector<string> const & v)
{
if (!v[0].empty())
if (v[0][0] == '#')
return;
m_maps.push_back(v[0]);
}
};
void BenchmarkFramework::ReAddLocalMaps()
{
// remove all previously added maps in framework constructor
Platform::FilesList files;
Framework::GetLocalMaps(files);
for_each(files.begin(), files.end(),
bind(&BenchmarkFramework::RemoveMap, this, _1));
// add only maps needed for benchmarks
MapsCollector collector;
ForEachBenchmarkRecord(collector);
for_each(collector.m_maps.begin(), collector.m_maps.end(),
bind(&BenchmarkFramework::AddMap, this, _1));
}
BenchmarkFramework::BenchmarkFramework()
: m_paintDuration(0),
m_maxDuration(0),
m_isBenchmarkFinished(false),
m_isBenchmarkInitialized(false)
{
m_startTime = my::FormatCurrentTime();
Framework::m_informationDisplay.enableBenchmarkInfo(true);
ReAddLocalMaps();
}
void BenchmarkFramework::BenchmarkCommandFinished()
{
double duration = m_paintDuration;
if (duration > m_maxDuration)
{
m_maxDuration = duration;
m_maxDurationRect = m_curBenchmarkRect;
Framework::m_informationDisplay.addBenchmarkInfo("maxDurationRect: ", m_maxDurationRect, m_maxDuration);
}
BenchmarkResult res;
res.m_name = m_benchmarks[m_curBenchmark].m_name;
res.m_rect = m_curBenchmarkRect;
res.m_time = duration;
m_benchmarkResults.push_back(res);
if (m_benchmarkResults.size() > 100)
SaveBenchmarkResults();
m_paintDuration = 0;
if (!m_isBenchmarkFinished)
NextBenchmarkCommand();
}
void BenchmarkFramework::SaveBenchmarkResults()
{
string resultsPath;
Settings::Get("BenchmarkResults", resultsPath);
LOG(LINFO, (resultsPath));
ofstream fout(GetPlatform().WritablePathForFile(resultsPath).c_str(), ios::app);
for (size_t i = 0; i < m_benchmarkResults.size(); ++i)
{
fout << GetPlatform().DeviceName() << " "
<< VERSION_STRING << " "
<< m_startTime << " "
<< m_benchmarkResults[i].m_name << " "
<< m_benchmarkResults[i].m_rect.minX() << " "
<< m_benchmarkResults[i].m_rect.minY() << " "
<< m_benchmarkResults[i].m_rect.maxX() << " "
<< m_benchmarkResults[i].m_rect.maxY() << " "
<< m_benchmarkResults[i].m_time << endl;
}
m_benchmarkResults.clear();
}
void BenchmarkFramework::SendBenchmarkResults()
{
// ofstream fout(GetPlatform().WritablePathForFile("benchmarks/results.txt").c_str(), ios::app);
// fout << "[COMPLETED]";
// fout.close();
/// send to server for adding to statistics graphics
/// and delete results file
}
void BenchmarkFramework::MarkBenchmarkResultsEnd()
{
string resultsPath;
Settings::Get("BenchmarkResults", resultsPath);
LOG(LINFO, (resultsPath));
ofstream fout(GetPlatform().WritablePathForFile(resultsPath).c_str(), ios::app);
fout << "END " << m_startTime << endl;
}
void BenchmarkFramework::MarkBenchmarkResultsStart()
{
string resultsPath;
Settings::Get("BenchmarkResults", resultsPath);
LOG(LINFO, (resultsPath));
ofstream fout(GetPlatform().WritablePathForFile(resultsPath).c_str(), ios::app);
fout << "START " << m_startTime << endl;
}
void BenchmarkFramework::NextBenchmarkCommand()
{
if ((m_benchmarks[m_curBenchmark].m_provider->hasRect()) || (++m_curBenchmark < m_benchmarks.size()))
{
Framework::m_navigator.SetFromRect(m2::AnyRectD(m_benchmarks[m_curBenchmark].m_provider->nextRect()));
m_curBenchmarkRect = Framework::m_navigator.Screen().GlobalRect().GetGlobalRect();
Framework::Invalidate();
}
else
{
static bool isFirstTime = true;
if (isFirstTime)
{
m_isBenchmarkFinished = true;
isFirstTime = false;
SaveBenchmarkResults();
MarkBenchmarkResultsEnd();
SendBenchmarkResults();
LOG(LINFO, ("Bechmarks took ", m_benchmarksTimer.ElapsedSeconds(), " seconds to complete"));
}
}
}
void BenchmarkFramework::InitBenchmark()
{
DoGetBenchmarks<Benchmark> doGet(m_benchmarks, Framework::m_navigator);
ForEachBenchmarkRecord(doGet);
m_curBenchmark = 0;
//base_type::m_renderPolicy->addAfterFrame(bind(&this_type::BenchmarkCommandFinished, this));
m_benchmarksTimer.Reset();
MarkBenchmarkResultsStart();
NextBenchmarkCommand();
Framework::Invalidate();
}
void BenchmarkFramework::OnSize(int w, int h)
{
Framework::OnSize(w, h);
if (!m_isBenchmarkInitialized)
{
m_isBenchmarkInitialized = true;
InitBenchmark();
}
}
void BenchmarkFramework::DoPaint(shared_ptr<PaintEvent> const & e)
{
double s = m_benchmarksTimer.ElapsedSeconds();
Framework::DoPaint(e);
m_paintDuration += m_benchmarksTimer.ElapsedSeconds() - s;
if (!m_isBenchmarkFinished)
BenchmarkCommandFinished();
}
<|endoftext|>
|
<commit_before>#include "drakeJointUtil.h"
#include "makeUnique.h"
#include "DrakeJoint.h"
#include "HelicalJoint.h"
#include "PrismaticJoint.h"
#include "RevoluteJoint.h"
#include "QuaternionFloatingJoint.h"
#include "RollPitchYawFloatingJoint.h"
#include <cmath>
#include <stdexcept>
using namespace Eigen;
std::unique_ptr<DrakeJoint> createJoint(const std::string& joint_name, const Isometry3d& transform_to_parent_body, int floating, const Vector3d& joint_axis, double pitch)
{
std::unique_ptr<DrakeJoint> joint;
switch (floating) {
case 0: {
if (pitch == 0.0) {
joint = std::make_unique<RevoluteJoint>(joint_name, transform_to_parent_body, joint_axis);
} else if (std::isinf(pitch)) {
joint = std::make_unique<PrismaticJoint>(joint_name, transform_to_parent_body, joint_axis);
} else {
joint = std::make_unique<HelicalJoint>(joint_name, transform_to_parent_body, joint_axis, pitch);
}
break;
}
case 1: {
joint = std::make_unique<RollPitchYawFloatingJoint>(joint_name, transform_to_parent_body);
break;
}
case 2: {
joint = std::make_unique<QuaternionFloatingJoint>(joint_name, transform_to_parent_body);
break;
}
default: {
std::ostringstream stream;
stream << "floating type " << floating << " not recognized.";
throw std::runtime_error(stream.str());
break;
}
}
return joint;
}
<commit_msg>got rid of makeUnique.h include and std::make_unique calls.<commit_after>#include "drakeJointUtil.h"
#include "DrakeJoint.h"
#include "HelicalJoint.h"
#include "PrismaticJoint.h"
#include "RevoluteJoint.h"
#include "QuaternionFloatingJoint.h"
#include "RollPitchYawFloatingJoint.h"
#include <cmath>
#include <stdexcept>
using namespace Eigen;
std::unique_ptr<DrakeJoint> createJoint(const std::string& joint_name, const Isometry3d& transform_to_parent_body, int floating, const Vector3d& joint_axis, double pitch)
{
std::unique_ptr<DrakeJoint> joint;
switch (floating) {
case 0: {
if (pitch == 0.0) {
joint = std::unique_ptr<RevoluteJoint>(new RevoluteJoint(joint_name, transform_to_parent_body, joint_axis));
} else if (std::isinf(pitch)) {
joint = std::unique_ptr<PrismaticJoint>(new PrismaticJoint(joint_name, transform_to_parent_body, joint_axis));
} else {
joint = std::unique_ptr<HelicalJoint>(new HelicalJoint(joint_name, transform_to_parent_body, joint_axis, pitch));
}
break;
}
case 1: {
joint = std::unique_ptr<RollPitchYawFloatingJoint>(new RollPitchYawFloatingJoint(joint_name, transform_to_parent_body));
break;
}
case 2: {
joint = std::unique_ptr<QuaternionFloatingJoint>(new QuaternionFloatingJoint(joint_name, transform_to_parent_body));
break;
}
default: {
std::ostringstream stream;
stream << "floating type " << floating << " not recognized.";
throw std::runtime_error(stream.str());
break;
}
}
return joint;
}
<|endoftext|>
|
<commit_before>#include "condor_common.h"
#include "MyString.h"
#include "condor_arglist.h"
#include "my_popen.h"
#include "condor_partition.h"
#include "condor_debug.h"
#include "condor_classad.h"
#include "condor_uid.h"
#include "XXX_bgd_attrs.h"
MyString pkind_xlate(PKind pkind);
PKind pkind_xlate(MyString pkind);
Partition::Partition() {
m_data = NULL;
m_initialized = false;
}
Partition::~Partition()
{
delete m_data;
m_initialized = false;
}
void Partition::attach(ClassAd *ad)
{
// if we attach over and over, then assume the previous data is defunct and
// get rid of it.
if (m_data != NULL) {
delete(m_data);
}
m_data = ad;
m_initialized = true;
}
ClassAd* Partition::detach(void)
{
ClassAd *ad = NULL;
ad = m_data;
m_initialized = false;
m_data = NULL;
return ad;
}
void Partition::set_name(MyString &name)
{
m_data->Assign(ATTR_PARTITION_NAME, name);
}
MyString Partition::get_name(void)
{
MyString name;
m_data->LookupString(ATTR_PARTITION_NAME, name);
return name;
}
void Partition::set_backer(MyString &name)
{
m_data->Assign(ATTR_PARTITION_BACKER, name);
}
MyString Partition::get_backer(void)
{
MyString name;
m_data->LookupString(ATTR_PARTITION_BACKER, name);
return name;
}
void Partition::set_size(size_t size)
{
// typecast due to classad integral types
m_data->Assign(ATTR_PARTITION_SIZE, (int)size);
}
size_t Partition::get_size(void)
{
int size;
m_data->LookupInteger(ATTR_PARTITION_SIZE, size);
// typecast due to classad integral types
return (size_t)size;
}
void Partition::set_pstate(PState pstate)
{
// typecast due to classad integral types
switch(pstate) {
case NOT_GENERATED:
m_data->Assign(ATTR_PARTITION_STATE, "NOT_GENERATED");
break;
case GENERATED:
m_data->Assign(ATTR_PARTITION_STATE, "GENERATED");
break;
case BOOTED:
m_data->Assign(ATTR_PARTITION_STATE, "BOOTED");
break;
case ASSIGNED:
m_data->Assign(ATTR_PARTITION_STATE, "ASSIGNED");
break;
case BACKED:
m_data->Assign(ATTR_PARTITION_STATE, "BACKED");
break;
default:
EXCEPT("Partition::set_pstate: Invalid pstate: %d\n", pstate);
break;
}
}
void Partition::set_pstate(MyString pstate)
{
if (pstate != "NOT_GENERATED" &&
pstate != "GENERATED" &&
pstate != "BOOTED" &&
pstate != "ASSIGNED" &&
pstate != "BACKED")
{
EXCEPT("Partition::set_pstate(): Invalid assignment string: %s\n",
pstate.Value());
}
m_data->Assign(ATTR_PARTITION_STATE, pstate);
}
PState Partition::get_pstate(void)
{
MyString pstate;
m_data->LookupString(ATTR_PARTITION_STATE, pstate);
if (pstate == "NOT_GENERATED") {
return NOT_GENERATED;
}
if (pstate == "GENERATED") {
return GENERATED;
}
if (pstate == "BOOTED") {
return BOOTED;
}
if (pstate == "ASSIGNED") {
return ASSIGNED;
}
if (pstate == "BACKED") {
return BACKED;
}
// should never happen, but in case it does...
return PSTATE_ERROR;
}
void Partition::set_pkind(PKind pkind)
{
// typecast due to classad integral types
switch(pkind) {
case SMP:
m_data->Assign(ATTR_PARTITION_KIND, "SMP");
break;
case DUAL:
m_data->Assign(ATTR_PARTITION_KIND, "DUAL");
break;
case VN:
m_data->Assign(ATTR_PARTITION_KIND, "VN");
break;
default:
EXCEPT("Partition::set_pstate: Invalid pkind: %d\n", pkind);
break;
}
}
void Partition::set_pkind(MyString pkind)
{
if (pkind != "SMP" &&
pkind != "DUAL" &&
pkind != "VN")
{
EXCEPT("Partition::set_pkind(): Invalid assignment string: %s\n",
pkind.Value());
}
m_data->Assign(ATTR_PARTITION_KIND, pkind);
}
PKind Partition::get_pkind(void)
{
MyString pkind;
m_data->LookupString(ATTR_PARTITION_KIND, pkind);
if (pkind == "SMP") {
return SMP;
}
if (pkind == "DUAL") {
return DUAL;
}
if (pkind == "VN") {
return VN;
}
// should never happen, but in case it does...
return PKIND_ERROR;
}
// This is a blocking call and must provide a fully booted partition when it
// returns. Otherwise, this partition could be overcommitted given the
// nature of the use of this call.
// script partition_name size kind
void Partition::boot(char *script, PKind pkind)
{
FILE *fin = NULL;
ArgList args;
MyString line;
priv_state priv;
// we're told what kind of partition this is going to be
set_pkind(pkind);
dprintf(D_ALWAYS, "\t%s %s %d %s\n",
script,
get_name().Value(),
get_size(),
pkind_xlate(get_pkind()).Value());
args.AppendArg(script);
args.AppendArg(get_name());
args.AppendArg(get_size());
args.AppendArg(pkind_xlate(get_pkind()).Value());
priv = set_root_priv();
fin = my_popen(args, "r", TRUE);
line.readLine(fin); // read back OK or NOT_OK, XXX ignore
my_pclose(fin);
set_priv(priv);
// Now that the script is done, mark it booted.
set_pstate(BOOTED);
}
void Partition::back(char *script)
{
FILE *fin = NULL;
ArgList args;
MyString line;
priv_state priv;
dprintf(D_ALWAYS, "\t%s %s %d %s\n",
script,
get_name().Value(),
get_size(),
pkind_xlate(get_pkind()).Value());
args.AppendArg(script);
args.AppendArg(get_name());
args.AppendArg(get_size());
args.AppendArg(pkind_xlate(get_pkind()).Value());
priv = set_root_priv();
fin = my_popen(args, "r", TRUE);
line.readLine(fin); // read back OK or NOT_OK, XXX ignore
my_pclose(fin);
set_priv(priv);
// we don't know it is backed until the BGD_SCRIPT_AVAILABLE_PARTITIONS
// tells us it is actually backed. This prevents overcommit of a
// partition to multiple startds.
set_pstate(ASSIGNED);
}
void Partition::dump(int flags)
{
MyString backer;
if (m_initialized == false) {
dprintf(flags, "Partition is not initialized!\n");
return;
}
dprintf(flags, "Parition: %s\n", get_name().Value());
backer = get_backer();
if (backer == "") {
dprintf(flags, "\tBacked by: [NONE]\n");
} else {
dprintf(flags, "\tBacked by: %s\n", backer.Value());
}
dprintf(flags, "\tSize: %d\n", get_size());
dprintf(flags, "\tPState: %d\n", get_pstate());
switch(get_pstate()) {
case BOOTED:
case ASSIGNED:
case BACKED:
dprintf(flags, "\tPKind: %d\n", get_pkind());
break;
default:
dprintf(flags, "\tPKind: N/A\n");
break;
}
}
MyString pkind_xlate(PKind pkind)
{
MyString p;
switch(pkind) {
case PKIND_ERROR:
p = "PKIND_ERROR";
break;
case SMP:
p = "SMP";
break;
case DUAL:
p = "DUAL";
break;
case VN:
p = "VN";
break;
case PKIND_END:
p = "PKIND_END";
break;
default:
p = "PKIND_ERROR";
break;
}
return p;
}
PKind pkind_xlate(MyString pkind)
{
if (pkind == "PKIND_ERROR") {
return PKIND_ERROR;
}
if (pkind == "SMP") {
return SMP;
}
if (pkind == "DUAL") {
return DUAL;
}
if (pkind == "VN") {
return VN;
}
if (pkind == "PKIND_END") {
return PKIND_END;
}
return PKIND_ERROR;
}
<commit_msg>Clarified debugging output.<commit_after>#include "condor_common.h"
#include "MyString.h"
#include "condor_arglist.h"
#include "my_popen.h"
#include "condor_partition.h"
#include "condor_debug.h"
#include "condor_classad.h"
#include "condor_uid.h"
#include "XXX_bgd_attrs.h"
MyString pkind_xlate(PKind pkind);
PKind pkind_xlate(MyString pkind);
MyString pstate_xlate(PState pstate);
PState pstate_xlate(MyString pstate);
Partition::Partition() {
m_data = NULL;
m_initialized = false;
}
Partition::~Partition()
{
delete m_data;
m_initialized = false;
}
void Partition::attach(ClassAd *ad)
{
// if we attach over and over, then assume the previous data is defunct and
// get rid of it.
if (m_data != NULL) {
delete(m_data);
}
m_data = ad;
m_initialized = true;
}
ClassAd* Partition::detach(void)
{
ClassAd *ad = NULL;
ad = m_data;
m_initialized = false;
m_data = NULL;
return ad;
}
void Partition::set_name(MyString &name)
{
m_data->Assign(ATTR_PARTITION_NAME, name);
}
MyString Partition::get_name(void)
{
MyString name;
m_data->LookupString(ATTR_PARTITION_NAME, name);
return name;
}
void Partition::set_backer(MyString &name)
{
m_data->Assign(ATTR_PARTITION_BACKER, name);
}
MyString Partition::get_backer(void)
{
MyString name;
m_data->LookupString(ATTR_PARTITION_BACKER, name);
return name;
}
void Partition::set_size(size_t size)
{
// typecast due to classad integral types
m_data->Assign(ATTR_PARTITION_SIZE, (int)size);
}
size_t Partition::get_size(void)
{
int size;
m_data->LookupInteger(ATTR_PARTITION_SIZE, size);
// typecast due to classad integral types
return (size_t)size;
}
void Partition::set_pstate(PState pstate)
{
// typecast due to classad integral types
switch(pstate) {
case NOT_GENERATED:
m_data->Assign(ATTR_PARTITION_STATE, "NOT_GENERATED");
break;
case GENERATED:
m_data->Assign(ATTR_PARTITION_STATE, "GENERATED");
break;
case BOOTED:
m_data->Assign(ATTR_PARTITION_STATE, "BOOTED");
break;
case ASSIGNED:
m_data->Assign(ATTR_PARTITION_STATE, "ASSIGNED");
break;
case BACKED:
m_data->Assign(ATTR_PARTITION_STATE, "BACKED");
break;
default:
EXCEPT("Partition::set_pstate: Invalid pstate: %d\n", pstate);
break;
}
}
void Partition::set_pstate(MyString pstate)
{
if (pstate != "NOT_GENERATED" &&
pstate != "GENERATED" &&
pstate != "BOOTED" &&
pstate != "ASSIGNED" &&
pstate != "BACKED")
{
EXCEPT("Partition::set_pstate(): Invalid assignment string: %s\n",
pstate.Value());
}
m_data->Assign(ATTR_PARTITION_STATE, pstate);
}
PState Partition::get_pstate(void)
{
MyString pstate;
m_data->LookupString(ATTR_PARTITION_STATE, pstate);
if (pstate == "NOT_GENERATED") {
return NOT_GENERATED;
}
if (pstate == "GENERATED") {
return GENERATED;
}
if (pstate == "BOOTED") {
return BOOTED;
}
if (pstate == "ASSIGNED") {
return ASSIGNED;
}
if (pstate == "BACKED") {
return BACKED;
}
// should never happen, but in case it does...
return PSTATE_ERROR;
}
void Partition::set_pkind(PKind pkind)
{
// typecast due to classad integral types
switch(pkind) {
case SMP:
m_data->Assign(ATTR_PARTITION_KIND, "SMP");
break;
case DUAL:
m_data->Assign(ATTR_PARTITION_KIND, "DUAL");
break;
case VN:
m_data->Assign(ATTR_PARTITION_KIND, "VN");
break;
default:
EXCEPT("Partition::set_pstate: Invalid pkind: %d\n", pkind);
break;
}
}
void Partition::set_pkind(MyString pkind)
{
if (pkind != "SMP" &&
pkind != "DUAL" &&
pkind != "VN")
{
EXCEPT("Partition::set_pkind(): Invalid assignment string: %s\n",
pkind.Value());
}
m_data->Assign(ATTR_PARTITION_KIND, pkind);
}
PKind Partition::get_pkind(void)
{
MyString pkind;
m_data->LookupString(ATTR_PARTITION_KIND, pkind);
if (pkind == "SMP") {
return SMP;
}
if (pkind == "DUAL") {
return DUAL;
}
if (pkind == "VN") {
return VN;
}
// should never happen, but in case it does...
return PKIND_ERROR;
}
// This is a blocking call and must provide a fully booted partition when it
// returns. Otherwise, this partition could be overcommitted given the
// nature of the use of this call.
// script partition_name size kind
void Partition::boot(char *script, PKind pkind)
{
FILE *fin = NULL;
ArgList args;
MyString line;
priv_state priv;
// we're told what kind of partition this is going to be
set_pkind(pkind);
dprintf(D_ALWAYS, "\t%s %s %d %s\n",
script,
get_name().Value(),
get_size(),
pkind_xlate(get_pkind()).Value());
args.AppendArg(script);
args.AppendArg(get_name());
args.AppendArg(get_size());
args.AppendArg(pkind_xlate(get_pkind()).Value());
priv = set_root_priv();
fin = my_popen(args, "r", TRUE);
line.readLine(fin); // read back OK or NOT_OK, XXX ignore
my_pclose(fin);
set_priv(priv);
// Now that the script is done, mark it booted.
set_pstate(BOOTED);
}
void Partition::back(char *script)
{
FILE *fin = NULL;
ArgList args;
MyString line;
priv_state priv;
dprintf(D_ALWAYS, "\t%s %s %d %s\n",
script,
get_name().Value(),
get_size(),
pkind_xlate(get_pkind()).Value());
args.AppendArg(script);
args.AppendArg(get_name());
args.AppendArg(get_size());
args.AppendArg(pkind_xlate(get_pkind()).Value());
priv = set_root_priv();
fin = my_popen(args, "r", TRUE);
line.readLine(fin); // read back OK or NOT_OK, XXX ignore
my_pclose(fin);
set_priv(priv);
// we don't know it is backed until the BGD_SCRIPT_AVAILABLE_PARTITIONS
// tells us it is actually backed. This prevents overcommit of a
// partition to multiple startds.
set_pstate(ASSIGNED);
}
void Partition::dump(int flags)
{
MyString backer;
if (m_initialized == false) {
dprintf(flags, "Partition is not initialized!\n");
return;
}
dprintf(flags, "Parition: %s\n", get_name().Value());
backer = get_backer();
if (backer == "") {
dprintf(flags, "\tBacked by: [NONE]\n");
} else {
dprintf(flags, "\tBacked by: %s\n", backer.Value());
}
dprintf(flags, "\tSize: %d\n", get_size());
dprintf(flags, "\tPState: %s\n", pstate_xlate(get_pstate()).Value());
switch(get_pstate()) {
case BOOTED:
case ASSIGNED:
case BACKED:
dprintf(flags, "\tPKind: %s\n", pkind_xlate(get_pkind()).Value());
break;
default:
dprintf(flags, "\tPKind: N/A\n");
break;
}
}
MyString pkind_xlate(PKind pkind)
{
MyString p;
switch(pkind) {
case PKIND_ERROR:
p = "PKIND_ERROR";
break;
case SMP:
p = "SMP";
break;
case DUAL:
p = "DUAL";
break;
case VN:
p = "VN";
break;
case PKIND_END:
p = "PKIND_END";
break;
default:
p = "PKIND_ERROR";
break;
}
return p;
}
PKind pkind_xlate(MyString pkind)
{
if (pkind == "PKIND_ERROR") {
return PKIND_ERROR;
}
if (pkind == "SMP") {
return SMP;
}
if (pkind == "DUAL") {
return DUAL;
}
if (pkind == "VN") {
return VN;
}
if (pkind == "PKIND_END") {
return PKIND_END;
}
return PKIND_ERROR;
}
MyString pstate_xlate(PState pstate)
{
MyString p;
switch(pstate) {
case PSTATE_ERROR:
p = "PSTATE_ERROR";
break;
case NOT_GENERATED:
p = "NOT_GENERATED";
break;
case GENERATED:
p = "GENERATED";
break;
case BOOTED:
p = "BOOTED";
break;
case ASSIGNED:
p = "ASSIGNED";
break;
case BACKED:
p = "BACKED";
break;
case PSTATE_END:
p = "PSTATE_END";
break;
default:
p = "PKIND_ERROR";
break;
}
return p;
}
PState pstate_xlate(MyString pstate)
{
if (pstate == "PSTATE_ERROR") {
return PSTATE_ERROR;
}
if (pstate == "NOT_GENERATED") {
return NOT_GENERATED;
}
if (pstate == "GENERATED") {
return GENERATED;
}
if (pstate == "BOOTED") {
return BOOTED;
}
if (pstate == "ASSIGNED") {
return ASSIGNED;
}
if (pstate == "BACKED") {
return BACKED;
}
if (pstate == "PSTATE_END") {
return PSTATE_END;
}
return PSTATE_ERROR;
}
<|endoftext|>
|
<commit_before>/*
* Copyright (C) 2013 midnightBITS
*
* 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 "pch.h"
#include <handlers.hpp>
#include <dbconn.hpp>
#include <locale.hpp>
#include <string.h>
#include <http.hpp>
#include "args.hpp"
#include "server_config.hpp"
#include <exception>
#include <stdexcept>
#include <remote/signals.hpp>
#include <remote/pid.hpp>
#include <remote/identity.hpp>
namespace fs = filesystem;
#define THREAD_COUNT 1
#ifdef _WIN32
# define CONFIG_FILE APP_PATH "config/reedr.conf"
#else
# define CONFIG_FILE "/etc/reedr/reedr.conf"
#endif
//#define CONFIG_DBG
REGISTER_REDIRECT("/", "/view/");
class Thread: public FastCGI::Thread
{
unsigned long m_load;
public:
Thread(): m_load(0) {}
Thread(const char* uri): FastCGI::Thread(uri) {}
void onRequest(FastCGI::Request& req)
{
++m_load;
FastCGI::app::HandlerPtr handler = FastCGI::app::Handlers::handler(req);
if (handler.get() != nullptr)
handler->visit(req);
else
req.on404();
}
unsigned long getLoad() const
{
return m_load;
}
};
#define RETURN_IF_ERROR(cmd) do { auto ret = (cmd); if (ret) return ret; } while (0)
class RemoteLogger : public remote::logger
{
class StreamLogger : public remote::stream_logger
{
FastCGI::ApplicationLog m_log;
public:
StreamLogger(const char* path, int line)
: m_log{ path, line }
{}
std::ostream& out() override { return m_log.log(); }
};
public:
remote::stream_logger_ptr line(const char* path, int line) override
{
return std::make_shared<StreamLogger>(path, line);
}
};
struct Main
{
FastCGI::FLogSource log;
remote::signals signals;
Args args;
fs::path cfg_dir;
std::shared_ptr<ProxyConfig> config_file;
Config config{ config_file };
Main()
: signals{ std::make_shared<RemoteLogger>() }
, config_file{ std::make_shared<ProxyConfig>() }
{
}
int run(int argc, char* argv[])
{
RETURN_IF_ERROR(args.read(argc, argv));
if (args.version)
return version();
bool cfg_needed = true;
fs::path cfg{ args.config };
if (cfg.empty())
{
cfg_needed = false;
cfg = CONFIG_FILE;
}
if (cfg.is_relative())
cfg = fs::absolute(cfg);
cfg_dir = cfg.parent_path();
#ifdef CONFIG_DBG
std::cout << "Config is: " << cfg << std::endl;
#endif
config_file->m_proxy = config::base::file_config(cfg, cfg_needed);
if (!config_file->m_proxy)
{
FLOG << "Could not open " << args.config;
std::cerr << "Could not open " << args.config << std::endl;
return 1;
}
config_file->set_read_only(true);
#ifdef CONFIG_DBG
std::cout
<< "\nconfig.server.address: " << config.server.address
<< "\nconfig.server.static_web: " << config.server.static_web
<< "\nconfig.server.user: " << config.server.user
<< "\nconfig.server.group: " << config.server.group
<< "\nconfig.server.pidfile: " << config.server.pidfile << " -> " << path(config.server.pidfile)
<< "\nconfig.connection.database: " << config.connection.database << " -> " << path(config.connection.database)
<< "\nconfig.connection.smtp: " << config.connection.smtp << " -> " << path(config.connection.smtp)
<< "\nconfig.data.dir: " << config.data.dir << " -> " << path(config.data.dir)
<< "\nconfig.data.locales: " << config.data.locales
<< "\nconfig.data.charset: " << config.data.charset
<< "\nconfig.logs.dir: " << config.logs.dir << " -> " << path(config.logs.dir)
<< "\nconfig.logs.access: " << config.logs.access
<< "\nconfig.logs.debug: " << config.logs.debug
<< std::endl;
#endif
config.server.pidfile = canonical(config.server.pidfile);
config.connection.database = canonical(config.connection.database);
config.connection.smtp = canonical(config.connection.smtp);
config.data.dir = canonical(config.data.dir);
config.data.locales = fs::canonical(config.data.locales, config.data.dir);
config.data.charset = fs::canonical(config.data.charset, config.data.dir);
config.logs.dir = canonical(config.logs.dir);
config.logs.access = fs::canonical(config.logs.access, config.logs.dir);
config.logs.debug = fs::canonical(config.logs.debug, config.logs.dir);
#ifdef CONFIG_DBG
std::cout
<< "\nconfig.data.locales: " << config.data.locales
<< "\nconfig.data.charset: " << config.data.charset
<< "\nconfig.logs.access: " << config.logs.access
<< "\nconfig.logs.debug: " << config.logs.debug
<< std::endl;
#endif
if (!log.open(debug_log()))
std::cerr << "Could not open " << debug_log() << std::endl;
if (!args.command.empty())
return commands(argc, argv);
if (!args.uri.empty())
return run<Debug>();
return run<FCGI>();
}
int version()
{
std::cout << http::getUserAgent() << std::endl;
return 0;
}
fs::path canonical(const fs::path& file)
{
return fs::canonical(file, cfg_dir);
}
fs::path pidfile() { return config.server.pidfile; }
fs::path charset() { return config.data.charset; }
fs::path locale() { return config.data.locales; }
fs::path debug_log() { return config.logs.debug; }
fs::path access_log() { return config.logs.access; }
int commands(int argc, char* argv[])
{
for (auto& c : args.command)
c = ::tolower((unsigned char)c);
if (args.command == "start")
return args.respawn(std::make_shared<RemoteLogger>(), config.server.address, argc, argv);
int pid = -1;
if (!remote::pid::read(pidfile().native(), pid))
{
std::cerr << pidfile() << " not found.\n";
return 1;
}
signals.signal(args.command.c_str(), pid);
return 0;
}
bool impersonate()
{
std::string name = config.server.user;
if (name.empty())
return true;
std::string group = config.server.group;
switch (remote::change_identity(name.c_str(), group.c_str()))
{
case remote::identity::ok:
return true;
case remote::identity::no_access:
FLOG << "Could not impersonate " << name << "/" << group;
break;
case remote::identity::name_unknown:
FLOG << "User " << name << " unknown";
break;
case remote::identity::group_unknown:
FLOG << "Group " << group << " unknown";
break;
case remote::identity::oom:
FLOG << "Out of memory when trying to impersonate " << name << "/" << group;
break;
}
return false;
}
template <typename Runtime>
int run()
{
try
{
remote::pid guard(pidfile().native());
if (!impersonate())
return 1;
db::environment env;
if (env.failed) return 1;
http::init(charset());
FastCGI::Application app;
RETURN_IF_ERROR(app.init(locale()));
app.setStaticResources(config.server.static_web);
app.setDBConn(config.connection.database);
app.setSMTPConn(config.connection.smtp);
app.setAccessLog(config.logs.access);
signals.set("stop", [&app](){ app.shutdown(); });
return Runtime::run(*this, app);
}
catch (std::exception& ex)
{
std::cout << "error:" << ex.what() << std::endl;
FLOG << "error: " << ex.what();
return 1;
}
catch (...)
{
std::cout << "unknown error." << std::endl;
FLOG << "unknown error";
return 1;
}
}
struct Debug
{
static int run(Main& service, FastCGI::Application& app)
{
Thread local(service.args.uri.c_str());
local.setApplication(app);
app.addStlSession();
std::cout << "Enter the input stream and finish with ^Z:" << std::endl;
local.handleRequest();
return 0;
}
};
struct FCGI
{
static int run(Main& service, FastCGI::Application& app)
{
if (!app.addThreads<Thread>(THREAD_COUNT))
return 1;
FLOG << "Application started";
app.run();
FLOG << "Application stopped";
return 0;
}
};
};
int main (int argc, char* argv[])
{
Main service;
return service.run(argc, argv);
}
<commit_msg>Compilation fix<commit_after>/*
* Copyright (C) 2013 midnightBITS
*
* 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 "pch.h"
#include <handlers.hpp>
#include <dbconn.hpp>
#include <locale.hpp>
#include <string.h>
#include <http.hpp>
#include "args.hpp"
#include "server_config.hpp"
#include <exception>
#include <stdexcept>
#include <remote/signals.hpp>
#include <remote/pid.hpp>
#include <remote/identity.hpp>
namespace fs = filesystem;
#define THREAD_COUNT 1
#ifdef _WIN32
# define CONFIG_FILE APP_PATH "config/reedr.conf"
#else
# define CONFIG_FILE "/etc/reedr/reedr.conf"
#endif
//#define CONFIG_DBG
REGISTER_REDIRECT("/", "/view/");
class Thread: public FastCGI::Thread
{
unsigned long m_load;
public:
Thread(): m_load(0) {}
Thread(const char* uri): FastCGI::Thread(uri) {}
void onRequest(FastCGI::Request& req)
{
++m_load;
FastCGI::app::HandlerPtr handler = FastCGI::app::Handlers::handler(req);
if (handler.get() != nullptr)
handler->visit(req);
else
req.on404();
}
unsigned long getLoad() const
{
return m_load;
}
};
#define RETURN_IF_ERROR(cmd) do { auto ret = (cmd); if (ret) return ret; } while (0)
class RemoteLogger : public remote::logger
{
class StreamLogger : public remote::stream_logger
{
FastCGI::ApplicationLog m_log;
public:
StreamLogger(const char* path, int line)
: m_log{ path, line }
{}
std::ostream& out() override { return m_log.log(); }
};
public:
remote::stream_logger_ptr line(const char* path, int line) override
{
return std::make_shared<StreamLogger>(path, line);
}
};
struct Main
{
FastCGI::FLogSource log;
remote::signals signals;
Args args;
fs::path cfg_dir;
std::shared_ptr<ProxyConfig> config_file;
Config config{ config_file };
Main()
: signals{ std::make_shared<RemoteLogger>() }
, config_file{ std::make_shared<ProxyConfig>() }
{
}
int run(int argc, char* argv[])
{
RETURN_IF_ERROR(args.read(argc, argv));
if (args.version)
return version();
bool cfg_needed = true;
fs::path cfg{ args.config };
if (cfg.empty())
{
cfg_needed = false;
cfg = CONFIG_FILE;
}
if (cfg.is_relative())
cfg = fs::absolute(cfg);
cfg_dir = cfg.parent_path();
#ifdef CONFIG_DBG
std::cout << "Config is: " << cfg << std::endl;
#endif
config_file->m_proxy = config::base::file_config(cfg, cfg_needed);
if (!config_file->m_proxy)
{
FLOG << "Could not open " << args.config;
std::cerr << "Could not open " << args.config << std::endl;
return 1;
}
config_file->set_read_only(true);
#ifdef CONFIG_DBG
std::cout
<< "\nconfig.server.address: " << config.server.address
<< "\nconfig.server.static_web: " << config.server.static_web
<< "\nconfig.server.user: " << config.server.user
<< "\nconfig.server.group: " << config.server.group
<< "\nconfig.server.pidfile: " << config.server.pidfile << " -> " << canonical(config.server.pidfile)
<< "\nconfig.connection.database: " << config.connection.database << " -> " << canonical(config.connection.database)
<< "\nconfig.connection.smtp: " << config.connection.smtp << " -> " << canonical(config.connection.smtp)
<< "\nconfig.data.dir: " << config.data.dir << " -> " << canonical(config.data.dir)
<< "\nconfig.data.locales: " << config.data.locales
<< "\nconfig.data.charset: " << config.data.charset
<< "\nconfig.logs.dir: " << config.logs.dir << " -> " << canonical(config.logs.dir)
<< "\nconfig.logs.access: " << config.logs.access
<< "\nconfig.logs.debug: " << config.logs.debug
<< std::endl;
#endif
config.server.pidfile = canonical(config.server.pidfile);
config.connection.database = canonical(config.connection.database);
config.connection.smtp = canonical(config.connection.smtp);
config.data.dir = canonical(config.data.dir);
config.data.locales = fs::canonical(config.data.locales, config.data.dir);
config.data.charset = fs::canonical(config.data.charset, config.data.dir);
config.logs.dir = canonical(config.logs.dir);
config.logs.access = fs::canonical(config.logs.access, config.logs.dir);
config.logs.debug = fs::canonical(config.logs.debug, config.logs.dir);
#ifdef CONFIG_DBG
std::cout
<< "\nconfig.data.locales: " << config.data.locales
<< "\nconfig.data.charset: " << config.data.charset
<< "\nconfig.logs.access: " << config.logs.access
<< "\nconfig.logs.debug: " << config.logs.debug
<< std::endl;
#endif
if (!log.open(debug_log()))
std::cerr << "Could not open " << debug_log() << std::endl;
if (!args.command.empty())
return commands(argc, argv);
if (!args.uri.empty())
return run<Debug>();
return run<FCGI>();
}
int version()
{
std::cout << http::getUserAgent() << std::endl;
return 0;
}
fs::path canonical(const fs::path& file)
{
return fs::canonical(file, cfg_dir);
}
fs::path pidfile() { return config.server.pidfile; }
fs::path charset() { return config.data.charset; }
fs::path locale() { return config.data.locales; }
fs::path debug_log() { return config.logs.debug; }
fs::path access_log() { return config.logs.access; }
int commands(int argc, char* argv[])
{
for (auto& c : args.command)
c = ::tolower((unsigned char)c);
if (args.command == "start")
return args.respawn(std::make_shared<RemoteLogger>(), config.server.address, argc, argv);
int pid = -1;
if (!remote::pid::read(pidfile().native(), pid))
{
std::cerr << pidfile() << " not found.\n";
return 1;
}
signals.signal(args.command.c_str(), pid);
return 0;
}
bool impersonate()
{
std::string name = config.server.user;
if (name.empty())
return true;
std::string group = config.server.group;
switch (remote::change_identity(name.c_str(), group.c_str()))
{
case remote::identity::ok:
return true;
case remote::identity::no_access:
FLOG << "Could not impersonate " << name << "/" << group;
break;
case remote::identity::name_unknown:
FLOG << "User " << name << " unknown";
break;
case remote::identity::group_unknown:
FLOG << "Group " << group << " unknown";
break;
case remote::identity::oom:
FLOG << "Out of memory when trying to impersonate " << name << "/" << group;
break;
}
return false;
}
template <typename Runtime>
int run()
{
try
{
remote::pid guard(pidfile().native());
if (!impersonate())
return 1;
db::environment env;
if (env.failed) return 1;
http::init(charset());
FastCGI::Application app;
RETURN_IF_ERROR(app.init(locale()));
app.setStaticResources(config.server.static_web);
app.setDBConn(config.connection.database);
app.setSMTPConn(config.connection.smtp);
app.setAccessLog(config.logs.access);
signals.set("stop", [&app](){ app.shutdown(); });
return Runtime::run(*this, app);
}
catch (std::exception& ex)
{
std::cout << "error:" << ex.what() << std::endl;
FLOG << "error: " << ex.what();
return 1;
}
catch (...)
{
std::cout << "unknown error." << std::endl;
FLOG << "unknown error";
return 1;
}
}
struct Debug
{
static int run(Main& service, FastCGI::Application& app)
{
Thread local(service.args.uri.c_str());
local.setApplication(app);
app.addStlSession();
std::cout << "Enter the input stream and finish with ^Z:" << std::endl;
local.handleRequest();
return 0;
}
};
struct FCGI
{
static int run(Main& service, FastCGI::Application& app)
{
if (!app.addThreads<Thread>(THREAD_COUNT))
return 1;
FLOG << "Application started";
app.run();
FLOG << "Application stopped";
return 0;
}
};
};
int main (int argc, char* argv[])
{
Main service;
return service.run(argc, argv);
}
<|endoftext|>
|
<commit_before>/**************************************************************************
*
* Copyright 2011 Jose Fonseca
* All Rights Reserved.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
**************************************************************************/
#include <assert.h>
#include <stdlib.h>
#include <iostream>
#include "glproc.hpp"
#include "glws.hpp"
#include "glws_xlib.hpp"
namespace glws {
static unsigned glxVersion = 0;
static const char *extensions = 0;
static bool has_GLX_ARB_create_context = false;
static bool has_GLX_ARB_create_context_profile = false;
static bool has_GLX_EXT_create_context_es_profile = false;
static bool has_GLX_EXT_create_context_es2_profile = false;
class GlxVisual : public Visual
{
public:
GLXFBConfig fbconfig;
XVisualInfo *visinfo;
GlxVisual(Profile prof) :
Visual(prof),
fbconfig(0),
visinfo(0)
{}
~GlxVisual() {
XFree(visinfo);
}
};
class GlxDrawable : public Drawable
{
public:
Window window;
bool ever_current;
GlxDrawable(const Visual *vis, int w, int h, bool pbuffer) :
Drawable(vis, w, h, pbuffer),
ever_current(false)
{
XVisualInfo *visinfo = static_cast<const GlxVisual *>(visual)->visinfo;
const char *name = "glretrace";
window = createWindow(visinfo, name, width, height);
glXWaitX();
}
~GlxDrawable() {
XDestroyWindow(display, window);
}
void
resize(int w, int h) {
if (w == width && h == height) {
return;
}
glXWaitGL();
// We need to ensure that pending events are processed here, and XSync
// with discard = True guarantees that, but it appears the limited
// event processing we do so far is sufficient
//XSync(display, True);
Drawable::resize(w, h);
resizeWindow(window, w, h);
glXWaitX();
}
void show(void) {
if (visible) {
return;
}
glXWaitGL();
showWindow(window);
glXWaitX();
Drawable::show();
}
void copySubBuffer(int x, int y, int width, int height) {
glXCopySubBufferMESA(display, window, x, y, width, height);
processKeys(window);
}
void swapBuffers(void) {
if (ever_current) {
// The window has been bound to a context at least once
glXSwapBuffers(display, window);
} else {
// Don't call glXSwapBuffers on this window to avoid an
// (untrappable) X protocol error with NVIDIA's driver.
std::cerr << "warning: attempt to issue SwapBuffers on unbound window "
" - skipping.\n";
}
processKeys(window);
}
};
class GlxContext : public Context
{
public:
GLXContext context;
GlxContext(const Visual *vis, GLXContext ctx) :
Context(vis),
context(ctx)
{}
~GlxContext() {
glXDestroyContext(display, context);
}
};
void
init(void) {
initX();
int major = 0, minor = 0;
glXQueryVersion(display, &major, &minor);
glxVersion = (major << 8) | minor;
extensions = glXQueryExtensionsString(display, screen);
#define CHECK_EXTENSION(name) \
has_##name = checkExtension(#name, extensions)
CHECK_EXTENSION(GLX_ARB_create_context);
CHECK_EXTENSION(GLX_ARB_create_context_profile);
CHECK_EXTENSION(GLX_EXT_create_context_es_profile);
CHECK_EXTENSION(GLX_EXT_create_context_es2_profile);
#undef CHECK_EXTENSION
}
void
cleanup(void) {
cleanupX();
}
Visual *
createVisual(bool doubleBuffer, unsigned samples, Profile profile) {
GlxVisual *visual = new GlxVisual(profile);
if (glxVersion >= 0x0103) {
Attributes<int> attribs;
attribs.add(GLX_DRAWABLE_TYPE, GLX_WINDOW_BIT);
attribs.add(GLX_RENDER_TYPE, GLX_RGBA_BIT);
attribs.add(GLX_RED_SIZE, 1);
attribs.add(GLX_GREEN_SIZE, 1);
attribs.add(GLX_BLUE_SIZE, 1);
attribs.add(GLX_ALPHA_SIZE, 1);
attribs.add(GLX_DOUBLEBUFFER, doubleBuffer ? GL_TRUE : GL_FALSE);
attribs.add(GLX_DEPTH_SIZE, 1);
attribs.add(GLX_STENCIL_SIZE, 1);
if (samples > 1) {
attribs.add(GLX_SAMPLE_BUFFERS, 1);
attribs.add(GLX_SAMPLES_ARB, samples);
}
attribs.end();
int num_configs = 0;
GLXFBConfig * fbconfigs;
fbconfigs = glXChooseFBConfig(display, screen, attribs, &num_configs);
if (!num_configs || !fbconfigs) {
return NULL;
}
visual->fbconfig = fbconfigs[0];
assert(visual->fbconfig);
visual->visinfo = glXGetVisualFromFBConfig(display, visual->fbconfig);
assert(visual->visinfo);
} else {
Attributes<int> attribs;
attribs.add(GLX_RGBA);
attribs.add(GLX_RED_SIZE, 1);
attribs.add(GLX_GREEN_SIZE, 1);
attribs.add(GLX_BLUE_SIZE, 1);
attribs.add(GLX_ALPHA_SIZE, 1);
if (doubleBuffer) {
attribs.add(GLX_DOUBLEBUFFER);
}
attribs.add(GLX_DEPTH_SIZE, 1);
attribs.add(GLX_STENCIL_SIZE, 1);
if (samples > 1) {
attribs.add(GLX_SAMPLE_BUFFERS, 1);
attribs.add(GLX_SAMPLES_ARB, samples);
}
attribs.end();
visual->visinfo = glXChooseVisual(display, screen, attribs);
}
return visual;
}
Drawable *
createDrawable(const Visual *visual, int width, int height, bool pbuffer)
{
return new GlxDrawable(visual, width, height, pbuffer);
}
bool
bindApi(Api api)
{
return true;
}
Context *
createContext(const Visual *_visual, Context *shareContext, bool debug)
{
const GlxVisual *visual = static_cast<const GlxVisual *>(_visual);
Profile profile = visual->profile;
GLXContext share_context = NULL;
GLXContext context;
if (shareContext) {
share_context = static_cast<GlxContext*>(shareContext)->context;
}
if (glxVersion >= 0x0104 && has_GLX_ARB_create_context) {
Attributes<int> attribs;
attribs.add(GLX_RENDER_TYPE, GLX_RGBA_TYPE);
if (debug) {
attribs.add(GLX_CONTEXT_FLAGS_ARB, GLX_CONTEXT_DEBUG_BIT_ARB);
}
ProfileDesc desc;
getProfileDesc(profile, desc);
switch (profile) {
case PROFILE_COMPAT:
break;
case PROFILE_ES1:
if (!has_GLX_EXT_create_context_es_profile) {
return NULL;
}
attribs.add(GLX_CONTEXT_PROFILE_MASK_ARB, GLX_CONTEXT_ES_PROFILE_BIT_EXT);
attribs.add(GLX_CONTEXT_MAJOR_VERSION_ARB, 1);
break;
case PROFILE_ES2:
if (!has_GLX_EXT_create_context_es_profile &&
!has_GLX_EXT_create_context_es2_profile) {
return NULL;
}
attribs.add(GLX_CONTEXT_PROFILE_MASK_ARB, GLX_CONTEXT_ES_PROFILE_BIT_EXT);
attribs.add(GLX_CONTEXT_MAJOR_VERSION_ARB, 2);
break;
default:
{
attribs.add(GLX_CONTEXT_MAJOR_VERSION_ARB, desc.major);
attribs.add(GLX_CONTEXT_MINOR_VERSION_ARB, desc.minor);
if (desc.versionGreaterOrEqual(3, 2)) {
if (!has_GLX_ARB_create_context_profile) {
return NULL;
}
int profileMask = desc.core ? GLX_CONTEXT_CORE_PROFILE_BIT_ARB : GLX_CONTEXT_COMPATIBILITY_PROFILE_BIT_ARB;
attribs.add(GLX_CONTEXT_PROFILE_MASK_ARB, profileMask);
}
break;
}
}
attribs.end();
context = glXCreateContextAttribsARB(display, visual->fbconfig, share_context, True, attribs);
if (!context && debug) {
// XXX: Mesa has problems with GLX_CONTEXT_DEBUG_BIT_ARB with
// OpenGL ES contexts, so retry without it
return createContext(_visual, shareContext, false);
}
} else {
if (profile != PROFILE_COMPAT) {
return NULL;
}
if (glxVersion >= 0x103) {
context = glXCreateNewContext(display, visual->fbconfig, GLX_RGBA_TYPE, share_context, True);
} else {
context = glXCreateContext(display, visual->visinfo, share_context, True);
}
}
if (!context) {
return NULL;
}
return new GlxContext(visual, context);
}
bool
makeCurrent(Drawable *drawable, Context *context)
{
if (!drawable || !context) {
return glXMakeCurrent(display, None, NULL);
} else {
GlxDrawable *glxDrawable = static_cast<GlxDrawable *>(drawable);
GlxContext *glxContext = static_cast<GlxContext *>(context);
glxDrawable->ever_current = true;
return glXMakeCurrent(display, glxDrawable->window, glxContext->context);
}
}
} /* namespace glws */
<commit_msg>glws: Avoid referring to PROFILE_xxx directly in GLX backend.<commit_after>/**************************************************************************
*
* Copyright 2011 Jose Fonseca
* All Rights Reserved.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
**************************************************************************/
#include <assert.h>
#include <stdlib.h>
#include <iostream>
#include "glproc.hpp"
#include "glws.hpp"
#include "glws_xlib.hpp"
namespace glws {
static unsigned glxVersion = 0;
static const char *extensions = 0;
static bool has_GLX_ARB_create_context = false;
static bool has_GLX_ARB_create_context_profile = false;
static bool has_GLX_EXT_create_context_es_profile = false;
static bool has_GLX_EXT_create_context_es2_profile = false;
class GlxVisual : public Visual
{
public:
GLXFBConfig fbconfig;
XVisualInfo *visinfo;
GlxVisual(Profile prof) :
Visual(prof),
fbconfig(0),
visinfo(0)
{}
~GlxVisual() {
XFree(visinfo);
}
};
class GlxDrawable : public Drawable
{
public:
Window window;
bool ever_current;
GlxDrawable(const Visual *vis, int w, int h, bool pbuffer) :
Drawable(vis, w, h, pbuffer),
ever_current(false)
{
XVisualInfo *visinfo = static_cast<const GlxVisual *>(visual)->visinfo;
const char *name = "glretrace";
window = createWindow(visinfo, name, width, height);
glXWaitX();
}
~GlxDrawable() {
XDestroyWindow(display, window);
}
void
resize(int w, int h) {
if (w == width && h == height) {
return;
}
glXWaitGL();
// We need to ensure that pending events are processed here, and XSync
// with discard = True guarantees that, but it appears the limited
// event processing we do so far is sufficient
//XSync(display, True);
Drawable::resize(w, h);
resizeWindow(window, w, h);
glXWaitX();
}
void show(void) {
if (visible) {
return;
}
glXWaitGL();
showWindow(window);
glXWaitX();
Drawable::show();
}
void copySubBuffer(int x, int y, int width, int height) {
glXCopySubBufferMESA(display, window, x, y, width, height);
processKeys(window);
}
void swapBuffers(void) {
if (ever_current) {
// The window has been bound to a context at least once
glXSwapBuffers(display, window);
} else {
// Don't call glXSwapBuffers on this window to avoid an
// (untrappable) X protocol error with NVIDIA's driver.
std::cerr << "warning: attempt to issue SwapBuffers on unbound window "
" - skipping.\n";
}
processKeys(window);
}
};
class GlxContext : public Context
{
public:
GLXContext context;
GlxContext(const Visual *vis, GLXContext ctx) :
Context(vis),
context(ctx)
{}
~GlxContext() {
glXDestroyContext(display, context);
}
};
void
init(void) {
initX();
int major = 0, minor = 0;
glXQueryVersion(display, &major, &minor);
glxVersion = (major << 8) | minor;
extensions = glXQueryExtensionsString(display, screen);
#define CHECK_EXTENSION(name) \
has_##name = checkExtension(#name, extensions)
CHECK_EXTENSION(GLX_ARB_create_context);
CHECK_EXTENSION(GLX_ARB_create_context_profile);
CHECK_EXTENSION(GLX_EXT_create_context_es_profile);
CHECK_EXTENSION(GLX_EXT_create_context_es2_profile);
#undef CHECK_EXTENSION
}
void
cleanup(void) {
cleanupX();
}
Visual *
createVisual(bool doubleBuffer, unsigned samples, Profile profile) {
GlxVisual *visual = new GlxVisual(profile);
if (glxVersion >= 0x0103) {
Attributes<int> attribs;
attribs.add(GLX_DRAWABLE_TYPE, GLX_WINDOW_BIT);
attribs.add(GLX_RENDER_TYPE, GLX_RGBA_BIT);
attribs.add(GLX_RED_SIZE, 1);
attribs.add(GLX_GREEN_SIZE, 1);
attribs.add(GLX_BLUE_SIZE, 1);
attribs.add(GLX_ALPHA_SIZE, 1);
attribs.add(GLX_DOUBLEBUFFER, doubleBuffer ? GL_TRUE : GL_FALSE);
attribs.add(GLX_DEPTH_SIZE, 1);
attribs.add(GLX_STENCIL_SIZE, 1);
if (samples > 1) {
attribs.add(GLX_SAMPLE_BUFFERS, 1);
attribs.add(GLX_SAMPLES_ARB, samples);
}
attribs.end();
int num_configs = 0;
GLXFBConfig * fbconfigs;
fbconfigs = glXChooseFBConfig(display, screen, attribs, &num_configs);
if (!num_configs || !fbconfigs) {
return NULL;
}
visual->fbconfig = fbconfigs[0];
assert(visual->fbconfig);
visual->visinfo = glXGetVisualFromFBConfig(display, visual->fbconfig);
assert(visual->visinfo);
} else {
Attributes<int> attribs;
attribs.add(GLX_RGBA);
attribs.add(GLX_RED_SIZE, 1);
attribs.add(GLX_GREEN_SIZE, 1);
attribs.add(GLX_BLUE_SIZE, 1);
attribs.add(GLX_ALPHA_SIZE, 1);
if (doubleBuffer) {
attribs.add(GLX_DOUBLEBUFFER);
}
attribs.add(GLX_DEPTH_SIZE, 1);
attribs.add(GLX_STENCIL_SIZE, 1);
if (samples > 1) {
attribs.add(GLX_SAMPLE_BUFFERS, 1);
attribs.add(GLX_SAMPLES_ARB, samples);
}
attribs.end();
visual->visinfo = glXChooseVisual(display, screen, attribs);
}
return visual;
}
Drawable *
createDrawable(const Visual *visual, int width, int height, bool pbuffer)
{
return new GlxDrawable(visual, width, height, pbuffer);
}
bool
bindApi(Api api)
{
return true;
}
Context *
createContext(const Visual *_visual, Context *shareContext, bool debug)
{
const GlxVisual *visual = static_cast<const GlxVisual *>(_visual);
Profile profile = visual->profile;
GLXContext share_context = NULL;
GLXContext context;
if (shareContext) {
share_context = static_cast<GlxContext*>(shareContext)->context;
}
ProfileDesc desc;
getProfileDesc(profile, desc);
if (glxVersion >= 0x0104 && has_GLX_ARB_create_context) {
Attributes<int> attribs;
attribs.add(GLX_RENDER_TYPE, GLX_RGBA_TYPE);
if (desc.api == API_GL) {
attribs.add(GLX_CONTEXT_MAJOR_VERSION_ARB, desc.major);
attribs.add(GLX_CONTEXT_MINOR_VERSION_ARB, desc.minor);
if (desc.versionGreaterOrEqual(3, 2)) {
if (!has_GLX_ARB_create_context_profile) {
std::cerr << "error: GLX_ARB_create_context_profile not supported\n";
return NULL;
}
int profileMask = desc.core ? GLX_CONTEXT_CORE_PROFILE_BIT_ARB : GLX_CONTEXT_COMPATIBILITY_PROFILE_BIT_ARB;
attribs.add(GLX_CONTEXT_PROFILE_MASK_ARB, profileMask);
}
} else if (desc.api == API_GLES) {
if (has_GLX_EXT_create_context_es_profile) {
attribs.add(GLX_CONTEXT_PROFILE_MASK_ARB, GLX_CONTEXT_ES_PROFILE_BIT_EXT);
attribs.add(GLX_CONTEXT_MAJOR_VERSION_ARB, desc.major);
attribs.add(GLX_CONTEXT_MINOR_VERSION_ARB, desc.minor);
} else if (desc.major != 2) {
std::cerr << "warning: OpenGL ES " << desc.major << " requested but GLX_EXT_create_context_es_profile not supported\n";
} else if (has_GLX_EXT_create_context_es2_profile) {
assert(desc.major == 2);
attribs.add(GLX_CONTEXT_PROFILE_MASK_ARB, GLX_CONTEXT_ES2_PROFILE_BIT_EXT);
attribs.add(GLX_CONTEXT_MAJOR_VERSION_ARB, desc.major);
attribs.add(GLX_CONTEXT_MINOR_VERSION_ARB, desc.minor);
} else {
std::cerr << "warning: OpenGL ES " << desc.major << " requested but GLX_EXT_create_context_es_profile or GLX_EXT_create_context_es2_profile not supported\n";
}
} else {
assert(0);
}
if (debug) {
attribs.add(GLX_CONTEXT_FLAGS_ARB, GLX_CONTEXT_DEBUG_BIT_ARB);
}
attribs.end();
context = glXCreateContextAttribsARB(display, visual->fbconfig, share_context, True, attribs);
if (!context && debug) {
// XXX: Mesa has problems with GLX_CONTEXT_DEBUG_BIT_ARB with
// OpenGL ES contexts, so retry without it
return createContext(_visual, shareContext, false);
}
} else {
if (desc.api != API_GL ||
desc.core) {
return NULL;
}
if (glxVersion >= 0x103) {
context = glXCreateNewContext(display, visual->fbconfig, GLX_RGBA_TYPE, share_context, True);
} else {
context = glXCreateContext(display, visual->visinfo, share_context, True);
}
}
if (!context) {
return NULL;
}
return new GlxContext(visual, context);
}
bool
makeCurrent(Drawable *drawable, Context *context)
{
if (!drawable || !context) {
return glXMakeCurrent(display, None, NULL);
} else {
GlxDrawable *glxDrawable = static_cast<GlxDrawable *>(drawable);
GlxContext *glxContext = static_cast<GlxContext *>(context);
glxDrawable->ever_current = true;
return glXMakeCurrent(display, glxDrawable->window, glxContext->context);
}
}
} /* namespace glws */
<|endoftext|>
|
<commit_before>// Copyright 2016 ESRI
//
// All rights reserved under the copyright laws of the United States
// and applicable international laws, treaties, and conventions.
//
// You may freely redistribute and use this sample code, with or
// without modification, provided you include the original copyright
// notice and use restrictions.
//
// See the Sample code usage restrictions document for further information.
//
#include "Basemap.h"
#include "Map.h"
#include "Scene.h"
#include "GeoView.h"
#include "MapView.h"
#include "SceneView.h"
#include "IdentifyGraphicsOverlayResult.h"
#include "ToolResourceProvider.h"
#include <QUuid>
namespace Esri
{
namespace ArcGISRuntime
{
namespace Toolkit
{
ToolResourceProvider::ToolResourceProvider(QObject* parent /*= nullptr*/):
QObject(parent)
{
}
ToolResourceProvider* ToolResourceProvider::instance()
{
static ToolResourceProvider s_instance;
return &s_instance;
}
ToolResourceProvider::~ToolResourceProvider()
{
}
Map* ToolResourceProvider::map() const
{
return m_map;
}
void ToolResourceProvider::setMap(Map* newMap)
{
if (!newMap || newMap == m_map)
return;
m_map = newMap;
emit mapChanged();
}
Scene* ToolResourceProvider::scene() const
{
return m_scene;
}
void ToolResourceProvider::setScene(Scene* newScene)
{
if (!newScene || newScene == m_scene)
return;
m_scene = newScene;
emit sceneChanged();
}
GeoView* ToolResourceProvider::geoView() const
{
return m_geoView;
}
void ToolResourceProvider::setGeoView(GeoView* newGeoView)
{
if (!newGeoView || newGeoView == m_geoView)
return;
m_geoView = newGeoView;
emit geoViewChanged();
if (!m_geoView->spatialReference().isEmpty())
emit spatialReferenceChanged();
}
SpatialReference ToolResourceProvider::spatialReference() const
{
return m_geoView ? m_geoView->spatialReference() : SpatialReference();
}
LayerListModel* ToolResourceProvider::operationalLayers() const
{
if (m_map)
return m_map->operationalLayers();
else if (m_scene)
return m_scene->operationalLayers();
return nullptr;
}
void ToolResourceProvider::setBasemap(Basemap* newBasemap)
{
if (!newBasemap)
return;
if (m_map)
{
newBasemap->setParent(m_map);
m_map->setBasemap(newBasemap);
}
else if (m_scene)
{
newBasemap->setParent(m_scene);
m_scene->setBasemap(newBasemap);
}
}
void ToolResourceProvider::setMouseCursor(const QCursor& cursor)
{
emit setMouseCursorRequested(cursor);
}
void ToolResourceProvider::onMouseClicked(QMouseEvent& mouseEvent)
{
emit mouseClicked(mouseEvent);
if (!m_geoView)
return;
if (m_scene)
emit mouseClickedPoint(static_cast<SceneView*>(m_geoView)->screenToBaseSurface(mouseEvent.x(), mouseEvent.y()));
else if (m_map)
emit mouseClickedPoint(static_cast<MapView*>(m_geoView)->screenToLocation(mouseEvent.x(), mouseEvent.y()));
else if (dynamic_cast<SceneView*>(m_geoView))
emit mouseClickedPoint(static_cast<SceneView*>(m_geoView)->screenToBaseSurface(mouseEvent.x(), mouseEvent.y()));
else if (dynamic_cast<MapView*>(m_geoView))
emit mouseClickedPoint(static_cast<MapView*>(m_geoView)->screenToLocation(mouseEvent.x(), mouseEvent.y()));
}
void ToolResourceProvider::onMousePressed(QMouseEvent &mouseEvent)
{
emit mousePressed(mouseEvent);
if (!m_geoView)
return;
if (m_scene)
emit mousePressedPoint(static_cast<SceneView*>(m_geoView)->screenToBaseSurface(mouseEvent.x(), mouseEvent.y()));
else if (m_map)
emit mousePressedPoint(static_cast<MapView*>(m_geoView)->screenToLocation(mouseEvent.x(), mouseEvent.y()));
else if (dynamic_cast<SceneView*>(m_geoView))
emit mousePressedPoint(static_cast<SceneView*>(m_geoView)->screenToBaseSurface(mouseEvent.x(), mouseEvent.y()));
else if (dynamic_cast<MapView*>(m_geoView))
emit mousePressedPoint(static_cast<MapView*>(m_geoView)->screenToLocation(mouseEvent.x(), mouseEvent.y()));
}
void ToolResourceProvider::onMouseMoved(QMouseEvent &mouseEvent)
{
emit mouseMoved(mouseEvent);
if (!m_geoView)
return;
if (m_scene)
emit mouseMovedPoint(static_cast<SceneView*>(m_geoView)->screenToBaseSurface(mouseEvent.x(), mouseEvent.y()));
else if (m_map)
emit mouseMovedPoint(static_cast<MapView*>(m_geoView)->screenToLocation(mouseEvent.x(), mouseEvent.y()));
else if (dynamic_cast<SceneView*>(m_geoView))
emit mouseMovedPoint(static_cast<SceneView*>(m_geoView)->screenToBaseSurface(mouseEvent.x(), mouseEvent.y()));
else if (dynamic_cast<MapView*>(m_geoView))
emit mouseMovedPoint(static_cast<MapView*>(m_geoView)->screenToLocation(mouseEvent.x(), mouseEvent.y()));
}
void ToolResourceProvider::onMouseReleased(QMouseEvent &mouseEvent)
{
emit mouseReleased(mouseEvent);
if (!m_geoView)
return;
if (m_scene)
emit mouseReleasedPoint(static_cast<SceneView*>(m_geoView)->screenToBaseSurface(mouseEvent.x(), mouseEvent.y()));
else if (m_map)
emit mouseReleasedPoint(static_cast<MapView*>(m_geoView)->screenToLocation(mouseEvent.x(), mouseEvent.y()));
else if (dynamic_cast<SceneView*>(m_geoView))
emit mouseReleasedPoint(static_cast<SceneView*>(m_geoView)->screenToBaseSurface(mouseEvent.x(), mouseEvent.y()));
else if (dynamic_cast<MapView*>(m_geoView))
emit mouseReleasedPoint(static_cast<MapView*>(m_geoView)->screenToLocation(mouseEvent.x(), mouseEvent.y()));
}
void ToolResourceProvider::onMousePressedAndHeld(QMouseEvent &mouseEvent)
{
emit mousePressedAndHeld(mouseEvent);
if (!m_geoView)
return;
if (m_scene)
emit mousePressedAndHeldPoint(static_cast<SceneView*>(m_geoView)->screenToBaseSurface(mouseEvent.x(), mouseEvent.y()));
else if (m_map)
emit mousePressedAndHeldPoint(static_cast<MapView*>(m_geoView)->screenToLocation(mouseEvent.x(), mouseEvent.y()));
else if (dynamic_cast<SceneView*>(m_geoView))
emit mousePressedAndHeldPoint(static_cast<SceneView*>(m_geoView)->screenToBaseSurface(mouseEvent.x(), mouseEvent.y()));
else if (dynamic_cast<MapView*>(m_geoView))
emit mousePressedAndHeldPoint(static_cast<MapView*>(m_geoView)->screenToLocation(mouseEvent.x(), mouseEvent.y()));
}
void ToolResourceProvider::onMouseDoubleClicked(QMouseEvent &mouseEvent)
{
emit mouseDoubleClicked(mouseEvent);
if (!m_geoView)
return;
if (m_scene)
emit mouseDoubleClickedPoint(static_cast<SceneView*>(m_geoView)->screenToBaseSurface(mouseEvent.x(), mouseEvent.y()));
else if (m_map)
emit mouseDoubleClickedPoint(static_cast<MapView*>(m_geoView)->screenToLocation(mouseEvent.x(), mouseEvent.y()));
else if (dynamic_cast<SceneView*>(m_geoView))
emit mouseDoubleClickedPoint(static_cast<SceneView*>(m_geoView)->screenToBaseSurface(mouseEvent.x(), mouseEvent.y()));
else if (dynamic_cast<MapView*>(m_geoView))
emit mouseDoubleClickedPoint(static_cast<MapView*>(m_geoView)->screenToLocation(mouseEvent.x(), mouseEvent.y()));
}
void ToolResourceProvider::onIdentifyGraphicsOverlayCompleted(QUuid id, IdentifyGraphicsOverlayResult* identifyResult)
{
emit identifyGraphicsOverlayCompleted(id, identifyResult);
}
void ToolResourceProvider::onIdentifyGraphicsOverlaysCompleted(QUuid taskId, QList<IdentifyGraphicsOverlayResult *> identifyResults)
{
emit identifyGraphicsOverlaysCompleted(taskId, identifyResults);
}
void ToolResourceProvider::onIdentifyLayerCompleted(QUuid taskId, IdentifyLayerResult* identifyResult)
{
emit identifyLayerCompleted(taskId, identifyResult);
}
void ToolResourceProvider::onIdentifyLayersCompleted(QUuid taskId, QList<IdentifyLayerResult*> identifyResults)
{
emit identifyLayersCompleted(taskId, identifyResults);
}
void ToolResourceProvider::onScreenToLocationCompleted(QUuid taskId, const Point& location)
{
emit screenToLocationCompleted(taskId, location);
}
void ToolResourceProvider::onLocationChanged(const Point& location)
{
emit locationChanged(location);
}
void ToolResourceProvider::clear()
{
m_map = nullptr;
m_scene = nullptr;
m_geoView = nullptr;
emit mapChanged();
emit sceneChanged();
emit geoViewChanged();
}
} // Toolkit
} // ArcGISRuntime
} // Esri
<commit_msg>update the ToolResourceProvider to clear members when they are destroyed<commit_after>// Copyright 2016 ESRI
//
// All rights reserved under the copyright laws of the United States
// and applicable international laws, treaties, and conventions.
//
// You may freely redistribute and use this sample code, with or
// without modification, provided you include the original copyright
// notice and use restrictions.
//
// See the Sample code usage restrictions document for further information.
//
#include "Basemap.h"
#include "Map.h"
#include "Scene.h"
#include "GeoView.h"
#include "MapView.h"
#include "SceneView.h"
#include "IdentifyGraphicsOverlayResult.h"
#include "ToolResourceProvider.h"
#include <QUuid>
namespace Esri
{
namespace ArcGISRuntime
{
namespace Toolkit
{
ToolResourceProvider::ToolResourceProvider(QObject* parent /*= nullptr*/):
QObject(parent)
{
}
ToolResourceProvider* ToolResourceProvider::instance()
{
static ToolResourceProvider s_instance;
return &s_instance;
}
ToolResourceProvider::~ToolResourceProvider()
{
}
Map* ToolResourceProvider::map() const
{
return m_map;
}
/*! \brief Sets the map to \a newMap.
*
* To clear the map pass \c nullptr.
*
* \sa mapChanged.
*/
void ToolResourceProvider::setMap(Map* newMap)
{
if (newMap == m_map)
return;
m_map = newMap;
emit mapChanged();
if (m_map == nullptr)
return;
QObject* mapObject = dynamic_cast<QObject*>(m_map);
if (mapObject)
{
connect(mapObject, &QObject::destroyed, this, [this]
{
m_map = nullptr;
emit mapChanged();
});
}
}
Scene* ToolResourceProvider::scene() const
{
return m_scene;
}
/*! \brief Sets the scene to \a newScene.
*
* To clear the scene pass \c nullptr.
*
* \sa sceneChanged.
*/
void ToolResourceProvider::setScene(Scene* newScene)
{
if (newScene == m_scene)
return;
m_scene = newScene;
emit sceneChanged();
if (m_scene == nullptr)
return;
QObject* sceneObject = dynamic_cast<QObject*>(m_scene);
if (sceneObject)
{
connect(sceneObject, &QObject::destroyed, this, [this]
{
m_scene = nullptr;
emit sceneChanged();
});
}
}
GeoView* ToolResourceProvider::geoView() const
{
return m_geoView;
}
/*! \brief Sets the geoView to \a newGeoView.
*
* To clear the geoView pass \c nullptr.
*
* \sa geoViewChanged.
* \sa spatialReferenceChanged.
*/
void ToolResourceProvider::setGeoView(GeoView* newGeoView)
{
if (newGeoView == m_geoView)
return;
m_geoView = newGeoView;
emit geoViewChanged();
if (m_geoView == nullptr)
return;
if (!m_geoView->spatialReference().isEmpty())
emit spatialReferenceChanged();
QObject* geoViewObject = dynamic_cast<QObject*>(m_geoView);
if (geoViewObject)
{
connect(geoViewObject, &QObject::destroyed, this, [this]
{
m_geoView = nullptr;
emit geoViewChanged();
});
}
}
SpatialReference ToolResourceProvider::spatialReference() const
{
return m_geoView ? m_geoView->spatialReference() : SpatialReference();
}
LayerListModel* ToolResourceProvider::operationalLayers() const
{
if (m_map)
return m_map->operationalLayers();
else if (m_scene)
return m_scene->operationalLayers();
return nullptr;
}
void ToolResourceProvider::setBasemap(Basemap* newBasemap)
{
if (!newBasemap)
return;
if (m_map)
{
newBasemap->setParent(m_map);
m_map->setBasemap(newBasemap);
}
else if (m_scene)
{
newBasemap->setParent(m_scene);
m_scene->setBasemap(newBasemap);
}
}
void ToolResourceProvider::setMouseCursor(const QCursor& cursor)
{
emit setMouseCursorRequested(cursor);
}
void ToolResourceProvider::onMouseClicked(QMouseEvent& mouseEvent)
{
emit mouseClicked(mouseEvent);
if (!m_geoView)
return;
if (m_scene)
emit mouseClickedPoint(static_cast<SceneView*>(m_geoView)->screenToBaseSurface(mouseEvent.x(), mouseEvent.y()));
else if (m_map)
emit mouseClickedPoint(static_cast<MapView*>(m_geoView)->screenToLocation(mouseEvent.x(), mouseEvent.y()));
else if (dynamic_cast<SceneView*>(m_geoView))
emit mouseClickedPoint(static_cast<SceneView*>(m_geoView)->screenToBaseSurface(mouseEvent.x(), mouseEvent.y()));
else if (dynamic_cast<MapView*>(m_geoView))
emit mouseClickedPoint(static_cast<MapView*>(m_geoView)->screenToLocation(mouseEvent.x(), mouseEvent.y()));
}
void ToolResourceProvider::onMousePressed(QMouseEvent &mouseEvent)
{
emit mousePressed(mouseEvent);
if (!m_geoView)
return;
if (m_scene)
emit mousePressedPoint(static_cast<SceneView*>(m_geoView)->screenToBaseSurface(mouseEvent.x(), mouseEvent.y()));
else if (m_map)
emit mousePressedPoint(static_cast<MapView*>(m_geoView)->screenToLocation(mouseEvent.x(), mouseEvent.y()));
else if (dynamic_cast<SceneView*>(m_geoView))
emit mousePressedPoint(static_cast<SceneView*>(m_geoView)->screenToBaseSurface(mouseEvent.x(), mouseEvent.y()));
else if (dynamic_cast<MapView*>(m_geoView))
emit mousePressedPoint(static_cast<MapView*>(m_geoView)->screenToLocation(mouseEvent.x(), mouseEvent.y()));
}
void ToolResourceProvider::onMouseMoved(QMouseEvent &mouseEvent)
{
emit mouseMoved(mouseEvent);
if (!m_geoView)
return;
if (m_scene)
emit mouseMovedPoint(static_cast<SceneView*>(m_geoView)->screenToBaseSurface(mouseEvent.x(), mouseEvent.y()));
else if (m_map)
emit mouseMovedPoint(static_cast<MapView*>(m_geoView)->screenToLocation(mouseEvent.x(), mouseEvent.y()));
else if (dynamic_cast<SceneView*>(m_geoView))
emit mouseMovedPoint(static_cast<SceneView*>(m_geoView)->screenToBaseSurface(mouseEvent.x(), mouseEvent.y()));
else if (dynamic_cast<MapView*>(m_geoView))
emit mouseMovedPoint(static_cast<MapView*>(m_geoView)->screenToLocation(mouseEvent.x(), mouseEvent.y()));
}
void ToolResourceProvider::onMouseReleased(QMouseEvent &mouseEvent)
{
emit mouseReleased(mouseEvent);
if (!m_geoView)
return;
if (m_scene)
emit mouseReleasedPoint(static_cast<SceneView*>(m_geoView)->screenToBaseSurface(mouseEvent.x(), mouseEvent.y()));
else if (m_map)
emit mouseReleasedPoint(static_cast<MapView*>(m_geoView)->screenToLocation(mouseEvent.x(), mouseEvent.y()));
else if (dynamic_cast<SceneView*>(m_geoView))
emit mouseReleasedPoint(static_cast<SceneView*>(m_geoView)->screenToBaseSurface(mouseEvent.x(), mouseEvent.y()));
else if (dynamic_cast<MapView*>(m_geoView))
emit mouseReleasedPoint(static_cast<MapView*>(m_geoView)->screenToLocation(mouseEvent.x(), mouseEvent.y()));
}
void ToolResourceProvider::onMousePressedAndHeld(QMouseEvent &mouseEvent)
{
emit mousePressedAndHeld(mouseEvent);
if (!m_geoView)
return;
if (m_scene)
emit mousePressedAndHeldPoint(static_cast<SceneView*>(m_geoView)->screenToBaseSurface(mouseEvent.x(), mouseEvent.y()));
else if (m_map)
emit mousePressedAndHeldPoint(static_cast<MapView*>(m_geoView)->screenToLocation(mouseEvent.x(), mouseEvent.y()));
else if (dynamic_cast<SceneView*>(m_geoView))
emit mousePressedAndHeldPoint(static_cast<SceneView*>(m_geoView)->screenToBaseSurface(mouseEvent.x(), mouseEvent.y()));
else if (dynamic_cast<MapView*>(m_geoView))
emit mousePressedAndHeldPoint(static_cast<MapView*>(m_geoView)->screenToLocation(mouseEvent.x(), mouseEvent.y()));
}
void ToolResourceProvider::onMouseDoubleClicked(QMouseEvent &mouseEvent)
{
emit mouseDoubleClicked(mouseEvent);
if (!m_geoView)
return;
if (m_scene)
emit mouseDoubleClickedPoint(static_cast<SceneView*>(m_geoView)->screenToBaseSurface(mouseEvent.x(), mouseEvent.y()));
else if (m_map)
emit mouseDoubleClickedPoint(static_cast<MapView*>(m_geoView)->screenToLocation(mouseEvent.x(), mouseEvent.y()));
else if (dynamic_cast<SceneView*>(m_geoView))
emit mouseDoubleClickedPoint(static_cast<SceneView*>(m_geoView)->screenToBaseSurface(mouseEvent.x(), mouseEvent.y()));
else if (dynamic_cast<MapView*>(m_geoView))
emit mouseDoubleClickedPoint(static_cast<MapView*>(m_geoView)->screenToLocation(mouseEvent.x(), mouseEvent.y()));
}
void ToolResourceProvider::onIdentifyGraphicsOverlayCompleted(QUuid id, IdentifyGraphicsOverlayResult* identifyResult)
{
emit identifyGraphicsOverlayCompleted(id, identifyResult);
}
void ToolResourceProvider::onIdentifyGraphicsOverlaysCompleted(QUuid taskId, QList<IdentifyGraphicsOverlayResult *> identifyResults)
{
emit identifyGraphicsOverlaysCompleted(taskId, identifyResults);
}
void ToolResourceProvider::onIdentifyLayerCompleted(QUuid taskId, IdentifyLayerResult* identifyResult)
{
emit identifyLayerCompleted(taskId, identifyResult);
}
void ToolResourceProvider::onIdentifyLayersCompleted(QUuid taskId, QList<IdentifyLayerResult*> identifyResults)
{
emit identifyLayersCompleted(taskId, identifyResults);
}
void ToolResourceProvider::onScreenToLocationCompleted(QUuid taskId, const Point& location)
{
emit screenToLocationCompleted(taskId, location);
}
void ToolResourceProvider::onLocationChanged(const Point& location)
{
emit locationChanged(location);
}
void ToolResourceProvider::clear()
{
m_map = nullptr;
m_scene = nullptr;
m_geoView = nullptr;
emit mapChanged();
emit sceneChanged();
emit geoViewChanged();
}
} // Toolkit
} // ArcGISRuntime
} // Esri
<|endoftext|>
|
<commit_before>// Copyright 2013 The Flutter 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 "flutter/shell/platform/windows/keyboard_key_channel_handler.h"
#include <windows.h>
#include <iostream>
#include "flutter/shell/platform/common/json_message_codec.h"
namespace flutter {
namespace {
static constexpr char kChannelName[] = "flutter/keyevent";
static constexpr char kKeyCodeKey[] = "keyCode";
static constexpr char kScanCodeKey[] = "scanCode";
static constexpr char kCharacterCodePointKey[] = "characterCodePoint";
static constexpr char kModifiersKey[] = "modifiers";
static constexpr char kKeyMapKey[] = "keymap";
static constexpr char kTypeKey[] = "type";
static constexpr char kHandledKey[] = "handled";
static constexpr char kWindowsKeyMap[] = "windows";
static constexpr char kKeyUp[] = "keyup";
static constexpr char kKeyDown[] = "keydown";
// The maximum number of pending events to keep before
// emitting a warning on the console about unhandled events.
static constexpr int kMaxPendingEvents = 1000;
// The bit for a scancode indicating the key is extended.
//
// Win32 defines some keys to be "extended", such as ShiftRight, which shares
// the same scancode as its non-extended counterpart, such as ShiftLeft. In
// Chromium's scancode table, from which Flutter's physical key list is
// derived, these keys are marked with this bit. See
// https://chromium.googlesource.com/codesearch/chromium/src/+/refs/heads/master/ui/events/keycodes/dom/dom_code_data.inc
static constexpr int kScancodeExtended = 0xe000;
// Re-definition of the modifiers for compatibility with the Flutter framework.
// These have to be in sync with the framework's RawKeyEventDataWindows
// modifiers definition.
// https://github.com/flutter/flutter/blob/19ff596979e407c484a32f4071420fca4f4c885f/packages/flutter/lib/src/services/raw_keyboard_windows.dart#L203
static constexpr int kShift = 1 << 0;
static constexpr int kShiftLeft = 1 << 1;
static constexpr int kShiftRight = 1 << 2;
static constexpr int kControl = 1 << 3;
static constexpr int kControlLeft = 1 << 4;
static constexpr int kControlRight = 1 << 5;
static constexpr int kAlt = 1 << 6;
static constexpr int kAltLeft = 1 << 7;
static constexpr int kAltRight = 1 << 8;
static constexpr int kWinLeft = 1 << 9;
static constexpr int kWinRight = 1 << 10;
static constexpr int kCapsLock = 1 << 11;
static constexpr int kNumLock = 1 << 12;
static constexpr int kScrollLock = 1 << 13;
/// Calls GetKeyState() an all modifier keys and packs the result in an int,
/// with the re-defined values declared above for compatibility with the Flutter
/// framework.
int GetModsForKeyState() {
// TODO(clarkezone) need to add support for get modifier state for UWP
// https://github.com/flutter/flutter/issues/70202
#ifdef WINUWP
return 0;
#else
int mods = 0;
if (GetKeyState(VK_SHIFT) < 0)
mods |= kShift;
if (GetKeyState(VK_LSHIFT) < 0)
mods |= kShiftLeft;
if (GetKeyState(VK_RSHIFT) < 0)
mods |= kShiftRight;
if (GetKeyState(VK_CONTROL) < 0)
mods |= kControl;
if (GetKeyState(VK_LCONTROL) < 0)
mods |= kControlLeft;
if (GetKeyState(VK_RCONTROL) < 0)
mods |= kControlRight;
if (GetKeyState(VK_MENU) < 0)
mods |= kAlt;
if (GetKeyState(VK_LMENU) < 0)
mods |= kAltLeft;
if (GetKeyState(VK_RMENU) < 0)
mods |= kAltRight;
if (GetKeyState(VK_LWIN) < 0)
mods |= kWinLeft;
if (GetKeyState(VK_RWIN) < 0)
mods |= kWinRight;
if (GetKeyState(VK_CAPITAL) < 0)
mods |= kCapsLock;
if (GetKeyState(VK_NUMLOCK) < 0)
mods |= kNumLock;
if (GetKeyState(VK_SCROLL) < 0)
mods |= kScrollLock;
return mods;
#endif
}
// Revert the "character" for a dead key to its normal value, or the argument
// unchanged otherwise.
//
// When a dead key is pressed, the WM_KEYDOWN's lParam is mapped to a special
// value: the "normal character" | 0x80000000. For example, when pressing
// "dead key caret" (one that makes the following e into ê), its mapped
// character is 0x8000005E. "Reverting" it gives 0x5E, which is character '^'.
uint32_t _UndeadChar(uint32_t ch) {
return ch & ~0x80000000;
}
} // namespace
KeyboardKeyChannelHandler::KeyboardKeyChannelHandler(
flutter::BinaryMessenger* messenger)
: channel_(
std::make_unique<flutter::BasicMessageChannel<rapidjson::Document>>(
messenger,
kChannelName,
&flutter::JsonMessageCodec::GetInstance())) {}
KeyboardKeyChannelHandler::~KeyboardKeyChannelHandler() = default;
void KeyboardKeyChannelHandler::KeyboardHook(
int key,
int scancode,
int action,
char32_t character,
bool extended,
bool was_down,
std::function<void(bool)> callback) {
// TODO: Translate to a cross-platform key code system rather than passing
// the native key code.
rapidjson::Document event(rapidjson::kObjectType);
auto& allocator = event.GetAllocator();
event.AddMember(kKeyCodeKey, key, allocator);
event.AddMember(kScanCodeKey, scancode | (extended ? kScancodeExtended : 0),
allocator);
event.AddMember(kCharacterCodePointKey, _UndeadChar(character), allocator);
event.AddMember(kKeyMapKey, kWindowsKeyMap, allocator);
event.AddMember(kModifiersKey, GetModsForKeyState(), allocator);
switch (action) {
case WM_KEYDOWN:
event.AddMember(kTypeKey, kKeyDown, allocator);
break;
case WM_KEYUP:
event.AddMember(kTypeKey, kKeyUp, allocator);
break;
default:
std::cerr << "Unknown key event action: " << action << std::endl;
callback(false);
return;
}
channel_->Send(event, [callback = std::move(callback)](const uint8_t* reply,
size_t reply_size) {
auto decoded = flutter::JsonMessageCodec::GetInstance().DecodeMessage(
reply, reply_size);
bool handled = (*decoded)[kHandledKey].GetBool();
callback(handled);
});
}
} // namespace flutter
<commit_msg>[UWP] Add modifier keys support (#28724)<commit_after>// Copyright 2013 The Flutter 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 "flutter/shell/platform/windows/keyboard_key_channel_handler.h"
#include <windows.h>
#ifdef WINUWP
#include "third_party/cppwinrt/generated/winrt/Windows.System.h"
#include "third_party/cppwinrt/generated/winrt/Windows.UI.Core.h"
#endif
#include <iostream>
#include "flutter/shell/platform/common/json_message_codec.h"
namespace flutter {
namespace {
static constexpr char kChannelName[] = "flutter/keyevent";
static constexpr char kKeyCodeKey[] = "keyCode";
static constexpr char kScanCodeKey[] = "scanCode";
static constexpr char kCharacterCodePointKey[] = "characterCodePoint";
static constexpr char kModifiersKey[] = "modifiers";
static constexpr char kKeyMapKey[] = "keymap";
static constexpr char kTypeKey[] = "type";
static constexpr char kHandledKey[] = "handled";
static constexpr char kWindowsKeyMap[] = "windows";
static constexpr char kKeyUp[] = "keyup";
static constexpr char kKeyDown[] = "keydown";
// The maximum number of pending events to keep before
// emitting a warning on the console about unhandled events.
static constexpr int kMaxPendingEvents = 1000;
// The bit for a scancode indicating the key is extended.
//
// Win32 defines some keys to be "extended", such as ShiftRight, which shares
// the same scancode as its non-extended counterpart, such as ShiftLeft. In
// Chromium's scancode table, from which Flutter's physical key list is
// derived, these keys are marked with this bit. See
// https://chromium.googlesource.com/codesearch/chromium/src/+/refs/heads/master/ui/events/keycodes/dom/dom_code_data.inc
static constexpr int kScancodeExtended = 0xe000;
// Re-definition of the modifiers for compatibility with the Flutter framework.
// These have to be in sync with the framework's RawKeyEventDataWindows
// modifiers definition.
// https://github.com/flutter/flutter/blob/19ff596979e407c484a32f4071420fca4f4c885f/packages/flutter/lib/src/services/raw_keyboard_windows.dart#L203
static constexpr int kShift = 1 << 0;
static constexpr int kShiftLeft = 1 << 1;
static constexpr int kShiftRight = 1 << 2;
static constexpr int kControl = 1 << 3;
static constexpr int kControlLeft = 1 << 4;
static constexpr int kControlRight = 1 << 5;
static constexpr int kAlt = 1 << 6;
static constexpr int kAltLeft = 1 << 7;
static constexpr int kAltRight = 1 << 8;
static constexpr int kWinLeft = 1 << 9;
static constexpr int kWinRight = 1 << 10;
static constexpr int kCapsLock = 1 << 11;
static constexpr int kNumLock = 1 << 12;
static constexpr int kScrollLock = 1 << 13;
/// Calls GetKeyState() an all modifier keys and packs the result in an int,
/// with the re-defined values declared above for compatibility with the Flutter
/// framework.
int GetModsForKeyState() {
#ifdef WINUWP
using namespace winrt::Windows::System;
using namespace winrt::Windows::UI::Core;
auto window = CoreWindow::GetForCurrentThread();
auto key_is_down = [&window](VirtualKey key) {
auto state = window.GetKeyState(key);
return (state & CoreVirtualKeyStates::Down) == CoreVirtualKeyStates::Down;
};
int mods = 0;
if (key_is_down(VirtualKey::Shift))
mods |= kShift;
if (key_is_down(VirtualKey::LeftShift))
mods |= kShiftLeft;
if (key_is_down(VirtualKey::RightShift))
mods |= kShiftRight;
if (key_is_down(VirtualKey::Control))
mods |= kControl;
if (key_is_down(VirtualKey::LeftControl))
mods |= kControlLeft;
if (key_is_down(VirtualKey::RightControl))
mods |= kControlRight;
if (key_is_down(VirtualKey::Menu))
mods |= kAlt;
if (key_is_down(VirtualKey::LeftMenu))
mods |= kAltLeft;
if (key_is_down(VirtualKey::RightMenu))
mods |= kAltRight;
if (key_is_down(VirtualKey::LeftWindows))
mods |= kWinLeft;
if (key_is_down(VirtualKey::RightWindows))
mods |= kWinRight;
if (key_is_down(VirtualKey::CapitalLock))
mods |= kCapsLock;
if (key_is_down(VirtualKey::NumberKeyLock))
mods |= kNumLock;
if (key_is_down(VirtualKey::Scroll))
mods |= kScrollLock;
return mods;
#else
int mods = 0;
if (GetKeyState(VK_SHIFT) < 0)
mods |= kShift;
if (GetKeyState(VK_LSHIFT) < 0)
mods |= kShiftLeft;
if (GetKeyState(VK_RSHIFT) < 0)
mods |= kShiftRight;
if (GetKeyState(VK_CONTROL) < 0)
mods |= kControl;
if (GetKeyState(VK_LCONTROL) < 0)
mods |= kControlLeft;
if (GetKeyState(VK_RCONTROL) < 0)
mods |= kControlRight;
if (GetKeyState(VK_MENU) < 0)
mods |= kAlt;
if (GetKeyState(VK_LMENU) < 0)
mods |= kAltLeft;
if (GetKeyState(VK_RMENU) < 0)
mods |= kAltRight;
if (GetKeyState(VK_LWIN) < 0)
mods |= kWinLeft;
if (GetKeyState(VK_RWIN) < 0)
mods |= kWinRight;
if (GetKeyState(VK_CAPITAL) < 0)
mods |= kCapsLock;
if (GetKeyState(VK_NUMLOCK) < 0)
mods |= kNumLock;
if (GetKeyState(VK_SCROLL) < 0)
mods |= kScrollLock;
return mods;
#endif
}
// Revert the "character" for a dead key to its normal value, or the argument
// unchanged otherwise.
//
// When a dead key is pressed, the WM_KEYDOWN's lParam is mapped to a special
// value: the "normal character" | 0x80000000. For example, when pressing
// "dead key caret" (one that makes the following e into ê), its mapped
// character is 0x8000005E. "Reverting" it gives 0x5E, which is character '^'.
uint32_t _UndeadChar(uint32_t ch) {
return ch & ~0x80000000;
}
} // namespace
KeyboardKeyChannelHandler::KeyboardKeyChannelHandler(
flutter::BinaryMessenger* messenger)
: channel_(
std::make_unique<flutter::BasicMessageChannel<rapidjson::Document>>(
messenger,
kChannelName,
&flutter::JsonMessageCodec::GetInstance())) {}
KeyboardKeyChannelHandler::~KeyboardKeyChannelHandler() = default;
void KeyboardKeyChannelHandler::KeyboardHook(
int key,
int scancode,
int action,
char32_t character,
bool extended,
bool was_down,
std::function<void(bool)> callback) {
// TODO: Translate to a cross-platform key code system rather than passing
// the native key code.
rapidjson::Document event(rapidjson::kObjectType);
auto& allocator = event.GetAllocator();
event.AddMember(kKeyCodeKey, key, allocator);
event.AddMember(kScanCodeKey, scancode | (extended ? kScancodeExtended : 0),
allocator);
event.AddMember(kCharacterCodePointKey, _UndeadChar(character), allocator);
event.AddMember(kKeyMapKey, kWindowsKeyMap, allocator);
event.AddMember(kModifiersKey, GetModsForKeyState(), allocator);
switch (action) {
case WM_KEYDOWN:
event.AddMember(kTypeKey, kKeyDown, allocator);
break;
case WM_KEYUP:
event.AddMember(kTypeKey, kKeyUp, allocator);
break;
default:
std::cerr << "Unknown key event action: " << action << std::endl;
callback(false);
return;
}
channel_->Send(event, [callback = std::move(callback)](const uint8_t* reply,
size_t reply_size) {
auto decoded = flutter::JsonMessageCodec::GetInstance().DecodeMessage(
reply, reply_size);
bool handled = (*decoded)[kHandledKey].GetBool();
callback(handled);
});
}
} // namespace flutter
<|endoftext|>
|
<commit_before>/**
* For conditions of distribution and use, see copyright notice in license.txt
*
* @file SceneStructureWindow.cpp
* @brief
*/
#include "StableHeaders.h"
#include "SceneStructureWindow.h"
#include "SceneTreeWidget.h"
#include "Framework.h"
#include "SceneManager.h"
#include "ECEditorWindow.h"
#include "UiServiceInterface.h"
using namespace Scene;
SceneStructureWindow::SceneStructureWindow(Foundation::Framework *fw) : framework(fw)
{
QVBoxLayout *layout = new QVBoxLayout(this);
layout->setContentsMargins(0, 0, 0, 0);
setLayout(layout);
setWindowTitle(tr("Scene Structure"));
resize(200,300);
treeWidget = new SceneTreeWidget(fw, this);
layout->addWidget(treeWidget);
}
SceneStructureWindow::~SceneStructureWindow()
{
Clear();
}
void SceneStructureWindow::SetScene(const Scene::ScenePtr &s)
{
scene = s;
SceneManager *scenePtr = scene.lock().get();
assert(scenePtr);
connect(scenePtr, SIGNAL(EntityCreated(Scene::Entity *, AttributeChange::Type)), SLOT(AddEntity(Scene::Entity *)));
connect(scenePtr, SIGNAL(EntityRemoved(Scene::Entity *, AttributeChange::Type)), SLOT(RemoveEntity(Scene::Entity *)));
Populate();
}
void SceneStructureWindow::changeEvent(QEvent* e)
{
if (e->type() == QEvent::LanguageChange)
setWindowTitle(tr("Scene Structure"));
else
QWidget::changeEvent(e);
}
void SceneStructureWindow::Populate()
{
ScenePtr s = scene.lock();
if (!s)
{
// warning print
return;
}
SceneManager::iterator it = s->begin();
while(it != s->end())
{
const EntityPtr &e = *it;
SceneTreeWidgetItem *item = new SceneTreeWidgetItem(e->GetId());
item->setText(0, QString("%1 %2").arg(e->GetId()).arg(e->GetName()));
treeWidget->addTopLevelItem(item);
++it;
}
}
void SceneStructureWindow::Clear()
{
for (int i = 0; i < treeWidget->topLevelItemCount(); ++i)
{
QTreeWidgetItem *item = treeWidget->topLevelItem(i);
SAFE_DELETE(item);
}
}
void SceneStructureWindow::AddEntity(Scene::Entity* entity)
{
SceneTreeWidgetItem *item = new SceneTreeWidgetItem(entity->GetId());
item->setText(0, QString("%1 %2").arg(entity->GetId()).arg(entity->GetName()));
treeWidget->addTopLevelItem(item);
}
void SceneStructureWindow::RemoveEntity(Scene::Entity* entity)
{
for (int i = 0; i < treeWidget->topLevelItemCount(); ++i)
{
SceneTreeWidgetItem *item = static_cast<SceneTreeWidgetItem *>(treeWidget->topLevelItem(i));
if (item && (item->id == entity->GetId()))
{
SAFE_DELETE(item);
break;
}
}
}
<commit_msg>Scene struct window: decorate local entities with blue text color.<commit_after>/**
* For conditions of distribution and use, see copyright notice in license.txt
*
* @file SceneStructureWindow.cpp
* @brief
*/
#include "StableHeaders.h"
#include "SceneStructureWindow.h"
#include "SceneTreeWidget.h"
#include "Framework.h"
#include "SceneManager.h"
#include "ECEditorWindow.h"
#include "UiServiceInterface.h"
using namespace Scene;
SceneStructureWindow::SceneStructureWindow(Foundation::Framework *fw) : framework(fw)
{
QVBoxLayout *layout = new QVBoxLayout(this);
layout->setContentsMargins(0, 0, 0, 0);
setLayout(layout);
setWindowTitle(tr("Scene Structure"));
resize(200,300);
treeWidget = new SceneTreeWidget(fw, this);
layout->addWidget(treeWidget);
}
SceneStructureWindow::~SceneStructureWindow()
{
Clear();
}
void SceneStructureWindow::SetScene(const Scene::ScenePtr &s)
{
scene = s;
SceneManager *scenePtr = scene.lock().get();
assert(scenePtr);
connect(scenePtr, SIGNAL(EntityCreated(Scene::Entity *, AttributeChange::Type)), SLOT(AddEntity(Scene::Entity *)));
connect(scenePtr, SIGNAL(EntityRemoved(Scene::Entity *, AttributeChange::Type)), SLOT(RemoveEntity(Scene::Entity *)));
Populate();
}
void SceneStructureWindow::changeEvent(QEvent* e)
{
if (e->type() == QEvent::LanguageChange)
setWindowTitle(tr("Scene Structure"));
else
QWidget::changeEvent(e);
}
void SceneStructureWindow::Populate()
{
ScenePtr s = scene.lock();
if (!s)
{
// warning print
return;
}
SceneManager::iterator it = s->begin();
while(it != s->end())
{
AddEntity((*it).get());
++it;
}
}
void SceneStructureWindow::Clear()
{
for (int i = 0; i < treeWidget->topLevelItemCount(); ++i)
{
QTreeWidgetItem *item = treeWidget->topLevelItem(i);
SAFE_DELETE(item);
}
}
void SceneStructureWindow::AddEntity(Scene::Entity* entity)
{
SceneTreeWidgetItem *item = new SceneTreeWidgetItem(entity->GetId());
item->setText(0, QString("%1 %2").arg(entity->GetId()).arg(entity->GetName()));
// Set local entity's font color blue
if (entity->GetId() & Scene::LocalEntity)
item->setTextColor(0, QColor(Qt::blue));
treeWidget->addTopLevelItem(item);
}
void SceneStructureWindow::RemoveEntity(Scene::Entity* entity)
{
for (int i = 0; i < treeWidget->topLevelItemCount(); ++i)
{
SceneTreeWidgetItem *item = static_cast<SceneTreeWidgetItem *>(treeWidget->topLevelItem(i));
if (item && (item->id == entity->GetId()))
{
SAFE_DELETE(item);
break;
}
}
}
<|endoftext|>
|
<commit_before>//----------------------------------------------------------------------------
// 프로그램명 : MS5540S
//
// 만든이 :
//
// 날 짜 :
//
// 최종 수정 :
//
// MPU_Type :
//
// 파일명 : MS5540S.cpp
//----------------------------------------------------------------------------
////////////////////////////////////////////
// MS5540S
////////////////////////////////////////////
#include "MS5540S.h"
int clock = 6;
//int clock = 6;
/*---------------------------------------------------------------------------
TITLE : ms5540s_reset
WORK :
ARG : void
RET : void
---------------------------------------------------------------------------*/
void ms5540s_reset() //this function keeps the sketch a little shorter
{
SPI.setDataMode(SPI_MODE0);
SPI.transfer(0x15);
SPI.transfer(0x55);
SPI.transfer(0x40);
}
/*---------------------------------------------------------------------------
TITLE : ms5540s_setup
WORK :
ARG : void
RET : void
---------------------------------------------------------------------------*/
void ms5540s_setup() {
SPI.begin(); //see SPI library details on arduino.cc for details
SPI.setBitOrder(MSBFIRST);
SPI.setClockDivider(SPI_CLOCK_DIV32); //divide 16 MHz to communicate on 500 kHz
pinMode(clock, OUTPUT);
delay(100);
}
/*---------------------------------------------------------------------------
TITLE : ms5540s_loop
WORK :
ARG : void
RET : void
---------------------------------------------------------------------------*/
void ms5540s_loop()
{
TCCR4B = (TCCR4B & 0xF0) | 1 ; //generates the MCKL signal
analogWrite (clock, 128) ;
ms5540s_reset();//resets the sensor - caution: afterwards mode = SPI_MODE0!
//Calibration word 1
unsigned int word1 = 0;
unsigned int word11 = 0;
SPI.transfer(0x1D); //send first byte of command to get calibration word 1
SPI.transfer(0x50); //send second byte of command to get calibration word 1
SPI.setDataMode(SPI_MODE1); //change mode in order to listen
word1 = SPI.transfer(0x00); //send dummy byte to read first byte of word
word1 = word1 << 8; //shift returned byte
word11 = SPI.transfer(0x00); //send dummy byte to read second byte of word
word1 = word1 | word11; //combine first and second byte of word
ms5540s_reset();//resets the sensor
//Calibration word 2; see comments on calibration word 1
unsigned int word2 = 0;
byte word22 = 0;
SPI.transfer(0x1D);
SPI.transfer(0x60);
SPI.setDataMode(SPI_MODE1);
word2 = SPI.transfer(0x00);
word2 = word2 <<8;
word22 = SPI.transfer(0x00);
word2 = word2 | word22;
ms5540s_reset();//resets the sensor
//Calibration word 3; see comments on calibration word 1
unsigned int word3 = 0;
byte word33 = 0;
SPI.transfer(0x1D);
SPI.transfer(0x90);
SPI.setDataMode(SPI_MODE1);
word3 = SPI.transfer(0x00);
word3 = word3 <<8;
word33 = SPI.transfer(0x00);
word3 = word3 | word33;
ms5540s_reset();//resets the sensor
//Calibration word 4; see comments on calibration word 1
unsigned int word4 = 0;
byte word44 = 0;
SPI.transfer(0x1D);
SPI.transfer(0xA0);
SPI.setDataMode(SPI_MODE1);
word4 = SPI.transfer(0x00);
word4 = word4 <<8;
word44 = SPI.transfer(0x00);
word4 = word4 | word44;
long c1 = word1 << 1;
long c2 = ((word3 & 0x3F) >> 6) | ((word4 & 0x3F));
long c3 = (word4 << 6) ;
long c4 = (word3 << 6);
long c5 = (word2 << 6) | ((word1 & 0x1) >> 10);
long c6 = word2 & 0x3F;
ms5540s_reset();//resets the sensor
//Temperature:
unsigned int tempMSB = 0; //first byte of value
unsigned int tempLSB = 0; //last byte of value
unsigned int D2 = 0;
SPI.transfer(0x0F); //send first byte of command to get temperature value
SPI.transfer(0x20); //send second byte of command to get temperature value
delay(35); //wait for conversion end
SPI.setDataMode(SPI_MODE1); //change mode in order to listen
tempMSB = SPI.transfer(0x00); //send dummy byte to read first byte of value
tempMSB = tempMSB << 8; //shift first byte
tempLSB = SPI.transfer(0x00); //send dummy byte to read second byte of value
D2 = tempMSB | tempLSB; //combine first and second byte of value
ms5540s_reset();//resets the sensor
//Pressure:
unsigned int presMSB = 0; //first byte of value
unsigned int presLSB =0; //last byte of value
unsigned int D1 = 0;
SPI.transfer(0x0F); //send first byte of command to get pressure value
SPI.transfer(0x40); //send second byte of command to get pressure value
delay(35); //wait for conversion end
SPI.setDataMode(SPI_MODE1); //change mode in order to listen
presMSB = SPI.transfer(0x00); //send dummy byte to read first byte of value
presMSB = presMSB << 8; //shift first byte
presLSB = SPI.transfer(0x00); //send dummy byte to read second byte of value
D1 = presMSB | presLSB;
const long UT1 = (c5 * 8) + 20224;
const long dT =(D2 - UT1);
const long TEMP = 200 + ((dT * (c6 + 50))/1024);
const long OFF = (c2*4) + (((c4 - 512) * dT)/4096);
const long SENS = c1 + ((c3 * dT)/1024) + 24576;
long PCOMP = ((((SENS * (D1 - 7168))/16384)- OFF)/32)+250;
float TEMPREAL = TEMP/10;
Serial.print("pressure = ");
Serial.print(PCOMP);
Serial.println(" mbar");
const long dT2 = dT - ((dT >> 7 * dT >> 7) >> 3);
const float TEMPCOMP = (200 + (dT2*(c6+100) >>11))/10;
Serial.print("temperature = ");
Serial.print(TEMPCOMP);
Serial.println(" °C");
Serial.println("************************************");
// delay(1000);
}
<commit_msg>- MS5540S 읽기 개선<commit_after>//----------------------------------------------------------------------------
// 프로그램명 : MS5540S
//
// 만든이 :
//
// 날 짜 :
//
// 최종 수정 :
//
// MPU_Type :
//
// 파일명 : MS5540S.cpp
//----------------------------------------------------------------------------
////////////////////////////////////////////
// MS5540S
////////////////////////////////////////////
#include "MS5540S.h"
int clock = 6;
//int clock = 6;
static int ms5540s_state = 0;
/*---------------------------------------------------------------------------
TITLE : ms5540s_reset
WORK :
ARG : void
RET : void
---------------------------------------------------------------------------*/
void ms5540s_reset() //this function keeps the sketch a little shorter
{
SPI.setDataMode(SPI_MODE0);
SPI.transfer(0x15);
SPI.transfer(0x55);
SPI.transfer(0x40);
}
/*---------------------------------------------------------------------------
TITLE : ms5540s_setup
WORK :
ARG : void
RET : void
---------------------------------------------------------------------------*/
void ms5540s_setup() {
SPI.begin(); //see SPI library details on arduino.cc for details
SPI.setBitOrder(MSBFIRST);
SPI.setClockDivider(SPI_CLOCK_DIV32); //divide 16 MHz to communicate on 500 kHz
pinMode(clock, OUTPUT);
delay(100);
}
/*---------------------------------------------------------------------------
TITLE : ms5540s_loop
WORK :
ARG : void
RET : void
---------------------------------------------------------------------------*/
void ms5540s_loop()
{
static uint32_t tTime;
unsigned int word1 = 0;
unsigned int word11 = 0;
unsigned int word2 = 0;
unsigned int word3 = 0;
byte word22 = 0;
byte word33 = 0;
unsigned int word4 = 0;
byte word44 = 0;
static long c1;
static long c2;
static long c3;
static long c4;
static long c5;
static long c6;
unsigned int presMSB = 0; //first byte of value
unsigned int presLSB =0; //last byte of value
static unsigned int D1 = 0;
unsigned int tempMSB = 0; //first byte of value
unsigned int tempLSB = 0; //last byte of value
static unsigned int D2 = 0;
long UT1 = 0;
long dT = 0;
long TEMP = 0;
long OFF = 0;
long SENS = 0;
static long PCOMP = 0;
static float TEMPREAL = 0;
long dT2 = 0;
static float TEMPCOMP = 0;
bool ret = false;
switch( ms5540s_state )
{
case 0:
TCCR4B = (TCCR4B & 0xF0) | 1 ; //generates the MCKL signal
analogWrite (clock, 128) ;
ms5540s_reset();//resets the sensor - caution: afterwards mode = SPI_MODE0!
//Calibration word 1
word1 = 0;
word11 = 0;
SPI.transfer(0x1D); //send first byte of command to get calibration word 1
SPI.transfer(0x50); //send second byte of command to get calibration word 1
SPI.setDataMode(SPI_MODE1); //change mode in order to listen
word1 = SPI.transfer(0x00); //send dummy byte to read first byte of word
word1 = word1 << 8; //shift returned byte
word11 = SPI.transfer(0x00); //send dummy byte to read second byte of word
word1 = word1 | word11; //combine first and second byte of word
ms5540s_reset();//resets the sensor
//Calibration word 2; see comments on calibration word 1
word2 = 0;
word22 = 0;
SPI.transfer(0x1D);
SPI.transfer(0x60);
SPI.setDataMode(SPI_MODE1);
word2 = SPI.transfer(0x00);
word2 = word2 <<8;
word22 = SPI.transfer(0x00);
word2 = word2 | word22;
ms5540s_reset();//resets the sensor
//Calibration word 3; see comments on calibration word 1
word3 = 0;
word33 = 0;
SPI.transfer(0x1D);
SPI.transfer(0x90);
SPI.setDataMode(SPI_MODE1);
word3 = SPI.transfer(0x00);
word3 = word3 <<8;
word33 = SPI.transfer(0x00);
word3 = word3 | word33;
ms5540s_reset();//resets the sensor
//Calibration word 4; see comments on calibration word 1
word4 = 0;
word44 = 0;
SPI.transfer(0x1D);
SPI.transfer(0xA0);
SPI.setDataMode(SPI_MODE1);
word4 = SPI.transfer(0x00);
word4 = word4 <<8;
word44 = SPI.transfer(0x00);
word4 = word4 | word44;
c1 = word1 << 1;
c2 = ((word3 & 0x3F) >> 6) | ((word4 & 0x3F));
c3 = (word4 << 6) ;
c4 = (word3 << 6);
c5 = (word2 << 6) | ((word1 & 0x1) >> 10);
c6 = word2 & 0x3F;
ms5540s_reset();//resets the sensor
//Temperature:
SPI.transfer(0x0F); //send first byte of command to get temperature value
SPI.transfer(0x20); //send second byte of command to get temperature value
tTime = millis();
ms5540s_state = 1;
break;
case 1:
if( (millis()-tTime) >= 35 )
{
ms5540s_state = 2;
}
break;
case 2:
SPI.setDataMode(SPI_MODE1); //change mode in order to listen
tempMSB = SPI.transfer(0x00); //send dummy byte to read first byte of value
tempMSB = tempMSB << 8; //shift first byte
tempLSB = SPI.transfer(0x00); //send dummy byte to read second byte of value
D2 = tempMSB | tempLSB; //combine first and second byte of value
ms5540s_reset();//resets the sensor
//Pressure:
SPI.transfer(0x0F); //send first byte of command to get pressure value
SPI.transfer(0x40); //send second byte of command to get pressure value
tTime = millis();
ms5540s_state = 3;
break;
case 3:
if( (millis()-tTime) >= 35 )
{
ms5540s_state = 4;
}
break;
case 4:
SPI.setDataMode(SPI_MODE1); //change mode in order to listen
presMSB = SPI.transfer(0x00); //send dummy byte to read first byte of value
presMSB = presMSB << 8; //shift first byte
presLSB = SPI.transfer(0x00); //send dummy byte to read second byte of value
D1 = presMSB | presLSB;
UT1 = (c5 * 8) + 20224;
dT =(D2 - UT1);
TEMP = 200 + ((dT * (c6 + 50))/1024);
OFF = (c2*4) + (((c4 - 512) * dT)/4096);
SENS = c1 + ((c3 * dT)/1024) + 24576;
PCOMP = ((((SENS * (D1 - 7168))/16384)- OFF)/32)+250;
TEMPREAL = TEMP/10;
Serial.print("pressure = ");
Serial.print(PCOMP);
Serial.println(" mbar");
dT2 = dT - ((dT >> 7 * dT >> 7) >> 3);
TEMPCOMP = (200 + (dT2*(c6+100) >>11))/10;
Serial.print("temperature = ");
Serial.print(TEMPCOMP);
Serial.println(" °C");
Serial.println("************************************");
ret = true;
ms5540s_state = 0;
break;
default:
ms5540s_state = 0;
break;
}
}
<|endoftext|>
|
<commit_before>// Copyright (c) Microsoft Corporation
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
#include "pch.h"
#include "../httpcall.h"
#include "xmlhttp_http_task.h"
#include "http_request_callback.h"
http_request_callback::http_request_callback(_In_ const std::shared_ptr<xmlhttp_http_task>& httpTask)
: m_httpTask(httpTask)
{
}
HRESULT STDMETHODCALLTYPE http_request_callback::OnRedirect(
_In_opt_ IXMLHTTPRequest2*,
__RPC__in_string const WCHAR*)
{
return S_OK;
}
HRESULT STDMETHODCALLTYPE http_request_callback::OnHeadersAvailable(
_In_ IXMLHTTPRequest2* xmlReq,
DWORD statusCode,
__RPC__in_string const WCHAR* phrase
)
{
m_httpTask->set_status_code(statusCode);
WCHAR* allResponseHeaders = nullptr;
HRESULT hr = xmlReq->GetAllResponseHeaders(&allResponseHeaders);
if (SUCCEEDED(hr))
{
try
{
if (allResponseHeaders != nullptr)
{
m_httpTask->set_headers(allResponseHeaders);
}
}
catch (...)
{
m_httpTask->set_exception(std::current_exception());
hr = ERROR_UNHANDLED_EXCEPTION;
}
}
if (allResponseHeaders != nullptr)
{
::CoTaskMemFree(allResponseHeaders);
}
return hr;
}
HRESULT STDMETHODCALLTYPE http_request_callback::OnDataAvailable(
_In_opt_ IXMLHTTPRequest2*,
_In_opt_ ISequentialStream*
)
{
return S_OK;
}
HRESULT STDMETHODCALLTYPE http_request_callback::OnResponseReceived(
_In_opt_ IXMLHTTPRequest2*,
_In_opt_ ISequentialStream*
)
{
auto call = m_httpTask->call();
auto taskHandle = m_httpTask->task_handle();
HCHttpCallResponseSetStatusCode(call, m_httpTask->get_status_code());
auto& headerNames = m_httpTask->get_headers_names();
auto& headerValues = m_httpTask->get_headers_values();
HC_ASSERT(headerNames.size() == headerValues.size());
for (int i = 0; i < headerNames.size(); i++)
{
HCHttpCallResponseSetHeader(call, headerNames[i].c_str(), headerValues[i].c_str());
}
auto const& responseString = m_httpTask->response_buffer().as_string();
HCHttpCallResponseSetResponseString(call, responseString.c_str());
HC_RESULT hr = HC_OK;
if (m_httpTask->has_error())
{
hr = HC_E_FAIL;
}
HCHttpCallResponseSetNetworkErrorCode(call, hr, hr);
HCTaskSetCompleted(taskHandle);
// Break the circular reference loop.
// - xmlhttp_http_task holds a reference to IXmlHttpRequest2
// - IXmlHttpRequest2 holds a reference to HttpRequestCallback
// - HttpRequestCallback holds a reference to xmlhttp_http_task
//
// Not releasing the winrt_request_context below previously worked due to the
// implementation of IXmlHttpRequest2, after calling OnError/OnResponseReceived
// it would immediately release its reference to HttpRequestCallback. However
// it since has been discovered on Xbox that the implementation is different,
// the reference to HttpRequestCallback is NOT immediately released and is only
// done at destruction of IXmlHttpRequest2.
//
// To be safe we now will break the circular reference.
m_httpTask.reset();
return S_OK;
}
HRESULT STDMETHODCALLTYPE http_request_callback::OnError(
_In_opt_ IXMLHTTPRequest2*,
HRESULT hrError
)
{
HCHttpCallResponseSetNetworkErrorCode(m_httpTask->call(), HC_E_FAIL, hrError);
HCTaskSetCompleted(m_httpTask->task_handle());
// Break the circular reference loop.
// See full explanation in OnResponseReceived
m_httpTask.reset();
return S_OK;
}
<commit_msg>Fix a warning when building for x86 (#65)<commit_after>// Copyright (c) Microsoft Corporation
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
#include "pch.h"
#include "../httpcall.h"
#include "xmlhttp_http_task.h"
#include "http_request_callback.h"
http_request_callback::http_request_callback(_In_ const std::shared_ptr<xmlhttp_http_task>& httpTask)
: m_httpTask(httpTask)
{
}
HRESULT STDMETHODCALLTYPE http_request_callback::OnRedirect(
_In_opt_ IXMLHTTPRequest2*,
__RPC__in_string const WCHAR*)
{
return S_OK;
}
HRESULT STDMETHODCALLTYPE http_request_callback::OnHeadersAvailable(
_In_ IXMLHTTPRequest2* xmlReq,
DWORD statusCode,
__RPC__in_string const WCHAR* phrase
)
{
m_httpTask->set_status_code(statusCode);
WCHAR* allResponseHeaders = nullptr;
HRESULT hr = xmlReq->GetAllResponseHeaders(&allResponseHeaders);
if (SUCCEEDED(hr))
{
try
{
if (allResponseHeaders != nullptr)
{
m_httpTask->set_headers(allResponseHeaders);
}
}
catch (...)
{
m_httpTask->set_exception(std::current_exception());
hr = ERROR_UNHANDLED_EXCEPTION;
}
}
if (allResponseHeaders != nullptr)
{
::CoTaskMemFree(allResponseHeaders);
}
return hr;
}
HRESULT STDMETHODCALLTYPE http_request_callback::OnDataAvailable(
_In_opt_ IXMLHTTPRequest2*,
_In_opt_ ISequentialStream*
)
{
return S_OK;
}
HRESULT STDMETHODCALLTYPE http_request_callback::OnResponseReceived(
_In_opt_ IXMLHTTPRequest2*,
_In_opt_ ISequentialStream*
)
{
auto call = m_httpTask->call();
auto taskHandle = m_httpTask->task_handle();
HCHttpCallResponseSetStatusCode(call, m_httpTask->get_status_code());
auto& headerNames = m_httpTask->get_headers_names();
auto& headerValues = m_httpTask->get_headers_values();
HC_ASSERT(headerNames.size() == headerValues.size());
for (unsigned i = 0; i < headerNames.size(); i++)
{
HCHttpCallResponseSetHeader(call, headerNames[i].c_str(), headerValues[i].c_str());
}
auto const& responseString = m_httpTask->response_buffer().as_string();
HCHttpCallResponseSetResponseString(call, responseString.c_str());
HC_RESULT hr = HC_OK;
if (m_httpTask->has_error())
{
hr = HC_E_FAIL;
}
HCHttpCallResponseSetNetworkErrorCode(call, hr, hr);
HCTaskSetCompleted(taskHandle);
// Break the circular reference loop.
// - xmlhttp_http_task holds a reference to IXmlHttpRequest2
// - IXmlHttpRequest2 holds a reference to HttpRequestCallback
// - HttpRequestCallback holds a reference to xmlhttp_http_task
//
// Not releasing the winrt_request_context below previously worked due to the
// implementation of IXmlHttpRequest2, after calling OnError/OnResponseReceived
// it would immediately release its reference to HttpRequestCallback. However
// it since has been discovered on Xbox that the implementation is different,
// the reference to HttpRequestCallback is NOT immediately released and is only
// done at destruction of IXmlHttpRequest2.
//
// To be safe we now will break the circular reference.
m_httpTask.reset();
return S_OK;
}
HRESULT STDMETHODCALLTYPE http_request_callback::OnError(
_In_opt_ IXMLHTTPRequest2*,
HRESULT hrError
)
{
HCHttpCallResponseSetNetworkErrorCode(m_httpTask->call(), HC_E_FAIL, hrError);
HCTaskSetCompleted(m_httpTask->task_handle());
// Break the circular reference loop.
// See full explanation in OnResponseReceived
m_httpTask.reset();
return S_OK;
}
<|endoftext|>
|
<commit_before>// PluginHelpers.cpp : Defines the exported functions for the DLL application.
//
#include "stdafx.h"
#include "pluginhelpers.h"
////////////////////////////////////////////////////////////////////////////////////////////////
using namespace Abstractspoon::Tdl::PluginHelpers;
////////////////////////////////////////////////////////////////////////////////////////////////
MarshalledString::MarshalledString(String^ str) : m_wszGlobal(NULL)
{
m_wszGlobal = (LPCWSTR)Marshal::StringToHGlobalUni(str).ToPointer();
}
MarshalledString::~MarshalledString()
{
Marshal::FreeHGlobal((IntPtr)(void*)m_wszGlobal);
}
MarshalledString::operator LPCWSTR()
{
return m_wszGlobal;
}
////////////////////////////////////////////////////////////////////////////////////////////////
void DialogUtils::SetFont(System::Windows::Forms::Control^ ctrl, System::Drawing::Font^ font)
{
ctrl->Font = font;
SetFont(ctrl->Controls, font);
}
void DialogUtils::SetFont(System::Windows::Forms::Control::ControlCollection^ ctrls, System::Drawing::Font^ font)
{
int nCtrl = ctrls->Count;
while (nCtrl--)
SetFont(ctrls[nCtrl], font); // RECURSIVE CALL
}
////////////////////////////////////////////////////////////////////////////////////////////////
<commit_msg>Use legacy font rendering for consistency<commit_after>// PluginHelpers.cpp : Defines the exported functions for the DLL application.
//
#include "stdafx.h"
#include "pluginhelpers.h"
////////////////////////////////////////////////////////////////////////////////////////////////
using namespace Abstractspoon::Tdl::PluginHelpers;
////////////////////////////////////////////////////////////////////////////////////////////////
class ModuleInitialiser
{
public:
ModuleInitialiser()
{
System::Windows::Forms::Application::SetCompatibleTextRenderingDefault(false);
}
};
static ModuleInitialiser* _init = new ModuleInitialiser();
////////////////////////////////////////////////////////////////////////////////////////////////
MarshalledString::MarshalledString(String^ str) : m_wszGlobal(NULL)
{
m_wszGlobal = (LPCWSTR)Marshal::StringToHGlobalUni(str).ToPointer();
}
MarshalledString::~MarshalledString()
{
Marshal::FreeHGlobal((IntPtr)(void*)m_wszGlobal);
}
MarshalledString::operator LPCWSTR()
{
return m_wszGlobal;
}
////////////////////////////////////////////////////////////////////////////////////////////////
void DialogUtils::SetFont(System::Windows::Forms::Control^ ctrl, System::Drawing::Font^ font)
{
ctrl->Font = font;
SetFont(ctrl->Controls, font);
}
void DialogUtils::SetFont(System::Windows::Forms::Control::ControlCollection^ ctrls, System::Drawing::Font^ font)
{
int nCtrl = ctrls->Count;
while (nCtrl--)
SetFont(ctrls[nCtrl], font); // RECURSIVE CALL
}
////////////////////////////////////////////////////////////////////////////////////////////////
<|endoftext|>
|
<commit_before>//
// Face.hpp
//
// Sketchup C++ Wrapper for C API
// MIT License
//
// Copyright (c) 2017 Tom Kaneko
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
//
#ifndef Face_hpp
#define Face_hpp
#include <stdio.h>
#include <vector>
#include "SUAPI-CppWrapper/model/DrawingElement.hpp"
#include "SUAPI-CppWrapper/model/TextureWriter.hpp"
#include "SUAPI-CppWrapper/model/UVHelper.hpp"
#include <SketchUpAPI/model/face.h>
#include <SketchUpAPI/model/material.h>
#include <SketchUpAPI/model/loop.h>
namespace CW {
enum FacePointClass {
PointUnknown, // (indicates an error),
PointInside, // (point is on the face, not in a hole),
PointOnVertex, // (point touches a vertex),
PointOnEdge, // (point is on an edge),
PointOutside, // (point outside the face or in a hole),
PointNotOnPlane // (point off the face's plane).
};
class Point3D;
class Vector3D;
class Material;
class Vertex;
class Loop;
class LoopInput;
class Edge;
class Face :public DrawingElement {
private:
SUFaceRef m_face;
//SUResult m_create_result = SU_ERROR_NONE;
/**
* Creates a SUFaceRef object from an array of points that represent the outer loop.
* @param outer_loop vector of points for the vertices in the outer loop.
* @return SUFaceRef object with the defined loops. If there was an error, a SU_INVALID SUFaceRef will be returned.
*/
static SUFaceRef create_face(std::vector<Point3D>& outer_points);
static SUFaceRef create_face(std::vector<Point3D>& outer_points, LoopInput& loop_input);
/**
* Creates a SUFaceRef object from an array of points that represent the loops.
* @param outer_loop vector of points for the vertices in the outer loop.
* @param inner_loops vector of vectors of points. The first dimension represents the inner loops, and the second represents the points in each loop.
* @return SUFaceRef object with the defined loops. If there was an error, a SU_INVALID SUFaceRef will be returned.
*/
//static SUFaceRef create_face(std::vector<Point3D> outer_loop, std::vector<std::vector<Point3D>> inner_loops);
/**
* Creates a SUFaceRef derived from an existing Face object.
* @param face - Face object to derive the new SUFaceRef object from
* @return if the Face object is already attached to a model, its SUFaceRef object will be returned. If the Face object has not been attached to a model, a new SUFaceRef object will be created. Bear in mind all properties will not be copied in the latter case
*/
static SUFaceRef copy_reference(const Face& face);
//static SUFaceRef create_face(std::vector<Point3D> outer_loop, std::vector<std::vector<Point3D>> inner_loops, SUResult &create_result);
//static SUFaceRef check_face(SUFaceRef face, SUResult &create_result);
public:
/**
* Constructor for creating a null object.
*/
Face();
/*
* Face constructor, which takes an array of points representing the outer loop, and an array of arrays of points representing the inner loops of the face. A new SUFaceRef object will be created within this class and handled internally.
*/
Face(std::vector<Point3D>& outer_loop);
Face(std::vector<Point3D>& outer_loop, LoopInput& loop_input);
//Face(std::vector<Point3D> outer_loop, std::vector<std::vector<Point3D>> inner_loops = {{}});
/*
* Face constructor that essentially wraps around an already created SUFaceRef object.
* @param SUFaceRef* pointer to the face.
* @param bool false if the face should be released when this class object is destroyed. True, if the destruction of the face object is handled elsewhere (use with caution).
*/
Face(SUFaceRef face, bool attached = true);
/** Copy constructor */
Face(const Face& other);
/** Destructor */
~Face();
/** Copy assignment operator */
Face& operator=(const Face& other);
/*
* Returns the C-style face_ref object
*/
SUFaceRef ref() const;
/*
* The class object can be converted to a SUFaceRef without loss of data.
*/
operator SUFaceRef() const;
operator SUFaceRef*();
/*
* Returns whether the class is a valid SU object.
*/
operator bool() const;
/**
* NOT operator. Checks if the object is valid.
* @return true if the curve is invalid
*/
bool operator!() const;
/*
* Retrieves the area of a face in SU units.
* @return double area in square inches (SU units).
*/
double area() const;
/**
* Adds an inner loop to the face.
* @param points - a vector of points representing the vertices of the inner loop.
* @param loop_input - the loop input object with details about the edges
*/
void add_inner_loop(std::vector<Point3D>& points, LoopInput &loop_input);
/*
* Retrieves the material assigned to the back side of the face.
* @return Material object of the back side of the face
*/
Material back_material() const;
/*
* Sets the material assigned to the back side of the face.
* @param Material object or the name of a valid material.
* @return Material object of the back side of the face
*/
Material back_material(const Material& material);
/*
* determine if a given Point3d is on the referenced Face. The return value is calculated from this list:
PointUnknown (indicates an error),
PointInside (point is on the face, not in a hole),
PointOnVertex (point touches a vertex),
PointOnEdge (point is on an edge),
PointOutside (point outside the face or in a hole),
PointNotOnPlane (point off the face's plane).
* @param SUPoint3D object.
* @return FacePointClass enum indicating the status of the point relative to the face.
*/
FacePointClass classify_point(const Point3D& point);
/*
* Get an array of edges that bound the face, including the edges of inner loops.
* @return std::vector of Edge objects that bound the Face.
*/
std::vector<Edge> edges();
/*
* Retrieves a UVHelper object for use in texture manipulation on a face.
* @param front true if you want the texture coordinates for the front face, false if not. Defaults to true.
* @param back True if you want the texture coordinates for the back face, false if not. Defaults to true.
* @param TextureWriter object.
* @return a UVHelper object.
*/
// TODO
//UVHelper get_UVHelper(bool front = true, bool back = true, TextureWriter tex_writer = TextureWriter());
/*
* Returns a vector representing the projection for either the front or back side of the face.
* @param bool true for frontside, false for back side.
*/
Vector3D get_texture_projection(const bool frontside) const;
/*
* Gets an array of all of the inner loops that bound the face.
*/
std::vector<Loop> inner_loops() const;
/*
* Gets an array of all of the loops that bound the face. The first Loop is the outer loop.
*/
std::vector<Loop> loops() const;
/*
// TODO
PolygonMesh mesh();
*/
/*
* Retrieve the 3D vector normal to the face in the front direction.
*/
Vector3D normal() const;
/*
* Retrieves the outer loop that bounds the face.
*/
Loop outer_loop() const;
/*
* Retreives the plane of this face.
*/
Plane3D plane() const;
/*
* Positions a material on a face.
* The pt_array must contain 2, 4, 6 or 8 points. The points are used in pairs to tell where a point in the texture image is positioned on the Face. The first point in each pair is a 3D point in the model. It should be a point on the Face. The second point in each pair of points is a 2D point that gives the (u,v) coordinates of a point in the image to match up with the 3D point.
* @param Material object to position.
* @param vector of Point3d objects used to position the material.
* @param bool true to position the texture on the front of the Face or false to position it on the back of the Face.
*/
/** NOT POSSIBLE WITH C API - @see class MaterialInput **/
// bool position_material(const Material& material, const std::vector<Point3D>& pt_array, bool o_front);
/*
* Reverses the face's orientation, meaning the front becomes the back.
* @return the reversed Face object
*/
Face& reverse();
/*
* Sets the texture projection direction.
* @param SUVector3D object representing the direction of the projection. Or bool true to remove texture projection.
* @param bool true for front side, false for back side.
* @return true on success
*/
/** NOT POSSIBLE WITH C API - @see class MaterialInput **/
//bool set_texture_projection(const Vector3D& vector, bool frontside);
//bool set_texture_projection(bool remove, bool frontside);
/*
* Gets an array of all of the vertices that bound the face.
* @return std::vector array of Vertex objects.
*/
std::vector<Vertex> vertices() const;
};
} /* namespace CW */
#endif /* Face_hpp */
<commit_msg>Added missing forward declaration to Face class<commit_after>//
// Face.hpp
//
// Sketchup C++ Wrapper for C API
// MIT License
//
// Copyright (c) 2017 Tom Kaneko
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
//
#ifndef Face_hpp
#define Face_hpp
#include <stdio.h>
#include <vector>
#include "SUAPI-CppWrapper/model/DrawingElement.hpp"
#include "SUAPI-CppWrapper/model/TextureWriter.hpp"
#include "SUAPI-CppWrapper/model/UVHelper.hpp"
#include <SketchUpAPI/model/face.h>
#include <SketchUpAPI/model/material.h>
#include <SketchUpAPI/model/loop.h>
namespace CW {
enum FacePointClass {
PointUnknown, // (indicates an error),
PointInside, // (point is on the face, not in a hole),
PointOnVertex, // (point touches a vertex),
PointOnEdge, // (point is on an edge),
PointOutside, // (point outside the face or in a hole),
PointNotOnPlane // (point off the face's plane).
};
class Point3D;
class Plane3D;
class Vector3D;
class Material;
class Vertex;
class Loop;
class LoopInput;
class Edge;
class Face :public DrawingElement {
private:
SUFaceRef m_face;
//SUResult m_create_result = SU_ERROR_NONE;
/**
* Creates a SUFaceRef object from an array of points that represent the outer loop.
* @param outer_loop vector of points for the vertices in the outer loop.
* @return SUFaceRef object with the defined loops. If there was an error, a SU_INVALID SUFaceRef will be returned.
*/
static SUFaceRef create_face(std::vector<Point3D>& outer_points);
static SUFaceRef create_face(std::vector<Point3D>& outer_points, LoopInput& loop_input);
/**
* Creates a SUFaceRef object from an array of points that represent the loops.
* @param outer_loop vector of points for the vertices in the outer loop.
* @param inner_loops vector of vectors of points. The first dimension represents the inner loops, and the second represents the points in each loop.
* @return SUFaceRef object with the defined loops. If there was an error, a SU_INVALID SUFaceRef will be returned.
*/
//static SUFaceRef create_face(std::vector<Point3D> outer_loop, std::vector<std::vector<Point3D>> inner_loops);
/**
* Creates a SUFaceRef derived from an existing Face object.
* @param face - Face object to derive the new SUFaceRef object from
* @return if the Face object is already attached to a model, its SUFaceRef object will be returned. If the Face object has not been attached to a model, a new SUFaceRef object will be created. Bear in mind all properties will not be copied in the latter case
*/
static SUFaceRef copy_reference(const Face& face);
//static SUFaceRef create_face(std::vector<Point3D> outer_loop, std::vector<std::vector<Point3D>> inner_loops, SUResult &create_result);
//static SUFaceRef check_face(SUFaceRef face, SUResult &create_result);
public:
/**
* Constructor for creating a null object.
*/
Face();
/*
* Face constructor, which takes an array of points representing the outer loop, and an array of arrays of points representing the inner loops of the face. A new SUFaceRef object will be created within this class and handled internally.
*/
Face(std::vector<Point3D>& outer_loop);
Face(std::vector<Point3D>& outer_loop, LoopInput& loop_input);
//Face(std::vector<Point3D> outer_loop, std::vector<std::vector<Point3D>> inner_loops = {{}});
/*
* Face constructor that essentially wraps around an already created SUFaceRef object.
* @param SUFaceRef* pointer to the face.
* @param bool false if the face should be released when this class object is destroyed. True, if the destruction of the face object is handled elsewhere (use with caution).
*/
Face(SUFaceRef face, bool attached = true);
/** Copy constructor */
Face(const Face& other);
/** Destructor */
~Face();
/** Copy assignment operator */
Face& operator=(const Face& other);
/*
* Returns the C-style face_ref object
*/
SUFaceRef ref() const;
/*
* The class object can be converted to a SUFaceRef without loss of data.
*/
operator SUFaceRef() const;
operator SUFaceRef*();
/*
* Returns whether the class is a valid SU object.
*/
operator bool() const;
/**
* NOT operator. Checks if the object is valid.
* @return true if the curve is invalid
*/
bool operator!() const;
/*
* Retrieves the area of a face in SU units.
* @return double area in square inches (SU units).
*/
double area() const;
/**
* Adds an inner loop to the face.
* @param points - a vector of points representing the vertices of the inner loop.
* @param loop_input - the loop input object with details about the edges
*/
void add_inner_loop(std::vector<Point3D>& points, LoopInput &loop_input);
/*
* Retrieves the material assigned to the back side of the face.
* @return Material object of the back side of the face
*/
Material back_material() const;
/*
* Sets the material assigned to the back side of the face.
* @param Material object or the name of a valid material.
* @return Material object of the back side of the face
*/
Material back_material(const Material& material);
/*
* determine if a given Point3d is on the referenced Face. The return value is calculated from this list:
PointUnknown (indicates an error),
PointInside (point is on the face, not in a hole),
PointOnVertex (point touches a vertex),
PointOnEdge (point is on an edge),
PointOutside (point outside the face or in a hole),
PointNotOnPlane (point off the face's plane).
* @param SUPoint3D object.
* @return FacePointClass enum indicating the status of the point relative to the face.
*/
FacePointClass classify_point(const Point3D& point);
/*
* Get an array of edges that bound the face, including the edges of inner loops.
* @return std::vector of Edge objects that bound the Face.
*/
std::vector<Edge> edges();
/*
* Retrieves a UVHelper object for use in texture manipulation on a face.
* @param front true if you want the texture coordinates for the front face, false if not. Defaults to true.
* @param back True if you want the texture coordinates for the back face, false if not. Defaults to true.
* @param TextureWriter object.
* @return a UVHelper object.
*/
// TODO
//UVHelper get_UVHelper(bool front = true, bool back = true, TextureWriter tex_writer = TextureWriter());
/*
* Returns a vector representing the projection for either the front or back side of the face.
* @param bool true for frontside, false for back side.
*/
Vector3D get_texture_projection(const bool frontside) const;
/*
* Gets an array of all of the inner loops that bound the face.
*/
std::vector<Loop> inner_loops() const;
/*
* Gets an array of all of the loops that bound the face. The first Loop is the outer loop.
*/
std::vector<Loop> loops() const;
/*
// TODO
PolygonMesh mesh();
*/
/*
* Retrieve the 3D vector normal to the face in the front direction.
*/
Vector3D normal() const;
/*
* Retrieves the outer loop that bounds the face.
*/
Loop outer_loop() const;
/*
* Retreives the plane of this face.
*/
Plane3D plane() const;
/*
* Positions a material on a face.
* The pt_array must contain 2, 4, 6 or 8 points. The points are used in pairs to tell where a point in the texture image is positioned on the Face. The first point in each pair is a 3D point in the model. It should be a point on the Face. The second point in each pair of points is a 2D point that gives the (u,v) coordinates of a point in the image to match up with the 3D point.
* @param Material object to position.
* @param vector of Point3d objects used to position the material.
* @param bool true to position the texture on the front of the Face or false to position it on the back of the Face.
*/
/** NOT POSSIBLE WITH C API - @see class MaterialInput **/
// bool position_material(const Material& material, const std::vector<Point3D>& pt_array, bool o_front);
/*
* Reverses the face's orientation, meaning the front becomes the back.
* @return the reversed Face object
*/
Face& reverse();
/*
* Sets the texture projection direction.
* @param SUVector3D object representing the direction of the projection. Or bool true to remove texture projection.
* @param bool true for front side, false for back side.
* @return true on success
*/
/** NOT POSSIBLE WITH C API - @see class MaterialInput **/
//bool set_texture_projection(const Vector3D& vector, bool frontside);
//bool set_texture_projection(bool remove, bool frontside);
/*
* Gets an array of all of the vertices that bound the face.
* @return std::vector array of Vertex objects.
*/
std::vector<Vertex> vertices() const;
};
} /* namespace CW */
#endif /* Face_hpp */
<|endoftext|>
|
<commit_before>// This file is a part of the IncludeOS unikernel - www.includeos.org
//
// Copyright 2016-2017 Oslo and Akershus University College of Applied Sciences
// and Alfred Bratterud
//
// 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 <net/ws/websocket.hpp>
#include <kernel/os.hpp>
#include <util/base64.hpp>
#include <util/sha1.hpp>
#include <cstdint>
#include <net/ws/connector.hpp>
namespace net {
static inline std::string
encode_hash(const std::string& key)
{
static const std::string GUID = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
SHA1 sha;
sha.update(key);
sha.update(GUID);
return base64::encode(sha.as_raw());
}
const char* WebSocket::to_string(op_code code)
{
switch (code) {
case op_code::CONTINUE:
return "Continuation frame";
case op_code::TEXT:
return "Text frame";
case op_code::BINARY:
return "Binary frame";
case op_code::CLOSE:
return "Connection close";
case op_code::PING:
return "Ping";
case op_code::PONG:
return "Pong";
default:
return "Reserved (unspecified)";
}
}
WebSocket_ptr WebSocket::upgrade(http::Request& req, http::Response_writer& writer)
{
// validate handshake
auto view = req.header().value("Sec-WebSocket-Version");
if (view == nullptr || view != "13") {
writer.write_header(http::Bad_Request);
return nullptr;
}
auto key = req.header().value("Sec-WebSocket-Key");
if (key == nullptr || key.size() < 16) {
writer.write_header(http::Bad_Request);
return nullptr;
}
// create handshake response
auto& header = writer.header();
header.set_field(http::header::Connection, "Upgrade");
header.set_field(http::header::Upgrade, "WebSocket");
header.set_field("Sec-WebSocket-Accept", encode_hash(key.to_string()));
writer.write_header(http::Switching_Protocols);
auto stream = writer.connection().release();
// discard streams which can be FIN-WAIT-1
if (stream->is_connected()) {
// for now, only accept fully connected streams
return std::make_unique<WebSocket>(std::move(stream), false);
}
return nullptr;
}
WebSocket_ptr WebSocket::upgrade(http::Error err, http::Response& res, http::Connection& conn, const std::string& key)
{
if (err or res.status_code() != http::Switching_Protocols)
{
return nullptr;
}
else
{
/// validate response
auto hash = res.header().value("Sec-WebSocket-Accept");
if (hash.empty() or hash != encode_hash(key))
{
return nullptr;
}
/// create open websocket
auto stream = conn.release();
assert(stream->is_connected());
// create client websocket and call callback
return std::make_unique<WebSocket>(std::move(stream), true);
}
}
std::vector<char> WebSocket::generate_key()
{
std::vector<char> key(16);
uint16_t v;
for (size_t i = 0; i < key.size(); i += sizeof(v))
{
v = rand() & 0xffff;
memcpy(&key[i], &v, sizeof(v));
}
return key;
}
http::Server::Request_handler WebSocket::create_request_handler(
Connect_handler on_connect, Accept_handler on_accept)
{
auto handler = http::Server::Request_handler::make_packed(
[
on_connect{std::move(on_connect)},
on_accept{std::move(on_accept)}
]
(http::Request_ptr req, http::Response_writer_ptr writer)
{
if (on_accept)
{
const bool accepted = on_accept(writer->connection().peer(),
req->header().value("Origin").to_string());
if (not accepted)
{
writer->write_header(http::Unauthorized);
on_connect(nullptr);
return;
}
}
auto ws = WebSocket::upgrade(*req, *writer);
on_connect(std::move(ws));
});
return handler;
}
http::Client::Response_handler WebSocket::create_response_handler(
Connect_handler on_connect, std::string key)
{
auto handler = http::Client::Response_handler::make_packed(
[
on_connect{std::move(on_connect)},
key{std::move(key)}
]
(http::Error err, http::Response_ptr res, http::Connection& conn)
{
auto ws = WebSocket::upgrade(err, *res, conn, key);
on_connect(std::move(ws));
});
return handler;
}
void WebSocket::connect(
http::Client& client,
uri::URI remote,
Connect_handler callback)
{
// doesn't have to be extremely random, just random
std::string key = base64::encode(generate_key());
http::Header_set ws_headers {
{"Host", remote.to_string()},
{"Connection", "Upgrade" },
{"Upgrade", "WebSocket"},
{"Sec-WebSocket-Version", "13"},
{"Sec-WebSocket-Key", key }
};
// send HTTP request
client.get(remote, ws_headers,
WS_client_connector::create_response_handler(std::move(callback), std::move(key)));
}
void WebSocket::read_data(net::tcp::buffer_t buf)
{
// silently ignore data from reset connection
if (this->stream == nullptr) return;
char* data = (char*) buf->data();
// parse message
size_t len = buf->size();
while (len) {
if (message != nullptr)
{
len -= message->add(data, len);
}
// create new message
else
{
len -= create_message(data, len);
}
if(message->is_complete()) {
finalize_message();
}
}
}
size_t WebSocket::create_message(char* buf, size_t len){
// parse header
if (len < sizeof(ws_header)) {
failure("read_data: Header was too short");
// Consider the remaining buffer as garbage
return len;
}
ws_header& hdr = *reinterpret_cast<ws_header*>(buf);
// TODO: Add configuration for this, hardcoded max msgs of 5MB for now
if (hdr.data_length() > (1024 * 1024 * 5)) {
failure("read: Maximum message size exceeded (5MB)");
// consume and discard current message, leave any remaining data in buffer
return std::min(hdr.data_length(), len);
}
/*
printf("Code: %hhu (%s) (final=%d)\n",
hdr.opcode(), opcode_string(hdr.opcode()), hdr.is_final());
printf("Mask: %d len=%u\n", hdr.is_masked(), hdr.mask_length());
printf("Payload: len=%u dataofs=%u\n",
hdr.data_length(), hdr.data_offset());
*/
/// unmask data (if masked)
if (hdr.is_masked()) {
if (clientside == true) {
failure("Read masked message from server");
return std::min(hdr.data_length(), len);
}
} else if (clientside == false) {
failure("Read unmasked message from client");
return std::min(hdr.data_length(), len);
}
auto msg_size = std::min(len, hdr.reported_length());
message = std::make_unique<Message>(buf, msg_size);
return msg_size;
}
void WebSocket::finalize_message() {
Expects(message != nullptr and message->is_complete());
message->unmask();
const auto& hdr = message->header();
switch (hdr.opcode()) {
case op_code::TEXT:
case op_code::BINARY:
/// .. call on_read
if (on_read) {
on_read(std::move(message));
}
break;
case op_code::CLOSE:
// they are angry with us :(
if (hdr.data_length() >= 2) {
// provide reason to user
uint16_t reason = *(uint16_t*) message->data();
if (this->on_close)
this->on_close(__builtin_bswap16(reason));
}
else {
if (this->on_close) this->on_close(1000);
}
// close it down
this->close();
break;
case op_code::PING:
write_opcode(op_code::PONG, hdr.data(), hdr.data_length());
break;
case op_code::PONG:
break;
default:
printf("Unknown opcode: %d\n", (int) hdr.opcode());
break;
}
message.reset();
}
static size_t make_header(char* dest, size_t len, op_code code, bool client)
{
new (dest) ws_header;
auto& hdr = *(ws_header*) dest;
hdr.bits = 0;
hdr.set_final();
hdr.set_payload(len);
hdr.set_opcode(code);
if (client) {
hdr.set_masked(OS::cycles_since_boot() & 0xffffffff);
}
// header size + data offset
return sizeof(ws_header) + hdr.data_offset();
}
void WebSocket::write(const char* buffer, size_t len, op_code code)
{
if (UNLIKELY(this->stream == nullptr)) {
failure("write: Already closed");
return;
}
if (UNLIKELY(this->stream->is_writable() == false)) {
failure("write: Connection not writable");
return;
}
Expects((code == op_code::TEXT or code == op_code::BINARY)
&& "Write currently only supports TEXT or BINARY");
// allocate header and data at the same time
auto buf = tcp::construct_buffer(WS_HEADER_MAXLEN + len);
// fill header
int header_len = make_header((char*) buf->data(), len, code, clientside);
buf->resize(header_len);
// get data offset & fill in data into buffer
std::copy(buffer, buffer + len, std::back_inserter(*buf));
// for client-side we have to mask the data
if (clientside)
{
// mask data to server
auto& hdr = *(ws_header*) buf->data();
assert(hdr.is_masked());
hdr.masking_algorithm();
}
/// send everything as shared buffer
this->stream->write(buf);
}
void WebSocket::write(net::tcp::buffer_t buffer, op_code code)
{
if (UNLIKELY(this->stream == nullptr)) {
failure("write: Already closed");
return;
}
if (UNLIKELY(this->stream->is_writable() == false)) {
failure("write: Connection not writable");
return;
}
if (UNLIKELY(clientside == true)) {
failure("write: Client-side does not support sending shared buffers");
return;
}
Expects((code == op_code::TEXT or code == op_code::BINARY)
&& "Write currently only supports TEXT or BINARY");
/// write header
char header[WS_HEADER_MAXLEN];
int header_len = make_header(header, buffer->size(), code, false);
assert(header_len <= WS_HEADER_MAXLEN);
this->stream->write(header, header_len);
/// write shared buffer
this->stream->write(buffer);
}
bool WebSocket::write_opcode(op_code code, const char* buffer, size_t datalen)
{
if (UNLIKELY(stream == nullptr || stream->is_writable() == false)) {
return false;
}
/// write header
char header[WS_HEADER_MAXLEN];
int header_len = make_header(header, datalen, code, clientside);
this->stream->write(header, header_len);
/// write buffer (if present)
if (buffer != nullptr && datalen > 0)
this->stream->write(buffer, datalen);
return true;
}
void WebSocket::tcp_closed()
{
if (this->on_close != nullptr) this->on_close(1000);
this->reset();
}
WebSocket::WebSocket(net::Stream_ptr stream_ptr, bool client)
: stream(std::move(stream_ptr)), clientside(client)
{
assert(stream != nullptr);
this->stream->on_read(16384, {this, &WebSocket::read_data});
this->stream->on_close({this, &WebSocket::tcp_closed});
}
WebSocket::WebSocket(WebSocket&& other)
{
other.on_close = std::move(on_close);
other.on_error = std::move(on_error);
other.on_read = std::move(on_read);
other.stream = std::move(stream);
other.clientside = clientside;
}
WebSocket::~WebSocket()
{
if (stream != nullptr && stream->is_connected())
this->close();
}
void WebSocket::close()
{
/// send CLOSE message
if (this->stream->is_writable())
this->write_opcode(op_code::CLOSE, nullptr, 0);
/// close and unset socket
this->stream->close();
this->reset();
}
void WebSocket::reset()
{
this->on_close = nullptr;
this->on_error = nullptr;
this->on_read = nullptr;
stream->reset_callbacks();
stream->close();
stream = nullptr;
}
void WebSocket::failure(const std::string& reason)
{
if (stream != nullptr) stream->close();
if (this->on_error) on_error(reason);
}
const char* WebSocket::status_code(uint16_t code)
{
switch (code) {
case 1000:
return "Closed";
case 1001:
return "Going away";
case 1002:
return "Protocol error";
case 1003:
return "Cannot accept data";
case 1004:
return "Reserved";
case 1005:
return "Status code not present";
case 1006:
return "Connection closed abnormally";
case 1007:
return "Non UTF-8 data received";
case 1008:
return "Message violated policy";
case 1009:
return "Message too big";
case 1010:
return "Missing extension";
case 1011:
return "Internal server error";
case 1015:
return "TLS handshake failure";
default:
return "Unknown status code";
}
}
} // net
<commit_msg>net: Fixed websocket move constructor<commit_after>// This file is a part of the IncludeOS unikernel - www.includeos.org
//
// Copyright 2016-2017 Oslo and Akershus University College of Applied Sciences
// and Alfred Bratterud
//
// 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 <net/ws/websocket.hpp>
#include <kernel/os.hpp>
#include <util/base64.hpp>
#include <util/sha1.hpp>
#include <cstdint>
#include <net/ws/connector.hpp>
namespace net {
static inline std::string
encode_hash(const std::string& key)
{
static const std::string GUID = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
SHA1 sha;
sha.update(key);
sha.update(GUID);
return base64::encode(sha.as_raw());
}
const char* WebSocket::to_string(op_code code)
{
switch (code) {
case op_code::CONTINUE:
return "Continuation frame";
case op_code::TEXT:
return "Text frame";
case op_code::BINARY:
return "Binary frame";
case op_code::CLOSE:
return "Connection close";
case op_code::PING:
return "Ping";
case op_code::PONG:
return "Pong";
default:
return "Reserved (unspecified)";
}
}
WebSocket_ptr WebSocket::upgrade(http::Request& req, http::Response_writer& writer)
{
// validate handshake
auto view = req.header().value("Sec-WebSocket-Version");
if (view == nullptr || view != "13") {
writer.write_header(http::Bad_Request);
return nullptr;
}
auto key = req.header().value("Sec-WebSocket-Key");
if (key == nullptr || key.size() < 16) {
writer.write_header(http::Bad_Request);
return nullptr;
}
// create handshake response
auto& header = writer.header();
header.set_field(http::header::Connection, "Upgrade");
header.set_field(http::header::Upgrade, "WebSocket");
header.set_field("Sec-WebSocket-Accept", encode_hash(key.to_string()));
writer.write_header(http::Switching_Protocols);
auto stream = writer.connection().release();
// discard streams which can be FIN-WAIT-1
if (stream->is_connected()) {
// for now, only accept fully connected streams
return std::make_unique<WebSocket>(std::move(stream), false);
}
return nullptr;
}
WebSocket_ptr WebSocket::upgrade(http::Error err, http::Response& res, http::Connection& conn, const std::string& key)
{
if (err or res.status_code() != http::Switching_Protocols)
{
return nullptr;
}
else
{
/// validate response
auto hash = res.header().value("Sec-WebSocket-Accept");
if (hash.empty() or hash != encode_hash(key))
{
return nullptr;
}
/// create open websocket
auto stream = conn.release();
assert(stream->is_connected());
// create client websocket and call callback
return std::make_unique<WebSocket>(std::move(stream), true);
}
}
std::vector<char> WebSocket::generate_key()
{
std::vector<char> key(16);
uint16_t v;
for (size_t i = 0; i < key.size(); i += sizeof(v))
{
v = rand() & 0xffff;
memcpy(&key[i], &v, sizeof(v));
}
return key;
}
http::Server::Request_handler WebSocket::create_request_handler(
Connect_handler on_connect, Accept_handler on_accept)
{
auto handler = http::Server::Request_handler::make_packed(
[
on_connect{std::move(on_connect)},
on_accept{std::move(on_accept)}
]
(http::Request_ptr req, http::Response_writer_ptr writer)
{
if (on_accept)
{
const bool accepted = on_accept(writer->connection().peer(),
req->header().value("Origin").to_string());
if (not accepted)
{
writer->write_header(http::Unauthorized);
on_connect(nullptr);
return;
}
}
auto ws = WebSocket::upgrade(*req, *writer);
on_connect(std::move(ws));
});
return handler;
}
http::Client::Response_handler WebSocket::create_response_handler(
Connect_handler on_connect, std::string key)
{
auto handler = http::Client::Response_handler::make_packed(
[
on_connect{std::move(on_connect)},
key{std::move(key)}
]
(http::Error err, http::Response_ptr res, http::Connection& conn)
{
auto ws = WebSocket::upgrade(err, *res, conn, key);
on_connect(std::move(ws));
});
return handler;
}
void WebSocket::connect(
http::Client& client,
uri::URI remote,
Connect_handler callback)
{
// doesn't have to be extremely random, just random
std::string key = base64::encode(generate_key());
http::Header_set ws_headers {
{"Host", remote.to_string()},
{"Connection", "Upgrade" },
{"Upgrade", "WebSocket"},
{"Sec-WebSocket-Version", "13"},
{"Sec-WebSocket-Key", key }
};
// send HTTP request
client.get(remote, ws_headers,
WS_client_connector::create_response_handler(std::move(callback), std::move(key)));
}
void WebSocket::read_data(net::tcp::buffer_t buf)
{
// silently ignore data from reset connection
if (this->stream == nullptr) return;
char* data = (char*) buf->data();
// parse message
size_t len = buf->size();
while (len) {
if (message != nullptr)
{
len -= message->add(data, len);
}
// create new message
else
{
len -= create_message(data, len);
}
if(message->is_complete()) {
finalize_message();
}
}
}
size_t WebSocket::create_message(char* buf, size_t len){
// parse header
if (len < sizeof(ws_header)) {
failure("read_data: Header was too short");
// Consider the remaining buffer as garbage
return len;
}
ws_header& hdr = *reinterpret_cast<ws_header*>(buf);
// TODO: Add configuration for this, hardcoded max msgs of 5MB for now
if (hdr.data_length() > (1024 * 1024 * 5)) {
failure("read: Maximum message size exceeded (5MB)");
// consume and discard current message, leave any remaining data in buffer
return std::min(hdr.data_length(), len);
}
/*
printf("Code: %hhu (%s) (final=%d)\n",
hdr.opcode(), opcode_string(hdr.opcode()), hdr.is_final());
printf("Mask: %d len=%u\n", hdr.is_masked(), hdr.mask_length());
printf("Payload: len=%u dataofs=%u\n",
hdr.data_length(), hdr.data_offset());
*/
/// unmask data (if masked)
if (hdr.is_masked()) {
if (clientside == true) {
failure("Read masked message from server");
return std::min(hdr.data_length(), len);
}
} else if (clientside == false) {
failure("Read unmasked message from client");
return std::min(hdr.data_length(), len);
}
auto msg_size = std::min(len, hdr.reported_length());
message = std::make_unique<Message>(buf, msg_size);
return msg_size;
}
void WebSocket::finalize_message() {
Expects(message != nullptr and message->is_complete());
message->unmask();
const auto& hdr = message->header();
switch (hdr.opcode()) {
case op_code::TEXT:
case op_code::BINARY:
/// .. call on_read
if (on_read) {
on_read(std::move(message));
}
break;
case op_code::CLOSE:
// they are angry with us :(
if (hdr.data_length() >= 2) {
// provide reason to user
uint16_t reason = *(uint16_t*) message->data();
if (this->on_close)
this->on_close(__builtin_bswap16(reason));
}
else {
if (this->on_close) this->on_close(1000);
}
// close it down
this->close();
break;
case op_code::PING:
write_opcode(op_code::PONG, hdr.data(), hdr.data_length());
break;
case op_code::PONG:
break;
default:
printf("Unknown opcode: %d\n", (int) hdr.opcode());
break;
}
message.reset();
}
static size_t make_header(char* dest, size_t len, op_code code, bool client)
{
new (dest) ws_header;
auto& hdr = *(ws_header*) dest;
hdr.bits = 0;
hdr.set_final();
hdr.set_payload(len);
hdr.set_opcode(code);
if (client) {
hdr.set_masked(OS::cycles_since_boot() & 0xffffffff);
}
// header size + data offset
return sizeof(ws_header) + hdr.data_offset();
}
void WebSocket::write(const char* buffer, size_t len, op_code code)
{
if (UNLIKELY(this->stream == nullptr)) {
failure("write: Already closed");
return;
}
if (UNLIKELY(this->stream->is_writable() == false)) {
failure("write: Connection not writable");
return;
}
Expects((code == op_code::TEXT or code == op_code::BINARY)
&& "Write currently only supports TEXT or BINARY");
// allocate header and data at the same time
auto buf = tcp::construct_buffer(WS_HEADER_MAXLEN + len);
// fill header
int header_len = make_header((char*) buf->data(), len, code, clientside);
buf->resize(header_len);
// get data offset & fill in data into buffer
std::copy(buffer, buffer + len, std::back_inserter(*buf));
// for client-side we have to mask the data
if (clientside)
{
// mask data to server
auto& hdr = *(ws_header*) buf->data();
assert(hdr.is_masked());
hdr.masking_algorithm();
}
/// send everything as shared buffer
this->stream->write(buf);
}
void WebSocket::write(net::tcp::buffer_t buffer, op_code code)
{
if (UNLIKELY(this->stream == nullptr)) {
failure("write: Already closed");
return;
}
if (UNLIKELY(this->stream->is_writable() == false)) {
failure("write: Connection not writable");
return;
}
if (UNLIKELY(clientside == true)) {
failure("write: Client-side does not support sending shared buffers");
return;
}
Expects((code == op_code::TEXT or code == op_code::BINARY)
&& "Write currently only supports TEXT or BINARY");
/// write header
char header[WS_HEADER_MAXLEN];
int header_len = make_header(header, buffer->size(), code, false);
assert(header_len <= WS_HEADER_MAXLEN);
this->stream->write(header, header_len);
/// write shared buffer
this->stream->write(buffer);
}
bool WebSocket::write_opcode(op_code code, const char* buffer, size_t datalen)
{
if (UNLIKELY(stream == nullptr || stream->is_writable() == false)) {
return false;
}
/// write header
char header[WS_HEADER_MAXLEN];
int header_len = make_header(header, datalen, code, clientside);
this->stream->write(header, header_len);
/// write buffer (if present)
if (buffer != nullptr && datalen > 0)
this->stream->write(buffer, datalen);
return true;
}
void WebSocket::tcp_closed()
{
if (this->on_close != nullptr) this->on_close(1000);
this->reset();
}
WebSocket::WebSocket(net::Stream_ptr stream_ptr, bool client)
: stream(std::move(stream_ptr)), clientside(client)
{
assert(stream != nullptr);
this->stream->on_read(16384, {this, &WebSocket::read_data});
this->stream->on_close({this, &WebSocket::tcp_closed});
}
WebSocket::WebSocket(WebSocket&& other)
{
on_close = std::move(other.on_close);
on_error = std::move(other.on_error);
on_read = std::move(other.on_read);
stream = std::move(other.stream);
clientside = other.clientside;
}
WebSocket::~WebSocket()
{
if (stream != nullptr && stream->is_connected())
this->close();
}
void WebSocket::close()
{
/// send CLOSE message
if (this->stream->is_writable())
this->write_opcode(op_code::CLOSE, nullptr, 0);
/// close and unset socket
this->stream->close();
this->reset();
}
void WebSocket::reset()
{
this->on_close = nullptr;
this->on_error = nullptr;
this->on_read = nullptr;
stream->reset_callbacks();
stream->close();
stream = nullptr;
}
void WebSocket::failure(const std::string& reason)
{
if (stream != nullptr) stream->close();
if (this->on_error) on_error(reason);
}
const char* WebSocket::status_code(uint16_t code)
{
switch (code) {
case 1000:
return "Closed";
case 1001:
return "Going away";
case 1002:
return "Protocol error";
case 1003:
return "Cannot accept data";
case 1004:
return "Reserved";
case 1005:
return "Status code not present";
case 1006:
return "Connection closed abnormally";
case 1007:
return "Non UTF-8 data received";
case 1008:
return "Message violated policy";
case 1009:
return "Message too big";
case 1010:
return "Missing extension";
case 1011:
return "Internal server error";
case 1015:
return "TLS handshake failure";
default:
return "Unknown status code";
}
}
} // net
<|endoftext|>
|
<commit_before>/*
Copyright (C) 1998-2001 by Jorrit Tyberghein
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Library General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Library General Public License for more details.
You should have received a copy of the GNU Library General Public
License along with this library; if not, write to the Free
Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
#include "cssysdef.h"
#include "glcommon2d.h"
#include "cssys/sysdriv.h"
#include "cssys/csendian.h"
#include "video/canvas/common/scrshot.h"
#include "csgeom/csrect.h"
#include "isys/system.h"
#include "iutil/objreg.h"
#include "ivaria/reporter.h"
#include "qint.h"
SCF_IMPLEMENT_IBASE_EXT (csGraphics2DGLCommon)
SCF_IMPLEMENTS_INTERFACE (iEventPlug)
SCF_IMPLEMENT_IBASE_EXT_END
csGraphics2DGLCommon::csGraphics2DGLCommon (iBase *iParent) :
csGraphics2D (iParent), FontCache (NULL)
{
EventOutlet = NULL;
}
bool csGraphics2DGLCommon::Initialize (iObjectRegistry *object_reg)
{
if (!csGraphics2D::Initialize (object_reg))
return false;
// We don't really care about pixel format, except for ScreenShot ()
# if defined (CS_BIG_ENDIAN)
pfmt.RedMask = 0xff000000;
pfmt.GreenMask = 0x00ff0000;
pfmt.BlueMask = 0x0000ff00;
# else
pfmt.RedMask = 0x000000ff;
pfmt.GreenMask = 0x0000ff00;
pfmt.BlueMask = 0x00ff0000;
# endif
pfmt.PixelBytes = 4;
pfmt.PalEntries = 0;
pfmt.complete ();
return true;
}
csGraphics2DGLCommon::~csGraphics2DGLCommon ()
{
Close ();
if (EventOutlet)
EventOutlet->DecRef ();
}
bool csGraphics2DGLCommon::Open ()
{
if (is_open) return true;
// initialize font cache object
if (!FontCache)
FontCache = new GLFontCache (FontServer);
if (!csGraphics2D::Open ())
return false;
const char *renderer = (const char *)glGetString (GL_RENDERER);
const char *version = (const char *)glGetString (GL_VERSION);
iReporter* reporter = CS_QUERY_REGISTRY (object_reg, iReporter);
if (renderer || version)
if (reporter)
reporter->Report (CS_REPORTER_SEVERITY_NOTIFY,
"crystalspace.canvas.openglcommon",
"OpenGL renderer: %s version %s",
renderer ? renderer : "unknown", version ? version : "unknown");
if (reporter)
reporter->Report (CS_REPORTER_SEVERITY_NOTIFY,
"crystalspace.canvas.openglcommon",
"Using %s mode at resolution %dx%d.",
FullScreen ? "full screen" : "windowed", Width, Height);
glClearColor (0., 0., 0., 0.);
glClearDepth (-1.0);
glMatrixMode (GL_MODELVIEW);
glLoadIdentity ();
glViewport (0, 0, Width, Height);
Clear (0);
return true;
}
void csGraphics2DGLCommon::Close ()
{
if (!is_open) return;
delete FontCache;
FontCache = NULL;
csGraphics2D::Close ();
}
bool csGraphics2DGLCommon::BeginDraw ()
{
if (!csGraphics2D::BeginDraw ())
return false;
if (FrameBufferLocked != 1)
return true;
glMatrixMode (GL_PROJECTION);
glLoadIdentity ();
glOrtho (0, Width, 0, Height, -1.0, 10.0);
glViewport (0, 0, Width, Height);
glMatrixMode (GL_MODELVIEW);
glLoadIdentity ();
glColor3f (1., 0., 0.);
glClearColor (0., 0., 0., 0.);
return true;
}
void csGraphics2DGLCommon::SetClipRect (int xmin, int ymin, int xmax, int ymax)
{
csGraphics2D::SetClipRect (xmin, ymin, xmax, ymax);
if (FontCache)
FontCache->SetClipRect (xmin, Height - ymax, xmax, Height - ymin);
}
void csGraphics2DGLCommon::DecomposeColor (int iColor,
GLubyte &oR, GLubyte &oG, GLubyte &oB)
{
switch (pfmt.PixelBytes)
{
case 1: // paletted colors
oR = Palette [iColor].red;
oG = Palette [iColor].green;
oB = Palette [iColor].blue;
break;
case 2: // 16bit color
case 4: // truecolor
oR = ((iColor & pfmt.RedMask ) >> pfmt.RedShift );
oG = ((iColor & pfmt.GreenMask) >> pfmt.GreenShift);
oB = ((iColor & pfmt.BlueMask ) >> pfmt.BlueShift );
break;
}
}
void csGraphics2DGLCommon::DecomposeColor (int iColor,
float &oR, float &oG, float &oB)
{
GLubyte r, g, b;
DecomposeColor (iColor, r, g, b);
oR = r / 255.0;
oG = g / 255.0;
oB = b / 255.0;
}
void csGraphics2DGLCommon::setGLColorfromint (int color)
{
GLubyte r, g, b;
DecomposeColor (color, r, g, b);
glColor3ub (r, g, b);
}
void csGraphics2DGLCommon::Clear (int color)
{
float r, g, b;
DecomposeColor (color, r, g, b);
glClearColor (r, g, b, 0.0);
glClear (GL_COLOR_BUFFER_BIT);
}
void csGraphics2DGLCommon::SetRGB (int i, int r, int g, int b)
{
csGraphics2D::SetRGB (i, r, g, b);
}
void csGraphics2DGLCommon::DrawLine (
float x1, float y1, float x2, float y2, int color)
{
if (!ClipLine (x1, y1, x2, y2, ClipX1, ClipY1, ClipX2, ClipY2))
{
// prepare for 2D drawing--so we need no fancy GL effects!
glDisable (GL_TEXTURE_2D);
glDisable (GL_ALPHA_TEST);
setGLColorfromint (color);
// This is a workaround for a hard-to-really fix problem with OpenGL:
// whole Y coordinates are "rounded" up, this leads to one-pixel-shift
// compared to software line drawing. This is not exactly a bug (because
// this is an on-the-edge case) but it's different, thus we'll slightly
// shift whole coordinates down.
if (QInt (y1) == y1) { y1 += 0.05; }
if (QInt (y2) == y2) { y2 += 0.05; }
glBegin (GL_LINES);
glVertex2f (x1, Height - y1);
glVertex2f (x2, Height - y2);
glEnd ();
}
}
void csGraphics2DGLCommon::DrawBox (int x, int y, int w, int h, int color)
{
if ((x > ClipX2) || (y > ClipY2))
return;
if (x < ClipX1)
w -= (ClipX1 - x), x = ClipX1;
if (y < ClipY1)
h -= (ClipY1 - y), y = ClipY1;
if (x + w > ClipX2)
w = ClipX2 - x;
if (y + h > ClipY2)
h = ClipY2 - y;
if ((w <= 0) || (h <= 0))
return;
y = Height - y;
// prepare for 2D drawing--so we need no fancy GL effects!
glDisable (GL_TEXTURE_2D);
setGLColorfromint (color);
glBegin (GL_QUADS);
glVertex2i (x, y);
glVertex2i (x + w, y);
glVertex2i (x + w, y - h);
glVertex2i (x, y - h);
glEnd ();
}
void csGraphics2DGLCommon::DrawPixel (int x, int y, int color)
{
if ((x >= ClipX1) && (y < ClipX2) && (y >= ClipY1) && (y < ClipY2))
{
// prepare for 2D drawing--so we need no fancy GL effects!
glDisable (GL_TEXTURE_2D);
setGLColorfromint(color);
glBegin (GL_POINTS);
glVertex2i (x, Height - y);
glEnd ();
}
}
void csGraphics2DGLCommon::Write (iFont *font, int x, int y, int fg, int bg,
const char *text)
{
glDisable (GL_TEXTURE_2D);
if (bg >= 0)
{
int fw, fh;
font->GetDimensions (text, fw, fh);
DrawBox (x, y, fw, fh, bg);
}
setGLColorfromint (fg);
FontCache->Write (font, x, Height - y, text);
}
// This variable is usually NULL except when doing a screen shot:
// in this case it is a temporarily allocated buffer for glReadPixels ()
static UByte *screen_shot = NULL;
unsigned char* csGraphics2DGLCommon::GetPixelAt (int x, int y)
{
return screen_shot ?
(screen_shot + pfmt.PixelBytes * ((Height - y) * Width + x)) : NULL;
}
csImageArea *csGraphics2DGLCommon::SaveArea (int x, int y, int w, int h)
{
// For the time being copy data into system memory.
#ifndef GL_VERSION_1_2
if (pfmt.PixelBytes != 1 && pfmt.PixelBytes != 4)
return NULL;
#endif
// Convert to Opengl co-ordinate system
y = Height - (y + h);
if (x < 0)
{ w += x; x = 0; }
if (x + w > Width)
w = Width - x;
if (y < 0)
{ h += y; y = 0; }
if (y + h > Height)
h = Height - y;
if ((w <= 0) || (h <= 0))
return NULL;
csImageArea *Area = new csImageArea (x, y, w, h);
if (!Area)
return NULL;
int actual_width = pfmt.PixelBytes * w;
GLubyte* dest = new GLubyte [actual_width * h];
Area->data = (char *)dest;
if (!dest)
{
delete Area;
return NULL;
}
glDisable (GL_TEXTURE_2D);
//glDisable (GL_DITHER);
glDisable (GL_ALPHA_TEST);
GLenum format, type;
switch (pfmt.PixelBytes)
{
case 1:
format = GL_COLOR_INDEX;
type = GL_UNSIGNED_BYTE;
break;
#ifdef GL_VERSION_1_2
case 2:
format = GL_RGB;
type = GL_UNSIGNED_SHORT_5_6_5;
break;
#endif
case 4:
format = GL_RGBA;
type = GL_UNSIGNED_BYTE;
break;
default:
delete Area;
return NULL; // invalid format
}
glReadPixels (x, y, w, h, format, type, dest);
return Area;
}
void csGraphics2DGLCommon::RestoreArea (csImageArea *Area, bool Free)
{
glDisable (GL_TEXTURE_2D);
//glDisable (GL_DITHER);
glDisable (GL_ALPHA_TEST);
if (Area)
{
GLenum format, type;
switch (pfmt.PixelBytes)
{
case 1:
format = GL_COLOR_INDEX;
type = GL_UNSIGNED_BYTE;
break;
#ifdef GL_VERSION_1_2
case 2:
format = GL_RGB;
type = GL_UNSIGNED_SHORT_5_6_5;
break;
#endif
case 4:
format = GL_RGBA;
type = GL_UNSIGNED_BYTE;
break;
default:
return; // invalid format
}
glRasterPos2i (Area->x, Area->y);
glDrawPixels (Area->w, Area->h, format, type, Area->data);
glFlush ();
if (Free)
FreeArea (Area);
} /* endif */
}
iImage *csGraphics2DGLCommon::ScreenShot ()
{
#ifndef GL_VERSION_1_2
if (pfmt.PixelBytes != 1 && pfmt.PixelBytes != 4)
return NULL;
#endif
// Need to resolve pixel alignment issues
int screen_width = Width * pfmt.PixelBytes;
screen_shot = new UByte [screen_width * Height];
if (!screen_shot) return NULL;
// glPixelStore ()?
switch (pfmt.PixelBytes)
{
case 1:
glReadPixels (0, 0, Width, Height, GL_COLOR_INDEX,
GL_UNSIGNED_BYTE, screen_shot);
break;
#ifdef GL_VERSION_1_2
case 2:
// experimental
glReadPixels (0, 0, Width, Height, GL_RGB,
GL_UNSIGNED_SHORT_5_6_5, screen_shot);
break;
#endif
default:
glReadPixels (0, 0, Width, Height, GL_RGBA,
GL_UNSIGNED_BYTE, screen_shot);
break;
}
#if defined (CS_BIG_ENDIAN)
// On big endian and 32-bit displays we swap the RGBA
// colors.
if (pfmt.PixelBytes == 4)
{
ulong* s = (ulong*)screen_shot;
int i;
for (i = 0 ; i < Width*Height ; i++)
{
*s = convert_endian (*s);
s++;
}
}
#endif
csScreenShot *ss = new csScreenShot (this);
delete [] screen_shot;
screen_shot = NULL;
return ss;
}
bool csGraphics2DGLCommon::PerformExtensionV (char const* command, va_list)
{
if (!strcasecmp (command, "flush"))
{
glFlush ();
glFinish ();
return true;
}
return false;
}
bool csGraphics2DGLCommon::Resize (int width, int height)
{
if (!is_open)
{
Width = width;
Height = height;
SetClipRect (0, 0, Width - 1, Height - 1);
return true;
}
if (!AllowResizing)
return false;
Width = width;
Height = height;
SetClipRect (0, 0, Width - 1, Height - 1);
EventOutlet->Broadcast (cscmdContextResize, (iGraphics2D *)this);
return true;
}
<commit_msg>hopefully fixed the text problem in opengl 16 bit modes :)<commit_after>/*
Copyright (C) 1998-2001 by Jorrit Tyberghein
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Library General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Library General Public License for more details.
You should have received a copy of the GNU Library General Public
License along with this library; if not, write to the Free
Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
#include "cssysdef.h"
#include "glcommon2d.h"
#include "cssys/sysdriv.h"
#include "cssys/csendian.h"
#include "video/canvas/common/scrshot.h"
#include "csgeom/csrect.h"
#include "isys/system.h"
#include "iutil/objreg.h"
#include "ivaria/reporter.h"
#include "qint.h"
SCF_IMPLEMENT_IBASE_EXT (csGraphics2DGLCommon)
SCF_IMPLEMENTS_INTERFACE (iEventPlug)
SCF_IMPLEMENT_IBASE_EXT_END
csGraphics2DGLCommon::csGraphics2DGLCommon (iBase *iParent) :
csGraphics2D (iParent), FontCache (NULL)
{
EventOutlet = NULL;
}
bool csGraphics2DGLCommon::Initialize (iObjectRegistry *object_reg)
{
if (!csGraphics2D::Initialize (object_reg))
return false;
// We don't really care about pixel format, except for ScreenShot ()
# if defined (CS_BIG_ENDIAN)
pfmt.RedMask = 0xff000000;
pfmt.GreenMask = 0x00ff0000;
pfmt.BlueMask = 0x0000ff00;
# else
pfmt.RedMask = 0x000000ff;
pfmt.GreenMask = 0x0000ff00;
pfmt.BlueMask = 0x00ff0000;
# endif
pfmt.PixelBytes = 4;
pfmt.PalEntries = 0;
pfmt.complete ();
return true;
}
csGraphics2DGLCommon::~csGraphics2DGLCommon ()
{
Close ();
if (EventOutlet)
EventOutlet->DecRef ();
}
bool csGraphics2DGLCommon::Open ()
{
if (is_open) return true;
// initialize font cache object
if (!FontCache)
FontCache = new GLFontCache (FontServer);
if (!csGraphics2D::Open ())
return false;
const char *renderer = (const char *)glGetString (GL_RENDERER);
const char *version = (const char *)glGetString (GL_VERSION);
iReporter* reporter = CS_QUERY_REGISTRY (object_reg, iReporter);
if (renderer || version)
if (reporter)
reporter->Report (CS_REPORTER_SEVERITY_NOTIFY,
"crystalspace.canvas.openglcommon",
"OpenGL renderer: %s version %s",
renderer ? renderer : "unknown", version ? version : "unknown");
if (reporter)
reporter->Report (CS_REPORTER_SEVERITY_NOTIFY,
"crystalspace.canvas.openglcommon",
"Using %s mode at resolution %dx%d.",
FullScreen ? "full screen" : "windowed", Width, Height);
glClearColor (0., 0., 0., 0.);
glClearDepth (-1.0);
glMatrixMode (GL_MODELVIEW);
glLoadIdentity ();
glViewport (0, 0, Width, Height);
Clear (0);
return true;
}
void csGraphics2DGLCommon::Close ()
{
if (!is_open) return;
delete FontCache;
FontCache = NULL;
csGraphics2D::Close ();
}
bool csGraphics2DGLCommon::BeginDraw ()
{
if (!csGraphics2D::BeginDraw ())
return false;
if (FrameBufferLocked != 1)
return true;
glMatrixMode (GL_PROJECTION);
glLoadIdentity ();
glOrtho (0, Width, 0, Height, -1.0, 10.0);
glViewport (0, 0, Width, Height);
glMatrixMode (GL_MODELVIEW);
glLoadIdentity ();
glColor3f (1., 0., 0.);
glClearColor (0., 0., 0., 0.);
return true;
}
void csGraphics2DGLCommon::SetClipRect (int xmin, int ymin, int xmax, int ymax)
{
csGraphics2D::SetClipRect (xmin, ymin, xmax, ymax);
if (FontCache)
FontCache->SetClipRect (xmin, Height - ymax, xmax, Height - ymin);
}
void csGraphics2DGLCommon::DecomposeColor (int iColor,
GLubyte &oR, GLubyte &oG, GLubyte &oB)
{
switch (pfmt.PixelBytes)
{
case 1: // paletted colors
oR = Palette [iColor].red;
oG = Palette [iColor].green;
oB = Palette [iColor].blue;
break;
case 2: // 16bit color
case 4: // truecolor
oR = ((iColor & pfmt.RedMask ) >> pfmt.RedShift );
oG = ((iColor & pfmt.GreenMask) >> pfmt.GreenShift);
oB = ((iColor & pfmt.BlueMask ) >> pfmt.BlueShift );
oR = oR << (8-pfmt.RedBits);
oG = oG << (8-pfmt.GreenBits);
oB = oB << (8-pfmt.BlueBits);
break;
}
}
void csGraphics2DGLCommon::DecomposeColor (int iColor,
float &oR, float &oG, float &oB)
{
GLubyte r, g, b;
DecomposeColor (iColor, r, g, b);
oR = r / 255.0;
oG = g / 255.0;
oB = b / 255.0;
}
void csGraphics2DGLCommon::setGLColorfromint (int color)
{
GLubyte r, g, b;
DecomposeColor (color, r, g, b);
glColor3ub (r, g, b);
}
void csGraphics2DGLCommon::Clear (int color)
{
float r, g, b;
DecomposeColor (color, r, g, b);
glClearColor (r, g, b, 0.0);
glClear (GL_COLOR_BUFFER_BIT);
}
void csGraphics2DGLCommon::SetRGB (int i, int r, int g, int b)
{
csGraphics2D::SetRGB (i, r, g, b);
}
void csGraphics2DGLCommon::DrawLine (
float x1, float y1, float x2, float y2, int color)
{
if (!ClipLine (x1, y1, x2, y2, ClipX1, ClipY1, ClipX2, ClipY2))
{
// prepare for 2D drawing--so we need no fancy GL effects!
glDisable (GL_TEXTURE_2D);
glDisable (GL_ALPHA_TEST);
setGLColorfromint (color);
// This is a workaround for a hard-to-really fix problem with OpenGL:
// whole Y coordinates are "rounded" up, this leads to one-pixel-shift
// compared to software line drawing. This is not exactly a bug (because
// this is an on-the-edge case) but it's different, thus we'll slightly
// shift whole coordinates down.
if (QInt (y1) == y1) { y1 += 0.05; }
if (QInt (y2) == y2) { y2 += 0.05; }
glBegin (GL_LINES);
glVertex2f (x1, Height - y1);
glVertex2f (x2, Height - y2);
glEnd ();
}
}
void csGraphics2DGLCommon::DrawBox (int x, int y, int w, int h, int color)
{
if ((x > ClipX2) || (y > ClipY2))
return;
if (x < ClipX1)
w -= (ClipX1 - x), x = ClipX1;
if (y < ClipY1)
h -= (ClipY1 - y), y = ClipY1;
if (x + w > ClipX2)
w = ClipX2 - x;
if (y + h > ClipY2)
h = ClipY2 - y;
if ((w <= 0) || (h <= 0))
return;
y = Height - y;
// prepare for 2D drawing--so we need no fancy GL effects!
glDisable (GL_TEXTURE_2D);
setGLColorfromint (color);
glBegin (GL_QUADS);
glVertex2i (x, y);
glVertex2i (x + w, y);
glVertex2i (x + w, y - h);
glVertex2i (x, y - h);
glEnd ();
}
void csGraphics2DGLCommon::DrawPixel (int x, int y, int color)
{
if ((x >= ClipX1) && (y < ClipX2) && (y >= ClipY1) && (y < ClipY2))
{
// prepare for 2D drawing--so we need no fancy GL effects!
glDisable (GL_TEXTURE_2D);
setGLColorfromint(color);
glBegin (GL_POINTS);
glVertex2i (x, Height - y);
glEnd ();
}
}
void csGraphics2DGLCommon::Write (iFont *font, int x, int y, int fg, int bg,
const char *text)
{
glDisable (GL_TEXTURE_2D);
if (bg >= 0)
{
int fw, fh;
font->GetDimensions (text, fw, fh);
DrawBox (x, y, fw, fh, bg);
}
setGLColorfromint (fg);
FontCache->Write (font, x, Height - y, text);
}
// This variable is usually NULL except when doing a screen shot:
// in this case it is a temporarily allocated buffer for glReadPixels ()
static UByte *screen_shot = NULL;
unsigned char* csGraphics2DGLCommon::GetPixelAt (int x, int y)
{
return screen_shot ?
(screen_shot + pfmt.PixelBytes * ((Height - y) * Width + x)) : NULL;
}
csImageArea *csGraphics2DGLCommon::SaveArea (int x, int y, int w, int h)
{
// For the time being copy data into system memory.
#ifndef GL_VERSION_1_2
if (pfmt.PixelBytes != 1 && pfmt.PixelBytes != 4)
return NULL;
#endif
// Convert to Opengl co-ordinate system
y = Height - (y + h);
if (x < 0)
{ w += x; x = 0; }
if (x + w > Width)
w = Width - x;
if (y < 0)
{ h += y; y = 0; }
if (y + h > Height)
h = Height - y;
if ((w <= 0) || (h <= 0))
return NULL;
csImageArea *Area = new csImageArea (x, y, w, h);
if (!Area)
return NULL;
int actual_width = pfmt.PixelBytes * w;
GLubyte* dest = new GLubyte [actual_width * h];
Area->data = (char *)dest;
if (!dest)
{
delete Area;
return NULL;
}
glDisable (GL_TEXTURE_2D);
//glDisable (GL_DITHER);
glDisable (GL_ALPHA_TEST);
GLenum format, type;
switch (pfmt.PixelBytes)
{
case 1:
format = GL_COLOR_INDEX;
type = GL_UNSIGNED_BYTE;
break;
#ifdef GL_VERSION_1_2
case 2:
format = GL_RGB;
type = GL_UNSIGNED_SHORT_5_6_5;
break;
#endif
case 4:
format = GL_RGBA;
type = GL_UNSIGNED_BYTE;
break;
default:
delete Area;
return NULL; // invalid format
}
glReadPixels (x, y, w, h, format, type, dest);
return Area;
}
void csGraphics2DGLCommon::RestoreArea (csImageArea *Area, bool Free)
{
glDisable (GL_TEXTURE_2D);
//glDisable (GL_DITHER);
glDisable (GL_ALPHA_TEST);
if (Area)
{
GLenum format, type;
switch (pfmt.PixelBytes)
{
case 1:
format = GL_COLOR_INDEX;
type = GL_UNSIGNED_BYTE;
break;
#ifdef GL_VERSION_1_2
case 2:
format = GL_RGB;
type = GL_UNSIGNED_SHORT_5_6_5;
break;
#endif
case 4:
format = GL_RGBA;
type = GL_UNSIGNED_BYTE;
break;
default:
return; // invalid format
}
glRasterPos2i (Area->x, Area->y);
glDrawPixels (Area->w, Area->h, format, type, Area->data);
glFlush ();
if (Free)
FreeArea (Area);
} /* endif */
}
iImage *csGraphics2DGLCommon::ScreenShot ()
{
#ifndef GL_VERSION_1_2
if (pfmt.PixelBytes != 1 && pfmt.PixelBytes != 4)
return NULL;
#endif
// Need to resolve pixel alignment issues
int screen_width = Width * pfmt.PixelBytes;
screen_shot = new UByte [screen_width * Height];
if (!screen_shot) return NULL;
// glPixelStore ()?
switch (pfmt.PixelBytes)
{
case 1:
glReadPixels (0, 0, Width, Height, GL_COLOR_INDEX,
GL_UNSIGNED_BYTE, screen_shot);
break;
#ifdef GL_VERSION_1_2
case 2:
// experimental
glReadPixels (0, 0, Width, Height, GL_RGB,
GL_UNSIGNED_SHORT_5_6_5, screen_shot);
break;
#endif
default:
glReadPixels (0, 0, Width, Height, GL_RGBA,
GL_UNSIGNED_BYTE, screen_shot);
break;
}
#if defined (CS_BIG_ENDIAN)
// On big endian and 32-bit displays we swap the RGBA
// colors.
if (pfmt.PixelBytes == 4)
{
ulong* s = (ulong*)screen_shot;
int i;
for (i = 0 ; i < Width*Height ; i++)
{
*s = convert_endian (*s);
s++;
}
}
#endif
csScreenShot *ss = new csScreenShot (this);
delete [] screen_shot;
screen_shot = NULL;
return ss;
}
bool csGraphics2DGLCommon::PerformExtensionV (char const* command, va_list)
{
if (!strcasecmp (command, "flush"))
{
glFlush ();
glFinish ();
return true;
}
return false;
}
bool csGraphics2DGLCommon::Resize (int width, int height)
{
if (!is_open)
{
Width = width;
Height = height;
SetClipRect (0, 0, Width - 1, Height - 1);
return true;
}
if (!AllowResizing)
return false;
Width = width;
Height = height;
SetClipRect (0, 0, Width - 1, Height - 1);
EventOutlet->Broadcast (cscmdContextResize, (iGraphics2D *)this);
return true;
}
<|endoftext|>
|
<commit_before>#include "sha3_stream.h"
#include "sha3_factory.h"
#include "sha3_interface.h"
#include "eacirc/streams.h"
#include <algorithm>
template <typename I>
static void
hash_data(sha3_interface& hasher, const I& data, std::uint8_t* hash, const std::size_t hash_size) {
using std::to_string;
int status = hasher.Init(int(8 * hash_size));
if (status != 0)
throw std::runtime_error("cannot initialize hash (code: " + to_string(status) + ")");
status = hasher.Update(&(*data.begin()), 8 * (data.end() - data.begin()));
if (status != 0)
throw std::runtime_error("cannot update the hash (code: " + to_string(status) + ")");
status = hasher.Final(hash);
if (status != 0)
throw std::runtime_error("cannot finalize the hash (code: " + to_string(status) + ")");
}
sha3_stream::sha3_stream(const json& config, std::size_t osize)
: stream(osize)
, _algorithm(config.at("algorithm").get<std::string>())
, _round(config.at("round"))
, _hash_size(std::size_t(config.at("hash-bitsize")))
, _source(make_stream(config.at("source"), _hash_size / 8)) // TODO: hash-input-size?
, _hasher(sha3_factory::create(_algorithm, unsigned(_round)))
, _data(osize) {
if ((std::size_t(config.at("hash-bitsize")) % 8) != 0)
throw std::runtime_error("the SHA-3 hash-bitsize parameter must be multiple of 8");
if ((_hash_size / 8) != osize)
throw std::runtime_error("multiple/parts hashes in one vector are not supported yet");
}
sha3_stream::sha3_stream(sha3_stream&&) = default;
sha3_stream::~sha3_stream() = default;
vec_view sha3_stream::next() {
vec_view view = _source->next();
hash_data(*_hasher, view, _data.data(), _hash_size); // TODO: solve hash_size != osize
return make_cview(_data);
}
<commit_msg>SHA3 working as well<commit_after>#include "sha3_stream.h"
#include "eacirc/streams.h"
#include "sha3_factory.h"
#include "sha3_interface.h"
#include <algorithm>
template <typename I>
static void
hash_data(sha3_interface& hasher, const I& data, std::uint8_t* hash, const std::size_t hash_size) {
using std::to_string;
int status = hasher.Init(int(hash_size));
if (status != 0)
throw std::runtime_error("cannot initialize hash (code: " + to_string(status) + ")");
status = hasher.Update(&(*data.begin()), 8 * (data.end() - data.begin()));
if (status != 0)
throw std::runtime_error("cannot update the hash (code: " + to_string(status) + ")");
status = hasher.Final(hash);
if (status != 0)
throw std::runtime_error("cannot finalize the hash (code: " + to_string(status) + ")");
}
sha3_stream::sha3_stream(const json& config, std::size_t osize)
: stream(osize)
, _algorithm(config.at("algorithm").get<std::string>())
, _round(config.at("round"))
, _hash_size(std::size_t(config.at("hash-bitsize")))
, _source(make_stream(config.at("source"), _hash_size / 8)) // TODO: hash-input-size?
, _hasher(sha3_factory::create(_algorithm, unsigned(_round)))
, _data(((_hash_size / 8) % osize) ? ((osize / (_hash_size / 8)) + 1) * (_hash_size / 8)
: osize) { // round osize to multiple of _hash_size
if ((std::size_t(config.at("hash-bitsize")) % 8) != 0)
throw std::runtime_error("the SHA-3 hash-bitsize parameter must be multiple of 8");
if ((_hash_size / 8) != osize)
throw std::runtime_error("multiple/parts hashes in one vector are not supported yet");
}
sha3_stream::sha3_stream(sha3_stream&&) = default;
sha3_stream::~sha3_stream() = default;
vec_view sha3_stream::next() {
for (auto beg = _data.begin(); beg != _data.end(); beg += (_hash_size / 8)) {
vec_view view = _source->next();
hash_data(*_hasher, view, &(*beg), _hash_size);
}
return make_view(_data.cbegin(), osize());
}
<|endoftext|>
|
<commit_before>/*
* yosys -- Yosys Open SYnthesis Suite
*
* Copyright (C) 2016 Clifford Wolf <clifford@clifford.at>
*
* 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 "kernel/yosys.h"
#include "kernel/sigtools.h"
#include "kernel/modtools.h"
USING_YOSYS_NAMESPACE
PRIVATE_NAMESPACE_BEGIN
//get the list of cells hooked up to at least one bit of a given net
pool<Cell*> get_other_cells(const RTLIL::SigSpec& port, ModIndex& index, Cell* src)
{
pool<Cell*> rval;
for(auto b : port)
{
pool<ModIndex::PortInfo> ports = index.query_ports(b);
for(auto x : ports)
{
if(x.cell == src)
continue;
rval.insert(x.cell);
}
}
return rval;
}
//return true if there is a full-width bus connection from cell a port ap to cell b port bp
//if other_conns_allowed is false, then we require a strict point to point connection (no other links)
bool is_full_bus(
const RTLIL::SigSpec& sig,
ModIndex& index,
Cell* a,
RTLIL::IdString ap,
Cell* b,
RTLIL::IdString bp,
bool other_conns_allowed = false)
{
for(auto s : sig)
{
pool<ModIndex::PortInfo> ports = index.query_ports(s);
bool found_a = false;
bool found_b = false;
for(auto x : ports)
{
if( (x.cell == a) && (x.port == ap) )
found_a = true;
else if( (x.cell == b) && (x.port == bp) )
found_b = true;
else if(!other_conns_allowed)
return false;
}
if( (!found_a) || (!found_b) )
return false;
}
return true;
}
//return true if the signal connects to one port only (nothing on the other end)
bool is_unconnected(const RTLIL::SigSpec& port, ModIndex& index)
{
for(auto b : port)
{
pool<ModIndex::PortInfo> ports = index.query_ports(b);
if(ports.size() > 1)
return false;
}
return true;
}
void greenpak4_counters_worker(ModIndex& index, Module *module, Cell *cell, unsigned int& total_counters)
{
SigMap& sigmap = index.sigmap;
//Core of the counter must be an ALU
if (cell->type != "$alu")
return;
//GreenPak does not support counters larger than 14 bits so immediately skip anything bigger
int a_width = cell->getParam("\\A_WIDTH").as_int();
if(a_width > 14)
return;
//Second input must be a single bit
int b_width = cell->getParam("\\B_WIDTH").as_int();
if(b_width != 1)
return;
//Both inputs must be unsigned, so don't extract anything with a signed input
bool a_sign = cell->getParam("\\A_SIGNED").as_bool();
bool b_sign = cell->getParam("\\B_SIGNED").as_bool();
if(a_sign || b_sign)
return;
//To be a counter, one input of the ALU must be a constant 1
//TODO: can A or B be swapped in synthesized RTL or is B always the 1?
const RTLIL::SigSpec b_port = sigmap(cell->getPort("\\B"));
if(!b_port.is_fully_const() || (b_port.as_int() != 1) )
return;
//BI and CI must be constant 1 as well
const RTLIL::SigSpec bi_port = sigmap(cell->getPort("\\BI"));
if(!bi_port.is_fully_const() || (bi_port.as_int() != 1) )
return;
const RTLIL::SigSpec ci_port = sigmap(cell->getPort("\\CI"));
if(!ci_port.is_fully_const() || (ci_port.as_int() != 1) )
return;
//CO and X must be unconnected (exactly one connection to each port)
if(!is_unconnected(sigmap(cell->getPort("\\CO")), index))
return;
if(!is_unconnected(sigmap(cell->getPort("\\X")), index))
return;
//Y must have exactly one connection, and it has to be a $mux cell.
//We must have a direct bus connection from our Y to their A.
const RTLIL::SigSpec aluy = sigmap(cell->getPort("\\Y"));
pool<Cell*> y_loads = get_other_cells(aluy, index, cell);
if(y_loads.size() != 1)
return;
Cell* count_mux = *y_loads.begin();
if(count_mux->type != "$mux")
return;
if(!is_full_bus(aluy, index, cell, "\\Y", count_mux, "\\A"))
return;
//B connection of the mux is our underflow value
const RTLIL::SigSpec underflow = sigmap(count_mux->getPort("\\B"));
if(!underflow.is_fully_const())
return;
int count_value = underflow.as_int();
//S connection of the mux must come from an inverter (need not be the only load)
const RTLIL::SigSpec muxsel = sigmap(count_mux->getPort("\\S"));
pool<Cell*> muxsel_conns = get_other_cells(muxsel, index, count_mux);
Cell* underflow_inv = NULL;
for(auto c : muxsel_conns)
{
if(c->type != "$logic_not")
continue;
if(!is_full_bus(muxsel, index, c, "\\Y", count_mux, "\\S", true))
continue;
underflow_inv = c;
break;
}
if(underflow_inv == NULL)
return;
//Y connection of the mux must have exactly one load, the counter's internal register
const RTLIL::SigSpec muxy = sigmap(count_mux->getPort("\\Y"));
pool<Cell*> muxy_loads = get_other_cells(muxy, index, count_mux);
if(muxy_loads.size() != 1)
return;
Cell* count_reg = *muxy_loads.begin();
if(count_reg->type != "$dff") //TODO: support dffr/dffs?
return;
if(!is_full_bus(muxy, index, count_mux, "\\Y", count_reg, "\\D"))
return;
//Register output must have exactly two loads, the inverter and ALU
const RTLIL::SigSpec cnout = sigmap(count_reg->getPort("\\Q"));
pool<Cell*> cnout_loads = get_other_cells(cnout, index, count_reg);
if(cnout_loads.size() != 2)
return;
if(!is_full_bus(cnout, index, count_reg, "\\Q", underflow_inv, "\\A", true))
return;
if(!is_full_bus(cnout, index, count_reg, "\\Q", cell, "\\A", true))
return;
//Look up the clock from the register
const RTLIL::SigSpec clk = sigmap(count_reg->getPort("\\CLK"));
//Register output net must have an INIT attribute equal to the count value
auto rwire = cnout.as_wire();
if(rwire->attributes.find("\\init") == rwire->attributes.end())
return;
int rinit = rwire->attributes["\\init"].as_int();
if(rinit != count_value)
return;
//Figure out the final cell type based on the counter size
string celltype = "\\GP_COUNT8";
if(a_width > 8)
celltype = "\\GP_COUNT14";
//Log it
total_counters ++;
string count_reg_src = rwire->attributes["\\src"].decode_string().c_str();
log(" Found %d-bit non-resettable down counter (from %d) for register %s declared at %s\n",
a_width,
count_value,
log_id(rwire->name),
count_reg_src.c_str());
//Wipe all of the old connections to the ALU
cell->unsetPort("\\A");
cell->unsetPort("\\B");
cell->unsetPort("\\BI");
cell->unsetPort("\\CI");
cell->unsetPort("\\CO");
cell->unsetPort("\\X");
cell->unsetPort("\\Y");
cell->unsetParam("\\A_SIGNED");
cell->unsetParam("\\A_WIDTH");
cell->unsetParam("\\B_SIGNED");
cell->unsetParam("\\B_WIDTH");
cell->unsetParam("\\Y_WIDTH");
//Change the cell type
cell->type = celltype;
//Hook it up to everything
cell->setParam("\\RESET_MODE", RTLIL::Const("RISING"));
cell->setParam("\\CLKIN_DIVIDE", RTLIL::Const(1));
cell->setParam("\\COUNT_TO", RTLIL::Const(count_value));
cell->setPort("\\CLK", clk);
cell->setPort("\\RST", RTLIL::SigSpec(false));
cell->setPort("\\OUT", muxsel);
//Delete the cells we've replaced (let opt_clean handle deleting the now-redundant wires)
module->remove(count_mux);
module->remove(count_reg);
module->remove(underflow_inv);
}
struct Greenpak4CountersPass : public Pass {
Greenpak4CountersPass() : Pass("greenpak4_counters", "Extract GreenPak4 counter cells") { }
virtual void help()
{
// |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|
log("\n");
log(" greenpak4_counters [options] [selection]\n");
log("\n");
log("This pass converts non-resettable down counters to GreenPak4 counter cells\n");
log("(All other GreenPak4 counter modes must be instantiated manually for now.)\n");
log("\n");
}
virtual void execute(std::vector<std::string> args, RTLIL::Design *design)
{
log_header("Executing GREENPAK4_COUNTERS pass (mapping counters to hard IP blocks).\n");
size_t argidx;
for (argidx = 1; argidx < args.size(); argidx++)
{
// if (args[argidx] == "-v") {
// continue;
// }
break;
}
extra_args(args, argidx, design);
unsigned int total_counters = 0;
for (auto module : design->selected_modules())
{
ModIndex index(module);
for (auto cell : module->selected_cells())
greenpak4_counters_worker(index, module, cell, total_counters);
}
if(total_counters)
log("Extracted %u counters\n", total_counters);
}
} Greenpak4CountersPass;
PRIVATE_NAMESPACE_END
<commit_msg>Added support for inferring counters with asynchronous resets. Fixed use-after-free in inference pass.<commit_after>/*
* yosys -- Yosys Open SYnthesis Suite
*
* Copyright (C) 2016 Clifford Wolf <clifford@clifford.at>
*
* 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 "kernel/yosys.h"
#include "kernel/sigtools.h"
#include "kernel/modtools.h"
USING_YOSYS_NAMESPACE
PRIVATE_NAMESPACE_BEGIN
//get the list of cells hooked up to at least one bit of a given net
pool<Cell*> get_other_cells(const RTLIL::SigSpec& port, ModIndex& index, Cell* src)
{
pool<Cell*> rval;
for(auto b : port)
{
pool<ModIndex::PortInfo> ports = index.query_ports(b);
for(auto x : ports)
{
if(x.cell == src)
continue;
rval.insert(x.cell);
}
}
return rval;
}
//return true if there is a full-width bus connection from cell a port ap to cell b port bp
//if other_conns_allowed is false, then we require a strict point to point connection (no other links)
bool is_full_bus(
const RTLIL::SigSpec& sig,
ModIndex& index,
Cell* a,
RTLIL::IdString ap,
Cell* b,
RTLIL::IdString bp,
bool other_conns_allowed = false)
{
for(auto s : sig)
{
pool<ModIndex::PortInfo> ports = index.query_ports(s);
bool found_a = false;
bool found_b = false;
for(auto x : ports)
{
if( (x.cell == a) && (x.port == ap) )
found_a = true;
else if( (x.cell == b) && (x.port == bp) )
found_b = true;
else if(!other_conns_allowed)
return false;
}
if( (!found_a) || (!found_b) )
return false;
}
return true;
}
//return true if the signal connects to one port only (nothing on the other end)
bool is_unconnected(const RTLIL::SigSpec& port, ModIndex& index)
{
for(auto b : port)
{
pool<ModIndex::PortInfo> ports = index.query_ports(b);
if(ports.size() > 1)
return false;
}
return true;
}
struct CounterExtraction
{
int width; //counter width
RTLIL::Wire* rwire; //the register output
bool has_reset; //true if we have a reset
RTLIL::SigSpec rst; //reset pin
int count_value; //value we count from
RTLIL::SigSpec clk; //clock signal
RTLIL::SigSpec outsig; //counter output signal
RTLIL::Cell* count_mux; //counter mux
RTLIL::Cell* count_reg; //counter register
RTLIL::Cell* underflow_inv; //inverter reduction for output-underflow detect
};
//attempt to extract a counter centered on the given cell
int greenpak4_counters_tryextract(ModIndex& index, Cell *cell, CounterExtraction& extract)
{
SigMap& sigmap = index.sigmap;
//GreenPak does not support counters larger than 14 bits so immediately skip anything bigger
int a_width = cell->getParam("\\A_WIDTH").as_int();
extract.width = a_width;
if(a_width > 14)
return 1;
//Second input must be a single bit
int b_width = cell->getParam("\\B_WIDTH").as_int();
if(b_width != 1)
return 2;
//Both inputs must be unsigned, so don't extract anything with a signed input
bool a_sign = cell->getParam("\\A_SIGNED").as_bool();
bool b_sign = cell->getParam("\\B_SIGNED").as_bool();
if(a_sign || b_sign)
return 3;
//To be a counter, one input of the ALU must be a constant 1
//TODO: can A or B be swapped in synthesized RTL or is B always the 1?
const RTLIL::SigSpec b_port = sigmap(cell->getPort("\\B"));
if(!b_port.is_fully_const() || (b_port.as_int() != 1) )
return 4;
//BI and CI must be constant 1 as well
const RTLIL::SigSpec bi_port = sigmap(cell->getPort("\\BI"));
if(!bi_port.is_fully_const() || (bi_port.as_int() != 1) )
return 5;
const RTLIL::SigSpec ci_port = sigmap(cell->getPort("\\CI"));
if(!ci_port.is_fully_const() || (ci_port.as_int() != 1) )
return 6;
//CO and X must be unconnected (exactly one connection to each port)
if(!is_unconnected(sigmap(cell->getPort("\\CO")), index))
return 7;
if(!is_unconnected(sigmap(cell->getPort("\\X")), index))
return 8;
//Y must have exactly one connection, and it has to be a $mux cell.
//We must have a direct bus connection from our Y to their A.
const RTLIL::SigSpec aluy = sigmap(cell->getPort("\\Y"));
pool<Cell*> y_loads = get_other_cells(aluy, index, cell);
if(y_loads.size() != 1)
return 9;
Cell* count_mux = *y_loads.begin();
extract.count_mux = count_mux;
if(count_mux->type != "$mux")
return 10;
if(!is_full_bus(aluy, index, cell, "\\Y", count_mux, "\\A"))
return 11;
//B connection of the mux is our underflow value
const RTLIL::SigSpec underflow = sigmap(count_mux->getPort("\\B"));
if(!underflow.is_fully_const())
return 12;
extract.count_value = underflow.as_int();
//S connection of the mux must come from an inverter (need not be the only load)
const RTLIL::SigSpec muxsel = sigmap(count_mux->getPort("\\S"));
extract.outsig = muxsel;
pool<Cell*> muxsel_conns = get_other_cells(muxsel, index, count_mux);
Cell* underflow_inv = NULL;
for(auto c : muxsel_conns)
{
if(c->type != "$logic_not")
continue;
if(!is_full_bus(muxsel, index, c, "\\Y", count_mux, "\\S", true))
continue;
underflow_inv = c;
break;
}
if(underflow_inv == NULL)
return 13;
extract.underflow_inv = underflow_inv;
//Y connection of the mux must have exactly one load, the counter's internal register
const RTLIL::SigSpec muxy = sigmap(count_mux->getPort("\\Y"));
pool<Cell*> muxy_loads = get_other_cells(muxy, index, count_mux);
if(muxy_loads.size() != 1)
return 14;
Cell* count_reg = *muxy_loads.begin();
extract.count_reg = count_reg;
if(count_reg->type == "$dff")
extract.has_reset = false;
else if(count_reg->type == "$adff")
{
extract.has_reset = true;
//Verify ARST_VALUE is zero and ARST_POLARITY is 1
//TODO: infer an inverter to make it 1 if necessary, so we can support negative level resets?
if(count_reg->getParam("\\ARST_POLARITY").as_int() != 1)
return 22;
if(count_reg->getParam("\\ARST_VALUE").as_int() != 0)
return 23;
//Save the reset
extract.rst = sigmap(count_reg->getPort("\\ARST"));
}
//TODO: support synchronous reset
else
return 15;
if(!is_full_bus(muxy, index, count_mux, "\\Y", count_reg, "\\D"))
return 16;
//TODO: Verify count_reg CLK_POLARITY is 1
//Register output must have exactly two loads, the inverter and ALU
const RTLIL::SigSpec cnout = sigmap(count_reg->getPort("\\Q"));
pool<Cell*> cnout_loads = get_other_cells(cnout, index, count_reg);
if(cnout_loads.size() != 2)
return 17;
if(!is_full_bus(cnout, index, count_reg, "\\Q", underflow_inv, "\\A", true))
return 18;
if(!is_full_bus(cnout, index, count_reg, "\\Q", cell, "\\A", true))
return 19;
//Look up the clock from the register
extract.clk = sigmap(count_reg->getPort("\\CLK"));
//Register output net must have an INIT attribute equal to the count value
extract.rwire = cnout.as_wire();
if(extract.rwire->attributes.find("\\init") == extract.rwire->attributes.end())
return 20;
int rinit = extract.rwire->attributes["\\init"].as_int();
if(rinit != extract.count_value)
return 21;
return 0;
}
void greenpak4_counters_worker(
ModIndex& index,
Cell *cell,
unsigned int& total_counters,
pool<Cell*>& cells_to_remove)
{
SigMap& sigmap = index.sigmap;
//Core of the counter must be an ALU
if (cell->type != "$alu")
return;
//A input is the count value. Check if it has COUNT_EXTRACT set
RTLIL::Wire* a_wire = sigmap(cell->getPort("\\A")).as_wire();
bool force_extract = false;
bool never_extract = false;
string count_reg_src = a_wire->attributes["\\src"].decode_string().c_str();
if(a_wire->attributes.find("\\COUNT_EXTRACT") != a_wire->attributes.end())
{
pool<string> sa = a_wire->get_strpool_attribute("\\COUNT_EXTRACT");
string extract_value;
if(sa.size() >= 1)
{
extract_value = *sa.begin();
log(" Signal %s declared at %s has COUNT_EXTRACT = %s\n",
log_id(a_wire),
count_reg_src.c_str(),
extract_value.c_str());
if(extract_value == "FORCE")
force_extract = true;
else if(extract_value == "NO")
never_extract = true;
else if(extract_value == "AUTO")
{} //default
else
log_error(" Illegal COUNT_EXTRACT value %s (must be one of FORCE, NO, AUTO)\n",
extract_value.c_str());
}
}
//If we're explicitly told not to extract, don't infer a counter
if(never_extract)
return;
//Attempt to extract a counter
CounterExtraction extract;
int reason = greenpak4_counters_tryextract(index, cell, extract);
//Nonzero code - we could not find a matchable counter.
//Do nothing, unless extraction was forced in which case give an error
if(reason != 0)
{
static const char* reasons[24]=
{
"no problem", //0
"counter is larger than 14 bits", //1
"counter does not count by one", //2
"counter uses signed math", //3
"counter does not count by one", //4
"ALU is not a subtractor", //5
"ALU is not a subtractor", //6
"ALU ports used outside counter", //7
"ALU ports used outside counter", //8
"ALU output used outside counter", //9
"ALU output is not a mux", //10
"ALU output is not full bus", //11
"Underflow value is not constant", //12
"No underflow detector found", //13
"Mux output is used outside counter", //14
"Counter reg is not DFF/ADFF", //15
"Counter input is not full bus", //16
"Count register is used outside counter", //17
"Register output is not full bus", //18
"Register output is not full bus", //19
"No init value found", //20
"Underflow value is not equal to init value", //21
"Reset polarity is not positive", //22
"Reset is not to zero" //23
};
if(force_extract)
{
log_error(
"Counter extraction is set to FORCE on register %s, but a counter could not be inferred (%s)\n",
log_id(a_wire),
reasons[reason]);
}
return;
}
//Figure out the final cell type based on the counter size
string celltype = "\\GP_COUNT8";
if(extract.width > 8)
celltype = "\\GP_COUNT14";
//Log it
total_counters ++;
string reset_type = "non-resettable";
if(extract.has_reset)
{
//TODO: support other kind of reset
reset_type = "async resettable";
}
log(" Found %d-bit %s down counter (from %d) for register %s declared at %s\n",
extract.width,
reset_type.c_str(),
extract.count_value,
log_id(extract.rwire->name),
count_reg_src.c_str());
log("blah");
//Wipe all of the old connections to the ALU
cell->unsetPort("\\A");
cell->unsetPort("\\B");
cell->unsetPort("\\BI");
cell->unsetPort("\\CI");
cell->unsetPort("\\CO");
cell->unsetPort("\\X");
cell->unsetPort("\\Y");
cell->unsetParam("\\A_SIGNED");
cell->unsetParam("\\A_WIDTH");
cell->unsetParam("\\B_SIGNED");
cell->unsetParam("\\B_WIDTH");
cell->unsetParam("\\Y_WIDTH");
log("asdf");
//Change the cell type
cell->type = celltype;
//Hook up resets
if(extract.has_reset)
{
log("hello");
//TODO: support other kinds of reset
cell->setParam("\\RESET_MODE", RTLIL::Const("LEVEL"));
cell->setPort("\\RST", extract.rst);
}
else
{
cell->setParam("\\RESET_MODE", RTLIL::Const("RISING"));
cell->setPort("\\RST", RTLIL::SigSpec(false));
}
log("world");
//Hook up other stuff
cell->setParam("\\CLKIN_DIVIDE", RTLIL::Const(1));
cell->setParam("\\COUNT_TO", RTLIL::Const(extract.count_value));
cell->setPort("\\CLK", extract.clk);
cell->setPort("\\OUT", extract.outsig);
//Delete the cells we've replaced (let opt_clean handle deleting the now-redundant wires)
cells_to_remove.insert(extract.count_mux);
cells_to_remove.insert(extract.count_reg);
cells_to_remove.insert(extract.underflow_inv);
}
struct Greenpak4CountersPass : public Pass {
Greenpak4CountersPass() : Pass("greenpak4_counters", "Extract GreenPak4 counter cells") { }
virtual void help()
{
// |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|
log("\n");
log(" greenpak4_counters [options] [selection]\n");
log("\n");
log("This pass converts non-resettable or async resettable down counters to GreenPak4\n");
log("counter cells (All other GreenPak4 counter modes must be instantiated manually.)\n");
log("\n");
}
virtual void execute(std::vector<std::string> args, RTLIL::Design *design)
{
log_header("Executing GREENPAK4_COUNTERS pass (mapping counters to hard IP blocks).\n");
size_t argidx;
for (argidx = 1; argidx < args.size(); argidx++)
{
// if (args[argidx] == "-v") {
// continue;
// }
break;
}
extra_args(args, argidx, design);
//Extract all of the counters we could find
unsigned int total_counters = 0;
for (auto module : design->selected_modules())
{
pool<Cell*> cells_to_remove;
ModIndex index(module);
for (auto cell : module->selected_cells())
greenpak4_counters_worker(index, cell, total_counters, cells_to_remove);
for(auto cell : cells_to_remove)
module->remove(cell);
}
if(total_counters)
log("Extracted %u counters\n", total_counters);
}
} Greenpak4CountersPass;
PRIVATE_NAMESPACE_END
<|endoftext|>
|
<commit_before>/** \copyright
* Copyright (c) 2013, Balazs Racz
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* - Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* - Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
* \file main.cxx
*
* An application which acts as an openlcb hub with the GC protocol.
*
* @author Balazs Racz
* @date 3 Aug 2013
*/
#include <emscripten.h>
#include <emscripten/bind.h>
#include <emscripten/val.h>
#include <memory>
#include "os/os.h"
#include "utils/constants.hxx"
#include "utils/Hub.hxx"
#include "utils/GridConnectHub.hxx"
#include "utils/GcTcpHub.hxx"
#include "utils/JSTcpHub.hxx"
#include "utils/JSTcpClient.hxx"
#include "utils/JSSerialPort.hxx"
#include "executor/Executor.hxx"
#include "executor/Service.hxx"
Executor<1> g_executor{NO_THREAD()};
Service g_service(&g_executor);
CanHubFlow can_hub0(&g_service);
GcPacketPrinter packet_printer(&can_hub0, false);
OVERRIDE_CONST(gc_generate_newlines, 1);
int port = 12021;
std::vector<string> device_paths;
const char *static_dir = "";
int upstream_port = 12021;
const char *upstream_host = nullptr;
int ws_port = -1;
void usage(const char *e)
{
fprintf(stderr,
"Usage: %s [-p port] [-d device_path] [-w websocket_port [-l path_to_web]] [-u upstream_host [-q upstream_port]]\n\n", e);
fprintf(stderr, "GridConnect CAN HUB.\nListens to a specific TCP port, "
"reads CAN packets from the incoming connections using "
"the GridConnect protocol, and forwards all incoming "
"packets to all other participants.\n\nArguments:\n");
fprintf(stderr, "\t-p port specifies the port number to listen on, "
"default is 12021.\n");
fprintf(stderr, "\t-d device is a path to a physical device doing "
"serial-CAN or USB-CAN. If specified, opens device and "
"adds it to the hub.\n");
fprintf(stderr, "\t-D lists available serial ports.\n");
fprintf(stderr, "\t-w websocket_port Opens a webserver on this port "
"and serves up a websocket connection to the same "
"CAN-bus.\n");
fprintf(stderr, "\t-l path_to_web Exports the contents of this directory thorugh the websocket's webserver.\n");
fprintf(stderr, "\t-u upstream_host is the host name for an upstream "
"hub. If specified, this hub will connect to an upstream "
"hub.\n");
fprintf(stderr,
"\t-q upstream_port is the port number for the upstream hub.\n");
exit(1);
}
void parse_args(int argc, char *argv[])
{
int opt;
while ((opt = getopt(argc, argv, "hp:w:l:u:q:d:D")) >= 0)
{
switch (opt)
{
case 'h':
usage(argv[0]);
break;
case 'd':
device_paths.push_back(optarg);
break;
case 'D':
JSSerialPort::list_ports();
break;
case 'p':
port = atoi(optarg);
break;
case 'w':
ws_port = atoi(optarg);
break;
case 'l':
static_dir = optarg;
break;
case 'u':
upstream_host = optarg;
break;
case 'q':
upstream_port = atoi(optarg);
break;
default:
fprintf(stderr, "Unknown option %c\n", opt);
usage(argv[0]);
}
}
}
class JSWebsocketServer
{
public:
JSWebsocketServer(CanHubFlow *hflow, int port, string static_dir)
: canHub_(hflow)
{
if (!static_dir.empty()) {
string script = "Module.static_dir = '" + static_dir + "';\n";
emscripten_run_script(script.c_str());
}
EM_ASM_(
{
var WebSocketServer = require('websocket').server;
var http = require('http');
var ecstatic = require('ecstatic');
if (Module.static_dir) {
var serverImpl = ecstatic({ root: Module.static_dir });
} else {
var serverImpl = function(request, response){
// process HTTP request. Since we're writing just
// WebSockets server we don't have to implement anything.
};
}
var server = http.createServer(serverImpl);
console.log('try to listen on ', $0);
server.listen($0, function()
{
console.log(
'websocket server: listening on port ' + $0);
});
console.log('ws: listen done ', $0);
// create the server
wsServer = new WebSocketServer({httpServer : server});
// WebSocket server
wsServer.on('request', function(request)
{
var connection = request.accept(null, request.origin);
var client_port = new Module.JSHubPort($1,
function(gc_text)
{
var json = JSON.stringify(
{type : 'gc_can_frame', data : gc_text});
connection.sendUTF(json);
});
connection.on('message', function(message)
{
try
{
var json = JSON.parse(message.utf8Data);
}
catch (e)
{
console.log(
'This doesn\'t look like a valid JSON: ',
message.data, ' raw msg ' ,message);
return;
}
if (json.type === 'gc_can_frame')
{
// Send can frame data to the hub port
client_port.recv(json.data);
} else {
console.log('Unknown type ', message.type);
}
});
connection.on('close', function(connection)
{
console.log('websocket client disconnected');
client_port.delete();
});
});
},
port, (unsigned long)canHub_);
}
private:
CanHubFlow *canHub_;
};
/** Entry point to application.
* @param argc number of command line arguments
* @param argv array of command line arguments
* @return 0, should never return
*/
int appl_main(int argc, char *argv[])
{
parse_args(argc, argv);
JSTcpHub hub(&can_hub0, port);
std::unique_ptr<JSWebsocketServer> ws;
if (ws_port > 0) {
ws.reset(new JSWebsocketServer(&can_hub0, ws_port, static_dir));
}
std::unique_ptr<JSTcpClient> client;
if (upstream_host) {
client.reset(new JSTcpClient(&can_hub0, upstream_host, upstream_port));
}
std::vector<std::unique_ptr<JSSerialPort> > devices;
for (auto& d : device_paths) {
devices.emplace_back(new JSSerialPort(&can_hub0, d));
}
/* int dev_fd = 0;
while (1)
{
if (device_path && !dev_fd)
{
dev_fd = ::open(device_path, O_RDWR);
if (dev_fd > 0)
{
// Sets up the terminal in raw mode. Otherwise linux might echo
// characters coming in from the device and that will make
// packets go back to where they came from.
HASSERT(!tcflush(dev_fd, TCIOFLUSH));
struct termios settings;
HASSERT(!tcgetattr(dev_fd, &settings));
cfmakeraw(&settings);
HASSERT(!tcsetattr(dev_fd, TCSANOW, &settings));
LOG(INFO, "Opened device %s.\n", device_path);
create_gc_port_for_can_hub(&can_hub0, dev_fd);
}
else
{
LOG(ERROR, "Failed to open device %s: %s\n", device_path,
strerror(errno));
}
}
sleep(1);
}*/
g_executor.thread_body();
return 0;
}
<commit_msg>Stability improvements to the websocket server.<commit_after>/** \copyright
* Copyright (c) 2013, Balazs Racz
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* - Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* - Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
* \file main.cxx
*
* An application which acts as an openlcb hub with the GC protocol.
*
* @author Balazs Racz
* @date 3 Aug 2013
*/
#include <emscripten.h>
#include <emscripten/bind.h>
#include <emscripten/val.h>
#include <memory>
#include "os/os.h"
#include "utils/constants.hxx"
#include "utils/Hub.hxx"
#include "utils/GridConnectHub.hxx"
#include "utils/GcTcpHub.hxx"
#include "utils/JSTcpHub.hxx"
#include "utils/JSTcpClient.hxx"
#include "utils/JSSerialPort.hxx"
#include "executor/Executor.hxx"
#include "executor/Service.hxx"
Executor<1> g_executor{NO_THREAD()};
Service g_service(&g_executor);
CanHubFlow can_hub0(&g_service);
GcPacketPrinter packet_printer(&can_hub0, false);
OVERRIDE_CONST(gc_generate_newlines, 0);
int port = 12021;
std::vector<string> device_paths;
const char *static_dir = "";
int upstream_port = 12021;
const char *upstream_host = nullptr;
int ws_port = -1;
void usage(const char *e)
{
fprintf(stderr, "Usage: %s [-p port] [-d device_path] [-w websocket_port "
"[-l path_to_web]] [-u upstream_host [-q "
"upstream_port]]\n\n",
e);
fprintf(stderr, "GridConnect CAN HUB.\nListens to a specific TCP port, "
"reads CAN packets from the incoming connections using "
"the GridConnect protocol, and forwards all incoming "
"packets to all other participants.\n\nArguments:\n");
fprintf(stderr, "\t-p port specifies the port number to listen on, "
"default is 12021.\n");
fprintf(stderr, "\t-d device is a path to a physical device doing "
"serial-CAN or USB-CAN. If specified, opens device and "
"adds it to the hub.\n");
fprintf(stderr, "\t-D lists available serial ports.\n");
fprintf(stderr, "\t-w websocket_port Opens a webserver on this port "
"and serves up a websocket connection to the same "
"CAN-bus.\n");
fprintf(stderr, "\t-l path_to_web Exports the contents of this "
"directory thorugh the websocket's webserver.\n");
fprintf(stderr, "\t-u upstream_host is the host name for an upstream "
"hub. If specified, this hub will connect to an upstream "
"hub.\n");
fprintf(stderr,
"\t-q upstream_port is the port number for the upstream hub.\n");
exit(1);
}
void parse_args(int argc, char *argv[])
{
int opt;
while ((opt = getopt(argc, argv, "hp:w:l:u:q:d:D")) >= 0)
{
switch (opt)
{
case 'h':
usage(argv[0]);
break;
case 'd':
device_paths.push_back(optarg);
break;
case 'D':
JSSerialPort::list_ports();
break;
case 'p':
port = atoi(optarg);
break;
case 'w':
ws_port = atoi(optarg);
break;
case 'l':
static_dir = optarg;
break;
case 'u':
upstream_host = optarg;
break;
case 'q':
upstream_port = atoi(optarg);
break;
default:
fprintf(stderr, "Unknown option %c\n", opt);
usage(argv[0]);
}
}
}
class JSWebsocketServer
{
public:
JSWebsocketServer(CanHubFlow *hflow, int port, string static_dir)
: canHub_(hflow)
{
if (!static_dir.empty())
{
string script = "Module.static_dir = '" + static_dir + "';\n";
emscripten_run_script(script.c_str());
}
EM_ASM_(
{
var WebSocketServer = require('websocket').server;
var http = require('http');
var ecstatic = require('ecstatic');
if (Module.static_dir)
{
var serverImpl =
ecstatic({root : Module.static_dir, gzip : true});
}
else
{
var serverImpl = function(request, response){
// process HTTP request. Since we're writing just
// WebSockets server we don't have to implement
// anything.
};
}
var server = http.createServer(serverImpl);
console.log('try to listen on ', $0);
server.listen($0, function()
{
console.log(
'websocket server: listening on port ' + $0);
});
console.log('ws: listen done ', $0);
// create the server
wsServer = new WebSocketServer({httpServer : server});
// WebSocket server
wsServer.on('request', function(request)
{
var connection = request.accept(null, request.origin);
var client_port = new Module.JSHubPort($1,
function(gc_text)
{
var json = JSON.stringify(
{type : 'gc_can_frame', data : gc_text});
connection.sendUTF(json);
});
console.log('websocket client ',
client_port.get_port_num(), 'connected');
connection.on('message', function(message)
{
try
{
var json = JSON.parse(message.utf8Data);
}
catch (e)
{
console.log(
'This doesn\'t look like a valid JSON: ',
message.data, ' raw msg ', message);
return;
}
if (json.type === 'gc_can_frame')
{
// Send can frame data to the hub port
client_port.recv(json.data);
}
else
{
console.log('Unknown type ', message.type);
}
});
connection.on('close', function(connection)
{
console.log('websocket client ',
client_port.get_port_num(), 'disconnected');
client_port.pause();
});
connection.on('resume', function(connection)
{
console.log('websocket client ',
client_port.get_port_num(), ' resumed');
client_port.resume();
});
connection.on('pause', function(connection)
{
console.log('websocket client ',
client_port.get_port_num(), ' paused');
client_port.pause();
});
var ignevent = function(evname)
{
connection.on(evname, function(connection)
{
console.log(
'websocket ingoring event ', evname);
});
};
ignevent('drain');
});
},
port, (unsigned long)canHub_);
}
private:
CanHubFlow *canHub_;
};
/** Entry point to application.
* @param argc number of command line arguments
* @param argv array of command line arguments
* @return 0, should never return
*/
int appl_main(int argc, char *argv[])
{
parse_args(argc, argv);
JSTcpHub hub(&can_hub0, port);
std::unique_ptr<JSWebsocketServer> ws;
if (ws_port > 0)
{
ws.reset(new JSWebsocketServer(&can_hub0, ws_port, static_dir));
}
std::unique_ptr<JSTcpClient> client;
if (upstream_host)
{
client.reset(new JSTcpClient(&can_hub0, upstream_host, upstream_port));
}
std::vector<std::unique_ptr<JSSerialPort>> devices;
for (auto &d : device_paths)
{
devices.emplace_back(new JSSerialPort(&can_hub0, d));
}
/* int dev_fd = 0;
while (1)
{
if (device_path && !dev_fd)
{
dev_fd = ::open(device_path, O_RDWR);
if (dev_fd > 0)
{
// Sets up the terminal in raw mode. Otherwise linux might echo
// characters coming in from the device and that will make
// packets go back to where they came from.
HASSERT(!tcflush(dev_fd, TCIOFLUSH));
struct termios settings;
HASSERT(!tcgetattr(dev_fd, &settings));
cfmakeraw(&settings);
HASSERT(!tcsetattr(dev_fd, TCSANOW, &settings));
LOG(INFO, "Opened device %s.\n", device_path);
create_gc_port_for_can_hub(&can_hub0, dev_fd);
}
else
{
LOG(ERROR, "Failed to open device %s: %s\n", device_path,
strerror(errno));
}
}
sleep(1);
}*/
g_executor.thread_body();
return 0;
}
<|endoftext|>
|
<commit_before>#include <derecho/derecho.h>
#include <derecho/view.h>
#include <map>
#include <vector>
using namespace derecho;
using std::map;
using std::pair;
using std::vector;
class CookedMessages : public mutils::ByteRepresentable {
vector<pair<uint, uint>> msgs; // vector of (nodeid, msg #)
public:
CookedMessages() = default;
CookedMessages(const vector<pair<uint, uint>>& msgs) : msgs(msgs) {
}
void send(uint nodeid, uint msg) {
msgs.push_back(std::make_pair(nodeid, msg));
std::cout << "Node " << nodeid << " sent msg " << msg << std::endl;
}
vector<pair<uint, uint>> get_msgs(uint start_index, uint end_index) {
num_msgs = msgs.size();
if(end_index > num_msgs) {
end_index = num_msgs;
std::cout << "Msgs size: " << num_msgs << std::endl;
}
return vector<pair<uint, uint>>(msgs.begin() + start_index, msgs.begin() + end_index);
}
// default state
DEFAULT_SERIALIZATION_SUPPORT(CookedMessages, msgs);
// what operations you want as part of the subgroup
REGISTER_RPC_FUNCTIONS(CookedMessages, send, get_msgs);
};
bool verify_local_order(vector<pair<uint, uint>> msgs) {
map<uint, uint> order;
for(auto [nodeid, msg] : msgs) {
if(msg != order[nodeid] + 1) { // order.count(nodeid) != 0 && <= order[nodeid]
return false;
}
order[nodeid]++; // order[nodeid] = msg
}
return true;
}
int main(int argc, char* argv[]) {
pthread_setname_np(pthread_self(), "cooked_send");
if(argc < 2) {
std::cout << "Error: Provide the number of nodes as a command line argument!!!" << std::endl;
exit(1);
}
const uint32_t num_nodes = atoi(argv[1]);
Conf::initialize(argc, argv);
std::map<std::type_index, shard_view_generator_t>
subgroup_membership_functions{
{std::type_index(typeid(CookedMessages)),
[num_nodes](const View& view, int&) {
auto& members = view.members;
auto num_members = members.size();
if(num_members < num_nodes) {
throw subgroup_provisioning_exception();
}
subgroup_shard_layout_t layout(num_members);
layout[0].push_back(view.make_subview(vector<uint32_t>(members)));
return layout;
}}};
auto cooked_subgroup_factory = [](PersistentRegistry*) { return std::make_unique<CookedMessages>(); };
SubgroupInfo subgroup_info(subgroup_membership_functions);
Group<CookedMessages> group({}, subgroup_info, {}, cooked_subgroup_factory);
std::cout << "Finished constructing/joining the group" << std::endl;
auto group_members = group.get_members();
uint32_t my_id = getConfUInt32(CONF_DERECHO_LOCAL_ID);
uint32_t my_rank = -1;
std::cout << "Members are" << std::endl;
for(uint i = 0; i < group_members.size(); ++i) {
std::cout << group_members[i] << " ";
if(group_members[i] == my_id) {
my_rank = i;
}
}
std::cout << std::endl;
if(my_rank == (uint32_t)-1) {
std::cout << "Error: Could not join the group!!!" << std::endl;
exit(1);
}
Replicated<CookedMessages>& cookedMessagesHandle = group.get_subgroup<CookedMessages>();
uint32_t num_msgs = 500;
for(uint i = 1; i < num_msgs + 1; ++i) {
cookedMessagesHandle.ordered_send<RPC_NAME(send)>(my_rank, i);
}
if(my_rank == 0) {
uint32_t max_msg_size = getConfUInt64(CONF_DERECHO_MAX_PAYLOAD_SIZE);
uint32_t num_entries = max_msg_size / sizeof(pair<uint, uint>) - 5;
if(num_entries < 0) {
std::cout << "Error: Maximum message size too small!" << std::endl;
exit(1);
}
map<node_id_t, vector<pair<uint, uint>>> msgs_map;
for(uint i = 0; i < num_msgs * num_nodes; i += num_entries) {
auto&& results = cookedMessagesHandle.ordered_send<RPC_NAME(get_msgs)>(i, i + num_entries);
auto& replies = results.get();
for(auto& reply_pair : replies) {
vector<pair<uint, uint>> v = reply_pair.second.get();
msgs_map[reply_pair.first].insert(msgs_map[reply_pair.first].end(), v.begin(), v.end());
}
}
vector<pair<uint, uint>> first_reply = msgs_map.begin()->second;
if(!verify_local_order(first_reply)) {
std::cout << "Error: Violation of local order!!!" << std::endl;
exit(1);
}
std::cout << "Local ordering test successful!" << std::endl;
for(auto& msgs_map_entry : msgs_map) {
vector<pair<uint, uint>>& v = msgs_map_entry.second;
if(first_reply != v) {
std::cout << "Error: Violation of global order!!!" << std::endl;
exit(1);
}
}
std::cout << "Global ordering test successful!" << std::endl;
}
group.barrier_sync();
group.leave();
return 0;
}
<commit_msg>bugfixing get_msgs<commit_after>#include <derecho/derecho.h>
#include <derecho/view.h>
#include <map>
#include <vector>
using namespace derecho;
using std::map;
using std::pair;
using std::vector;
class CookedMessages : public mutils::ByteRepresentable {
vector<pair<uint, uint>> msgs; // vector of (nodeid, msg #)
public:
CookedMessages() = default;
CookedMessages(const vector<pair<uint, uint>>& msgs) : msgs(msgs) {
}
void send(uint nodeid, uint msg) {
msgs.push_back(std::make_pair(nodeid, msg));
std::cout << "Node " << nodeid << " sent msg " << msg << std::endl;
}
vector<pair<uint, uint>> get_msgs(uint start_index, uint end_index) {
uint num_msgs = msgs.size();
if(end_index > num_msgs) {
end_index = num_msgs;
std::cout << "Msgs size: " << num_msgs << std::endl;
}
return vector<pair<uint, uint>>(msgs.begin() + start_index, msgs.begin() + end_index);
}
// default state
DEFAULT_SERIALIZATION_SUPPORT(CookedMessages, msgs);
// what operations you want as part of the subgroup
REGISTER_RPC_FUNCTIONS(CookedMessages, send, get_msgs);
};
bool verify_local_order(vector<pair<uint, uint>> msgs) {
map<uint, uint> order;
for(auto [nodeid, msg] : msgs) {
if(msg != order[nodeid] + 1) { // order.count(nodeid) != 0 && <= order[nodeid]
return false;
}
order[nodeid]++; // order[nodeid] = msg
}
return true;
}
int main(int argc, char* argv[]) {
pthread_setname_np(pthread_self(), "cooked_send");
if(argc < 2) {
std::cout << "Error: Provide the number of nodes as a command line argument!!!" << std::endl;
exit(1);
}
const uint32_t num_nodes = atoi(argv[1]);
Conf::initialize(argc, argv);
std::map<std::type_index, shard_view_generator_t>
subgroup_membership_functions{
{std::type_index(typeid(CookedMessages)),
[num_nodes](const View& view, int&) {
auto& members = view.members;
auto num_members = members.size();
if(num_members < num_nodes) {
throw subgroup_provisioning_exception();
}
subgroup_shard_layout_t layout(num_members);
layout[0].push_back(view.make_subview(vector<uint32_t>(members)));
return layout;
}}};
auto cooked_subgroup_factory = [](PersistentRegistry*) { return std::make_unique<CookedMessages>(); };
SubgroupInfo subgroup_info(subgroup_membership_functions);
Group<CookedMessages> group({}, subgroup_info, {}, cooked_subgroup_factory);
std::cout << "Finished constructing/joining the group" << std::endl;
auto group_members = group.get_members();
uint32_t my_id = getConfUInt32(CONF_DERECHO_LOCAL_ID);
uint32_t my_rank = -1;
std::cout << "Members are" << std::endl;
for(uint i = 0; i < group_members.size(); ++i) {
std::cout << group_members[i] << " ";
if(group_members[i] == my_id) {
my_rank = i;
}
}
std::cout << std::endl;
if(my_rank == (uint32_t)-1) {
std::cout << "Error: Could not join the group!!!" << std::endl;
exit(1);
}
Replicated<CookedMessages>& cookedMessagesHandle = group.get_subgroup<CookedMessages>();
uint32_t num_msgs = 500;
for(uint i = 1; i < num_msgs + 1; ++i) {
cookedMessagesHandle.ordered_send<RPC_NAME(send)>(my_rank, i);
}
if(my_rank == 0) {
uint32_t max_msg_size = getConfUInt64(CONF_DERECHO_MAX_PAYLOAD_SIZE);
uint32_t num_entries = max_msg_size / sizeof(pair<uint, uint>) - 5;
if(num_entries < 0) {
std::cout << "Error: Maximum message size too small!" << std::endl;
exit(1);
}
map<node_id_t, vector<pair<uint, uint>>> msgs_map;
for(uint i = 0; i < num_msgs * num_nodes; i += num_entries) {
auto&& results = cookedMessagesHandle.ordered_send<RPC_NAME(get_msgs)>(i, i + num_entries);
auto& replies = results.get();
for(auto& reply_pair : replies) {
vector<pair<uint, uint>> v = reply_pair.second.get();
msgs_map[reply_pair.first].insert(msgs_map[reply_pair.first].end(), v.begin(), v.end());
}
}
vector<pair<uint, uint>> first_reply = msgs_map.begin()->second;
if(!verify_local_order(first_reply)) {
std::cout << "Error: Violation of local order!!!" << std::endl;
exit(1);
}
std::cout << "Local ordering test successful!" << std::endl;
for(auto& msgs_map_entry : msgs_map) {
vector<pair<uint, uint>>& v = msgs_map_entry.second;
if(first_reply != v) {
std::cout << "Error: Violation of global order!!!" << std::endl;
exit(1);
}
}
std::cout << "Global ordering test successful!" << std::endl;
}
group.barrier_sync();
group.leave();
return 0;
}
<|endoftext|>
|
<commit_before>#include "source/solver.h"
#include <iostream>
#include <cassert>
#include <cstring>
#include "include/gflags/gflags.h"
/*! \mainpage Main Page
*
*
* \section intro_sec Introduction
*
*
\b sym-ildl is a C++ package for producing fast incomplete factorizations of symmetric indefinite matrices. Given an \f$n\times n\f$ symmetric indefinite matrix \f$\mathbf{A}\f$, this package produces an incomplete \f$\mathbf{LDL^{T}}\f$ factorization. Prior to factorization, this package first scales the matrix to be equilibriated in the max-norm, and then preorders the matrix using the Reverse Cuthill-McKee (RCM) algorithm. To maintain stability, we use Bunch-Kaufman partial pivoting during the factorization process. The factorization produced is of the form
\f[
\mathbf{P^{T}SASP=LDL^{T}}.
\f]
where \f$\mathbf{P}\f$ is a permutation matrix, \f$\mathbf{S}\f$ a scaling matrix, and \f$\mathbf{L}\f$ and \f$\mathbf{D}\f$ are the unit lower triangular and diagonal factors respectively.
* \section quick_start Quick Start
*
To begin using the package, first download the files hosted at <a href="https://github.com/inutard/matrix-factor">https://github.com/inutard/matrix-factor</a>. The package works under most Unix distributions as well as Cygwin under Windows. The default compiler used is \c g++, simply type \c make at the command line to compile the entire package. In addition to \subpage ldl_driver "usage as a standalone program", the package also has a \subpage matlab_mex "Matlab interface".
\subsection ldl_driver Using the package as a standalone program
The compiled program \c ldl_driver takes in (through the command line) three parameters as well as four optional ones.
The format of execution is:
\code
./ldl_driver -filename=[matrix-name.mtx] -fill=[fill_factor] -tol=[drop_tol] -pp_tol=[pp_tol] -reordering=[amd/rcm/none] -save=[true/false] -display=[true/display]
\endcode
The parameters above can be given in any order, and will use a default value when not specified.
A description of each of these parameters can be accessed by typing
\code
./ldl_driver --help
\endcode
For convenience, the parameters are listed below:
\param filename The filename of the matrix to be loaded. Several test matrices exist in the test_matrices folder. All matrices loaded are required to be in matrix market (.mtx) form.
\param fill Controls memory usage. Each column is guaranteed to have fewer than \f$fill\cdot nnz(\mathbf{A})/n\f$ elements. When this argument is not given, the default value for \c fill is <c>1.0</c>.
\param tol Controls agressiveness of dropping. In each column k, elements less than \f$tol \cdot \left|\left|\mathbf{L}_{k+1:n,k}\right|\right|_1\f$ are dropped. The default value for \c tol is <c>0.001</c>.
\param pp_tol A parameter to aggressiveness of Bunch-Kaufman pivoting (BKP). When pp_tol >= 1, full BKP is used. When pp_tol is 0, there is no partial pivoting. Values between 0 and 1 varies the number of pivots of BKP makes.
\param reordering Determines what sort of preordering will be used on the matrix. Choices are 'amd', 'rcm', and 'none'. The default is 'amd'.
\param save Indicates whether the output matrices should be saved. \c true indicates yes, \c false indicates no. The default flag is \c true. All matrices are saved in matrix market (.mtx) form. The matrices are saved into an external folder named \c output_matrices. There are five saved files: <c>outA.mtx, outL.mtx, outD.mtx, outS.mtx</c>, and \c outP.mtx. \c outB.mtx is the matrix \f$\mathbf{B=P^{T}SASP}\f$. The rest of the outputs should be clear from the description above.
\param display Indicates whether the output matrices should be displayed to the command line. \c true indicates yes, \c false indicates no. The default flag is \c false.
Typically, the \c pp_tol and \c reordering parameters are best left to the default options.
\par Examples:
Suppose we wish to factor the \c aug3dcqp matrix stored in <c>test_matrices/aug3dcqp.mtx</c>. Using the parameters described above, the execution of the program may go something like this:
\code
./ldl_driver -filename=test_matrices/aug3dcqp.mtx -fill=1.0 tol=0.001 -save=true -display=false
Load succeeded. File test_matrices/aug3dcqp.mtx was loaded.
A is 35543 by 35543 with 128115 non-zeros.
Equilibration: 0.047 seconds.
AMD: 0.047 seconds.
Permutation: 0.047 seconds.
Factorization: 0.109 seconds.
Total time: 0.250 seconds.
L is 35543 by 35543 with 108794 non-zeros.
Saving matrices...
Save complete.
Factorization Complete. All output written to /output_matrices directory.
\endcode
The code above factors the \c aug3dcqp.mtx matrix (<c>lfil=1.0, tol=0.001</c>) from the \c test_matrices folder and saves the outputs. The time it took to pre-order and equilibriate the matrix (0.047s) as well as the actual factorization (0.109s) are also given.
\par
The program may also run without the last 4 arguments:
\code
./ldl_driver -filename=test_matrices/aug3dcqp.mtx -fill=1.0 -tol=0.001
Load succeeded. File test_matrices/aug3dcqp.mtx was loaded.
A is 35543 by ...
\endcode
This code does the exact same thing as the code in the previous example, except this time we take advantage of the fact that \c save defaults to \c true and \c display to \c false.
\par
Finally, we may use all optional arguments:
\code
./ldl_driver -filename=test_matrices/aug3dcqp.mtx
Load succeeded. File test_matrices/aug3dcqp.mtx was loaded.
A is 35543 by ...
\endcode
The code above would use the default arguments <c>-fill=1.0 -tol=0.001 -pp_tol=1.0 -reordering=amd -save=true -display=false</c>.
\subsection matlab_mex Using the \b sym-ildl within Matlab
If everything is compiled correctly, simply open Matlab in the package directory. The \c startup.m script adds all necessary paths to Matlab upon initiation. The program can now be called by its function handle, \c ildl.
\c ildl takes in five arguments, four of them being optional. A full description of the parameters can be displayed by typing
\code
help ildl
\endcode
For convenience, the parameters are listed below:
\param A The matrix to be factored.
\param fill Controls memory usage. Each column is guaranteed to have fewer than \f$fill\cdot nnz(\mathbf{A})/n\f$ elements. When this argument is not given, the default value for \c fill is <c>1.0</c>.
\param tol Controls agressiveness of dropping. In each column k, elements less than \f$tol \cdot \left|\left|\mathbf{L}_{k+1:n,k}\right|\right|_1\f$ are dropped. The default value for \c tol is <c>0.001</c>.
\param pp_tol A parameter to aggressiveness of Bunch-Kaufman pivoting (BKP). When pp_tol >= 1, full BKP is used. When pp_tol is 0, there is no partial pivoting. Values between 0 and 1 varies the number of pivots of BKP makes.
\param reordering Determines what sort of preordering will be used on the matrix. Choices are 'amd', 'rcm', and 'none'. The default is 'amd'.
As with the standalone executable, the function has five outputs: <c>L, D, p, S,</c> and \c B:
\return \b L Unit lower triangular factor of \f$\mathbf{P^{T}SASP}\f$.
\return \b D Block diagonal factor (consisting of 1x1 and 2x2 blocks) of \f$\mathbf{P^{T}SASP}\f$.
\return \b p Permutation vector containing permutations done to \f$\mathbf{A}\f$.
\return \b S Diagonal scaling matrix that equilibrations \f$\mathbf{A}\f$ in the max-norm.
\return \b B Permuted and scaled matrix \f$\mathbf{B=P^{T}SASP}\f$ after factorization.
*
* \par Examples:
Before we begin, let's first generate some symmetric indefinite matrices:
\code
>> B = sparse(gallery('uniformdata',100,0));
>> A = [speye(100) B; B' sparse(100, 100)];
\endcode
The \c A generated is a special type of matrix called a KKT matrix. These matrices are indefinite and arise often in optimzation problems. Note that A must be a Matlab \b sparse matrix.
\par
To factor the matrix, we supply \c ildl with the parameters described above:
\code
>> [L, D, p, S, B] = ildl(A, 1.0, 0.001);
Equilibration: 0.001 seconds.
AMD: 0.001 seconds.
Permutation: 0.000 seconds.
Factorization: 0.022 seconds.
Total time: 0.024 seconds.
L is 200 by 200 with 14388 non-zeros.
\endcode
As we can see above, \c ildl will supply some timing information to the console when used. The reordering time is the time taken to equilibriate and preorder the matrix. The factorization time is the time it took to factor and pivot the matrix with partial pivoting.
\par
We may also take advantage of the optional parameters and simply feed \c ildl only one parameter:
\code
>> [L, D, p, S, B] = ildl(A);
Equilibration: 0.001 seconds.
AMD: 0.001 seconds.
...
\endcode
*
*
* \section refs References
-# J. A. George and J. W-H. Liu, <em>Computer Solution of Large Sparse Positive Definite Systems</em>, Prentice-Hall, 1981.
-# J. R. Bunch, <em>Equilibration of Symmetric Matrices in the Max-Norm</em>, JACM, 18 (1971), pp. 566-572.
-# N. Li and Y. Saad, <em>Crout versions of the ILU factorization with pivoting for sparse symmetric matrices</em>, ETNA, 20 (2006), pp. 75-85.
-# N. Li, Y. Saad, and E. Chow, <em>Crout versions of ILU for general sparse matrices</em>, SISC, 25 (2003), pp. 716-728.
*
*/
DEFINE_string(filename, "", "The filename of the matrix to be factored"
"(in matrix-market format).");
DEFINE_double(fill, 1.0, "A parameter to control memory usage. Each column is guaranteed"
"to have fewer than fill*nnz(A)/n elements.");
DEFINE_double(tol, 0.001, "A parameter to control agressiveness of dropping. In each column k,"
"elements less than tol*||L(k+1:n,k)|| (1-norm) are dropped.");
DEFINE_double(pp_tol, 1.0, "A parameter to aggressiveness of Bunch-Kaufman pivoting (BKP). "
"When pp_tol >= 1, full BKP is used. When pp_tol is 0, no BKP"
"is used. Values between 0 and 1 varies the aggressivness of"
"BKP in a continuous manner.");
DEFINE_string(reordering, "amd", "Determines what sort of preordering will be used"
" on the matrix. Choices are 'amd', 'rcm', and 'none'.");
DEFINE_bool(equil, true, "Decides if the matrix should be equilibriated (in the max-norm) "
"before factoring is done.");
DEFINE_bool(save, true, "If yes, saves the factors (in matrix-market format) into a folder"
"called output_matrices/ in the same directory as ldl_driver.");
DEFINE_bool(display, false, "If yes, outputs a human readable version of the factors onto"
" standard out. Generates a large amount of output if the "
"matrix is big.");
int main(int argc, char* argv[])
{
std::string usage("Performs an incomplete LDL factorization of a given matrix.\n"
"Sample usage:\n"
"./ldl_driver -filename=test_matrices/testmat1.mtx "
"-fill=2.0 -display=true -save=false\n"
"Additionally, these flags can be loaded from a single file "
"with the option -flagfile=[filename].");
google::SetUsageMessage(usage);
google::ParseCommandLineFlags(&argc, &argv, true);
if (FLAGS_filename.empty()) {
std::cerr << "No file specified! Type ./ldl_driver --help for a description of the program parameters." << std::endl;
return 0;
}
solver<double> solv;
solv.load(FLAGS_filename);
//default reordering scheme is AMD
solv.set_reorder_scheme(FLAGS_reordering.c_str());
//default is equil on
solv.set_equil(FLAGS_equil);
solv.solve(FLAGS_fill, FLAGS_tol, FLAGS_pp_tol);
if (FLAGS_save) {
solv.save();
}
if (FLAGS_display) {
solv.display();
std::cout << endl;
}
std::cout << "Factorization Complete. All output written to /output_matrices directory." << std::endl;
return 0;
}<commit_msg>fixed typo<commit_after>#include "source/solver.h"
#include <iostream>
#include <cassert>
#include <cstring>
#include "include/gflags/gflags.h"
/*! \mainpage Main Page
*
*
* \section intro_sec Introduction
*
*
\b sym-ildl is a C++ package for producing fast incomplete factorizations of symmetric indefinite matrices. Given an \f$n\times n\f$ symmetric indefinite matrix \f$\mathbf{A}\f$, this package produces an incomplete \f$\mathbf{LDL^{T}}\f$ factorization. Prior to factorization, this package first scales the matrix to be equilibriated in the max-norm, and then preorders the matrix using the Reverse Cuthill-McKee (RCM) algorithm. To maintain stability, we use Bunch-Kaufman partial pivoting during the factorization process. The factorization produced is of the form
\f[
\mathbf{P^{T}SASP=LDL^{T}}.
\f]
where \f$\mathbf{P}\f$ is a permutation matrix, \f$\mathbf{S}\f$ a scaling matrix, and \f$\mathbf{L}\f$ and \f$\mathbf{D}\f$ are the unit lower triangular and diagonal factors respectively.
* \section quick_start Quick Start
*
To begin using the package, first download the files hosted at <a href="https://github.com/inutard/matrix-factor">https://github.com/inutard/matrix-factor</a>. The package works under most Unix distributions as well as Cygwin under Windows. The default compiler used is \c g++, simply type \c make at the command line to compile the entire package. In addition to \subpage ldl_driver "usage as a standalone program", the package also has a \subpage matlab_mex "Matlab interface".
\subsection ldl_driver Using the package as a standalone program
The compiled program \c ldl_driver takes in (through the command line) three parameters as well as four optional ones.
The format of execution is:
\code
./ldl_driver -filename=[matrix-name.mtx] -fill=[fill_factor] -tol=[drop_tol] -pp_tol=[pp_tol] -reordering=[amd/rcm/none] -save=[true/false] -display=[true/display]
\endcode
The parameters above can be given in any order, and will use a default value when not specified.
A description of each of these parameters can be accessed by typing
\code
./ldl_driver --help
\endcode
For convenience, the parameters are listed below:
\param filename The filename of the matrix to be loaded. Several test matrices exist in the test_matrices folder. All matrices loaded are required to be in matrix market (.mtx) form.
\param fill Controls memory usage. Each column is guaranteed to have fewer than \f$fill\cdot nnz(\mathbf{A})/n\f$ elements. When this argument is not given, the default value for \c fill is <c>1.0</c>.
\param tol Controls agressiveness of dropping. In each column k, elements less than \f$tol \cdot \left|\left|\mathbf{L}_{k+1:n,k}\right|\right|_1\f$ are dropped. The default value for \c tol is <c>0.001</c>.
\param pp_tol A parameter to aggressiveness of Bunch-Kaufman pivoting (BKP). When pp_tol >= 1, full BKP is used. When pp_tol is 0, there is no partial pivoting. Values between 0 and 1 varies the number of pivots of BKP makes.
\param reordering Determines what sort of preordering will be used on the matrix. Choices are 'amd', 'rcm', and 'none'. The default is 'amd'.
\param save Indicates whether the output matrices should be saved. \c true indicates yes, \c false indicates no. The default flag is \c true. All matrices are saved in matrix market (.mtx) form. The matrices are saved into an external folder named \c output_matrices. There are five saved files: <c>outA.mtx, outL.mtx, outD.mtx, outS.mtx</c>, and \c outP.mtx. \c outB.mtx is the matrix \f$\mathbf{B=P^{T}SASP}\f$. The rest of the outputs should be clear from the description above.
\param display Indicates whether the output matrices should be displayed to the command line. \c true indicates yes, \c false indicates no. The default flag is \c false.
Typically, the \c pp_tol and \c reordering parameters are best left to the default options.
\par Examples:
Suppose we wish to factor the \c aug3dcqp matrix stored in <c>test_matrices/aug3dcqp.mtx</c>. Using the parameters described above, the execution of the program may go something like this:
\code
./ldl_driver -filename=test_matrices/aug3dcqp.mtx -fill=1.0 tol=0.001 -save=true -display=false
Load succeeded. File test_matrices/aug3dcqp.mtx was loaded.
A is 35543 by 35543 with 128115 non-zeros.
Equilibration: 0.047 seconds.
AMD: 0.047 seconds.
Permutation: 0.047 seconds.
Factorization: 0.109 seconds.
Total time: 0.250 seconds.
L is 35543 by 35543 with 108794 non-zeros.
Saving matrices...
Save complete.
Factorization Complete. All output written to /output_matrices directory.
\endcode
The code above factors the \c aug3dcqp.mtx matrix (<c>lfil=1.0, tol=0.001</c>) from the \c test_matrices folder and saves the outputs. The time it took to pre-order and equilibriate the matrix (0.047s) as well as the actual factorization (0.109s) are also given.
\par
The program may also run without the last 4 arguments:
\code
./ldl_driver -filename=test_matrices/aug3dcqp.mtx -fill=1.0 -tol=0.001
Load succeeded. File test_matrices/aug3dcqp.mtx was loaded.
A is 35543 by ...
\endcode
This code does the exact same thing as the code in the previous example, except this time we take advantage of the fact that \c save defaults to \c true and \c display to \c false.
\par
Finally, we may use all optional arguments:
\code
./ldl_driver -filename=test_matrices/aug3dcqp.mtx
Load succeeded. File test_matrices/aug3dcqp.mtx was loaded.
A is 35543 by ...
\endcode
The code above would use the default arguments <c>-fill=1.0 -tol=0.001 -pp_tol=1.0 -reordering=amd -save=true -display=false</c>.
\subsection matlab_mex Using the sym-ildl within Matlab
If everything is compiled correctly, simply open Matlab in the package directory. The \c startup.m script adds all necessary paths to Matlab upon initiation. The program can now be called by its function handle, \c ildl.
\c ildl takes in five arguments, four of them being optional. A full description of the parameters can be displayed by typing
\code
help ildl
\endcode
For convenience, the parameters are listed below:
\param A The matrix to be factored.
\param fill Controls memory usage. Each column is guaranteed to have fewer than \f$fill\cdot nnz(\mathbf{A})/n\f$ elements. When this argument is not given, the default value for \c fill is <c>1.0</c>.
\param tol Controls agressiveness of dropping. In each column k, elements less than \f$tol \cdot \left|\left|\mathbf{L}_{k+1:n,k}\right|\right|_1\f$ are dropped. The default value for \c tol is <c>0.001</c>.
\param pp_tol A parameter to aggressiveness of Bunch-Kaufman pivoting (BKP). When pp_tol >= 1, full BKP is used. When pp_tol is 0, there is no partial pivoting. Values between 0 and 1 varies the number of pivots of BKP makes.
\param reordering Determines what sort of preordering will be used on the matrix. Choices are 'amd', 'rcm', and 'none'. The default is 'amd'.
As with the standalone executable, the function has five outputs: <c>L, D, p, S,</c> and \c B:
\return \b L Unit lower triangular factor of \f$\mathbf{P^{T}SASP}\f$.
\return \b D Block diagonal factor (consisting of 1x1 and 2x2 blocks) of \f$\mathbf{P^{T}SASP}\f$.
\return \b p Permutation vector containing permutations done to \f$\mathbf{A}\f$.
\return \b S Diagonal scaling matrix that equilibrations \f$\mathbf{A}\f$ in the max-norm.
\return \b B Permuted and scaled matrix \f$\mathbf{B=P^{T}SASP}\f$ after factorization.
*
* \par Examples:
Before we begin, let's first generate some symmetric indefinite matrices:
\code
>> B = sparse(gallery('uniformdata',100,0));
>> A = [speye(100) B; B' sparse(100, 100)];
\endcode
The \c A generated is a special type of matrix called a KKT matrix. These matrices are indefinite and arise often in optimzation problems. Note that A must be a Matlab \b sparse matrix.
\par
To factor the matrix, we supply \c ildl with the parameters described above:
\code
>> [L, D, p, S, B] = ildl(A, 1.0, 0.001);
Equilibration: 0.001 seconds.
AMD: 0.001 seconds.
Permutation: 0.000 seconds.
Factorization: 0.022 seconds.
Total time: 0.024 seconds.
L is 200 by 200 with 14388 non-zeros.
\endcode
As we can see above, \c ildl will supply some timing information to the console when used. The reordering time is the time taken to equilibriate and preorder the matrix. The factorization time is the time it took to factor and pivot the matrix with partial pivoting.
\par
We may also take advantage of the optional parameters and simply feed \c ildl only one parameter:
\code
>> [L, D, p, S, B] = ildl(A);
Equilibration: 0.001 seconds.
AMD: 0.001 seconds.
...
\endcode
*
*
* \section refs References
-# J. A. George and J. W-H. Liu, <em>Computer Solution of Large Sparse Positive Definite Systems</em>, Prentice-Hall, 1981.
-# J. R. Bunch, <em>Equilibration of Symmetric Matrices in the Max-Norm</em>, JACM, 18 (1971), pp. 566-572.
-# N. Li and Y. Saad, <em>Crout versions of the ILU factorization with pivoting for sparse symmetric matrices</em>, ETNA, 20 (2006), pp. 75-85.
-# N. Li, Y. Saad, and E. Chow, <em>Crout versions of ILU for general sparse matrices</em>, SISC, 25 (2003), pp. 716-728.
*
*/
DEFINE_string(filename, "", "The filename of the matrix to be factored"
"(in matrix-market format).");
DEFINE_double(fill, 1.0, "A parameter to control memory usage. Each column is guaranteed"
"to have fewer than fill*nnz(A)/n elements.");
DEFINE_double(tol, 0.001, "A parameter to control agressiveness of dropping. In each column k,"
"elements less than tol*||L(k+1:n,k)|| (1-norm) are dropped.");
DEFINE_double(pp_tol, 1.0, "A parameter to aggressiveness of Bunch-Kaufman pivoting (BKP). "
"When pp_tol >= 1, full BKP is used. When pp_tol is 0, no BKP"
"is used. Values between 0 and 1 varies the aggressivness of"
"BKP in a continuous manner.");
DEFINE_string(reordering, "amd", "Determines what sort of preordering will be used"
" on the matrix. Choices are 'amd', 'rcm', and 'none'.");
DEFINE_bool(equil, true, "Decides if the matrix should be equilibriated (in the max-norm) "
"before factoring is done.");
DEFINE_bool(save, true, "If yes, saves the factors (in matrix-market format) into a folder"
"called output_matrices/ in the same directory as ldl_driver.");
DEFINE_bool(display, false, "If yes, outputs a human readable version of the factors onto"
" standard out. Generates a large amount of output if the "
"matrix is big.");
int main(int argc, char* argv[])
{
std::string usage("Performs an incomplete LDL factorization of a given matrix.\n"
"Sample usage:\n"
"./ldl_driver -filename=test_matrices/testmat1.mtx "
"-fill=2.0 -display=true -save=false\n"
"Additionally, these flags can be loaded from a single file "
"with the option -flagfile=[filename].");
google::SetUsageMessage(usage);
google::ParseCommandLineFlags(&argc, &argv, true);
if (FLAGS_filename.empty()) {
std::cerr << "No file specified! Type ./ldl_driver --help for a description of the program parameters." << std::endl;
return 0;
}
solver<double> solv;
solv.load(FLAGS_filename);
//default reordering scheme is AMD
solv.set_reorder_scheme(FLAGS_reordering.c_str());
//default is equil on
solv.set_equil(FLAGS_equil);
solv.solve(FLAGS_fill, FLAGS_tol, FLAGS_pp_tol);
if (FLAGS_save) {
solv.save();
}
if (FLAGS_display) {
solv.display();
std::cout << endl;
}
std::cout << "Factorization Complete. All output written to /output_matrices directory." << std::endl;
return 0;
}<|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; version 2 of the License.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */
#include <ndb_global.h>
#include <NdbTCP.h>
#include "TCP_Transporter.hpp"
#include <NdbOut.hpp>
#include <NdbSleep.h>
// End of stuff to be moved
#if defined NDB_OSE || defined NDB_SOFTOSE
#define inet_send inet_send
#else
#define inet_send send
#endif
#ifdef NDB_WIN32
class ndbstrerror
{
public:
ndbstrerror(int iError);
~ndbstrerror(void);
operator char*(void) { return m_szError; };
private:
int m_iError;
char* m_szError;
};
ndbstrerror::ndbstrerror(int iError)
: m_iError(iError)
{
FormatMessage(
FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
0,
iError,
MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
(LPTSTR)&m_szError,
0,
0);
}
ndbstrerror::~ndbstrerror(void)
{
LocalFree( m_szError );
m_szError = 0;
}
#else
#define ndbstrerror strerror
#endif
TCP_Transporter::TCP_Transporter(TransporterRegistry &t_reg,
int sendBufSize, int maxRecvSize,
const char *lHostName,
const char *rHostName,
int r_port,
bool isMgmConnection,
NodeId lNodeId,
NodeId rNodeId,
NodeId serverNodeId,
bool chksm, bool signalId,
Uint32 _reportFreq) :
Transporter(t_reg, tt_TCP_TRANSPORTER,
lHostName, rHostName, r_port, isMgmConnection,
lNodeId, rNodeId, serverNodeId,
0, false, chksm, signalId),
m_sendBuffer(sendBufSize)
{
maxReceiveSize = maxRecvSize;
// Initialize member variables
theSocket = NDB_INVALID_SOCKET;
sendCount = receiveCount = 0;
sendSize = receiveSize = 0;
reportFreq = _reportFreq;
sockOptRcvBufSize = 70080;
sockOptSndBufSize = 71540;
sockOptNodelay = 1;
sockOptTcpMaxSeg = 4096;
}
TCP_Transporter::~TCP_Transporter() {
// Disconnect
if (theSocket != NDB_INVALID_SOCKET)
doDisconnect();
// Delete send buffers
// Delete receive buffer!!
receiveBuffer.destroy();
}
bool TCP_Transporter::connect_server_impl(NDB_SOCKET_TYPE sockfd)
{
DBUG_ENTER("TCP_Transpporter::connect_server_impl");
DBUG_RETURN(connect_common(sockfd));
}
bool TCP_Transporter::connect_client_impl(NDB_SOCKET_TYPE sockfd)
{
DBUG_ENTER("TCP_Transpporter::connect_client_impl");
DBUG_RETURN(connect_common(sockfd));
}
bool TCP_Transporter::connect_common(NDB_SOCKET_TYPE sockfd)
{
theSocket = sockfd;
setSocketOptions();
setSocketNonBlocking(theSocket);
DBUG_PRINT("info", ("Successfully set-up TCP transporter to node %d",
remoteNodeId));
return true;
}
bool
TCP_Transporter::initTransporter() {
// Allocate buffer for receiving
// Let it be the maximum size we receive plus 8 kB for any earlier received
// incomplete messages (slack)
Uint32 recBufSize = maxReceiveSize;
if(recBufSize < MAX_MESSAGE_SIZE){
recBufSize = MAX_MESSAGE_SIZE;
}
if(!receiveBuffer.init(recBufSize+MAX_MESSAGE_SIZE)){
return false;
}
// Allocate buffers for sending
if (!m_sendBuffer.initBuffer(remoteNodeId)) {
// XXX What shall be done here?
// The same is valid for the other init-methods
return false;
}
return true;
}
void
TCP_Transporter::setSocketOptions(){
if (setsockopt(theSocket, SOL_SOCKET, SO_RCVBUF,
(char*)&sockOptRcvBufSize, sizeof(sockOptRcvBufSize)) < 0) {
#ifdef DEBUG_TRANSPORTER
ndbout_c("The setsockopt SO_RCVBUF error code = %d", InetErrno);
#endif
}//if
if (setsockopt(theSocket, SOL_SOCKET, SO_SNDBUF,
(char*)&sockOptSndBufSize, sizeof(sockOptSndBufSize)) < 0) {
#ifdef DEBUG_TRANSPORTER
ndbout_c("The setsockopt SO_SNDBUF error code = %d", InetErrno);
#endif
}//if
//-----------------------------------------------
// Set the TCP_NODELAY option so also small packets are sent
// as soon as possible
//-----------------------------------------------
if (setsockopt(theSocket, IPPROTO_TCP, TCP_NODELAY,
(char*)&sockOptNodelay, sizeof(sockOptNodelay)) < 0) {
#ifdef DEBUG_TRANSPORTER
ndbout_c("The setsockopt TCP_NODELAY error code = %d", InetErrno);
#endif
}//if
}
#ifdef NDB_WIN32
bool
TCP_Transporter::setSocketNonBlocking(NDB_SOCKET_TYPE socket){
unsigned long ul = 1;
if(ioctlsocket(socket, FIONBIO, &ul))
{
#ifdef DEBUG_TRANSPORTER
ndbout_c("Set non-blocking server error3: %d", InetErrno);
#endif
}//if
return true;
}
#else
bool
TCP_Transporter::setSocketNonBlocking(NDB_SOCKET_TYPE socket){
int flags;
flags = fcntl(socket, F_GETFL, 0);
if (flags < 0) {
#ifdef DEBUG_TRANSPORTER
ndbout_c("Set non-blocking server error1: %s", strerror(InetErrno));
#endif
}//if
flags |= NDB_NONBLOCK;
if (fcntl(socket, F_SETFL, flags) == -1) {
#ifdef DEBUG_TRANSPORTER
ndbout_c("Set non-blocking server error2: %s", strerror(InetErrno));
#endif
}//if
return true;
}
#endif
bool
TCP_Transporter::sendIsPossible(struct timeval * timeout) {
#ifdef NDB_OSE
/**
* In OSE you cant do select without owning a socket,
* and since this method might be called by any thread in the api
* we choose not to implementet and always return true after sleeping
* a while.
*
* Note that this only sensible as long as the sockets are non blocking
*/
if(theSocket >= 0){
Uint32 timeOutMillis = timeout->tv_sec * 1000 + timeout->tv_usec / 1000;
NdbSleep_MilliSleep(timeOutMillis);
return true;
}
return false;
#else
if(theSocket != NDB_INVALID_SOCKET){
fd_set writeset;
FD_ZERO(&writeset);
FD_SET(theSocket, &writeset);
int selectReply = select(theSocket + 1, NULL, &writeset, NULL, timeout);
if ((selectReply > 0) && FD_ISSET(theSocket, &writeset))
return true;
else
return false;
}
return false;
#endif
}
Uint32
TCP_Transporter::get_free_buffer() const
{
return m_sendBuffer.bufferSizeRemaining();
}
Uint32 *
TCP_Transporter::getWritePtr(Uint32 lenBytes, Uint32 prio){
Uint32 * insertPtr = m_sendBuffer.getInsertPtr(lenBytes);
struct timeval timeout = {0, 10000};
if (insertPtr == 0) {
//-------------------------------------------------
// Buffer was completely full. We have severe problems.
// We will attempt to wait for a small time
//-------------------------------------------------
if(sendIsPossible(&timeout)) {
//-------------------------------------------------
// Send is possible after the small timeout.
//-------------------------------------------------
if(!doSend()){
return 0;
} else {
//-------------------------------------------------
// Since send was successful we will make a renewed
// attempt at inserting the signal into the buffer.
//-------------------------------------------------
insertPtr = m_sendBuffer.getInsertPtr(lenBytes);
}//if
} else {
return 0;
}//if
}
return insertPtr;
}
void
TCP_Transporter::updateWritePtr(Uint32 lenBytes, Uint32 prio){
m_sendBuffer.updateInsertPtr(lenBytes);
const int bufsize = m_sendBuffer.bufferSize();
if(bufsize > TCP_SEND_LIMIT) {
//-------------------------------------------------
// Buffer is full and we are ready to send. We will
// not wait since the signal is already in the buffer.
// Force flag set has the same indication that we
// should always send. If it is not possible to send
// we will not worry since we will soon be back for
// a renewed trial.
//-------------------------------------------------
struct timeval no_timeout = {0,0};
if(sendIsPossible(&no_timeout)) {
//-------------------------------------------------
// Send was possible, attempt at a send.
//-------------------------------------------------
doSend();
}//if
}
}
#define DISCONNECT_ERRNO(e, sz) ((sz == 0) || \
(!((sz == -1) && (e == EAGAIN) || (e == EWOULDBLOCK) || (e == EINTR))))
bool
TCP_Transporter::doSend() {
// If no sendbuffers are used nothing is done
// Sends the contents of the SendBuffers until they are empty
// or until select does not select the socket for write.
// Before calling send, the socket must be selected for write
// using "select"
// It writes on the external TCP/IP interface until the send buffer is empty
// and as long as write is possible (test it using select)
// Empty the SendBuffers
const char * const sendPtr = m_sendBuffer.sendPtr;
const Uint32 sizeToSend = m_sendBuffer.sendDataSize;
if (sizeToSend > 0){
const int nBytesSent = inet_send(theSocket, sendPtr, sizeToSend, 0);
if (nBytesSent > 0) {
m_sendBuffer.bytesSent(nBytesSent);
sendCount ++;
sendSize += nBytesSent;
if(sendCount == reportFreq){
reportSendLen(get_callback_obj(), remoteNodeId, sendCount, sendSize);
sendCount = 0;
sendSize = 0;
}
} else {
// Send failed
#if defined DEBUG_TRANSPORTER
ndbout_c("Send Failure(disconnect==%d) to node = %d nBytesSent = %d "
"errno = %d strerror = %s",
DISCONNECT_ERRNO(InetErrno, nBytesSent),
remoteNodeId, nBytesSent, InetErrno,
(char*)ndbstrerror(InetErrno));
#endif
if(DISCONNECT_ERRNO(InetErrno, nBytesSent)){
doDisconnect();
report_disconnect(InetErrno);
}
return false;
}
}
return true;
}
int
TCP_Transporter::doReceive() {
// Select-function must return the socket for read
// before this method is called
// It reads the external TCP/IP interface once
Uint32 size = receiveBuffer.sizeOfBuffer - receiveBuffer.sizeOfData;
if(size > 0){
const int nBytesRead = recv(theSocket,
receiveBuffer.insertPtr,
size < maxReceiveSize ? size : maxReceiveSize,
0);
if (nBytesRead > 0) {
receiveBuffer.sizeOfData += nBytesRead;
receiveBuffer.insertPtr += nBytesRead;
if(receiveBuffer.sizeOfData > receiveBuffer.sizeOfBuffer){
#ifdef DEBUG_TRANSPORTER
ndbout_c("receiveBuffer.sizeOfData(%d) > receiveBuffer.sizeOfBuffer(%d)",
receiveBuffer.sizeOfData, receiveBuffer.sizeOfBuffer);
ndbout_c("nBytesRead = %d", nBytesRead);
#endif
ndbout_c("receiveBuffer.sizeOfData(%d) > receiveBuffer.sizeOfBuffer(%d)",
receiveBuffer.sizeOfData, receiveBuffer.sizeOfBuffer);
report_error(TE_INVALID_MESSAGE_LENGTH);
return 0;
}
receiveCount ++;
receiveSize += nBytesRead;
if(receiveCount == reportFreq){
reportReceiveLen(get_callback_obj(), remoteNodeId, receiveCount, receiveSize);
receiveCount = 0;
receiveSize = 0;
}
return nBytesRead;
} else {
#if defined DEBUG_TRANSPORTER
ndbout_c("Receive Failure(disconnect==%d) to node = %d nBytesSent = %d "
"errno = %d strerror = %s",
DISCONNECT_ERRNO(InetErrno, nBytesRead),
remoteNodeId, nBytesRead, InetErrno,
(char*)ndbstrerror(InetErrno));
#endif
if(DISCONNECT_ERRNO(InetErrno, nBytesRead)){
// The remote node has closed down
doDisconnect();
report_disconnect(InetErrno);
}
}
return nBytesRead;
} else {
return 0;
}
}
void
TCP_Transporter::disconnectImpl() {
if(theSocket != NDB_INVALID_SOCKET){
if(NDB_CLOSE_SOCKET(theSocket) < 0){
report_error(TE_ERROR_CLOSING_SOCKET);
}
}
// Empty send och receive buffers
receiveBuffer.clear();
m_sendBuffer.emptyBuffer();
theSocket = NDB_INVALID_SOCKET;
}
<commit_msg>BUG#24793 Add SO_KEEPALIVE socket option to avoid cluster nodes keeping dead connections forever.<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; version 2 of the License.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */
#include <ndb_global.h>
#include <NdbTCP.h>
#include "TCP_Transporter.hpp"
#include <NdbOut.hpp>
#include <NdbSleep.h>
// End of stuff to be moved
#if defined NDB_OSE || defined NDB_SOFTOSE
#define inet_send inet_send
#else
#define inet_send send
#endif
#ifdef NDB_WIN32
class ndbstrerror
{
public:
ndbstrerror(int iError);
~ndbstrerror(void);
operator char*(void) { return m_szError; };
private:
int m_iError;
char* m_szError;
};
ndbstrerror::ndbstrerror(int iError)
: m_iError(iError)
{
FormatMessage(
FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
0,
iError,
MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
(LPTSTR)&m_szError,
0,
0);
}
ndbstrerror::~ndbstrerror(void)
{
LocalFree( m_szError );
m_szError = 0;
}
#else
#define ndbstrerror strerror
#endif
TCP_Transporter::TCP_Transporter(TransporterRegistry &t_reg,
int sendBufSize, int maxRecvSize,
const char *lHostName,
const char *rHostName,
int r_port,
bool isMgmConnection,
NodeId lNodeId,
NodeId rNodeId,
NodeId serverNodeId,
bool chksm, bool signalId,
Uint32 _reportFreq) :
Transporter(t_reg, tt_TCP_TRANSPORTER,
lHostName, rHostName, r_port, isMgmConnection,
lNodeId, rNodeId, serverNodeId,
0, false, chksm, signalId),
m_sendBuffer(sendBufSize)
{
maxReceiveSize = maxRecvSize;
// Initialize member variables
theSocket = NDB_INVALID_SOCKET;
sendCount = receiveCount = 0;
sendSize = receiveSize = 0;
reportFreq = _reportFreq;
sockOptRcvBufSize = 70080;
sockOptSndBufSize = 71540;
sockOptNodelay = 1;
sockOptTcpMaxSeg = 4096;
}
TCP_Transporter::~TCP_Transporter() {
// Disconnect
if (theSocket != NDB_INVALID_SOCKET)
doDisconnect();
// Delete send buffers
// Delete receive buffer!!
receiveBuffer.destroy();
}
bool TCP_Transporter::connect_server_impl(NDB_SOCKET_TYPE sockfd)
{
DBUG_ENTER("TCP_Transpporter::connect_server_impl");
DBUG_RETURN(connect_common(sockfd));
}
bool TCP_Transporter::connect_client_impl(NDB_SOCKET_TYPE sockfd)
{
DBUG_ENTER("TCP_Transpporter::connect_client_impl");
DBUG_RETURN(connect_common(sockfd));
}
bool TCP_Transporter::connect_common(NDB_SOCKET_TYPE sockfd)
{
theSocket = sockfd;
setSocketOptions();
setSocketNonBlocking(theSocket);
DBUG_PRINT("info", ("Successfully set-up TCP transporter to node %d",
remoteNodeId));
return true;
}
bool
TCP_Transporter::initTransporter() {
// Allocate buffer for receiving
// Let it be the maximum size we receive plus 8 kB for any earlier received
// incomplete messages (slack)
Uint32 recBufSize = maxReceiveSize;
if(recBufSize < MAX_MESSAGE_SIZE){
recBufSize = MAX_MESSAGE_SIZE;
}
if(!receiveBuffer.init(recBufSize+MAX_MESSAGE_SIZE)){
return false;
}
// Allocate buffers for sending
if (!m_sendBuffer.initBuffer(remoteNodeId)) {
// XXX What shall be done here?
// The same is valid for the other init-methods
return false;
}
return true;
}
void
TCP_Transporter::setSocketOptions(){
int sockOptKeepAlive = 1;
if (setsockopt(theSocket, SOL_SOCKET, SO_RCVBUF,
(char*)&sockOptRcvBufSize, sizeof(sockOptRcvBufSize)) < 0) {
#ifdef DEBUG_TRANSPORTER
ndbout_c("The setsockopt SO_RCVBUF error code = %d", InetErrno);
#endif
}//if
if (setsockopt(theSocket, SOL_SOCKET, SO_SNDBUF,
(char*)&sockOptSndBufSize, sizeof(sockOptSndBufSize)) < 0) {
#ifdef DEBUG_TRANSPORTER
ndbout_c("The setsockopt SO_SNDBUF error code = %d", InetErrno);
#endif
}//if
if (setsockopt(theSocket, SOL_SOCKET, SO_KEEPALIVE,
(char*)&sockOptKeepAlive, sizeof(sockOptKeepAlive)) < 0) {
ndbout_c("The setsockopt SO_KEEPALIVE error code = %d", InetErrno);
}//if
//-----------------------------------------------
// Set the TCP_NODELAY option so also small packets are sent
// as soon as possible
//-----------------------------------------------
if (setsockopt(theSocket, IPPROTO_TCP, TCP_NODELAY,
(char*)&sockOptNodelay, sizeof(sockOptNodelay)) < 0) {
#ifdef DEBUG_TRANSPORTER
ndbout_c("The setsockopt TCP_NODELAY error code = %d", InetErrno);
#endif
}//if
}
#ifdef NDB_WIN32
bool
TCP_Transporter::setSocketNonBlocking(NDB_SOCKET_TYPE socket){
unsigned long ul = 1;
if(ioctlsocket(socket, FIONBIO, &ul))
{
#ifdef DEBUG_TRANSPORTER
ndbout_c("Set non-blocking server error3: %d", InetErrno);
#endif
}//if
return true;
}
#else
bool
TCP_Transporter::setSocketNonBlocking(NDB_SOCKET_TYPE socket){
int flags;
flags = fcntl(socket, F_GETFL, 0);
if (flags < 0) {
#ifdef DEBUG_TRANSPORTER
ndbout_c("Set non-blocking server error1: %s", strerror(InetErrno));
#endif
}//if
flags |= NDB_NONBLOCK;
if (fcntl(socket, F_SETFL, flags) == -1) {
#ifdef DEBUG_TRANSPORTER
ndbout_c("Set non-blocking server error2: %s", strerror(InetErrno));
#endif
}//if
return true;
}
#endif
bool
TCP_Transporter::sendIsPossible(struct timeval * timeout) {
#ifdef NDB_OSE
/**
* In OSE you cant do select without owning a socket,
* and since this method might be called by any thread in the api
* we choose not to implementet and always return true after sleeping
* a while.
*
* Note that this only sensible as long as the sockets are non blocking
*/
if(theSocket >= 0){
Uint32 timeOutMillis = timeout->tv_sec * 1000 + timeout->tv_usec / 1000;
NdbSleep_MilliSleep(timeOutMillis);
return true;
}
return false;
#else
if(theSocket != NDB_INVALID_SOCKET){
fd_set writeset;
FD_ZERO(&writeset);
FD_SET(theSocket, &writeset);
int selectReply = select(theSocket + 1, NULL, &writeset, NULL, timeout);
if ((selectReply > 0) && FD_ISSET(theSocket, &writeset))
return true;
else
return false;
}
return false;
#endif
}
Uint32
TCP_Transporter::get_free_buffer() const
{
return m_sendBuffer.bufferSizeRemaining();
}
Uint32 *
TCP_Transporter::getWritePtr(Uint32 lenBytes, Uint32 prio){
Uint32 * insertPtr = m_sendBuffer.getInsertPtr(lenBytes);
struct timeval timeout = {0, 10000};
if (insertPtr == 0) {
//-------------------------------------------------
// Buffer was completely full. We have severe problems.
// We will attempt to wait for a small time
//-------------------------------------------------
if(sendIsPossible(&timeout)) {
//-------------------------------------------------
// Send is possible after the small timeout.
//-------------------------------------------------
if(!doSend()){
return 0;
} else {
//-------------------------------------------------
// Since send was successful we will make a renewed
// attempt at inserting the signal into the buffer.
//-------------------------------------------------
insertPtr = m_sendBuffer.getInsertPtr(lenBytes);
}//if
} else {
return 0;
}//if
}
return insertPtr;
}
void
TCP_Transporter::updateWritePtr(Uint32 lenBytes, Uint32 prio){
m_sendBuffer.updateInsertPtr(lenBytes);
const int bufsize = m_sendBuffer.bufferSize();
if(bufsize > TCP_SEND_LIMIT) {
//-------------------------------------------------
// Buffer is full and we are ready to send. We will
// not wait since the signal is already in the buffer.
// Force flag set has the same indication that we
// should always send. If it is not possible to send
// we will not worry since we will soon be back for
// a renewed trial.
//-------------------------------------------------
struct timeval no_timeout = {0,0};
if(sendIsPossible(&no_timeout)) {
//-------------------------------------------------
// Send was possible, attempt at a send.
//-------------------------------------------------
doSend();
}//if
}
}
#define DISCONNECT_ERRNO(e, sz) ((sz == 0) || \
(!((sz == -1) && (e == EAGAIN) || (e == EWOULDBLOCK) || (e == EINTR))))
bool
TCP_Transporter::doSend() {
// If no sendbuffers are used nothing is done
// Sends the contents of the SendBuffers until they are empty
// or until select does not select the socket for write.
// Before calling send, the socket must be selected for write
// using "select"
// It writes on the external TCP/IP interface until the send buffer is empty
// and as long as write is possible (test it using select)
// Empty the SendBuffers
const char * const sendPtr = m_sendBuffer.sendPtr;
const Uint32 sizeToSend = m_sendBuffer.sendDataSize;
if (sizeToSend > 0){
const int nBytesSent = inet_send(theSocket, sendPtr, sizeToSend, 0);
if (nBytesSent > 0) {
m_sendBuffer.bytesSent(nBytesSent);
sendCount ++;
sendSize += nBytesSent;
if(sendCount == reportFreq){
reportSendLen(get_callback_obj(), remoteNodeId, sendCount, sendSize);
sendCount = 0;
sendSize = 0;
}
} else {
// Send failed
#if defined DEBUG_TRANSPORTER
ndbout_c("Send Failure(disconnect==%d) to node = %d nBytesSent = %d "
"errno = %d strerror = %s",
DISCONNECT_ERRNO(InetErrno, nBytesSent),
remoteNodeId, nBytesSent, InetErrno,
(char*)ndbstrerror(InetErrno));
#endif
if(DISCONNECT_ERRNO(InetErrno, nBytesSent)){
doDisconnect();
report_disconnect(InetErrno);
}
return false;
}
}
return true;
}
int
TCP_Transporter::doReceive() {
// Select-function must return the socket for read
// before this method is called
// It reads the external TCP/IP interface once
Uint32 size = receiveBuffer.sizeOfBuffer - receiveBuffer.sizeOfData;
if(size > 0){
const int nBytesRead = recv(theSocket,
receiveBuffer.insertPtr,
size < maxReceiveSize ? size : maxReceiveSize,
0);
if (nBytesRead > 0) {
receiveBuffer.sizeOfData += nBytesRead;
receiveBuffer.insertPtr += nBytesRead;
if(receiveBuffer.sizeOfData > receiveBuffer.sizeOfBuffer){
#ifdef DEBUG_TRANSPORTER
ndbout_c("receiveBuffer.sizeOfData(%d) > receiveBuffer.sizeOfBuffer(%d)",
receiveBuffer.sizeOfData, receiveBuffer.sizeOfBuffer);
ndbout_c("nBytesRead = %d", nBytesRead);
#endif
ndbout_c("receiveBuffer.sizeOfData(%d) > receiveBuffer.sizeOfBuffer(%d)",
receiveBuffer.sizeOfData, receiveBuffer.sizeOfBuffer);
report_error(TE_INVALID_MESSAGE_LENGTH);
return 0;
}
receiveCount ++;
receiveSize += nBytesRead;
if(receiveCount == reportFreq){
reportReceiveLen(get_callback_obj(), remoteNodeId, receiveCount, receiveSize);
receiveCount = 0;
receiveSize = 0;
}
return nBytesRead;
} else {
#if defined DEBUG_TRANSPORTER
ndbout_c("Receive Failure(disconnect==%d) to node = %d nBytesSent = %d "
"errno = %d strerror = %s",
DISCONNECT_ERRNO(InetErrno, nBytesRead),
remoteNodeId, nBytesRead, InetErrno,
(char*)ndbstrerror(InetErrno));
#endif
if(DISCONNECT_ERRNO(InetErrno, nBytesRead)){
// The remote node has closed down
doDisconnect();
report_disconnect(InetErrno);
}
}
return nBytesRead;
} else {
return 0;
}
}
void
TCP_Transporter::disconnectImpl() {
if(theSocket != NDB_INVALID_SOCKET){
if(NDB_CLOSE_SOCKET(theSocket) < 0){
report_error(TE_ERROR_CLOSING_SOCKET);
}
}
// Empty send och receive buffers
receiveBuffer.clear();
m_sendBuffer.emptyBuffer();
theSocket = NDB_INVALID_SOCKET;
}
<|endoftext|>
|
<commit_before>//===--- CFG.cpp - Defines the CFG data structure ----------------*- C++ -*-==//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
#include "swift/CFG/CFG.h"
#include "swift/AST/AST.h"
#include "swift/AST/ASTVisitor.h"
#include "llvm/ADT/OwningPtr.h"
using namespace swift;
CFG::CFG() {}
CFG::~CFG() {
// FIXME: if all parts of BasicBlock are BumpPtrAllocated, this shouldn't
// eventually be needed.
for (BasicBlock &B : BlockList) {
B.~BasicBlock();
}
}
//===----------------------------------------------------------------------===//
// CFG construction.
//===----------------------------------------------------------------------===//
static Expr *ignoreParens(Expr *Ex) {
while (ParenExpr *P = dyn_cast<ParenExpr>(Ex))
Ex = P->getSubExpr();
return Ex;
}
static bool hasTerminator(BasicBlock *BB) {
return !BB->empty() && isa<TermInst>(BB->getInsts().back());
}
namespace {
class CFGBuilder : public ASTVisitor<CFGBuilder, CFGValue> {
typedef llvm::SmallVector<BasicBlock *, 4> BlocksVector;
BlocksVector BasePendingMerges;
llvm::SmallVector<BlocksVector *, 4> PendingMergesStack;
llvm::SmallVector<BlocksVector *, 4> BreakStack;
llvm::SmallVector<BlocksVector *, 4> ContinueStack;
/// Mapping from expressions to instructions.
llvm::DenseMap<Expr *, Instruction *> ExprToInst;
/// The current basic block being constructed.
BasicBlock *Block;
/// The CFG being constructed.
CFG &C;
public:
CFGBuilder(CFG &C) : Block(0), C(C), badCFG(false) {
PendingMergesStack.push_back(&BasePendingMerges);
}
~CFGBuilder() {}
/// A flag indicating whether or not there were problems
/// constructing the CFG.
bool badCFG;
BlocksVector &pendingMerges() {
assert(!PendingMergesStack.empty());
return *PendingMergesStack.back();
}
void flushPending(BasicBlock *TargetBlock) {
for (auto PredBlock : pendingMerges()) {
// If the block has no terminator, we need to add an unconditional
// jump to the block we are creating.
if (!hasTerminator(PredBlock)) {
UncondBranchInst *UB = new (C) UncondBranchInst(PredBlock);
UB->setTarget(TargetBlock, ArrayRef<CFGValue>());
continue;
}
TermInst &Term = *PredBlock->getTerminator();
if (UncondBranchInst *UBI = dyn_cast<UncondBranchInst>(&Term)) {
assert(UBI->targetBlock() == nullptr);
UBI->setTarget(TargetBlock, ArrayRef<CFGValue>());
continue;
}
// If the block already has a CondBranch terminator, then it means
// we are fixing up one of the branch targets because it wasn't
// available when the instruction was created.
CondBranchInst &CBI = cast<CondBranchInst>(Term);
assert(CBI.branches()[0]);
assert(!CBI.branches()[1]);
CBI.branches()[1] = TargetBlock;
TargetBlock->addPred(PredBlock);
}
pendingMerges().clear();
}
/// The current basic block being constructed.
BasicBlock *currentBlock() {
if (!Block) {
Block = new (C) BasicBlock(&C);
// Flush out all pending merges. These are basic blocks waiting
// for a successor.
flushPending(Block);
}
return Block;
}
void addCurrentBlockToPending() {
if (Block && !hasTerminator(Block))
pendingMerges().push_back(Block);
Block = 0;
}
/// Reset the currently active basic block by creating a new one.
BasicBlock *createFreshBlock() {
Block = new (C) BasicBlock(&C);
return Block;
}
CFGValue addInst(Expr *Ex, Instruction *I) {
ExprToInst[Ex] = I;
return I;
}
void finishUp() {
assert(PendingMergesStack.size() == 1);
if (!pendingMerges().empty()) {
assert(Block == 0);
new (C) ReturnInst(currentBlock());
return;
}
// Check if the last block has a Return.
if (!Block)
return;
if (Block->empty() || !isa<ReturnInst>(Block->getInsts().back()))
new (C) ReturnInst(Block);
}
void popBreakStack(BlocksVector &BlocksThatBreak) {
assert(BreakStack.back() == &BlocksThatBreak);
for (auto BreakBlock : BlocksThatBreak) {
pendingMerges().push_back(BreakBlock);
}
BreakStack.pop_back();
}
void popContinueStack(BlocksVector &BlocksThatContinue,
BasicBlock *TargetBlock) {
assert(ContinueStack.back() == &BlocksThatContinue);
for (auto ContinueBlock : BlocksThatContinue) {
auto UB = cast<UncondBranchInst>(ContinueBlock->getTerminator());
UB->setTarget(TargetBlock, ArrayRef<CFGValue>());
}
ContinueStack.pop_back();
}
//===--------------------------------------------------------------------===//
// Statements.
//===--------------------------------------------------------------------===//
/// Construct the CFG components for the given BraceStmt.
void visitBraceStmt(BraceStmt *S);
/// SemiStmts are ignored for CFG construction.
void visitSemiStmt(SemiStmt *S) {}
void visitAssignStmt(AssignStmt *S) {
assert(false && "Not yet implemented");
}
void visitReturnStmt(ReturnStmt *S) {
CFGValue ArgV = S->hasResult() ? visit(S->getResult()) : (Instruction*) 0;
(void) new (C) ReturnInst(S, ArgV, currentBlock());
// Treat the current block as "complete" with no successors.
Block = 0;
}
void visitIfStmt(IfStmt *S);
void visitWhileStmt(WhileStmt *S);
void visitDoWhileStmt(DoWhileStmt *S);
void visitForStmt(ForStmt *S) {
assert(false && "Not yet implemented");
}
void visitForEachStmt(ForEachStmt *S) {
badCFG = true;
return;
}
void visitBreakStmt(BreakStmt *S);
void visitContinueStmt(ContinueStmt *S);
//===--------------------------------------------------------------------===//
// Expressions.
//===--------------------------------------------------------------------===//
CFGValue visitExpr(Expr *E) {
llvm_unreachable("Not yet implemented");
}
CFGValue visitCallExpr(CallExpr *E);
CFGValue visitDeclRefExpr(DeclRefExpr *E);
CFGValue visitIntegerLiteralExpr(IntegerLiteralExpr *E);
CFGValue visitLoadExpr(LoadExpr *E);
CFGValue visitParenExpr(ParenExpr *E);
CFGValue visitThisApplyExpr(ThisApplyExpr *E);
CFGValue visitTupleExpr(TupleExpr *E);
CFGValue visitTypeOfExpr(TypeOfExpr *E);
};
} // end anonymous namespace
CFG *CFG::constructCFG(Stmt *S) {
// FIXME: implement CFG construction.
llvm::OwningPtr<CFG> C(new CFG());
CFGBuilder builder(*C);
builder.visit(S);
if (!builder.badCFG) {
builder.finishUp();
C->verify();
return C.take();
}
return nullptr;
}
void CFGBuilder::visitBraceStmt(BraceStmt *S) {
// BraceStmts do not need to be explicitly represented in the CFG.
// We should consider whether or not the scopes they introduce are
// represented in the CFG.
for (const BraceStmt::ExprStmtOrDecl &ESD : S->getElements()) {
assert(!ESD.is<Decl*>() && "FIXME: Handle Decls");
if (Stmt *S = ESD.dyn_cast<Stmt*>())
visit(S);
if (Expr *E = ESD.dyn_cast<Expr*>())
visit(E);
}
}
//===--------------------------------------------------------------------===//
// Control-flow.
//===--------------------------------------------------------------------===//
void CFGBuilder::visitBreakStmt(BreakStmt *S) {
assert(!BreakStack.empty());
BasicBlock *BreakBlock = currentBlock();
BreakStack.back()->push_back(BreakBlock);
// FIXME: we need to be able to include the BreakStmt in the jump.
new (C) UncondBranchInst(BreakBlock);
Block = 0;
}
void CFGBuilder::visitContinueStmt(ContinueStmt *S) {
assert(!ContinueStack.empty());
BasicBlock *ContinueBlock = currentBlock();
ContinueStack.back()->push_back(ContinueBlock);
// FIXME: we need to be able to include the ContinueStmt in the jump.
new (C) UncondBranchInst(ContinueBlock);
Block = 0;
}
void CFGBuilder::visitDoWhileStmt(DoWhileStmt *S) {
// Set up a vector to record blocks that 'break'.
BlocksVector BlocksThatBreak;
BreakStack.push_back(&BlocksThatBreak);
// Set up a vector to record blocks that 'continue'.
BlocksVector BlocksThatContinue;
ContinueStack.push_back(&BlocksThatContinue);
// Create a new basic block for the body.
addCurrentBlockToPending();
BasicBlock *BodyBlock = currentBlock();
// Push a new context to record pending blocks. These will
// get linked up the condition block.
BlocksVector PendingWithinLoop;
PendingMergesStack.push_back(&PendingWithinLoop);
// Now visit the loop body.
visit(S->getBody());
addCurrentBlockToPending();
// Create the condition block.
BasicBlock *ConditionBlock = currentBlock();
CFGValue CondV = (Instruction*) 0;
// visit(S->getCond());
assert(ConditionBlock == Block);
Block = 0;
// Pop the pending merges.
assert(PendingMergesStack.back() == &PendingWithinLoop);
flushPending(ConditionBlock);
PendingMergesStack.pop_back();
// Pop the 'break' context.
popBreakStack(BlocksThatBreak);
// Pop the 'continue' context.
popContinueStack(BlocksThatContinue, ConditionBlock);
// Finally, hook up the block with the condition to the target blocks.
CFGValue Branch = new (C) CondBranchInst(S, CondV,
BodyBlock,
0, /* will be fixed up later */
ConditionBlock);
(void) Branch;
pendingMerges().push_back(ConditionBlock);
}
void CFGBuilder::visitIfStmt(IfStmt *S) {
// ** FIXME ** Handle the condition. We need to handle more of the
// statements first.
// The condition should be the last value evaluated just before the
// terminator.
// CFGValue CondV = visit(S->getCond());
CFGValue CondV = (Instruction*) 0;
// Save the current block. We will use it to construct the
// CondBranchInst.
BasicBlock *IfTermBlock = currentBlock();
// Reset the state for the current block.
Block = 0;
// Create a new basic block for the first target.
BasicBlock *Target1 = createFreshBlock();
visit(S->getThenStmt());
addCurrentBlockToPending();
// Handle an (optional) 'else'. If no 'else' is found, the false branch
// will be fixed up later.
BasicBlock *Target2 = nullptr;
if (Stmt *Else = S->getElseStmt()) {
// Create a new basic block for the second target. The first target's
// blocks will get added the "pending" list.
Target2 = createFreshBlock();
visit(Else);
addCurrentBlockToPending();
}
else {
// If we have no 'else', we need to fix up the branch later.
pendingMerges().push_back(IfTermBlock);
}
// Finally, hook up the block with the condition to the target blocks.
CFGValue Branch = new (C) CondBranchInst(S, CondV,
Target1,
Target2 /* may be null*/,
IfTermBlock);
(void) Branch;
}
void CFGBuilder::visitWhileStmt(WhileStmt *S) {
// The condition needs to be in its own basic block so that
// it can be the loop-back target. We thus finish up the currently
// active block. It will get linked to the new block once we
// create it.
addCurrentBlockToPending();
// Process the condition. This will link up the previous block
// with the condition block.
BasicBlock *ConditionBlock = currentBlock();
CFGValue CondV = (Instruction*) 0;
// visit(S->getCond());
assert(ConditionBlock == Block);
Block = 0;
// Set up a vector to record blocks that 'break'.
BlocksVector BlocksThatBreak;
BreakStack.push_back(&BlocksThatBreak);
// Set up a vector to record blocks that 'continue'.
BlocksVector BlocksThatContinue;
ContinueStack.push_back(&BlocksThatContinue);
// Push a new context to record pending blocks. These will
// get linked up the condition block.
BlocksVector PendingWithinLoop;
PendingMergesStack.push_back(&PendingWithinLoop);
// Create a new basic block for the body.
BasicBlock *BodyBlock = createFreshBlock();
visit(S->getBody());
addCurrentBlockToPending();
// Pop the pending merges.
assert(PendingMergesStack.back() == &PendingWithinLoop);
flushPending(ConditionBlock);
PendingMergesStack.pop_back();
// Pop the 'break' context.
popBreakStack(BlocksThatBreak);
// Pop the 'continue' context.
popContinueStack(BlocksThatContinue, ConditionBlock);
// Finally, hook up the block with the condition to the target blocks.
CFGValue Branch = new (C) CondBranchInst(S, CondV,
BodyBlock,
0, /* will be fixed up later */
ConditionBlock);
(void) Branch;
pendingMerges().push_back(ConditionBlock);
}
//===--------------------------------------------------------------------===//
// Expressions.
//===--------------------------------------------------------------------===//
CFGValue CFGBuilder::visitCallExpr(CallExpr *E) {
Expr *Arg = ignoreParens(E->getArg());
Expr *Fn = E->getFn();
CFGValue FnV = visit(Fn);
llvm::SmallVector<CFGValue, 10> ArgsV;
// Special case Arg being a TupleExpr, to inline the arguments and
// not create another instruction.
if (TupleExpr *TU = dyn_cast<TupleExpr>(Arg)) {
for (auto arg : TU->getElements())
ArgsV.push_back(visit(arg));
}
else {
ArgsV.push_back(visit(Arg));
}
return addInst(E, CallInst::create(E, currentBlock(), FnV, ArgsV));
}
CFGValue CFGBuilder::visitDeclRefExpr(DeclRefExpr *E) {
return addInst(E, new (C) DeclRefInst(E, currentBlock()));
}
CFGValue CFGBuilder::visitThisApplyExpr(ThisApplyExpr *E) {
CFGValue FnV = visit(E->getFn());
CFGValue ArgV = visit(E->getArg());
return addInst(E, new (C) ThisApplyInst(E, FnV, ArgV, currentBlock()));
}
CFGValue CFGBuilder::visitIntegerLiteralExpr(IntegerLiteralExpr *E) {
return addInst(E, new (C) IntegerLiteralInst(E, currentBlock()));
}
CFGValue CFGBuilder::visitLoadExpr(LoadExpr *E) {
CFGValue SubV = visit(E->getSubExpr());
return addInst(E, new (C) LoadInst(E, SubV, currentBlock()));
}
CFGValue CFGBuilder::visitParenExpr(ParenExpr *E) {
return visit(E->getSubExpr());
}
CFGValue CFGBuilder::visitTupleExpr(TupleExpr *E) {
llvm::SmallVector<CFGValue, 10> ArgsV;
for (auto &I : E->getElements()) {
ArgsV.push_back(visit(I));
}
return addInst(E, TupleInst::create(E, ArgsV, currentBlock()));
}
CFGValue CFGBuilder::visitTypeOfExpr(TypeOfExpr *E) {
return addInst(E, new (C) TypeOfInst(E, currentBlock()));
}
<commit_msg>rename CFGBuilder class, I want the name for something else.<commit_after>//===--- CFG.cpp - Defines the CFG data structure ----------------*- C++ -*-==//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
#include "swift/CFG/CFG.h"
#include "swift/AST/AST.h"
#include "swift/AST/ASTVisitor.h"
#include "llvm/ADT/OwningPtr.h"
using namespace swift;
CFG::CFG() {}
CFG::~CFG() {
// FIXME: if all parts of BasicBlock are BumpPtrAllocated, this shouldn't
// eventually be needed.
for (BasicBlock &B : BlockList) {
B.~BasicBlock();
}
}
//===----------------------------------------------------------------------===//
// CFG construction.
//===----------------------------------------------------------------------===//
static Expr *ignoreParens(Expr *Ex) {
while (ParenExpr *P = dyn_cast<ParenExpr>(Ex))
Ex = P->getSubExpr();
return Ex;
}
static bool hasTerminator(BasicBlock *BB) {
return !BB->empty() && isa<TermInst>(BB->getInsts().back());
}
namespace {
class Builder : public ASTVisitor<Builder, CFGValue> {
typedef llvm::SmallVector<BasicBlock *, 4> BlocksVector;
BlocksVector BasePendingMerges;
llvm::SmallVector<BlocksVector *, 4> PendingMergesStack;
llvm::SmallVector<BlocksVector *, 4> BreakStack;
llvm::SmallVector<BlocksVector *, 4> ContinueStack;
/// Mapping from expressions to instructions.
llvm::DenseMap<Expr *, Instruction *> ExprToInst;
/// The current basic block being constructed.
BasicBlock *Block;
/// The CFG being constructed.
CFG &C;
public:
Builder(CFG &C) : Block(0), C(C), badCFG(false) {
PendingMergesStack.push_back(&BasePendingMerges);
}
~Builder() {}
/// A flag indicating whether or not there were problems
/// constructing the CFG.
bool badCFG;
BlocksVector &pendingMerges() {
assert(!PendingMergesStack.empty());
return *PendingMergesStack.back();
}
void flushPending(BasicBlock *TargetBlock) {
for (auto PredBlock : pendingMerges()) {
// If the block has no terminator, we need to add an unconditional
// jump to the block we are creating.
if (!hasTerminator(PredBlock)) {
UncondBranchInst *UB = new (C) UncondBranchInst(PredBlock);
UB->setTarget(TargetBlock, ArrayRef<CFGValue>());
continue;
}
TermInst &Term = *PredBlock->getTerminator();
if (UncondBranchInst *UBI = dyn_cast<UncondBranchInst>(&Term)) {
assert(UBI->targetBlock() == nullptr);
UBI->setTarget(TargetBlock, ArrayRef<CFGValue>());
continue;
}
// If the block already has a CondBranch terminator, then it means
// we are fixing up one of the branch targets because it wasn't
// available when the instruction was created.
CondBranchInst &CBI = cast<CondBranchInst>(Term);
assert(CBI.branches()[0]);
assert(!CBI.branches()[1]);
CBI.branches()[1] = TargetBlock;
TargetBlock->addPred(PredBlock);
}
pendingMerges().clear();
}
/// The current basic block being constructed.
BasicBlock *currentBlock() {
if (!Block) {
Block = new (C) BasicBlock(&C);
// Flush out all pending merges. These are basic blocks waiting
// for a successor.
flushPending(Block);
}
return Block;
}
void addCurrentBlockToPending() {
if (Block && !hasTerminator(Block))
pendingMerges().push_back(Block);
Block = 0;
}
/// Reset the currently active basic block by creating a new one.
BasicBlock *createFreshBlock() {
Block = new (C) BasicBlock(&C);
return Block;
}
CFGValue addInst(Expr *Ex, Instruction *I) {
ExprToInst[Ex] = I;
return I;
}
void finishUp() {
assert(PendingMergesStack.size() == 1);
if (!pendingMerges().empty()) {
assert(Block == 0);
new (C) ReturnInst(currentBlock());
return;
}
// Check if the last block has a Return.
if (!Block)
return;
if (Block->empty() || !isa<ReturnInst>(Block->getInsts().back()))
new (C) ReturnInst(Block);
}
void popBreakStack(BlocksVector &BlocksThatBreak) {
assert(BreakStack.back() == &BlocksThatBreak);
for (auto BreakBlock : BlocksThatBreak) {
pendingMerges().push_back(BreakBlock);
}
BreakStack.pop_back();
}
void popContinueStack(BlocksVector &BlocksThatContinue,
BasicBlock *TargetBlock) {
assert(ContinueStack.back() == &BlocksThatContinue);
for (auto ContinueBlock : BlocksThatContinue) {
auto UB = cast<UncondBranchInst>(ContinueBlock->getTerminator());
UB->setTarget(TargetBlock, ArrayRef<CFGValue>());
}
ContinueStack.pop_back();
}
//===--------------------------------------------------------------------===//
// Statements.
//===--------------------------------------------------------------------===//
/// Construct the CFG components for the given BraceStmt.
void visitBraceStmt(BraceStmt *S);
/// SemiStmts are ignored for CFG construction.
void visitSemiStmt(SemiStmt *S) {}
void visitAssignStmt(AssignStmt *S) {
assert(false && "Not yet implemented");
}
void visitReturnStmt(ReturnStmt *S) {
CFGValue ArgV = S->hasResult() ? visit(S->getResult()) : (Instruction*) 0;
(void) new (C) ReturnInst(S, ArgV, currentBlock());
// Treat the current block as "complete" with no successors.
Block = 0;
}
void visitIfStmt(IfStmt *S);
void visitWhileStmt(WhileStmt *S);
void visitDoWhileStmt(DoWhileStmt *S);
void visitForStmt(ForStmt *S) {
assert(false && "Not yet implemented");
}
void visitForEachStmt(ForEachStmt *S) {
badCFG = true;
return;
}
void visitBreakStmt(BreakStmt *S);
void visitContinueStmt(ContinueStmt *S);
//===--------------------------------------------------------------------===//
// Expressions.
//===--------------------------------------------------------------------===//
CFGValue visitExpr(Expr *E) {
llvm_unreachable("Not yet implemented");
}
CFGValue visitCallExpr(CallExpr *E);
CFGValue visitDeclRefExpr(DeclRefExpr *E);
CFGValue visitIntegerLiteralExpr(IntegerLiteralExpr *E);
CFGValue visitLoadExpr(LoadExpr *E);
CFGValue visitParenExpr(ParenExpr *E);
CFGValue visitThisApplyExpr(ThisApplyExpr *E);
CFGValue visitTupleExpr(TupleExpr *E);
CFGValue visitTypeOfExpr(TypeOfExpr *E);
};
} // end anonymous namespace
CFG *CFG::constructCFG(Stmt *S) {
// FIXME: implement CFG construction.
llvm::OwningPtr<CFG> C(new CFG());
Builder builder(*C);
builder.visit(S);
if (!builder.badCFG) {
builder.finishUp();
C->verify();
return C.take();
}
return nullptr;
}
void Builder::visitBraceStmt(BraceStmt *S) {
// BraceStmts do not need to be explicitly represented in the CFG.
// We should consider whether or not the scopes they introduce are
// represented in the CFG.
for (const BraceStmt::ExprStmtOrDecl &ESD : S->getElements()) {
assert(!ESD.is<Decl*>() && "FIXME: Handle Decls");
if (Stmt *S = ESD.dyn_cast<Stmt*>())
visit(S);
if (Expr *E = ESD.dyn_cast<Expr*>())
visit(E);
}
}
//===--------------------------------------------------------------------===//
// Control-flow.
//===--------------------------------------------------------------------===//
void Builder::visitBreakStmt(BreakStmt *S) {
assert(!BreakStack.empty());
BasicBlock *BreakBlock = currentBlock();
BreakStack.back()->push_back(BreakBlock);
// FIXME: we need to be able to include the BreakStmt in the jump.
new (C) UncondBranchInst(BreakBlock);
Block = 0;
}
void Builder::visitContinueStmt(ContinueStmt *S) {
assert(!ContinueStack.empty());
BasicBlock *ContinueBlock = currentBlock();
ContinueStack.back()->push_back(ContinueBlock);
// FIXME: we need to be able to include the ContinueStmt in the jump.
new (C) UncondBranchInst(ContinueBlock);
Block = 0;
}
void Builder::visitDoWhileStmt(DoWhileStmt *S) {
// Set up a vector to record blocks that 'break'.
BlocksVector BlocksThatBreak;
BreakStack.push_back(&BlocksThatBreak);
// Set up a vector to record blocks that 'continue'.
BlocksVector BlocksThatContinue;
ContinueStack.push_back(&BlocksThatContinue);
// Create a new basic block for the body.
addCurrentBlockToPending();
BasicBlock *BodyBlock = currentBlock();
// Push a new context to record pending blocks. These will
// get linked up the condition block.
BlocksVector PendingWithinLoop;
PendingMergesStack.push_back(&PendingWithinLoop);
// Now visit the loop body.
visit(S->getBody());
addCurrentBlockToPending();
// Create the condition block.
BasicBlock *ConditionBlock = currentBlock();
CFGValue CondV = (Instruction*) 0;
// visit(S->getCond());
assert(ConditionBlock == Block);
Block = 0;
// Pop the pending merges.
assert(PendingMergesStack.back() == &PendingWithinLoop);
flushPending(ConditionBlock);
PendingMergesStack.pop_back();
// Pop the 'break' context.
popBreakStack(BlocksThatBreak);
// Pop the 'continue' context.
popContinueStack(BlocksThatContinue, ConditionBlock);
// Finally, hook up the block with the condition to the target blocks.
CFGValue Branch = new (C) CondBranchInst(S, CondV,
BodyBlock,
0, /* will be fixed up later */
ConditionBlock);
(void) Branch;
pendingMerges().push_back(ConditionBlock);
}
void Builder::visitIfStmt(IfStmt *S) {
// ** FIXME ** Handle the condition. We need to handle more of the
// statements first.
// The condition should be the last value evaluated just before the
// terminator.
// CFGValue CondV = visit(S->getCond());
CFGValue CondV = (Instruction*) 0;
// Save the current block. We will use it to construct the
// CondBranchInst.
BasicBlock *IfTermBlock = currentBlock();
// Reset the state for the current block.
Block = 0;
// Create a new basic block for the first target.
BasicBlock *Target1 = createFreshBlock();
visit(S->getThenStmt());
addCurrentBlockToPending();
// Handle an (optional) 'else'. If no 'else' is found, the false branch
// will be fixed up later.
BasicBlock *Target2 = nullptr;
if (Stmt *Else = S->getElseStmt()) {
// Create a new basic block for the second target. The first target's
// blocks will get added the "pending" list.
Target2 = createFreshBlock();
visit(Else);
addCurrentBlockToPending();
}
else {
// If we have no 'else', we need to fix up the branch later.
pendingMerges().push_back(IfTermBlock);
}
// Finally, hook up the block with the condition to the target blocks.
CFGValue Branch = new (C) CondBranchInst(S, CondV,
Target1,
Target2 /* may be null*/,
IfTermBlock);
(void) Branch;
}
void Builder::visitWhileStmt(WhileStmt *S) {
// The condition needs to be in its own basic block so that
// it can be the loop-back target. We thus finish up the currently
// active block. It will get linked to the new block once we
// create it.
addCurrentBlockToPending();
// Process the condition. This will link up the previous block
// with the condition block.
BasicBlock *ConditionBlock = currentBlock();
CFGValue CondV = (Instruction*) 0;
// visit(S->getCond());
assert(ConditionBlock == Block);
Block = 0;
// Set up a vector to record blocks that 'break'.
BlocksVector BlocksThatBreak;
BreakStack.push_back(&BlocksThatBreak);
// Set up a vector to record blocks that 'continue'.
BlocksVector BlocksThatContinue;
ContinueStack.push_back(&BlocksThatContinue);
// Push a new context to record pending blocks. These will
// get linked up the condition block.
BlocksVector PendingWithinLoop;
PendingMergesStack.push_back(&PendingWithinLoop);
// Create a new basic block for the body.
BasicBlock *BodyBlock = createFreshBlock();
visit(S->getBody());
addCurrentBlockToPending();
// Pop the pending merges.
assert(PendingMergesStack.back() == &PendingWithinLoop);
flushPending(ConditionBlock);
PendingMergesStack.pop_back();
// Pop the 'break' context.
popBreakStack(BlocksThatBreak);
// Pop the 'continue' context.
popContinueStack(BlocksThatContinue, ConditionBlock);
// Finally, hook up the block with the condition to the target blocks.
CFGValue Branch = new (C) CondBranchInst(S, CondV,
BodyBlock,
0, /* will be fixed up later */
ConditionBlock);
(void) Branch;
pendingMerges().push_back(ConditionBlock);
}
//===--------------------------------------------------------------------===//
// Expressions.
//===--------------------------------------------------------------------===//
CFGValue Builder::visitCallExpr(CallExpr *E) {
Expr *Arg = ignoreParens(E->getArg());
Expr *Fn = E->getFn();
CFGValue FnV = visit(Fn);
llvm::SmallVector<CFGValue, 10> ArgsV;
// Special case Arg being a TupleExpr, to inline the arguments and
// not create another instruction.
if (TupleExpr *TU = dyn_cast<TupleExpr>(Arg)) {
for (auto arg : TU->getElements())
ArgsV.push_back(visit(arg));
}
else {
ArgsV.push_back(visit(Arg));
}
return addInst(E, CallInst::create(E, currentBlock(), FnV, ArgsV));
}
CFGValue Builder::visitDeclRefExpr(DeclRefExpr *E) {
return addInst(E, new (C) DeclRefInst(E, currentBlock()));
}
CFGValue Builder::visitThisApplyExpr(ThisApplyExpr *E) {
CFGValue FnV = visit(E->getFn());
CFGValue ArgV = visit(E->getArg());
return addInst(E, new (C) ThisApplyInst(E, FnV, ArgV, currentBlock()));
}
CFGValue Builder::visitIntegerLiteralExpr(IntegerLiteralExpr *E) {
return addInst(E, new (C) IntegerLiteralInst(E, currentBlock()));
}
CFGValue Builder::visitLoadExpr(LoadExpr *E) {
CFGValue SubV = visit(E->getSubExpr());
return addInst(E, new (C) LoadInst(E, SubV, currentBlock()));
}
CFGValue Builder::visitParenExpr(ParenExpr *E) {
return visit(E->getSubExpr());
}
CFGValue Builder::visitTupleExpr(TupleExpr *E) {
llvm::SmallVector<CFGValue, 10> ArgsV;
for (auto &I : E->getElements()) {
ArgsV.push_back(visit(I));
}
return addInst(E, TupleInst::create(E, ArgsV, currentBlock()));
}
CFGValue Builder::visitTypeOfExpr(TypeOfExpr *E) {
return addInst(E, new (C) TypeOfInst(E, currentBlock()));
}
<|endoftext|>
|
<commit_before>/**
* @file pi_calc.c
* @brief
* @author Travis Lane
* @version
* @date 2014-11-11
*/
#ifdef PARALLEL_PI_USE_CILK
#include <parallel_pi_cilk.h>
#include <cilk/cilk.h>
#include <cilk/reducer_opadd.h>
double
cilk_estimate_pi(int32_t radius, uint64_t total_iterations)
{
const uint64_t squared_radius = (uint64_t) radius * (uint64_t) radius;
cilk::reducer_opadd<uint64_t> total_inside(0);
cilk_for(uint64_t i = 0; i < total_iterations; i++) {
std::random_device rd;
std::mt19937 gen(rd());
std::uniform_int_distribution<int32_t> dist(-radius, radius);
x = dist(gen);
y = dist(gen);
if(IsInsideCircle(squared_radius, x, y))
total_inside++;
}
// Figure out what our estimate was.
return ((double) total_inside.get_value() / (double) total_iterations) * 4.0;
}
#endif
<commit_msg>Fixed bug<commit_after>/**
* @file pi_calc.c
* @brief
* @author Travis Lane
* @version
* @date 2014-11-11
*/
#ifdef PARALLEL_PI_USE_CILK
#include <parallel_pi_cilk.h>
#include <cilk/cilk.h>
#include <cilk/reducer_opadd.h>
double
cilk_estimate_pi(int32_t radius, uint64_t total_iterations)
{
const uint64_t squared_radius = (uint64_t) radius * (uint64_t) radius;
cilk::reducer_opadd<uint64_t> total_inside(0);
cilk_for(uint64_t i = 0; i < total_iterations; i++) {
int32_t x, y;
std::random_device rd;
std::mt19937 gen(rd());
std::uniform_int_distribution<int32_t> dist(-radius, radius);
x = dist(gen);
y = dist(gen);
if(IsInsideCircle(squared_radius, x, y))
total_inside++;
}
// Figure out what our estimate was.
return ((double) total_inside.get_value() / (double) total_iterations) * 4.0;
}
#endif
<|endoftext|>
|
<commit_before>#include "parameters_parser.hh"
namespace Kakoune
{
String generate_switches_doc(const SwitchMap& switches)
{
String res;
for (auto& sw : switches)
res += " -" + sw.first + (sw.second.takes_arg ? " <arg>: " : ": ") + sw.second.description + "\n";
return res;
}
ParametersParser::ParametersParser(ParameterList params,
const ParameterDesc& desc)
: m_params(params),
m_desc(desc)
{
bool only_pos = desc.flags & ParameterDesc::Flags::SwitchesAsPositional;
for (size_t i = 0; i < params.size(); ++i)
{
if (params[i] == "--")
only_pos = true;
else if (not only_pos and params[i][0] == '-')
{
auto it = m_desc.switches.find(params[i].substr(1_byte));
if (it == m_desc.switches.end())
throw unknown_option(params[i]);
if (it->second.takes_arg)
{
++i;
if (i == params.size() or params[i][0] == '-')
throw missing_option_value(params[i]);
}
}
else
{
if (desc.flags & ParameterDesc::Flags::SwitchesOnlyAtStart)
only_pos = true;
m_positional_indices.push_back(i);
}
}
size_t count = m_positional_indices.size();
if (count > desc.max_positionals or count < desc.min_positionals)
throw wrong_argument_count();
}
bool ParametersParser::has_option(const String& name) const
{
kak_assert(m_desc.switches.find(name) != m_desc.switches.end());
for (auto& param : m_params)
{
if (param[0] == '-' and param.substr(1_byte) == name)
return true;
if (param == "--")
break;
}
return false;
}
const String& ParametersParser::option_value(const String& name) const
{
#ifdef KAK_DEBUG
auto it = m_desc.switches.find(name);
kak_assert(it != m_desc.switches.end());
kak_assert(it->second.takes_arg);
#endif
for (size_t i = 0; i < m_params.size(); ++i)
{
if (m_params[i][0] == '-' and m_params[i].substr(1_byte) == name)
return m_params[i+1];
if (m_params[i] == "--")
break;
}
static String empty;
return empty;
}
size_t ParametersParser::positional_count() const
{
return m_positional_indices.size();
}
const String& ParametersParser::operator[] (size_t index) const
{
kak_assert(index < positional_count());
return m_params[m_positional_indices[index]];
}
ParametersParser::iterator ParametersParser::begin() const
{
return iterator(*this, 0);
}
ParametersParser::iterator ParametersParser::end() const
{
return iterator(*this, m_positional_indices.size());
}
}
<commit_msg>fix segfault in parameter parser<commit_after>#include "parameters_parser.hh"
namespace Kakoune
{
String generate_switches_doc(const SwitchMap& switches)
{
String res;
for (auto& sw : switches)
res += " -" + sw.first + (sw.second.takes_arg ? " <arg>: " : ": ") + sw.second.description + "\n";
return res;
}
ParametersParser::ParametersParser(ParameterList params,
const ParameterDesc& desc)
: m_params(params),
m_desc(desc)
{
bool only_pos = desc.flags & ParameterDesc::Flags::SwitchesAsPositional;
for (size_t i = 0; i < params.size(); ++i)
{
if (params[i] == "--")
only_pos = true;
else if (not only_pos and params[i][0] == '-')
{
auto it = m_desc.switches.find(params[i].substr(1_byte));
if (it == m_desc.switches.end())
throw unknown_option(params[i]);
if (it->second.takes_arg)
{
++i;
if (i == params.size() or params[i][0] == '-')
throw missing_option_value(it->first);
}
}
else
{
if (desc.flags & ParameterDesc::Flags::SwitchesOnlyAtStart)
only_pos = true;
m_positional_indices.push_back(i);
}
}
size_t count = m_positional_indices.size();
if (count > desc.max_positionals or count < desc.min_positionals)
throw wrong_argument_count();
}
bool ParametersParser::has_option(const String& name) const
{
kak_assert(m_desc.switches.find(name) != m_desc.switches.end());
for (auto& param : m_params)
{
if (param[0] == '-' and param.substr(1_byte) == name)
return true;
if (param == "--")
break;
}
return false;
}
const String& ParametersParser::option_value(const String& name) const
{
#ifdef KAK_DEBUG
auto it = m_desc.switches.find(name);
kak_assert(it != m_desc.switches.end());
kak_assert(it->second.takes_arg);
#endif
for (size_t i = 0; i < m_params.size(); ++i)
{
if (m_params[i][0] == '-' and m_params[i].substr(1_byte) == name)
return m_params[i+1];
if (m_params[i] == "--")
break;
}
static String empty;
return empty;
}
size_t ParametersParser::positional_count() const
{
return m_positional_indices.size();
}
const String& ParametersParser::operator[] (size_t index) const
{
kak_assert(index < positional_count());
return m_params[m_positional_indices[index]];
}
ParametersParser::iterator ParametersParser::begin() const
{
return iterator(*this, 0);
}
ParametersParser::iterator ParametersParser::end() const
{
return iterator(*this, m_positional_indices.size());
}
}
<|endoftext|>
|
<commit_before>// Copyright (c) 2015-2016 Andrew Sutton
// All rights reserved
#include "initialization.hpp"
#include "ast-type.hpp"
#include "ast-expr.hpp"
#include "conversion.hpp"
#include "inheritance.hpp"
#include "builder.hpp"
#include "printer.hpp"
#include <iostream>
namespace banjo
{
// FIXME: Initialization does not apply to dependent types or
// expressions. We should either extend the definition to accommodate
// them gracefully, or we should simply return a placeholder for
// the notation.
// Select a zero-initialization procedure for an object or
// reference of type `t`. Note that zero initialization never
// chooses a constructor.
//
// TODO: What about sequence types and incomplete types?
// Presumably object types are required to be complete prior
// to initialization (i.e., we need the size for memset).
//
// It's possible that T[] counts as a scalar (that's what it
// code-gens to).
Expr&
zero_initialize(Context& cxt, Type& t)
{
lingo_assert(!is_function_type(t));
Builder build(cxt);
// No initialization is performed for reference types.
if (is_reference_type(t))
return build.make_trivial_init(t);
// Zero initialize each sub-object in turn.
if (is_array_type(t))
lingo_unreachable();
if (is_dynarray_type(t))
lingo_unreachable();
Type& u = t.unqualified_type();
// FIXME: Determine the kind of zero that best matches the
// type (i.e., produce an appropriate literal).
if (is_scalar_type(u))
return build.make_copy_init(t, build.get_zero(t));
// FIXME: I'm not sure that we should have an error here.
throw std::runtime_error("cannot zero initialize type");
}
// Select a default initialization procedure for an object
// of type `t`.
//
// TODO: What about sequence types? What does it mean to
// default initialize a T[].
//
// TODO: Consider making these 0 initialized by defualt and
// using a special syntax to select trivial initialization.
Expr&
default_initialize(Context& cxt, Type& t)
{
Builder build(cxt);
if (is_reference_type(t))
throw std::runtime_error("default initialization of reference");
// Select a default initializer for each sub-object.
if (is_array_type(t))
lingo_unreachable();
// Otherwise, no initialization is performed.
return build.make_trivial_init(t);
}
// Select a procedure to value-initialize an object.
Expr&
value_initialize(Context& cxt, Type& t)
{
Builder build(cxt);
if (is_reference_type(t))
throw Translation_error("value initialization of reference");
// FIXME: Can you value initialize a T[]?
if (is_array_type(t))
lingo_unreachable();
// Are we sure that there are no other categories of types?
return zero_initialize(cxt, t);
}
// Select a procedure to copy initialize an object or reference of type
// `t` by an expression `e`. This corresponds to the initialization of
// a variable by the syntax:
//
// T x = e;
//
// This also applies in parameter passing, function return, exception
// throwing, and handling.
Expr&
copy_initialize(Context& cxt, Type& t, Expr& e)
{
Builder build(cxt);
// If the destination type is a T&, then perform reference
// initialization.
if (is_reference_type(t))
return reference_initialize(cxt, cast<Reference_type>(t), e);
// Otherwise, If the target type is dependent, perform dependent
// conversions.
if (is_dependent_type(t)) {
Expr& c = dependent_conversion(cxt, e, t);
return cxt.make_copy_init(t, c);
}
// If the destination type is T[N] or T[] and the initializer
// is `= s` where `s` is a string literal, perform string
// initialization.
if (is_array_type(t)) {
Expr& a_expr = array_initialize(t, e);
return cxt.make_copy_init(t, a_expr);
// banjo_unhandled_case(t);
}
if (is_tuple_type(t)) {
Expr& t_expr = tuple_initialize(t,e);
return cxt.make_copy_init(t,t_expr);
}
// If the initializer has a source type, then try to find a
// user-defined conversion from s to the destination type, which
// should be a (possibly qualified) fundamental type.
Type& s = e.type();
// If the source type is dependent, search for dependent conversions.
if (is_dependent_type(s)) {
Expr& c = dependent_conversion(cxt, e, t);
return cxt.make_copy_init(t, c);
}
// If all else fails, try a standard conversion. This should be the
// case that we have a non-class, fundamental, or dependent type.
//
// TODO: Catch exceptions and restructure the error with
// the conversion error as an explanation.
Expr& c = standard_conversion(e, t);
return build.make_copy_init(t, c);
}
//Array compared with array
Expr&
array_initialize(Type& t, Expr& e)
{
Type& et = e.type();
if(is_equivalent(t,et))
return e;
if(is_tuple_type(e.type())) {
return array_tuple_init(t,e);
}
}
//tuple compared with tuple
Expr&
tuple_initialize(Type& t, Expr& e)
{
Type& et = e.type();
if(is_equivalent(t,et))
return e;
if(is_array_type(e.type())) {
return tuple_array_init(t,e);
}
}
//e has array type
Expr&
tuple_array_init(Type& t, Expr& e)
{
if(is_tuple_equiv_to_array(t,e.type()))
return e;
throw std::runtime_error("cannot initialize tuple with array type");
}
//e has tuple type
Expr&
array_tuple_init(Type& t, Expr& e)
{
if(is_tuple_equiv_to_array(e.type(),t) {
return e;
}
throw std::runtime_error("cannot initialize array with tuple type");
}
// Select a procedure to direct-initialize an object or reference of
// type `t` by a paren-enclosed list of expressions `es`. This corresponds
// to the initialization of a variable by the syntax:
//
// T x(e1, e2, ..., en);
//
// When the list of expressions is empty, this selects value
// initialization.
//
// This also applies in new expressions, etc.
Expr&
direct_initialize(Context& cxt, Type& t, Expr_list& es)
{
// Arrays must be copy or list-initialized.
//
// FIXME: Provide a better diagnostic.
if (is_array_type(t))
throw Translation_error("invalid array initialization");
// If the initializer is (), the object is value initialized.
if (es.empty())
return value_initialize(cxt, t);
Expr& e = es.front();
// If the destination type is a T&, then perform reference
// initialization on the only element in the list of expressions.
if (is_reference_type(t))
return reference_initialize(cxt, cast<Reference_type>(t), e);
// Otherwise, If the target type is dependent, perform dependent
// conversions.
//
// FIXME: Why does this result in copy initialization?
if (is_dependent_type(t)) {
Expr& c = dependent_conversion(cxt, e, t);
return cxt.make_copy_init(t, c);
}
// If the initializer has a source type, then try to find a
// user-defined conversion from s to the destination type, which
// should be a (possibly qualified) fundamental type.
Type& s = e.type();
// Otherwise, If the target type is dependent, perform dependent
// conversions.
//
// FIXME: Why does this result in copy initialization?
if (is_dependent_type(s)) {
Expr& c = dependent_conversion(cxt, e, t);
return cxt.make_copy_init(t, c);
}
// If all else fails, try a a standard conversion. This should be
// the case that we have a non-class, fundamental type.
//
// TODO: Catch exceptions and restructure the error with
// the conversion error as an explanation.
Expr& c = standard_conversion(e, t);
return cxt.make_copy_init(t, c);
}
// Perform direct initialization from a single operand.
//
// TODO: We can optimize by simply duplicating cases from above.
Expr&
direct_initialize(Context& cxt, Type& t, Expr& e)
{
Expr_list args {&e};
return direct_initialize(cxt, t, args);
}
// -------------------------------------------------------------------------- //
// List initialization
// Select a procedure to direct-initialize an object or reference of
// type `t` by a brace-enclosed list of expressions `es`. This corresponds
// to the initialization of a variable by the syntax:
//
// T x{e1, e2, ..., en};
//
// When the list of expressions is empty, this selects value
// initialization.
//
// TODO: Implement me.
Expr&
list_initialize(Context& cxt, Type& t, Expr_list& es)
{
lingo_unreachable();
}
// -------------------------------------------------------------------------- //
// Reference initialization
// A type q-T1 is reference-related to a type q-T2 if T1 and T2 are
// the same type or T1 is a base class of T2.
//
// TODO: Implement the base class test.
bool
is_reference_related(Type const& t1, Type const& t2)
{
Type const& u1 = t1.unqualified_type();
Type const& u2 = t2.unqualified_type();
return is_equivalent(u1, u2);
}
// Two types q1-t1 and q-t2 are reference compatible if 1 is
// reference-related to t2, and q1 is a superset of q2 (i.e.,
// t1 is as qualified as or more qualified than t2).
//
// TODO: Check for ambiguous base classes.
bool
is_reference_compatible(Type const& t1, Type const& t2)
{
if (is_reference_related(t1, t2)) {
Qualifier_set q1 = t1.qualifier();
Qualifier_set q2 = t2.qualifier();
return is_superset(q1, q2);
}
return false;
}
// Select an initialization of the refernce type `t1` by an expression
// `e`.
//
// NOTE: This doesn't currently handle rvalue references (because the
// language doesn't define them).
//
// TODO: A reference binding may invoke a conversion in order
// to bind to a sub-objet or a user-defined conversion. However,
// these aren't conversions in the standard sense.
//
// TODO: Finish implementing me.
Expr&
reference_initialize(Context& cxt, Reference_type& t1, Expr& e)
{
Type& r1 = t1.non_reference_type();
// The initializer has reference type.
Type& t2 = e.type();
if (is_reference_type(t2)) {
Type& r2 = t2.non_reference_type();
// If t1 is reference-compatible with t2, then t1 binds directly
// to the initializer. This is true for dependent types also.
//
// TODO: If we bind to a base class, we might need to apply a
// base class conversion in order to explicitly adjust pointer
// offsets.
if (is_reference_compatible(r1, r2))
return cxt.make_bind_init(t1, e);
}
// The reference must be a const reference.
//
// TODO: Handle const reference bindings to compound objects.
if (t1.type().qualifier() == const_qual) {
}
// TODO: Handle bindings to temporaries.
throw Type_error("reference binding");
}
// -------------------------------------------------------------------------- //
// Aggregate initialization
Expr&
aggregate_initialize(Context& cxt, Type& t, Expr_list& i)
{
lingo_unreachable();
}
} // namespace banjo
<commit_msg>Compiles...might work?:<commit_after>// Copyright (c) 2015-2016 Andrew Sutton
// All rights reserved
#include "initialization.hpp"
#include "ast-type.hpp"
#include "ast-expr.hpp"
#include "conversion.hpp"
#include "inheritance.hpp"
#include "builder.hpp"
#include "printer.hpp"
#include <iostream>
namespace banjo
{
// FIXME: Initialization does not apply to dependent types or
// expressions. We should either extend the definition to accommodate
// them gracefully, or we should simply return a placeholder for
// the notation.
// Select a zero-initialization procedure for an object or
// reference of type `t`. Note that zero initialization never
// chooses a constructor.
//
// TODO: What about sequence types and incomplete types?
// Presumably object types are required to be complete prior
// to initialization (i.e., we need the size for memset).
//
// It's possible that T[] counts as a scalar (that's what it
// code-gens to).
Expr&
zero_initialize(Context& cxt, Type& t)
{
lingo_assert(!is_function_type(t));
Builder build(cxt);
// No initialization is performed for reference types.
if (is_reference_type(t))
return build.make_trivial_init(t);
// Zero initialize each sub-object in turn.
if (is_array_type(t))
lingo_unreachable();
if (is_dynarray_type(t))
lingo_unreachable();
Type& u = t.unqualified_type();
// FIXME: Determine the kind of zero that best matches the
// type (i.e., produce an appropriate literal).
if (is_scalar_type(u))
return build.make_copy_init(t, build.get_zero(t));
// FIXME: I'm not sure that we should have an error here.
throw std::runtime_error("cannot zero initialize type");
}
// Select a default initialization procedure for an object
// of type `t`.
//
// TODO: What about sequence types? What does it mean to
// default initialize a T[].
//
// TODO: Consider making these 0 initialized by defualt and
// using a special syntax to select trivial initialization.
Expr&
default_initialize(Context& cxt, Type& t)
{
Builder build(cxt);
if (is_reference_type(t))
throw std::runtime_error("default initialization of reference");
// Select a default initializer for each sub-object.
if (is_array_type(t))
lingo_unreachable();
// Otherwise, no initialization is performed.
return build.make_trivial_init(t);
}
// Select a procedure to value-initialize an object.
Expr&
value_initialize(Context& cxt, Type& t)
{
Builder build(cxt);
if (is_reference_type(t))
throw Translation_error("value initialization of reference");
// FIXME: Can you value initialize a T[]?
if (is_array_type(t))
lingo_unreachable();
// Are we sure that there are no other categories of types?
return zero_initialize(cxt, t);
}
// Select a procedure to copy initialize an object or reference of type
// `t` by an expression `e`. This corresponds to the initialization of
// a variable by the syntax:
//
// T x = e;
//
// This also applies in parameter passing, function return, exception
// throwing, and handling.
Expr&
copy_initialize(Context& cxt, Type& t, Expr& e)
{
Builder build(cxt);
// If the destination type is a T&, then perform reference
// initialization.
if (is_reference_type(t))
return reference_initialize(cxt, cast<Reference_type>(t), e);
// Otherwise, If the target type is dependent, perform dependent
// conversions.
if (is_dependent_type(t)) {
Expr& c = dependent_conversion(cxt, e, t);
return cxt.make_copy_init(t, c);
}
// If the destination type is T[N] or T[] and the initializer
// is `= s` where `s` is a string literal, perform string
// initialization.
if (is_array_type(t)) {
Expr& a_expr = array_initialize(t, e);
return cxt.make_copy_init(t, a_expr);
// banjo_unhandled_case(t);
}
if (is_tuple_type(t)) {
Expr& t_expr = tuple_initialize(t,e);
return cxt.make_copy_init(t,t_expr);
}
// If the initializer has a source type, then try to find a
// user-defined conversion from s to the destination type, which
// should be a (possibly qualified) fundamental type.
Type& s = e.type();
// If the source type is dependent, search for dependent conversions.
if (is_dependent_type(s)) {
Expr& c = dependent_conversion(cxt, e, t);
return cxt.make_copy_init(t, c);
}
// If all else fails, try a standard conversion. This should be the
// case that we have a non-class, fundamental, or dependent type.
//
// TODO: Catch exceptions and restructure the error with
// the conversion error as an explanation.
Expr& c = standard_conversion(e, t);
return build.make_copy_init(t, c);
}
//Array compared with array or tuple
Expr&
array_initialize(Type& t, Expr& e)
{
Type& et = e.type();
if(is_equivalent(t,et))
return e;
if(is_tuple_type(e.type())) {
return array_tuple_init(t,e);
}
throw std::runtime_error("cannot initialize array type");
}
//tuple compared with tuple or array
Expr&
tuple_initialize(Type& t, Expr& e)
{
Type& et = e.type();
if(is_equivalent(t,et))
return e;
if(is_array_type(e.type())) {
return tuple_array_init(t,e);
}
throw std::runtime_error("cannot initialize tuple type");
}
//e has array type
Expr&
tuple_array_init(Type& t, Expr& e)
{
Tuple_type& tt = as<Tuple_type>(t);
Array_type& at = as<Array_type>(e.type());
if(is_tuple_equiv_to_array(tt,at))
return e;
throw std::runtime_error("cannot initialize tuple with array type");
}
//e has tuple type
Expr&
array_tuple_init(Type& t, Expr& e)
{
Tuple_type& tt = as<Tuple_type>(e);
Array_type& at = as<Array_type>(e.type());
if(is_tuple_equiv_to_array(tt,at)) {
return e;
}
throw std::runtime_error("cannot initialize array with tuple type");
}
// Select a procedure to direct-initialize an object or reference of
// type `t` by a paren-enclosed list of expressions `es`. This corresponds
// to the initialization of a variable by the syntax:
//
// T x(e1, e2, ..., en);
//
// When the list of expressions is empty, this selects value
// initialization.
//
// This also applies in new expressions, etc.
Expr&
direct_initialize(Context& cxt, Type& t, Expr_list& es)
{
// Arrays must be copy or list-initialized.
//
// FIXME: Provide a better diagnostic.
if (is_array_type(t))
throw Translation_error("invalid array initialization");
// If the initializer is (), the object is value initialized.
if (es.empty())
return value_initialize(cxt, t);
Expr& e = es.front();
// If the destination type is a T&, then perform reference
// initialization on the only element in the list of expressions.
if (is_reference_type(t))
return reference_initialize(cxt, cast<Reference_type>(t), e);
// Otherwise, If the target type is dependent, perform dependent
// conversions.
//
// FIXME: Why does this result in copy initialization?
if (is_dependent_type(t)) {
Expr& c = dependent_conversion(cxt, e, t);
return cxt.make_copy_init(t, c);
}
// If the initializer has a source type, then try to find a
// user-defined conversion from s to the destination type, which
// should be a (possibly qualified) fundamental type.
Type& s = e.type();
// Otherwise, If the target type is dependent, perform dependent
// conversions.
//
// FIXME: Why does this result in copy initialization?
if (is_dependent_type(s)) {
Expr& c = dependent_conversion(cxt, e, t);
return cxt.make_copy_init(t, c);
}
// If all else fails, try a a standard conversion. This should be
// the case that we have a non-class, fundamental type.
//
// TODO: Catch exceptions and restructure the error with
// the conversion error as an explanation.
Expr& c = standard_conversion(e, t);
return cxt.make_copy_init(t, c);
}
// Perform direct initialization from a single operand.
//
// TODO: We can optimize by simply duplicating cases from above.
Expr&
direct_initialize(Context& cxt, Type& t, Expr& e)
{
Expr_list args {&e};
return direct_initialize(cxt, t, args);
}
// -------------------------------------------------------------------------- //
// List initialization
// Select a procedure to direct-initialize an object or reference of
// type `t` by a brace-enclosed list of expressions `es`. This corresponds
// to the initialization of a variable by the syntax:
//
// T x{e1, e2, ..., en};
//
// When the list of expressions is empty, this selects value
// initialization.
//
// TODO: Implement me.
Expr&
list_initialize(Context& cxt, Type& t, Expr_list& es)
{
lingo_unreachable();
}
// -------------------------------------------------------------------------- //
// Reference initialization
// A type q-T1 is reference-related to a type q-T2 if T1 and T2 are
// the same type or T1 is a base class of T2.
//
// TODO: Implement the base class test.
bool
is_reference_related(Type const& t1, Type const& t2)
{
Type const& u1 = t1.unqualified_type();
Type const& u2 = t2.unqualified_type();
return is_equivalent(u1, u2);
}
// Two types q1-t1 and q-t2 are reference compatible if 1 is
// reference-related to t2, and q1 is a superset of q2 (i.e.,
// t1 is as qualified as or more qualified than t2).
//
// TODO: Check for ambiguous base classes.
bool
is_reference_compatible(Type const& t1, Type const& t2)
{
if (is_reference_related(t1, t2)) {
Qualifier_set q1 = t1.qualifier();
Qualifier_set q2 = t2.qualifier();
return is_superset(q1, q2);
}
return false;
}
// Select an initialization of the refernce type `t1` by an expression
// `e`.
//
// NOTE: This doesn't currently handle rvalue references (because the
// language doesn't define them).
//
// TODO: A reference binding may invoke a conversion in order
// to bind to a sub-objet or a user-defined conversion. However,
// these aren't conversions in the standard sense.
//
// TODO: Finish implementing me.
Expr&
reference_initialize(Context& cxt, Reference_type& t1, Expr& e)
{
Type& r1 = t1.non_reference_type();
// The initializer has reference type.
Type& t2 = e.type();
if (is_reference_type(t2)) {
Type& r2 = t2.non_reference_type();
// If t1 is reference-compatible with t2, then t1 binds directly
// to the initializer. This is true for dependent types also.
//
// TODO: If we bind to a base class, we might need to apply a
// base class conversion in order to explicitly adjust pointer
// offsets.
if (is_reference_compatible(r1, r2))
return cxt.make_bind_init(t1, e);
}
// The reference must be a const reference.
//
// TODO: Handle const reference bindings to compound objects.
if (t1.type().qualifier() == const_qual) {
}
// TODO: Handle bindings to temporaries.
throw Type_error("reference binding");
}
// -------------------------------------------------------------------------- //
// Aggregate initialization
Expr&
aggregate_initialize(Context& cxt, Type& t, Expr_list& i)
{
lingo_unreachable();
}
} // namespace banjo
<|endoftext|>
|
<commit_before>// RUN: %clang_analyze_cc1 -analyzer-checker=core,cplusplus.NewDelete -std=c++11 -fblocks -verify %s
// RUN: %clang_analyze_cc1 -analyzer-checker=core,cplusplus.NewDeleteLeaks -DLEAKS -std=c++11 -fblocks -verify %s
// RUN: %clang_analyze_cc1 -analyzer-checker=core,cplusplus.NewDelete -std=c++11 -fblocks -analyzer-config c++-allocator-inlining=true -verify %s
// RUN: %clang_analyze_cc1 -analyzer-checker=core,cplusplus.NewDeleteLeaks -DLEAKS -std=c++11 -fblocks -analyzer-config c++-allocator-inlining=true -verify %s
#include "Inputs/system-header-simulator-cxx.h"
typedef __typeof__(sizeof(int)) size_t;
extern "C" void *malloc(size_t);
extern "C" void free (void* ptr);
int *global;
//------------------
// check for leaks
//------------------
//----- Standard non-placement operators
void testGlobalOpNew() {
void *p = operator new(0);
}
#ifdef LEAKS
// expected-warning@-2{{Potential leak of memory pointed to by 'p'}}
#endif
void testGlobalOpNewArray() {
void *p = operator new[](0);
}
#ifdef LEAKS
// expected-warning@-2{{Potential leak of memory pointed to by 'p'}}
#endif
void testGlobalNewExpr() {
int *p = new int;
}
#ifdef LEAKS
// expected-warning@-2{{Potential leak of memory pointed to by 'p'}}
#endif
void testGlobalNewExprArray() {
int *p = new int[0];
}
#ifdef LEAKS
// expected-warning@-2{{Potential leak of memory pointed to by 'p'}}
#endif
//----- Standard nothrow placement operators
void testGlobalNoThrowPlacementOpNewBeforeOverload() {
void *p = operator new(0, std::nothrow);
}
#ifdef LEAKS
#ifndef TEST_INLINABLE_ALLOCATORS
// expected-warning@-3{{Potential leak of memory pointed to by 'p'}}
#endif
#endif
void testGlobalNoThrowPlacementExprNewBeforeOverload() {
int *p = new(std::nothrow) int;
}
#ifdef LEAKS
#ifndef TEST_INLINABLE_ALLOCATORS
// expected-warning@-3{{Potential leak of memory pointed to by 'p'}}
#endif
#endif
//----- Standard pointer placement operators
void testGlobalPointerPlacementNew() {
int i;
void *p1 = operator new(0, &i); // no warn
void *p2 = operator new[](0, &i); // no warn
int *p3 = new(&i) int; // no warn
int *p4 = new(&i) int[0]; // no warn
}
//----- Other cases
void testNewMemoryIsInHeap() {
int *p = new int;
if (global != p) // condition is always true as 'p' wraps a heap region that
// is different from a region wrapped by 'global'
global = p; // pointer escapes
}
struct PtrWrapper {
int *x;
PtrWrapper(int *input) : x(input) {}
};
void testNewInvalidationPlacement(PtrWrapper *w) {
// Ensure that we don't consider this a leak.
new (w) PtrWrapper(new int); // no warn
}
//-----------------------------------------
// check for usage of zero-allocated memory
//-----------------------------------------
void testUseZeroAlloc1() {
int *p = (int *)operator new(0);
*p = 1; // expected-warning {{Use of zero-allocated memory}}
delete p;
}
int testUseZeroAlloc2() {
int *p = (int *)operator new[](0);
return p[0]; // expected-warning {{Use of zero-allocated memory}}
delete[] p;
}
void f(int);
void testUseZeroAlloc3() {
int *p = new int[0];
f(*p); // expected-warning {{Use of zero-allocated memory}}
delete[] p;
}
//---------------
// other checks
//---------------
class SomeClass {
public:
void f(int *p);
};
void f(int *p1, int *p2 = 0, int *p3 = 0);
void g(SomeClass &c, ...);
void testUseFirstArgAfterDelete() {
int *p = new int;
delete p;
f(p); // expected-warning{{Use of memory after it is freed}}
}
void testUseMiddleArgAfterDelete(int *p) {
delete p;
f(0, p); // expected-warning{{Use of memory after it is freed}}
}
void testUseLastArgAfterDelete(int *p) {
delete p;
f(0, 0, p); // expected-warning{{Use of memory after it is freed}}
}
void testUseSeveralArgsAfterDelete(int *p) {
delete p;
f(p, p, p); // expected-warning{{Use of memory after it is freed}}
}
void testUseRefArgAfterDelete(SomeClass &c) {
delete &c;
g(c); // expected-warning{{Use of memory after it is freed}}
}
void testVariadicArgAfterDelete() {
SomeClass c;
int *p = new int;
delete p;
g(c, 0, p); // expected-warning{{Use of memory after it is freed}}
}
void testUseMethodArgAfterDelete(int *p) {
SomeClass *c = new SomeClass;
delete p;
c->f(p); // expected-warning{{Use of memory after it is freed}}
}
void testUseThisAfterDelete() {
SomeClass *c = new SomeClass;
delete c;
c->f(0); // expected-warning{{Use of memory after it is freed}}
}
void testDoubleDelete() {
int *p = new int;
delete p;
delete p; // expected-warning{{Attempt to free released memory}}
}
void testExprDeleteArg() {
int i;
delete &i; // expected-warning{{Argument to 'delete' is the address of the local variable 'i', which is not memory allocated by 'new'}}
}
void testExprDeleteArrArg() {
int i;
delete[] &i; // expected-warning{{Argument to 'delete[]' is the address of the local variable 'i', which is not memory allocated by 'new[]'}}
}
void testAllocDeallocNames() {
int *p = new(std::nothrow) int[1];
delete[] (++p);
#ifndef TEST_INLINABLE_ALLOCATORS
// expected-warning@-2{{Argument to 'delete[]' is offset by 4 bytes from the start of memory allocated by 'new[]'}}
#endif
}
//--------------------------------
// Test escape of newed const pointer. Note, a const pointer can be deleted.
//--------------------------------
struct StWithConstPtr {
const int *memp;
};
void escape(const int &x);
void escapeStruct(const StWithConstPtr &x);
void escapePtr(const StWithConstPtr *x);
void escapeVoidPtr(const void *x);
void testConstEscape() {
int *p = new int(1);
escape(*p);
} // no-warning
void testConstEscapeStruct() {
StWithConstPtr *St = new StWithConstPtr();
escapeStruct(*St);
} // no-warning
void testConstEscapeStructPtr() {
StWithConstPtr *St = new StWithConstPtr();
escapePtr(St);
} // no-warning
void testConstEscapeMember() {
StWithConstPtr St;
St.memp = new int(2);
escapeVoidPtr(St.memp);
} // no-warning
void testConstEscapePlacementNew() {
int *x = (int *)malloc(sizeof(int));
void *y = new (x) int;
escapeVoidPtr(y);
} // no-warning
//============== Test Uninitialized delete delete[]========================
void testUninitDelete() {
int *x;
int * y = new int;
delete y;
delete x; // expected-warning{{Argument to 'delete' is uninitialized}}
}
void testUninitDeleteArray() {
int *x;
int * y = new int[5];
delete[] y;
delete[] x; // expected-warning{{Argument to 'delete[]' is uninitialized}}
}
void testUninitFree() {
int *x;
free(x); // expected-warning{{1st function call argument is an uninitialized value}}
}
void testUninitDeleteSink() {
int *x;
delete x; // expected-warning{{Argument to 'delete' is uninitialized}}
(*(volatile int *)0 = 1); // no warn
}
void testUninitDeleteArraySink() {
int *x;
delete[] x; // expected-warning{{Argument to 'delete[]' is uninitialized}}
(*(volatile int *)0 = 1); // no warn
}
namespace reference_count {
class control_block {
unsigned count;
public:
control_block() : count(0) {}
void retain() { ++count; }
int release() { return --count; }
};
template <typename T>
class shared_ptr {
T *p;
control_block *control;
public:
shared_ptr() : p(0), control(0) {}
explicit shared_ptr(T *p) : p(p), control(new control_block) {
control->retain();
}
shared_ptr(shared_ptr &other) : p(other.p), control(other.control) {
if (control)
control->retain();
}
~shared_ptr() {
if (control && control->release() == 0) {
delete p;
delete control;
}
};
T &operator *() {
return *p;
};
void swap(shared_ptr &other) {
T *tmp = p;
p = other.p;
other.p = tmp;
control_block *ctrlTmp = control;
control = other.control;
other.control = ctrlTmp;
}
};
void testSingle() {
shared_ptr<int> a(new int);
*a = 1;
}
void testDouble() {
shared_ptr<int> a(new int);
shared_ptr<int> b = a;
*a = 1;
}
void testInvalidated() {
shared_ptr<int> a(new int);
shared_ptr<int> b = a;
*a = 1;
extern void use(shared_ptr<int> &);
use(b);
}
void testNestedScope() {
shared_ptr<int> a(new int);
{
shared_ptr<int> b = a;
}
*a = 1;
}
void testSwap() {
shared_ptr<int> a(new int);
shared_ptr<int> b;
shared_ptr<int> c = a;
shared_ptr<int>(c).swap(b);
}
void testUseAfterFree() {
int *p = new int;
{
shared_ptr<int> a(p);
shared_ptr<int> b = a;
}
// FIXME: We should get a warning here, but we don't because we've
// conservatively modeled ~shared_ptr.
*p = 1;
}
}
// Test double delete
class DerefClass{
public:
int *x;
DerefClass() {}
~DerefClass() {*x = 1;}
};
void testDoubleDeleteClassInstance() {
DerefClass *foo = new DerefClass();
delete foo;
delete foo; // expected-warning {{Attempt to delete released memory}}
}
class EmptyClass{
public:
EmptyClass() {}
~EmptyClass() {}
};
void testDoubleDeleteEmptyClass() {
EmptyClass *foo = new EmptyClass();
delete foo;
delete foo; // expected-warning {{Attempt to delete released memory}}
}
struct Base {
virtual ~Base() {}
};
struct Derived : Base {
};
Base *allocate() {
return new Derived;
}
void shouldNotReportLeak() {
Derived *p = (Derived *)allocate();
delete p;
}
<commit_msg>[analyzer] NFC: Run many existing C++ tests with a custom operator new().<commit_after>// RUN: %clang_analyze_cc1 -analyzer-checker=core,cplusplus.NewDelete -std=c++11 -fblocks -verify %s
// RUN: %clang_analyze_cc1 -analyzer-checker=core,cplusplus.NewDeleteLeaks -DLEAKS -std=c++11 -fblocks -verify %s
// RUN: %clang_analyze_cc1 -analyzer-checker=core,cplusplus.NewDelete -std=c++11 -fblocks -analyzer-config c++-allocator-inlining=true -verify %s
// RUN: %clang_analyze_cc1 -analyzer-checker=core,cplusplus.NewDeleteLeaks -DLEAKS -std=c++11 -fblocks -analyzer-config c++-allocator-inlining=true -verify %s
// RUN: %clang_analyze_cc1 -analyzer-checker=core,cplusplus.NewDelete -std=c++11 -fblocks -DTEST_INLINABLE_ALLOCATORS -verify %s
// RUN: %clang_analyze_cc1 -analyzer-checker=core,cplusplus.NewDeleteLeaks -DLEAKS -std=c++11 -fblocks -DTEST_INLINABLE_ALLOCATORS -verify %s
// RUN: %clang_analyze_cc1 -analyzer-checker=core,cplusplus.NewDelete -std=c++11 -fblocks -analyzer-config c++-allocator-inlining=true -DTEST_INLINABLE_ALLOCATORS -verify %s
// RUN: %clang_analyze_cc1 -analyzer-checker=core,cplusplus.NewDeleteLeaks -DLEAKS -std=c++11 -fblocks -analyzer-config c++-allocator-inlining=true -DTEST_INLINABLE_ALLOCATORS -verify %s
#include "Inputs/system-header-simulator-cxx.h"
typedef __typeof__(sizeof(int)) size_t;
extern "C" void *malloc(size_t);
extern "C" void free (void* ptr);
int *global;
//------------------
// check for leaks
//------------------
//----- Standard non-placement operators
void testGlobalOpNew() {
void *p = operator new(0);
}
#ifdef LEAKS
// expected-warning@-2{{Potential leak of memory pointed to by 'p'}}
#endif
void testGlobalOpNewArray() {
void *p = operator new[](0);
}
#ifdef LEAKS
// expected-warning@-2{{Potential leak of memory pointed to by 'p'}}
#endif
void testGlobalNewExpr() {
int *p = new int;
}
#ifdef LEAKS
// expected-warning@-2{{Potential leak of memory pointed to by 'p'}}
#endif
void testGlobalNewExprArray() {
int *p = new int[0];
}
#ifdef LEAKS
// expected-warning@-2{{Potential leak of memory pointed to by 'p'}}
#endif
//----- Standard nothrow placement operators
void testGlobalNoThrowPlacementOpNewBeforeOverload() {
void *p = operator new(0, std::nothrow);
}
#ifdef LEAKS
#ifndef TEST_INLINABLE_ALLOCATORS
// expected-warning@-3{{Potential leak of memory pointed to by 'p'}}
#endif
#endif
void testGlobalNoThrowPlacementExprNewBeforeOverload() {
int *p = new(std::nothrow) int;
}
#ifdef LEAKS
#ifndef TEST_INLINABLE_ALLOCATORS
// expected-warning@-3{{Potential leak of memory pointed to by 'p'}}
#endif
#endif
//----- Standard pointer placement operators
void testGlobalPointerPlacementNew() {
int i;
void *p1 = operator new(0, &i); // no warn
void *p2 = operator new[](0, &i); // no warn
int *p3 = new(&i) int; // no warn
int *p4 = new(&i) int[0]; // no warn
}
//----- Other cases
void testNewMemoryIsInHeap() {
int *p = new int;
if (global != p) // condition is always true as 'p' wraps a heap region that
// is different from a region wrapped by 'global'
global = p; // pointer escapes
}
struct PtrWrapper {
int *x;
PtrWrapper(int *input) : x(input) {}
};
void testNewInvalidationPlacement(PtrWrapper *w) {
// Ensure that we don't consider this a leak.
new (w) PtrWrapper(new int); // no warn
}
//-----------------------------------------
// check for usage of zero-allocated memory
//-----------------------------------------
void testUseZeroAlloc1() {
int *p = (int *)operator new(0);
*p = 1; // expected-warning {{Use of zero-allocated memory}}
delete p;
}
int testUseZeroAlloc2() {
int *p = (int *)operator new[](0);
return p[0]; // expected-warning {{Use of zero-allocated memory}}
delete[] p;
}
void f(int);
void testUseZeroAlloc3() {
int *p = new int[0];
f(*p); // expected-warning {{Use of zero-allocated memory}}
delete[] p;
}
//---------------
// other checks
//---------------
class SomeClass {
public:
void f(int *p);
};
void f(int *p1, int *p2 = 0, int *p3 = 0);
void g(SomeClass &c, ...);
void testUseFirstArgAfterDelete() {
int *p = new int;
delete p;
f(p); // expected-warning{{Use of memory after it is freed}}
}
void testUseMiddleArgAfterDelete(int *p) {
delete p;
f(0, p); // expected-warning{{Use of memory after it is freed}}
}
void testUseLastArgAfterDelete(int *p) {
delete p;
f(0, 0, p); // expected-warning{{Use of memory after it is freed}}
}
void testUseSeveralArgsAfterDelete(int *p) {
delete p;
f(p, p, p); // expected-warning{{Use of memory after it is freed}}
}
void testUseRefArgAfterDelete(SomeClass &c) {
delete &c;
g(c); // expected-warning{{Use of memory after it is freed}}
}
void testVariadicArgAfterDelete() {
SomeClass c;
int *p = new int;
delete p;
g(c, 0, p); // expected-warning{{Use of memory after it is freed}}
}
void testUseMethodArgAfterDelete(int *p) {
SomeClass *c = new SomeClass;
delete p;
c->f(p); // expected-warning{{Use of memory after it is freed}}
}
void testUseThisAfterDelete() {
SomeClass *c = new SomeClass;
delete c;
c->f(0); // expected-warning{{Use of memory after it is freed}}
}
void testDoubleDelete() {
int *p = new int;
delete p;
delete p; // expected-warning{{Attempt to free released memory}}
}
void testExprDeleteArg() {
int i;
delete &i; // expected-warning{{Argument to 'delete' is the address of the local variable 'i', which is not memory allocated by 'new'}}
}
void testExprDeleteArrArg() {
int i;
delete[] &i; // expected-warning{{Argument to 'delete[]' is the address of the local variable 'i', which is not memory allocated by 'new[]'}}
}
void testAllocDeallocNames() {
int *p = new(std::nothrow) int[1];
delete[] (++p);
#ifndef TEST_INLINABLE_ALLOCATORS
// expected-warning@-2{{Argument to 'delete[]' is offset by 4 bytes from the start of memory allocated by 'new[]'}}
#endif
}
//--------------------------------
// Test escape of newed const pointer. Note, a const pointer can be deleted.
//--------------------------------
struct StWithConstPtr {
const int *memp;
};
void escape(const int &x);
void escapeStruct(const StWithConstPtr &x);
void escapePtr(const StWithConstPtr *x);
void escapeVoidPtr(const void *x);
void testConstEscape() {
int *p = new int(1);
escape(*p);
} // no-warning
void testConstEscapeStruct() {
StWithConstPtr *St = new StWithConstPtr();
escapeStruct(*St);
} // no-warning
void testConstEscapeStructPtr() {
StWithConstPtr *St = new StWithConstPtr();
escapePtr(St);
} // no-warning
void testConstEscapeMember() {
StWithConstPtr St;
St.memp = new int(2);
escapeVoidPtr(St.memp);
} // no-warning
void testConstEscapePlacementNew() {
int *x = (int *)malloc(sizeof(int));
void *y = new (x) int;
escapeVoidPtr(y);
} // no-warning
//============== Test Uninitialized delete delete[]========================
void testUninitDelete() {
int *x;
int * y = new int;
delete y;
delete x; // expected-warning{{Argument to 'delete' is uninitialized}}
}
void testUninitDeleteArray() {
int *x;
int * y = new int[5];
delete[] y;
delete[] x; // expected-warning{{Argument to 'delete[]' is uninitialized}}
}
void testUninitFree() {
int *x;
free(x); // expected-warning{{1st function call argument is an uninitialized value}}
}
void testUninitDeleteSink() {
int *x;
delete x; // expected-warning{{Argument to 'delete' is uninitialized}}
(*(volatile int *)0 = 1); // no warn
}
void testUninitDeleteArraySink() {
int *x;
delete[] x; // expected-warning{{Argument to 'delete[]' is uninitialized}}
(*(volatile int *)0 = 1); // no warn
}
namespace reference_count {
class control_block {
unsigned count;
public:
control_block() : count(0) {}
void retain() { ++count; }
int release() { return --count; }
};
template <typename T>
class shared_ptr {
T *p;
control_block *control;
public:
shared_ptr() : p(0), control(0) {}
explicit shared_ptr(T *p) : p(p), control(new control_block) {
control->retain();
}
shared_ptr(shared_ptr &other) : p(other.p), control(other.control) {
if (control)
control->retain();
}
~shared_ptr() {
if (control && control->release() == 0) {
delete p;
delete control;
}
};
T &operator *() {
return *p;
};
void swap(shared_ptr &other) {
T *tmp = p;
p = other.p;
other.p = tmp;
control_block *ctrlTmp = control;
control = other.control;
other.control = ctrlTmp;
}
};
void testSingle() {
shared_ptr<int> a(new int);
*a = 1;
}
void testDouble() {
shared_ptr<int> a(new int);
shared_ptr<int> b = a;
*a = 1;
}
void testInvalidated() {
shared_ptr<int> a(new int);
shared_ptr<int> b = a;
*a = 1;
extern void use(shared_ptr<int> &);
use(b);
}
void testNestedScope() {
shared_ptr<int> a(new int);
{
shared_ptr<int> b = a;
}
*a = 1;
}
void testSwap() {
shared_ptr<int> a(new int);
shared_ptr<int> b;
shared_ptr<int> c = a;
shared_ptr<int>(c).swap(b);
}
void testUseAfterFree() {
int *p = new int;
{
shared_ptr<int> a(p);
shared_ptr<int> b = a;
}
// FIXME: We should get a warning here, but we don't because we've
// conservatively modeled ~shared_ptr.
*p = 1;
}
}
// Test double delete
class DerefClass{
public:
int *x;
DerefClass() {}
~DerefClass() {*x = 1;}
};
void testDoubleDeleteClassInstance() {
DerefClass *foo = new DerefClass();
delete foo;
delete foo; // expected-warning {{Attempt to delete released memory}}
}
class EmptyClass{
public:
EmptyClass() {}
~EmptyClass() {}
};
void testDoubleDeleteEmptyClass() {
EmptyClass *foo = new EmptyClass();
delete foo;
delete foo; // expected-warning {{Attempt to delete released memory}}
}
struct Base {
virtual ~Base() {}
};
struct Derived : Base {
};
Base *allocate() {
return new Derived;
}
void shouldNotReportLeak() {
Derived *p = (Derived *)allocate();
delete p;
}
<|endoftext|>
|
<commit_before>// RUN: %clang_cc1 -verify -std=c++11 %s
// RUN: %clang_cc1 -xobjective-c++ -verify -std=c++11 %s
#if !__has_extension(pragma_clang_attribute_external_declaration)
#error
#endif
#define BEGIN_PRAGMA _Pragma("clang attribute push (__attribute__((availability(macos, introduced=1000))), apply_to=function)")
#define END_PRAGMA _Pragma("clang attribute pop")
extern "C" {
BEGIN_PRAGMA
int f(); // expected-note{{marked}}
END_PRAGMA
}
namespace my_ns {
BEGIN_PRAGMA
int g(); // expected-note{{marked}}
END_PRAGMA
namespace nested {
BEGIN_PRAGMA
int h(); // expected-note{{marked}}
END_PRAGMA
}
}
int a = f(); // expected-warning{{'f' is only available on macOS 1000 or newer}} expected-note{{annotate 'a'}}
int b = my_ns::g(); // expected-warning{{'g' is only available on macOS 1000 or newer}} expected-note{{annotate 'b'}}
int c = my_ns::nested::h(); // expected-warning{{'h' is only available on macOS 1000 or newer}} expected-note{{annotate 'c'}}
struct InStruct {
// FIXME: This asserts in Objective-C++!
// FIXME: This is a horrible diagnostic!
#ifndef __OBJC__
BEGIN_PRAGMA // expected-error {{expected member name or ';' after declaration specifiers}}
#endif
};
<commit_msg>[Test] Cherry-pick fix to make `ninja check-clang` work on Linux<commit_after>// RUN: %clang_cc1 -triple x86_64-apple-darwin9.0.0 -verify -std=c++11 %s
// RUN: %clang_cc1 -triple x86_64-apple-darwin9.0.0 -xobjective-c++ -verify -std=c++11 %s
#if !__has_extension(pragma_clang_attribute_external_declaration)
#error
#endif
#define BEGIN_PRAGMA _Pragma("clang attribute push (__attribute__((availability(macos, introduced=1000))), apply_to=function)")
#define END_PRAGMA _Pragma("clang attribute pop")
extern "C" {
BEGIN_PRAGMA
int f(); // expected-note{{marked}}
END_PRAGMA
}
namespace my_ns {
BEGIN_PRAGMA
int g(); // expected-note{{marked}}
END_PRAGMA
namespace nested {
BEGIN_PRAGMA
int h(); // expected-note{{marked}}
END_PRAGMA
}
}
int a = f(); // expected-warning{{'f' is only available on macOS 1000 or newer}} expected-note{{annotate 'a'}}
int b = my_ns::g(); // expected-warning{{'g' is only available on macOS 1000 or newer}} expected-note{{annotate 'b'}}
int c = my_ns::nested::h(); // expected-warning{{'h' is only available on macOS 1000 or newer}} expected-note{{annotate 'c'}}
struct InStruct {
// FIXME: This asserts in Objective-C++!
// FIXME: This is a horrible diagnostic!
#ifndef __OBJC__
BEGIN_PRAGMA // expected-error {{expected member name or ';' after declaration specifiers}}
#endif
};
<|endoftext|>
|
<commit_before>/*
* amp_raw_condition_variable_test.cpp
* amp
*
* Created by Björn Knafla on 28.09.09.
* Copyright 2009 Bjoern Knafla Parallelization + AI + Gamedev Consulting. All rights reserved.
*
*/
/**
* @file
*
* Tests the shallow wrapper around condition variables.
*
* TODO: @todo Add stress tests (eventually in their own file) with very high
* thread counts to potentially trigger problems.
*/
#include <amp/amp_raw_condition_variable.h>
#include <cassert>
#include <UnitTest++.h>
#include <amp/amp_stddef.h>
#include <amp/amp_raw_mutex.h>
#include <amp/amp_raw_semaphore.h>
#include <amp/amp_raw_thread.h>
namespace {
std::size_t const avg_thread_count = 4;
std::size_t const max_thread_count = 128;
} // anonymous namespace
SUITE(amp_raw_condition_variable)
{
TEST(init_and_finalize)
{
struct amp_raw_condition_variable_s cond;
int retval = amp_raw_condition_variable_init(&cond);
CHECK_EQUAL(AMP_SUCCESS, retval);
retval = amp_raw_condition_variable_finalize(&cond);
CHECK_EQUAL(AMP_SUCCESS, retval);
}
TEST(no_waiting_thread_and_signal)
{
struct amp_raw_condition_variable_s cond;
int retval = amp_raw_condition_variable_init(&cond);
CHECK_EQUAL(AMP_SUCCESS, retval);
retval = amp_raw_condition_variable_signal(&cond);
CHECK_EQUAL(AMP_SUCCESS, retval);
retval = amp_raw_condition_variable_finalize(&cond);
CHECK_EQUAL(AMP_SUCCESS, retval);
}
namespace {
int const state_initialized_flag = 23;
int const state_waiting_flag = 77;
int const state_awake_after_waiting_flag = 312;
struct mutex_with_cond_s {
struct amp_raw_mutex_s mutex;
struct amp_raw_condition_variable_s cond;
struct amp_raw_semaphore_s ready_for_signal_sem;
int state;
};
void cond_waiting_thread_func(void *ctxt)
{
struct mutex_with_cond_s *context = static_cast<struct mutex_with_cond_s*>(ctxt);
int retval = amp_raw_mutex_lock(&context->mutex);
assert(AMP_SUCCESS == retval);
context->state = state_waiting_flag;
retval = amp_raw_semaphore_signal(&context->ready_for_signal_sem);
assert(AMP_SUCCESS == retval);
retval = amp_raw_condition_variable_wait(&context->cond,
&context->mutex);
context->state = state_awake_after_waiting_flag;
retval = amp_raw_mutex_unlock(&context->mutex);
assert(AMP_SUCCESS == retval);
}
} // anonymous namespace
TEST(single_waiting_thread_and_signal_from_inside_mutex)
{
struct mutex_with_cond_s mwc;
int retval = amp_raw_mutex_init(&mwc.mutex);
CHECK_EQUAL(AMP_SUCCESS, retval);
retval = amp_raw_condition_variable_init(&mwc.cond);
CHECK_EQUAL(AMP_SUCCESS, retval);
retval = amp_raw_semaphore_init(&mwc.ready_for_signal_sem, 0);
CHECK_EQUAL(AMP_SUCCESS, retval);
mwc.state = state_initialized_flag;
// This signal should be lost - no waiting thread.
retval = amp_raw_condition_variable_signal(&mwc.cond);
CHECK_EQUAL(AMP_SUCCESS, retval);
struct amp_raw_thread_s thread;
retval = amp_raw_thread_launch(&thread, &mwc, cond_waiting_thread_func);
retval = amp_raw_semaphore_wait(&mwc.ready_for_signal_sem);
CHECK_EQUAL(AMP_SUCCESS, retval);
CHECK_EQUAL(state_waiting_flag, mwc.state);
retval = amp_raw_mutex_lock(&mwc.mutex);
CHECK_EQUAL(AMP_SUCCESS, retval);
retval = amp_raw_condition_variable_signal(&mwc.cond);
CHECK_EQUAL(AMP_SUCCESS, retval);
retval = amp_raw_mutex_unlock(&mwc.mutex);
CHECK_EQUAL(AMP_SUCCESS, retval);
retval = amp_raw_thread_join(&thread);
CHECK_EQUAL(AMP_SUCCESS, retval);
CHECK_EQUAL(state_awake_after_waiting_flag, mwc.state);
retval = amp_raw_condition_variable_finalize(&mwc.cond);
CHECK_EQUAL(AMP_SUCCESS, retval);
retval = amp_raw_mutex_finalize(&mwc.mutex);
CHECK_EQUAL(AMP_SUCCESS, retval);
}
TEST(single_waiting_thread_and_signal_from_outside_mutex)
{
struct mutex_with_cond_s mwc;
mwc.state = state_initialized_flag;
int retval = amp_raw_mutex_init(&mwc.mutex);
CHECK_EQUAL(AMP_SUCCESS, retval);
retval = amp_raw_condition_variable_init(&mwc.cond);
CHECK_EQUAL(AMP_SUCCESS, retval);
// This signal should be lost - no waiting thread.
retval = amp_raw_condition_variable_signal(&mwc.cond);
CHECK_EQUAL(AMP_SUCCESS, retval);
struct amp_raw_thread_s thread;
retval = amp_raw_thread_launch(&thread, &mwc, cond_waiting_thread_func);
retval = amp_raw_semaphore_wait(&mwc.ready_for_signal_sem);
CHECK_EQUAL(AMP_SUCCESS, retval);
CHECK_EQUAL(state_waiting_flag, mwc.state);
// Give the waiting thread a greater chance to start_waiting.
retval = amp_raw_thread_yield();
CHECK_EQUAL(AMP_SUCCESS, retval);
// Signaling the semaphore and even calling wait by the waiting thread
// aren't atomic. Loop until the waiting thread really caught the
// signal.
bool waiting_thread_is_awake = false;
while (! waiting_thread_is_awake) {
retval = amp_raw_condition_variable_signal(&mwc.cond);
CHECK_EQUAL(AMP_SUCCESS, retval);
int rv = amp_raw_mutex_lock(&mwc.mutex);
CHECK_EQUAL(AMP_SUCCESS, rv);
if (state_awake_after_waiting_flag == mwc.state) {
waiting_thread_is_awake = true;
}
rv = amp_raw_mutex_unlock(&mwc.mutex);
CHECK_EQUAL(AMP_SUCCESS, rv);
// Give the waiting thread a greater chance to get the mutex.
rv = amp_raw_thread_yield();
CHECK_EQUAL(AMP_SUCCESS, rv);
}
retval = amp_raw_thread_join(&thread);
CHECK_EQUAL(AMP_SUCCESS, retval);
CHECK_EQUAL(state_awake_after_waiting_flag, mwc.state);
retval = amp_raw_condition_variable_finalize(&mwc.cond);
CHECK_EQUAL(AMP_SUCCESS, retval);
retval = amp_raw_mutex_finalize(&mwc.mutex);
CHECK_EQUAL(AMP_SUCCESS, retval);
}
namespace {
struct threads_common_context_s {
struct amp_raw_mutex_s mutex;
struct amp_raw_condition_variable_s cond;
struct amp_raw_semaphore_s ready_for_signal_sem;
struct amp_raw_semaphore_s thread_awake_sem;
std::size_t thread_count;
std::size_t threads_waiting_count;
};
struct thread_context_s {
struct threads_common_context_s *common;
int state;
};
void multiple_waiting_threads_and_signal_func(void *ctxt)
{
struct thread_context_s *context =
static_cast<struct thread_context_s*>(ctxt);
int retval = amp_raw_mutex_lock(&context->common->mutex);
assert(AMP_SUCCESS == retval);
context->state = state_waiting_flag;
std::size_t const waiting_thread_count = ++(context->common->threads_waiting_count);
// If all threads adding themselves to wait call wait on the
// condition variable and mutex and inform the test thread via
// the semaphore that the last one is about to wait.
// Make sure that this is clear: it is not guaranteed that the last
// thread calling wait has registered with the condition variable
// before the testing thread signals or broadcasts it...
if (waiting_thread_count == context->common->thread_count) {
retval = amp_raw_semaphore_signal(&context->common->ready_for_signal_sem);
assert(AMP_SUCCESS == retval);
}
retval = amp_raw_condition_variable_wait(&context->common->cond,
&context->common->mutex);
assert(AMP_SUCCESS == retval);
context->state = state_awake_after_waiting_flag;
retval = amp_raw_semaphore_signal(&context->common->thread_awake_sem);
assert(AMP_SUCCESS == retval);
retval = amp_raw_mutex_unlock(&context->common->mutex);
assert(AMP_SUCCESS == retval);
}
struct thread_context_fixture {
thread_context_fixture()
: threads_common_context()
, thread_contexts(NULL)
{
int retval = amp_raw_mutex_init(&threads_common_context.mutex);
assert(AMP_SUCCESS == retval);
retval = amp_raw_condition_variable_init(&threads_common_context.cond);
assert(AMP_SUCCESS == retval);
retval = amp_raw_semaphore_init(&threads_common_context.ready_for_signal_sem, 0);
assert(AMP_SUCCESS == retval);
retval = amp_raw_semaphore_init(&threads_common_context.thread_awake_sem, 0);
assert(AMP_SUCCESS == retval);
threads_common_context.thread_count = thread_count;
threads_common_context.threads_waiting_count = 0;
thread_contexts = new struct thread_context_s[thread_count];
assert(NULL != thread_contexts);
for (std::size_t i = 0; i < thread_count; ++i) {
thread_contexts[i].common = &threads_common_context;
thread_contexts[i].state = state_initialized_flag;
}
}
~thread_context_fixture()
{
delete[] thread_contexts;
int retval = amp_raw_semaphore_finalize(&threads_common_context.thread_awake_sem);
assert(AMP_SUCCESS == retval);
retval = amp_raw_semaphore_finalize(&threads_common_context.ready_for_signal_sem);
assert(AMP_SUCCESS == retval);
retval = amp_raw_condition_variable_finalize(&threads_common_context.cond);
assert(AMP_SUCCESS == retval);
retval = amp_raw_mutex_finalize(&threads_common_context.mutex);
assert(AMP_SUCCESS == retval);
}
static std::size_t const thread_count = max_thread_count;
struct threads_common_context_s threads_common_context;
struct thread_context_s *thread_contexts;
};
} // anonymous namespace
TEST_FIXTURE(thread_context_fixture, multiple_waiting_threads_and_signal)
{
struct amp_raw_thread_s threads[thread_count];
// Start threads to wait on condition variable
for (std::size_t i = 0; i < thread_count; ++i) {
int const launch_retval = amp_raw_thread_launch(&threads[i],
&thread_contexts[i],
multiple_waiting_threads_and_signal_func);
CHECK_EQUAL(AMP_SUCCESS, launch_retval);
}
int retval = amp_raw_semaphore_wait(&threads_common_context.ready_for_signal_sem);
CHECK_EQUAL(AMP_SUCCESS, retval);
// retval = amp_raw_mutex_lock(&threads_common_context.mutex);
// CHECK_EQUAL(AMP_SUCCESS, retval);
{
// Waiting on the semaphore should have synced the memory view of
// the threads.
for (std::size_t i = 0; i < thread_count; ++i) {
CHECK_EQUAL(state_waiting_flag, thread_contexts[i].state);
}
}
// retval = amp_raw_mutex_unlock(&threads_common_context.mutex);
// CHECK_EQUAL(AMP_SUCCESS, retval);
// Signal while owning the mutex
for (std::size_t i = 0; i < thread_count/2; ++i) {
retval = amp_raw_mutex_lock(&threads_common_context.mutex);
CHECK_EQUAL(AMP_SUCCESS, retval);
{
retval = amp_raw_condition_variable_signal(&threads_common_context.cond);
CHECK_EQUAL(AMP_SUCCESS, retval);
}
retval = amp_raw_mutex_unlock(&threads_common_context.mutex);
CHECK_EQUAL(AMP_SUCCESS, retval);
retval = amp_raw_semaphore_wait(&threads_common_context.thread_awake_sem);
CHECK_EQUAL(AMP_SUCCESS, retval);
// Check that only as many threads are awake as signal has been
// called.
std::size_t awake_threads_count = 0;
for (std::size_t j = 0; j < thread_count; ++j) {
if (state_awake_after_waiting_flag == thread_contexts[j].state) {
++awake_threads_count;
}
}
CHECK_EQUAL(i + 1, awake_threads_count);
}
// Signal without owning the mutex after singaling while owning the
// mutex so the awake semaphore signals of the thread function have
// been consumed and the semaphore count isn't greater than zero
// while the mutex-holding signal method waits on the semaphore
// to know that the signal has been received and one thread awoke.
for (std::size_t i = thread_count/2; i < thread_count; ++i) {
// Give the waiting thread a greater chance to start waiting.
retval = amp_raw_thread_yield();
CHECK_EQUAL(AMP_SUCCESS, retval);
// Signaling the semaphore and calling wait by the waiting thread
// aren't atomic. Loop until the waiting thread really caught the
// signal.
bool waiting_thread_is_awake = false;
while (! waiting_thread_is_awake) {
retval = amp_raw_condition_variable_signal(&threads_common_context.cond);
CHECK_EQUAL(AMP_SUCCESS, retval);
retval = amp_raw_mutex_lock(&threads_common_context.mutex);
CHECK_EQUAL(AMP_SUCCESS, retval);
{
std::size_t awake_threads_count = 0;
for (std::size_t j = 0; j < thread_count; ++j) {
if (state_awake_after_waiting_flag == thread_contexts[j].state) {
++awake_threads_count;
}
}
if (i + 1 == awake_threads_count) {
// As many threads have set their state to be awake as
// the signal loop should have awakened.
waiting_thread_is_awake = true;
}
}
retval = amp_raw_mutex_unlock(&threads_common_context.mutex);
CHECK_EQUAL(AMP_SUCCESS, retval);
// Give the waiting thread a greater chance to get the mutex.
retval = amp_raw_thread_yield();
CHECK_EQUAL(AMP_SUCCESS, retval);
}
}
for (std::size_t i = 0; i < thread_count; ++i) {
CHECK_EQUAL(state_awake_after_waiting_flag, thread_contexts[i].state);
}
for (std::size_t i = 0; i < thread_count; ++i) {
retval = amp_raw_thread_join(&threads[i]);
CHECK_EQUAL(AMP_SUCCESS, retval);
}
}
TEST(no_waiting_thread_and_broadcast)
{
}
TEST(single_waiting_thread_and_broadcast)
{
}
TEST(multiple_waiting_threads_and_broadcast)
{
}
TEST(wait_signal_wait_signal)
{
}
TEST(wait_broadcast_wait_broadcast)
{
}
TEST(wait_signal_signal_broadcast_wait_broadcast_wait_signal_broadcast)
{
}
} // SUITE(amp_raw_condition_variable)
<commit_msg>Fixed an error in the test. While signalling a condition variable without hodling the lock I didn't take into account that the loop calling the signals and then testing if a thread catched it might awake multiple threads because the test loop gets the memory sync mutex before the thread whose condition variable wait caught the signal, so the next signal might wake another thread.<commit_after>/*
* amp_raw_condition_variable_test.cpp
* amp
*
* Created by Björn Knafla on 28.09.09.
* Copyright 2009 Bjoern Knafla Parallelization + AI + Gamedev Consulting. All rights reserved.
*
*/
/**
* @file
*
* Tests the shallow wrapper around condition variables.
*
* TODO: @todo Add stress tests (eventually in their own file) with very high
* thread counts to potentially trigger problems.
*/
#include <amp/amp_raw_condition_variable.h>
#include <cassert>
#include <UnitTest++.h>
#include <amp/amp_stddef.h>
#include <amp/amp_raw_mutex.h>
#include <amp/amp_raw_semaphore.h>
#include <amp/amp_raw_thread.h>
namespace {
std::size_t const avg_thread_count = 4;
std::size_t const max_thread_count = 128;
} // anonymous namespace
SUITE(amp_raw_condition_variable)
{
TEST(init_and_finalize)
{
struct amp_raw_condition_variable_s cond;
int retval = amp_raw_condition_variable_init(&cond);
CHECK_EQUAL(AMP_SUCCESS, retval);
retval = amp_raw_condition_variable_finalize(&cond);
CHECK_EQUAL(AMP_SUCCESS, retval);
}
TEST(no_waiting_thread_and_signal)
{
struct amp_raw_condition_variable_s cond;
int retval = amp_raw_condition_variable_init(&cond);
CHECK_EQUAL(AMP_SUCCESS, retval);
retval = amp_raw_condition_variable_signal(&cond);
CHECK_EQUAL(AMP_SUCCESS, retval);
retval = amp_raw_condition_variable_finalize(&cond);
CHECK_EQUAL(AMP_SUCCESS, retval);
}
namespace {
int const state_initialized_flag = 23;
int const state_waiting_flag = 77;
int const state_awake_after_waiting_flag = 312;
struct mutex_with_cond_s {
struct amp_raw_mutex_s mutex;
struct amp_raw_condition_variable_s cond;
struct amp_raw_semaphore_s ready_for_signal_sem;
int state;
};
void cond_waiting_thread_func(void *ctxt)
{
struct mutex_with_cond_s *context = static_cast<struct mutex_with_cond_s*>(ctxt);
int retval = amp_raw_mutex_lock(&context->mutex);
assert(AMP_SUCCESS == retval);
context->state = state_waiting_flag;
retval = amp_raw_semaphore_signal(&context->ready_for_signal_sem);
assert(AMP_SUCCESS == retval);
retval = amp_raw_condition_variable_wait(&context->cond,
&context->mutex);
context->state = state_awake_after_waiting_flag;
retval = amp_raw_mutex_unlock(&context->mutex);
assert(AMP_SUCCESS == retval);
}
} // anonymous namespace
TEST(single_waiting_thread_and_signal_from_inside_mutex)
{
struct mutex_with_cond_s mwc;
int retval = amp_raw_mutex_init(&mwc.mutex);
CHECK_EQUAL(AMP_SUCCESS, retval);
retval = amp_raw_condition_variable_init(&mwc.cond);
CHECK_EQUAL(AMP_SUCCESS, retval);
retval = amp_raw_semaphore_init(&mwc.ready_for_signal_sem, 0);
CHECK_EQUAL(AMP_SUCCESS, retval);
mwc.state = state_initialized_flag;
// This signal should be lost - no waiting thread.
retval = amp_raw_condition_variable_signal(&mwc.cond);
CHECK_EQUAL(AMP_SUCCESS, retval);
struct amp_raw_thread_s thread;
retval = amp_raw_thread_launch(&thread, &mwc, cond_waiting_thread_func);
retval = amp_raw_semaphore_wait(&mwc.ready_for_signal_sem);
CHECK_EQUAL(AMP_SUCCESS, retval);
CHECK_EQUAL(state_waiting_flag, mwc.state);
retval = amp_raw_mutex_lock(&mwc.mutex);
CHECK_EQUAL(AMP_SUCCESS, retval);
retval = amp_raw_condition_variable_signal(&mwc.cond);
CHECK_EQUAL(AMP_SUCCESS, retval);
retval = amp_raw_mutex_unlock(&mwc.mutex);
CHECK_EQUAL(AMP_SUCCESS, retval);
retval = amp_raw_thread_join(&thread);
CHECK_EQUAL(AMP_SUCCESS, retval);
CHECK_EQUAL(state_awake_after_waiting_flag, mwc.state);
retval = amp_raw_condition_variable_finalize(&mwc.cond);
CHECK_EQUAL(AMP_SUCCESS, retval);
retval = amp_raw_mutex_finalize(&mwc.mutex);
CHECK_EQUAL(AMP_SUCCESS, retval);
}
TEST(single_waiting_thread_and_signal_from_outside_mutex)
{
struct mutex_with_cond_s mwc;
mwc.state = state_initialized_flag;
int retval = amp_raw_mutex_init(&mwc.mutex);
CHECK_EQUAL(AMP_SUCCESS, retval);
retval = amp_raw_condition_variable_init(&mwc.cond);
CHECK_EQUAL(AMP_SUCCESS, retval);
// This signal should be lost - no waiting thread.
retval = amp_raw_condition_variable_signal(&mwc.cond);
CHECK_EQUAL(AMP_SUCCESS, retval);
struct amp_raw_thread_s thread;
retval = amp_raw_thread_launch(&thread, &mwc, cond_waiting_thread_func);
retval = amp_raw_semaphore_wait(&mwc.ready_for_signal_sem);
CHECK_EQUAL(AMP_SUCCESS, retval);
CHECK_EQUAL(state_waiting_flag, mwc.state);
// Give the waiting thread a greater chance to start_waiting.
retval = amp_raw_thread_yield();
CHECK_EQUAL(AMP_SUCCESS, retval);
// Signaling the semaphore and even calling wait by the waiting thread
// aren't atomic. Loop until the waiting thread really caught the
// signal.
bool waiting_thread_is_awake = false;
while (! waiting_thread_is_awake) {
retval = amp_raw_condition_variable_signal(&mwc.cond);
CHECK_EQUAL(AMP_SUCCESS, retval);
int rv = amp_raw_mutex_lock(&mwc.mutex);
CHECK_EQUAL(AMP_SUCCESS, rv);
if (state_awake_after_waiting_flag == mwc.state) {
waiting_thread_is_awake = true;
}
rv = amp_raw_mutex_unlock(&mwc.mutex);
CHECK_EQUAL(AMP_SUCCESS, rv);
// Give the waiting thread a greater chance to get the mutex.
// rv = amp_raw_thread_yield();
// CHECK_EQUAL(AMP_SUCCESS, rv);
}
retval = amp_raw_thread_join(&thread);
CHECK_EQUAL(AMP_SUCCESS, retval);
CHECK_EQUAL(state_awake_after_waiting_flag, mwc.state);
retval = amp_raw_condition_variable_finalize(&mwc.cond);
CHECK_EQUAL(AMP_SUCCESS, retval);
retval = amp_raw_mutex_finalize(&mwc.mutex);
CHECK_EQUAL(AMP_SUCCESS, retval);
}
namespace {
struct threads_common_context_s {
struct amp_raw_mutex_s mutex;
struct amp_raw_condition_variable_s cond;
struct amp_raw_semaphore_s ready_for_signal_sem;
struct amp_raw_semaphore_s thread_awake_sem;
std::size_t thread_count;
std::size_t threads_waiting_count;
};
struct thread_context_s {
struct threads_common_context_s *common;
int state;
};
void multiple_waiting_threads_and_signal_func(void *ctxt)
{
struct thread_context_s *context =
static_cast<struct thread_context_s*>(ctxt);
int retval = amp_raw_mutex_lock(&context->common->mutex);
assert(AMP_SUCCESS == retval);
context->state = state_waiting_flag;
std::size_t const waiting_thread_count = ++(context->common->threads_waiting_count);
// If all threads adding themselves to wait call wait on the
// condition variable and mutex and inform the test thread via
// the semaphore that the last one is about to wait.
// Make sure that this is clear: it is not guaranteed that the last
// thread calling wait has registered with the condition variable
// before the testing thread signals or broadcasts it...
if (waiting_thread_count == context->common->thread_count) {
retval = amp_raw_semaphore_signal(&context->common->ready_for_signal_sem);
assert(AMP_SUCCESS == retval);
}
retval = amp_raw_condition_variable_wait(&context->common->cond,
&context->common->mutex);
assert(AMP_SUCCESS == retval);
context->state = state_awake_after_waiting_flag;
retval = amp_raw_semaphore_signal(&context->common->thread_awake_sem);
assert(AMP_SUCCESS == retval);
retval = amp_raw_mutex_unlock(&context->common->mutex);
assert(AMP_SUCCESS == retval);
}
struct thread_context_fixture {
thread_context_fixture()
: threads_common_context()
, thread_contexts(NULL)
{
int retval = amp_raw_mutex_init(&threads_common_context.mutex);
assert(AMP_SUCCESS == retval);
retval = amp_raw_condition_variable_init(&threads_common_context.cond);
assert(AMP_SUCCESS == retval);
retval = amp_raw_semaphore_init(&threads_common_context.ready_for_signal_sem, 0);
assert(AMP_SUCCESS == retval);
retval = amp_raw_semaphore_init(&threads_common_context.thread_awake_sem, 0);
assert(AMP_SUCCESS == retval);
threads_common_context.thread_count = thread_count;
threads_common_context.threads_waiting_count = 0;
thread_contexts = new struct thread_context_s[thread_count];
assert(NULL != thread_contexts);
for (std::size_t i = 0; i < thread_count; ++i) {
thread_contexts[i].common = &threads_common_context;
thread_contexts[i].state = state_initialized_flag;
}
}
~thread_context_fixture()
{
delete[] thread_contexts;
int retval = amp_raw_semaphore_finalize(&threads_common_context.thread_awake_sem);
assert(AMP_SUCCESS == retval);
retval = amp_raw_semaphore_finalize(&threads_common_context.ready_for_signal_sem);
assert(AMP_SUCCESS == retval);
retval = amp_raw_condition_variable_finalize(&threads_common_context.cond);
assert(AMP_SUCCESS == retval);
retval = amp_raw_mutex_finalize(&threads_common_context.mutex);
assert(AMP_SUCCESS == retval);
}
static std::size_t const thread_count = avg_thread_count;
struct threads_common_context_s threads_common_context;
struct thread_context_s *thread_contexts;
};
} // anonymous namespace
TEST_FIXTURE(thread_context_fixture, multiple_waiting_threads_and_signal)
{
struct amp_raw_thread_s threads[thread_count];
// Start threads to wait on condition variable
for (std::size_t i = 0; i < thread_count; ++i) {
int const launch_retval = amp_raw_thread_launch(&threads[i],
&thread_contexts[i],
multiple_waiting_threads_and_signal_func);
CHECK_EQUAL(AMP_SUCCESS, launch_retval);
}
int retval = amp_raw_semaphore_wait(&threads_common_context.ready_for_signal_sem);
CHECK_EQUAL(AMP_SUCCESS, retval);
// retval = amp_raw_mutex_lock(&threads_common_context.mutex);
// CHECK_EQUAL(AMP_SUCCESS, retval);
{
// Waiting on the semaphore should have synced the memory view of
// the threads.
for (std::size_t i = 0; i < thread_count; ++i) {
CHECK_EQUAL(state_waiting_flag, thread_contexts[i].state);
}
}
// retval = amp_raw_mutex_unlock(&threads_common_context.mutex);
// CHECK_EQUAL(AMP_SUCCESS, retval);
// Signal while owning the mutex
for (std::size_t i = 0; i < thread_count/2; ++i) {
retval = amp_raw_mutex_lock(&threads_common_context.mutex);
CHECK_EQUAL(AMP_SUCCESS, retval);
{
retval = amp_raw_condition_variable_signal(&threads_common_context.cond);
CHECK_EQUAL(AMP_SUCCESS, retval);
}
retval = amp_raw_mutex_unlock(&threads_common_context.mutex);
CHECK_EQUAL(AMP_SUCCESS, retval);
retval = amp_raw_semaphore_wait(&threads_common_context.thread_awake_sem);
CHECK_EQUAL(AMP_SUCCESS, retval);
// Check that only as many threads are awake as signal has been
// called.
std::size_t awake_threads_count = 0;
for (std::size_t j = 0; j < thread_count; ++j) {
if (state_awake_after_waiting_flag == thread_contexts[j].state) {
++awake_threads_count;
}
}
CHECK_EQUAL(i + 1, awake_threads_count);
}
// Signal without owning the mutex after singaling while owning the
// mutex so the awake semaphore signals of the thread function have
// been consumed and the semaphore count isn't greater than zero
// while the mutex-holding signal method waits on the semaphore
// to know that the signal has been received and one thread awoke.
for (std::size_t i = thread_count/2; i < thread_count; ++i) {
// Give the waiting thread a greater chance to start waiting.
retval = amp_raw_thread_yield();
CHECK_EQUAL(AMP_SUCCESS, retval);
// Signaling the semaphore and calling wait by the waiting thread
// aren't atomic. Loop until the waiting thread really caught the
// signal.
bool waiting_thread_is_awake = false;
while (! waiting_thread_is_awake) {
retval = amp_raw_condition_variable_signal(&threads_common_context.cond);
CHECK_EQUAL(AMP_SUCCESS, retval);
retval = amp_raw_mutex_lock(&threads_common_context.mutex);
CHECK_EQUAL(AMP_SUCCESS, retval);
{
std::size_t awake_threads_count = 0;
for (std::size_t j = 0; j < thread_count; ++j) {
if (state_awake_after_waiting_flag == thread_contexts[j].state) {
++awake_threads_count;
}
}
if (i + 1 <= awake_threads_count) {
// As many threads have set their state to be awake as
// the signal loop should have awakened (or even more).
waiting_thread_is_awake = true;
}
}
retval = amp_raw_mutex_unlock(&threads_common_context.mutex);
CHECK_EQUAL(AMP_SUCCESS, retval);
// Give the waiting thread a greater chance to get the mutex.
retval = amp_raw_thread_yield();
CHECK_EQUAL(AMP_SUCCESS, retval);
}
}
for (std::size_t i = 0; i < thread_count; ++i) {
CHECK_EQUAL(state_awake_after_waiting_flag, thread_contexts[i].state);
}
for (std::size_t i = 0; i < thread_count; ++i) {
retval = amp_raw_thread_join(&threads[i]);
CHECK_EQUAL(AMP_SUCCESS, retval);
}
}
TEST(no_waiting_thread_and_broadcast)
{
}
TEST(single_waiting_thread_and_broadcast)
{
}
TEST(multiple_waiting_threads_and_broadcast)
{
}
TEST(wait_signal_wait_signal)
{
}
TEST(wait_broadcast_wait_broadcast)
{
}
TEST(wait_signal_signal_broadcast_wait_broadcast_wait_signal_broadcast)
{
}
} // SUITE(amp_raw_condition_variable)
<|endoftext|>
|
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: barcfg.hxx,v $
*
* $Revision: 1.7 $
*
* last change: $Author: hr $ $Date: 2007-09-27 11:53:35 $
*
* 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 SW_BARCFG_HXX
#define SW_BARCFG_HXX
#ifndef _UTL_CONFIGITEM_HXX_
#include <unotools/configitem.hxx>
#endif
class SwToolbarConfigItem : public utl::ConfigItem
{
sal_Int32 aTbxIdArray[5];
com::sun::star::uno::Sequence<rtl::OUString> GetPropertyNames();
public:
SwToolbarConfigItem( sal_Bool bWeb );
~SwToolbarConfigItem();
virtual void Commit();
void SetTopToolbar( sal_Int32 nSelType, sal_Int32 nBarId );
};
#endif
<commit_msg>INTEGRATION: CWS changefileheader (1.7.242); FILE MERGED 2008/04/01 15:59:07 thb 1.7.242.2: #i85898# Stripping all external header guards 2008/03/31 16:58:27 rt 1.7.242.1: #i87441# Change license header to LPGL v3.<commit_after>/*************************************************************************
*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* Copyright 2008 by Sun Microsystems, Inc.
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: barcfg.hxx,v $
* $Revision: 1.8 $
*
* This file is part of OpenOffice.org.
*
* OpenOffice.org is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License version 3
* only, as published by the Free Software Foundation.
*
* OpenOffice.org is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License version 3 for more details
* (a copy is included in the LICENSE file that accompanied this code).
*
* You should have received a copy of the GNU Lesser General Public License
* version 3 along with OpenOffice.org. If not, see
* <http://www.openoffice.org/license.html>
* for a copy of the LGPLv3 License.
*
************************************************************************/
#ifndef SW_BARCFG_HXX
#define SW_BARCFG_HXX
#include <unotools/configitem.hxx>
class SwToolbarConfigItem : public utl::ConfigItem
{
sal_Int32 aTbxIdArray[5];
com::sun::star::uno::Sequence<rtl::OUString> GetPropertyNames();
public:
SwToolbarConfigItem( sal_Bool bWeb );
~SwToolbarConfigItem();
virtual void Commit();
void SetTopToolbar( sal_Int32 nSelType, sal_Int32 nBarId );
};
#endif
<|endoftext|>
|
<commit_before>/*************************************************************************
*
* $RCSfile: tmpdlg.hxx,v $
*
* $Revision: 1.2 $
*
* last change: $Author: hr $ $Date: 2004-05-10 16:32:00 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the "License"); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#ifndef _SWTMPDLG_HXX //CHINA001 _SWCHARDLG_HXX
#define _SWTMPDLG_HXX //CHINA001 _SWCHARDLG_HXX
#ifndef _SFX_STYLEDLG_HXX //autogen
#include <sfx2/styledlg.hxx>
#endif
class SfxItemSet;
class FontList;
class SwWrtShell;
/*--------------------------------------------------------------------
Beschreibung: Der Tabdialog Traeger der TabPages
--------------------------------------------------------------------*/
class SwTemplateDlg: public SfxStyleDialog
{
USHORT nType;
USHORT nHtmlMode;
SwWrtShell* pWrtShell;
BOOL bNewStyle;
DECL_LINK( NumOptionsHdl, PushButton* );
public:
SwTemplateDlg( Window* pParent,
SfxStyleSheetBase& rBase,
USHORT nRegion,
BOOL bColumn = FALSE,
SwWrtShell* pActShell = 0,
BOOL bNew = FALSE );
~SwTemplateDlg();
const SfxItemSet* GetRefreshedSet();
virtual void PageCreated( USHORT nId, SfxTabPage &rPage );
virtual short Ok();
};
#endif
<commit_msg>INTEGRATION: CWS ooo19126 (1.2.726); FILE MERGED 2005/09/05 13:45:46 rt 1.2.726.1: #i54170# Change license header: remove SISSL<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: tmpdlg.hxx,v $
*
* $Revision: 1.3 $
*
* last change: $Author: rt $ $Date: 2005-09-09 10:10:08 $
*
* 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 _SWTMPDLG_HXX //CHINA001 _SWCHARDLG_HXX
#define _SWTMPDLG_HXX //CHINA001 _SWCHARDLG_HXX
#ifndef _SFX_STYLEDLG_HXX //autogen
#include <sfx2/styledlg.hxx>
#endif
class SfxItemSet;
class FontList;
class SwWrtShell;
/*--------------------------------------------------------------------
Beschreibung: Der Tabdialog Traeger der TabPages
--------------------------------------------------------------------*/
class SwTemplateDlg: public SfxStyleDialog
{
USHORT nType;
USHORT nHtmlMode;
SwWrtShell* pWrtShell;
BOOL bNewStyle;
DECL_LINK( NumOptionsHdl, PushButton* );
public:
SwTemplateDlg( Window* pParent,
SfxStyleSheetBase& rBase,
USHORT nRegion,
BOOL bColumn = FALSE,
SwWrtShell* pActShell = 0,
BOOL bNew = FALSE );
~SwTemplateDlg();
const SfxItemSet* GetRefreshedSet();
virtual void PageCreated( USHORT nId, SfxTabPage &rPage );
virtual short Ok();
};
#endif
<|endoftext|>
|
<commit_before>//*****************************************************************************
//
// Copyright 2016 Microsoft Corporation
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http ://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
//*****************************************************************************
#include "pch.h"
#include "UncompressedSampleProvider.h"
using namespace FFmpegInterop;
UncompressedSampleProvider::UncompressedSampleProvider(FFmpegReader^ reader, AVFormatContext* avFormatCtx, AVCodecContext* avCodecCtx)
: MediaSampleProvider(reader, avFormatCtx, avCodecCtx)
, m_pAvFrame(nullptr)
{
}
HRESULT UncompressedSampleProvider::ProcessDecodedFrame(DataWriter^ dataWriter)
{
return S_OK;
}
// Return S_FALSE for an incomplete frame
HRESULT UncompressedSampleProvider::GetFrameFromFFmpegDecoder(AVPacket* avPacket)
{
HRESULT hr = S_OK;
int decodeFrame = 0;
if (avPacket != nullptr)
{
int sendPacketResult = avcodec_send_packet(m_pAvCodecCtx, avPacket);
if (sendPacketResult == AVERROR(EAGAIN))
{
// The decoder should have been drained and always ready to access input
_ASSERT(FALSE);
hr = E_UNEXPECTED;
}
else if (sendPacketResult < 0)
{
// We failed to send the packet
hr = E_FAIL;
DebugMessage(L"Decoder failed on the sample\n");
}
}
if (SUCCEEDED(hr))
{
AVFrame *pFrame = av_frame_alloc();
// Try to get a frame from the decoder.
decodeFrame = avcodec_receive_frame(m_pAvCodecCtx, pFrame);
// The decoder is empty, send a packet to it.
if (decodeFrame == AVERROR(EAGAIN))
{
// The decoder doesn't have enough data to produce a frame,
// return S_FALSE to indicate a partial frame
hr = S_FALSE;
av_frame_unref(pFrame);
av_frame_free(&pFrame);
}
else if (decodeFrame < 0)
{
hr = E_FAIL;
av_frame_unref(pFrame);
av_frame_free(&pFrame);
DebugMessage(L"Failed to get a frame from the decoder\n");
}
else
{
m_pAvFrame = pFrame;
}
}
return hr;
}
HRESULT UncompressedSampleProvider::DecodeAVPacket(DataWriter^ dataWriter, AVPacket* avPacket, int64_t& framePts, int64_t& frameDuration)
{
HRESULT hr = S_OK;
bool fGotFrame = false;
AVPacket *pPacket = avPacket;
while (SUCCEEDED(hr))
{
hr = GetFrameFromFFmpegDecoder(pPacket);
pPacket = nullptr;
if (SUCCEEDED(hr))
{
if (hr == S_FALSE)
{
// If the decoder didn't give an initial frame we still need
// to feed it more frames. Keep S_FALSE as the result
if (fGotFrame)
{
hr = S_OK;
}
break;
}
// Update the timestamp if the packet has one
else if (m_pAvFrame->pts != AV_NOPTS_VALUE)
{
framePts = m_pAvFrame->pts;
frameDuration = m_pAvFrame->pkt_duration;
}
fGotFrame = true;
hr = ProcessDecodedFrame(dataWriter);
}
}
return hr;
}
<commit_msg>got rid of unneccessary line change<commit_after>//*****************************************************************************
//
// Copyright 2016 Microsoft Corporation
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http ://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
//*****************************************************************************
#include "pch.h"
#include "UncompressedSampleProvider.h"
using namespace FFmpegInterop;
UncompressedSampleProvider::UncompressedSampleProvider(FFmpegReader^ reader, AVFormatContext* avFormatCtx, AVCodecContext* avCodecCtx)
: MediaSampleProvider(reader, avFormatCtx, avCodecCtx)
, m_pAvFrame(nullptr)
{
}
HRESULT UncompressedSampleProvider::ProcessDecodedFrame(DataWriter^ dataWriter)
{
return S_OK;
}
// Return S_FALSE for an incomplete frame
HRESULT UncompressedSampleProvider::GetFrameFromFFmpegDecoder(AVPacket* avPacket)
{
HRESULT hr = S_OK;
int decodeFrame = 0;
if (avPacket != nullptr)
{
int sendPacketResult = avcodec_send_packet(m_pAvCodecCtx, avPacket);
if (sendPacketResult == AVERROR(EAGAIN))
{
// The decoder should have been drained and always ready to access input
_ASSERT(FALSE);
hr = E_UNEXPECTED;
}
else if (sendPacketResult < 0)
{
// We failed to send the packet
hr = E_FAIL;
DebugMessage(L"Decoder failed on the sample\n");
}
}
if (SUCCEEDED(hr))
{
AVFrame *pFrame = av_frame_alloc();
// Try to get a frame from the decoder.
decodeFrame = avcodec_receive_frame(m_pAvCodecCtx, pFrame);
// The decoder is empty, send a packet to it.
if (decodeFrame == AVERROR(EAGAIN))
{
// The decoder doesn't have enough data to produce a frame,
// return S_FALSE to indicate a partial frame
hr = S_FALSE;
av_frame_unref(pFrame);
av_frame_free(&pFrame);
}
else if (decodeFrame < 0)
{
hr = E_FAIL;
av_frame_unref(pFrame);
av_frame_free(&pFrame);
DebugMessage(L"Failed to get a frame from the decoder\n");
}
else
{
m_pAvFrame = pFrame;
}
}
return hr;
}
HRESULT UncompressedSampleProvider::DecodeAVPacket(DataWriter^ dataWriter, AVPacket* avPacket, int64_t& framePts, int64_t& frameDuration)
{
HRESULT hr = S_OK;
bool fGotFrame = false;
AVPacket *pPacket = avPacket;
while (SUCCEEDED(hr))
{
hr = GetFrameFromFFmpegDecoder(pPacket);
pPacket = nullptr;
if (SUCCEEDED(hr))
{
if (hr == S_FALSE)
{
// If the decoder didn't give an initial frame we still need
// to feed it more frames. Keep S_FALSE as the result
if (fGotFrame)
{
hr = S_OK;
}
break;
}
// Update the timestamp if the packet has one
else if (m_pAvFrame->pts != AV_NOPTS_VALUE)
{
framePts = m_pAvFrame->pts;
frameDuration = m_pAvFrame->pkt_duration;
}
fGotFrame = true;
hr = ProcessDecodedFrame(dataWriter);
}
}
return hr;
}
<|endoftext|>
|
<commit_before>#include "graphics/sprite/particles.h"
#include "halley/maths/random.h"
#include "halley/support/logger.h"
using namespace Halley;
Particles::Particles()
: rng(&Random::getGlobal())
{
}
Particles::Particles(const ConfigNode& node, Resources& resources)
: rng(&Random::getGlobal())
{
load(node, resources);
}
void Particles::load(const ConfigNode& node, Resources& resources)
{
spawnRate = node["spawnRate"].asFloat(100);
spawnArea = node["spawnArea"].asVector2f(Vector2f(0, 0));
ttl = node["ttl"].asFloat(1.0f);
ttlScatter = node["ttlScatter"].asFloat(0.0f);
speed = node["speed"].asFloat(100.0f);
speedScatter = node["speedScatter"].asFloat(0.0f);
speedDamp = node["speedDamp"].asFloat(0.0f);
acceleration = node["acceleration"].asVector3f(Vector3f());
angle = node["angle"].asVector2f(Vector2f());
angleScatter = node["angleScatter"].asVector2f(Vector2f());
startScale = node["startScale"].asFloat(1.0f);
endScale = node["endScale"].asFloat(1.0f);
fadeInTime = node["fadeInTime"].asFloat(0.0f);
fadeOutTime = node["fadeOutTime"].asFloat(0.0f);
stopTime = node["stopTime"].asFloat(0.0f);
directionScatter = node["directionScatter"].asFloat(0.0f);
rotateTowardsMovement = node["rotateTowardsMovement"].asBool(false);
destroyWhenDone = node["destroyWhenDone"].asBool(false);
velScale = node["velScale"].asVector3f(Vector3f(1, 1, 1));
if (node.hasKey("minHeight")) {
minHeight = node["minHeight"].asFloat();
}
startHeight = node["startHeight"].asFloat(0);
if (node.hasKey("maxParticles")) {
maxParticles = node["maxParticles"].asInt();
}
if (node.hasKey("burst")) {
burst = node["burst"].asInt();
}
}
ConfigNode Particles::toConfigNode() const
{
ConfigNode::MapType result;
result["spawnRate"] = spawnRate;
result["spawnArea"] = spawnArea;
result["ttl"] = ttl;
result["ttlScatter"] = ttlScatter;
result["speed"] = speed;
result["speedScatter"] = speedScatter;
result["speedDamp"] = speedDamp;
result["acceleration"] = acceleration;
result["angle"] = angle;
result["angleScatter"] = angleScatter;
result["startScale"] = startScale;
result["endScale"] = endScale;
result["fadeInTime"] = fadeInTime;
result["fadeOutTime"] = fadeOutTime;
result["stopTime"] = stopTime;
result["directionScatter"] = directionScatter;
result["rotateTowardsMovement"] = rotateTowardsMovement;
result["destroyWhenDone"] = destroyWhenDone;
result["velScale"] = velScale;
if (minHeight) {
result["minHeight"] = *minHeight;
}
result["startHeight"] = startHeight;
if (maxParticles) {
result["maxParticles"] = static_cast<int>(maxParticles.value());
}
if (burst) {
result["burst"] = static_cast<int>(burst.value());
}
return result;
}
void Particles::burstParticles(size_t n)
{
pendingSpawn += static_cast<float>(n);
}
void Particles::setEnabled(bool e)
{
enabled = e;
}
bool Particles::isEnabled() const
{
return enabled;
}
void Particles::setSpawnRateMultiplier(float value)
{
spawnRateMultiplier = value;
}
float Particles::getSpawnRateMultiplier() const
{
return spawnRateMultiplier;
}
void Particles::setPosition(Vector2f pos)
{
position = Vector3f(pos);
}
void Particles::setPosition(Vector3f pos)
{
position = pos;
}
void Particles::setSpawnArea(Vector2f area)
{
spawnArea = area;
}
void Particles::setAngle(float newAngle)
{
angle = Vector2f(newAngle, 0);
}
void Particles::setAngle(Vector2f newAngle)
{
angle = newAngle;
}
Vector2f Particles::getAngle() const
{
return angle;
}
void Particles::setSpeed(float newSpeed)
{
speed = newSpeed;
}
float Particles::getSpeed() const
{
return speed;
}
void Particles::setAcceleration(Vector3f accel)
{
acceleration = accel;
}
Vector3f Particles::getAcceleration() const
{
return acceleration;
}
void Particles::setMinHeight(std::optional<float> z)
{
minHeight = z;
}
std::optional<float> Particles::getMinHeight() const
{
return minHeight;
}
void Particles::setSpawnHeight(float height)
{
startHeight = height;
}
float Particles::getSpawnHeight() const
{
return startHeight;
}
void Particles::start()
{
if (burst) {
spawn(burst.value());
}
}
void Particles::update(Time t)
{
if (firstUpdate) {
firstUpdate = false;
start();
}
pendingSpawn += static_cast<float>(t * spawnRate * (enabled && !burst ? spawnRateMultiplier : 0));
const int toSpawn = static_cast<int>(floor(pendingSpawn));
pendingSpawn = pendingSpawn - static_cast<float>(toSpawn);
// Spawn new particles
spawn(static_cast<size_t>(toSpawn));
// Update particles
updateParticles(static_cast<float>(t));
// Remove dead particles
for (size_t i = 0; i < nParticlesAlive; ) {
if (!particles[i].alive) {
if (i != nParticlesAlive - 1) {
// Swap with last particle that's alive
std::swap(particles[i], particles[nParticlesAlive - 1]);
std::swap(sprites[i], sprites[nParticlesAlive - 1]);
if (isAnimated()) {
std::swap(animationPlayers[i], animationPlayers[nParticlesAlive - 1]);
}
}
--nParticlesAlive;
// Don't increment i here, since i is now a new particle that's still alive
} else {
++i;
}
}
// Update visibility
nParticlesVisible = nParticlesAlive;
if (nParticlesVisible > 0 && !sprites[0].hasMaterial()) {
nParticlesVisible = 0;
}
}
void Particles::setSprites(Vector<Sprite> sprites)
{
baseSprites = std::move(sprites);
}
void Particles::setAnimation(std::shared_ptr<const Animation> animation)
{
baseAnimation = std::move(animation);
}
bool Particles::isAnimated() const
{
return !!baseAnimation;
}
bool Particles::isAlive() const
{
return nParticlesAlive > 0 || !destroyWhenDone;
}
gsl::span<Sprite> Particles::getSprites()
{
return gsl::span<Sprite>(sprites).subspan(0, nParticlesVisible);
}
gsl::span<const Sprite> Particles::getSprites() const
{
return gsl::span<const Sprite>(sprites).subspan(0, nParticlesVisible);
}
void Particles::spawn(size_t n)
{
if (maxParticles) {
n = std::min(n, maxParticles.value() - nParticlesAlive);
}
const size_t start = nParticlesAlive;
nParticlesAlive += n;
const size_t size = std::max(size_t(8), nextPowerOf2(nParticlesAlive));
if (particles.size() < size) {
particles.resize(size);
sprites.resize(size);
if (isAnimated()) {
animationPlayers.resize(size, AnimationPlayerLite(baseAnimation));
}
}
for (size_t i = start; i < nParticlesAlive; ++i) {
initializeParticle(i);
}
}
void Particles::initializeParticle(size_t index)
{
const auto startAzimuth = Angle1f::fromDegrees(rng->getFloat(angle.x - angleScatter.x, angle.x + angleScatter.x));
const auto startElevation = Angle1f::fromDegrees(rng->getFloat(angle.y - angleScatter.y, angle.y + angleScatter.y));
auto& particle = particles[index];
particle.alive = true;
particle.time = 0;
particle.ttl = rng->getFloat(ttl - ttlScatter, ttl + ttlScatter);
particle.pos = getSpawnPosition();
particle.angle = rotateTowardsMovement ? startAzimuth : Angle1f();
particle.scale = startScale;
particle.vel = Vector3f(rng->getFloat(speed - speedScatter, speed + speedScatter), startAzimuth, startElevation) * velScale;
auto& sprite = sprites[index];
if (isAnimated()) {
auto& anim = animationPlayers[index];
anim.update(0, sprite);
} else if (!baseSprites.empty()) {
sprite = rng->getRandomElement(baseSprites);
}
}
void Particles::updateParticles(float time)
{
const bool hasAnim = isAnimated();
for (size_t i = 0; i < nParticlesAlive; ++i) {
if (hasAnim) {
animationPlayers[i].update(time, sprites[i]);
}
auto& particle = particles[i];
particle.time += time;
if (particle.time >= particle.ttl) {
particle.alive = false;
} else {
particle.pos += particle.vel * time + 0.5f * acceleration * time * time;
particle.vel += acceleration * time;
if (minHeight && particle.pos.z < minHeight) {
particle.alive = false;
}
if (stopTime > 0.00001f && particle.time + stopTime >= particle.ttl) {
particle.vel = damp(particle.vel, Vector3f(), 10.0f, time);
}
if (speedDamp > 0.0001f) {
particle.vel = damp(particle.vel, Vector3f(), speedDamp, time);
}
if (directionScatter > 0.00001f) {
particle.vel = Vector3f(particle.vel.xy().rotate(Angle1f::fromDegrees(rng->getFloat(-directionScatter * time, directionScatter * time))), particle.vel.z);
}
if (rotateTowardsMovement && particle.vel.squaredLength() > 0.001f) {
particle.angle = particle.vel.xy().angle();
}
particle.scale = lerp(startScale, endScale, particle.time / particle.ttl);
if (fadeInTime > 0.000001f || fadeOutTime > 0.00001f) {
const float alpha = clamp(std::min(particle.time / fadeInTime, (particle.ttl - particle.time) / fadeOutTime), 0.0f, 1.0f);
sprites[i].getColour().a = alpha;
}
sprites[i]
.setPosition(particle.pos.xy() + Vector2f(0, -particle.pos.z))
.setRotation(particle.angle)
.setScale(particle.scale);
}
}
}
Vector3f Particles::getSpawnPosition() const
{
return position + Vector3f(rng->getFloat(-spawnArea.x * 0.5f, spawnArea.x * 0.5f), rng->getFloat(-spawnArea.y * 0.5f, spawnArea.y * 0.5f), startHeight);
}
ConfigNode ConfigNodeSerializer<Particles>::serialize(const Particles& particles, const EntitySerializationContext& context)
{
return particles.toConfigNode();
}
Particles ConfigNodeSerializer<Particles>::deserialize(const EntitySerializationContext& context, const ConfigNode& node)
{
return Particles(node, *context.resources);
}
void ConfigNodeSerializer<Particles>::deserialize(const EntitySerializationContext& context, const ConfigNode& node, Particles& target)
{
target.load(node, *context.resources);
}
<commit_msg>Small particles fix<commit_after>#include "graphics/sprite/particles.h"
#include "halley/maths/random.h"
#include "halley/support/logger.h"
using namespace Halley;
Particles::Particles()
: rng(&Random::getGlobal())
{
}
Particles::Particles(const ConfigNode& node, Resources& resources)
: rng(&Random::getGlobal())
{
load(node, resources);
}
void Particles::load(const ConfigNode& node, Resources& resources)
{
spawnRate = node["spawnRate"].asFloat(100);
spawnArea = node["spawnArea"].asVector2f(Vector2f(0, 0));
ttl = node["ttl"].asFloat(1.0f);
ttlScatter = node["ttlScatter"].asFloat(0.0f);
speed = node["speed"].asFloat(100.0f);
speedScatter = node["speedScatter"].asFloat(0.0f);
speedDamp = node["speedDamp"].asFloat(0.0f);
acceleration = node["acceleration"].asVector3f(Vector3f());
angle = node["angle"].asVector2f(Vector2f());
angleScatter = node["angleScatter"].asVector2f(Vector2f());
startScale = node["startScale"].asFloat(1.0f);
endScale = node["endScale"].asFloat(1.0f);
fadeInTime = node["fadeInTime"].asFloat(0.0f);
fadeOutTime = node["fadeOutTime"].asFloat(0.0f);
stopTime = node["stopTime"].asFloat(0.0f);
directionScatter = node["directionScatter"].asFloat(0.0f);
rotateTowardsMovement = node["rotateTowardsMovement"].asBool(false);
destroyWhenDone = node["destroyWhenDone"].asBool(false);
velScale = node["velScale"].asVector3f(Vector3f(1, 1, 1));
if (node.hasKey("minHeight")) {
minHeight = node["minHeight"].asFloat();
}
startHeight = node["startHeight"].asFloat(0);
if (node.hasKey("maxParticles")) {
maxParticles = node["maxParticles"].asInt();
}
if (node.hasKey("burst")) {
burst = node["burst"].asInt();
}
}
ConfigNode Particles::toConfigNode() const
{
ConfigNode::MapType result;
result["spawnRate"] = spawnRate;
result["spawnArea"] = spawnArea;
result["ttl"] = ttl;
result["ttlScatter"] = ttlScatter;
result["speed"] = speed;
result["speedScatter"] = speedScatter;
result["speedDamp"] = speedDamp;
result["acceleration"] = acceleration;
result["angle"] = angle;
result["angleScatter"] = angleScatter;
result["startScale"] = startScale;
result["endScale"] = endScale;
result["fadeInTime"] = fadeInTime;
result["fadeOutTime"] = fadeOutTime;
result["stopTime"] = stopTime;
result["directionScatter"] = directionScatter;
result["rotateTowardsMovement"] = rotateTowardsMovement;
result["destroyWhenDone"] = destroyWhenDone;
result["velScale"] = velScale;
if (minHeight) {
result["minHeight"] = *minHeight;
}
result["startHeight"] = startHeight;
if (maxParticles) {
result["maxParticles"] = static_cast<int>(maxParticles.value());
}
if (burst) {
result["burst"] = static_cast<int>(burst.value());
}
return result;
}
void Particles::burstParticles(size_t n)
{
pendingSpawn += static_cast<float>(n);
}
void Particles::setEnabled(bool e)
{
enabled = e;
}
bool Particles::isEnabled() const
{
return enabled;
}
void Particles::setSpawnRateMultiplier(float value)
{
spawnRateMultiplier = value;
}
float Particles::getSpawnRateMultiplier() const
{
return spawnRateMultiplier;
}
void Particles::setPosition(Vector2f pos)
{
position = Vector3f(pos);
}
void Particles::setPosition(Vector3f pos)
{
position = pos;
}
void Particles::setSpawnArea(Vector2f area)
{
spawnArea = area;
}
void Particles::setAngle(float newAngle)
{
angle = Vector2f(newAngle, 0);
}
void Particles::setAngle(Vector2f newAngle)
{
angle = newAngle;
}
Vector2f Particles::getAngle() const
{
return angle;
}
void Particles::setSpeed(float newSpeed)
{
speed = newSpeed;
}
float Particles::getSpeed() const
{
return speed;
}
void Particles::setAcceleration(Vector3f accel)
{
acceleration = accel;
}
Vector3f Particles::getAcceleration() const
{
return acceleration;
}
void Particles::setMinHeight(std::optional<float> z)
{
minHeight = z;
}
std::optional<float> Particles::getMinHeight() const
{
return minHeight;
}
void Particles::setSpawnHeight(float height)
{
startHeight = height;
}
float Particles::getSpawnHeight() const
{
return startHeight;
}
void Particles::start()
{
if (burst) {
spawn(burst.value());
}
}
void Particles::update(Time t)
{
if (firstUpdate) {
firstUpdate = false;
start();
}
pendingSpawn += static_cast<float>(t * spawnRate * (enabled && !burst ? spawnRateMultiplier : 0));
const int toSpawn = static_cast<int>(floor(pendingSpawn));
pendingSpawn = pendingSpawn - static_cast<float>(toSpawn);
// Spawn new particles
spawn(static_cast<size_t>(toSpawn));
// Update particles
updateParticles(static_cast<float>(t));
// Remove dead particles
for (size_t i = 0; i < nParticlesAlive; ) {
if (!particles[i].alive) {
if (i != nParticlesAlive - 1) {
// Swap with last particle that's alive
std::swap(particles[i], particles[nParticlesAlive - 1]);
std::swap(sprites[i], sprites[nParticlesAlive - 1]);
if (isAnimated()) {
std::swap(animationPlayers[i], animationPlayers[nParticlesAlive - 1]);
}
}
--nParticlesAlive;
// Don't increment i here, since i is now a new particle that's still alive
} else {
++i;
}
}
// Update visibility
nParticlesVisible = nParticlesAlive;
if (nParticlesVisible > 0 && !sprites[0].hasMaterial()) {
nParticlesVisible = 0;
}
}
void Particles::setSprites(Vector<Sprite> sprites)
{
baseSprites = std::move(sprites);
}
void Particles::setAnimation(std::shared_ptr<const Animation> animation)
{
baseAnimation = std::move(animation);
}
bool Particles::isAnimated() const
{
return !!baseAnimation;
}
bool Particles::isAlive() const
{
return nParticlesAlive > 0 || !destroyWhenDone;
}
gsl::span<Sprite> Particles::getSprites()
{
return gsl::span<Sprite>(sprites).subspan(0, nParticlesVisible);
}
gsl::span<const Sprite> Particles::getSprites() const
{
return gsl::span<const Sprite>(sprites).subspan(0, nParticlesVisible);
}
void Particles::spawn(size_t n)
{
if (maxParticles) {
n = std::min(n, maxParticles.value() - nParticlesAlive);
}
const size_t start = nParticlesAlive;
nParticlesAlive += n;
const size_t size = std::max(size_t(8), nextPowerOf2(nParticlesAlive));
if (particles.size() < size) {
particles.resize(size);
sprites.resize(size);
if (isAnimated()) {
animationPlayers.resize(size, AnimationPlayerLite(baseAnimation));
}
}
for (size_t i = start; i < nParticlesAlive; ++i) {
initializeParticle(i);
}
}
void Particles::initializeParticle(size_t index)
{
const auto startAzimuth = Angle1f::fromDegrees(rng->getFloat(angle.x - angleScatter.x, angle.x + angleScatter.x));
const auto startElevation = Angle1f::fromDegrees(rng->getFloat(angle.y - angleScatter.y, angle.y + angleScatter.y));
auto& particle = particles[index];
particle.alive = true;
particle.time = 0;
particle.ttl = rng->getFloat(ttl - ttlScatter, ttl + ttlScatter);
particle.pos = getSpawnPosition();
particle.angle = rotateTowardsMovement ? startAzimuth : Angle1f();
particle.scale = startScale;
particle.vel = Vector3f(rng->getFloat(speed - speedScatter, speed + speedScatter), startAzimuth, startElevation);
auto& sprite = sprites[index];
if (isAnimated()) {
auto& anim = animationPlayers[index];
anim.update(0, sprite);
} else if (!baseSprites.empty()) {
sprite = rng->getRandomElement(baseSprites);
}
}
void Particles::updateParticles(float time)
{
const bool hasAnim = isAnimated();
for (size_t i = 0; i < nParticlesAlive; ++i) {
if (hasAnim) {
animationPlayers[i].update(time, sprites[i]);
}
auto& particle = particles[i];
particle.time += time;
if (particle.time >= particle.ttl) {
particle.alive = false;
} else {
particle.pos += (particle.vel * time + acceleration * (0.5f * time * time)) * velScale;
particle.vel += acceleration * time;
if (minHeight && particle.pos.z < minHeight) {
particle.alive = false;
}
if (stopTime > 0.00001f && particle.time + stopTime >= particle.ttl) {
particle.vel = damp(particle.vel, Vector3f(), 10.0f, time);
}
if (speedDamp > 0.0001f) {
particle.vel = damp(particle.vel, Vector3f(), speedDamp, time);
}
if (directionScatter > 0.00001f) {
particle.vel = Vector3f(particle.vel.xy().rotate(Angle1f::fromDegrees(rng->getFloat(-directionScatter * time, directionScatter * time))), particle.vel.z);
}
if (rotateTowardsMovement && particle.vel.squaredLength() > 0.001f) {
particle.angle = particle.vel.xy().angle();
}
particle.scale = lerp(startScale, endScale, particle.time / particle.ttl);
if (fadeInTime > 0.000001f || fadeOutTime > 0.00001f) {
const float alpha = clamp(std::min(particle.time / fadeInTime, (particle.ttl - particle.time) / fadeOutTime), 0.0f, 1.0f);
sprites[i].getColour().a = alpha;
}
sprites[i]
.setPosition(particle.pos.xy() + Vector2f(0, -particle.pos.z))
.setRotation(particle.angle)
.setScale(particle.scale);
}
}
}
Vector3f Particles::getSpawnPosition() const
{
return position + Vector3f(rng->getFloat(-spawnArea.x * 0.5f, spawnArea.x * 0.5f), rng->getFloat(-spawnArea.y * 0.5f, spawnArea.y * 0.5f), startHeight);
}
ConfigNode ConfigNodeSerializer<Particles>::serialize(const Particles& particles, const EntitySerializationContext& context)
{
return particles.toConfigNode();
}
Particles ConfigNodeSerializer<Particles>::deserialize(const EntitySerializationContext& context, const ConfigNode& node)
{
return Particles(node, *context.resources);
}
void ConfigNodeSerializer<Particles>::deserialize(const EntitySerializationContext& context, const ConfigNode& node, Particles& target)
{
target.load(node, *context.resources);
}
<|endoftext|>
|
<commit_before>#include "Configuration.h"
#include "../hardware\board\Board.h"
#include "..\interface\settings\MIDIsettings.h"
#include "..\interface\settings\LEDsettings.h"
void Configuration::createMemoryLayout() {
/*
*BLOCK CONTENT DEFINITON*
section number of sections inside block
subsectionType value formatting of parameters inside block
*BIT_PARAMETER 8 parameters per byte
*BYTE_PARAMETER 1 parameter per byte
defaultValue any value 0-127 or AUTO_INCREMENT (next value gets increased by 1)
sectionParameters number of parameters in section
*/
{
blocks[CONF_MIDI_BLOCK].sections = MIDI_SECTIONS;
blocks[CONF_MIDI_BLOCK].subsectionType[midiFeatureSection] = BIT_PARAMETER;
blocks[CONF_MIDI_BLOCK].defaultValue[midiFeatureSection] = 0;
blocks[CONF_MIDI_BLOCK].sectionParameters[midiFeatureSection] = MIDI_FEATURES;
blocks[CONF_MIDI_BLOCK].subsectionType[midiChannelSection] = BYTE_PARAMETER;
blocks[CONF_MIDI_BLOCK].defaultValue[midiChannelSection] = 0x01;
blocks[CONF_MIDI_BLOCK].sectionParameters[midiChannelSection] = MIDI_CHANNELS;
}
{
blocks[CONF_BUTTON_BLOCK].sections = BUTTON_SECTIONS;
blocks[CONF_BUTTON_BLOCK].subsectionType[buttonTypeSection] = BIT_PARAMETER;
blocks[CONF_BUTTON_BLOCK].defaultValue[buttonTypeSection] = 0;
blocks[CONF_BUTTON_BLOCK].sectionParameters[buttonTypeSection] = MAX_NUMBER_OF_BUTTONS;
blocks[CONF_BUTTON_BLOCK].subsectionType[buttonProgramChangeEnabledSection] = BIT_PARAMETER;
blocks[CONF_BUTTON_BLOCK].defaultValue[buttonProgramChangeEnabledSection] = 0;
blocks[CONF_BUTTON_BLOCK].sectionParameters[buttonProgramChangeEnabledSection] = MAX_NUMBER_OF_BUTTONS;
blocks[CONF_BUTTON_BLOCK].subsectionType[buttonMIDIidSection] = BYTE_PARAMETER;
blocks[CONF_BUTTON_BLOCK].defaultValue[buttonMIDIidSection] = AUTO_INCREMENT;
blocks[CONF_BUTTON_BLOCK].sectionParameters[buttonMIDIidSection] = MAX_NUMBER_OF_BUTTONS;
}
{
blocks[CONF_ENCODER_BLOCK].sections = ENCODER_SECTIONS;
blocks[CONF_ENCODER_BLOCK].subsectionType[encoderEnabledSection] = BIT_PARAMETER;
blocks[CONF_ENCODER_BLOCK].defaultValue[encoderEnabledSection] = 0;
blocks[CONF_ENCODER_BLOCK].sectionParameters[encoderEnabledSection] = MAX_NUMBER_OF_ENCODERS;
blocks[CONF_ENCODER_BLOCK].subsectionType[encoderInvertedSection] = BIT_PARAMETER;
blocks[CONF_ENCODER_BLOCK].defaultValue[encoderInvertedSection] = 0;
blocks[CONF_ENCODER_BLOCK].sectionParameters[encoderInvertedSection] = MAX_NUMBER_OF_ENCODERS;
blocks[CONF_ENCODER_BLOCK].subsectionType[encoderEncodingModeSection] = BYTE_PARAMETER;
blocks[CONF_ENCODER_BLOCK].defaultValue[encoderEncodingModeSection] = enc7Fh01h;
blocks[CONF_ENCODER_BLOCK].sectionParameters[encoderEncodingModeSection] = MAX_NUMBER_OF_ENCODERS;
blocks[CONF_ENCODER_BLOCK].subsectionType[encoderMIDIidSection] = BYTE_PARAMETER;
blocks[CONF_ENCODER_BLOCK].defaultValue[encoderMIDIidSection] = AUTO_INCREMENT;
blocks[CONF_ENCODER_BLOCK].sectionParameters[encoderMIDIidSection] = MAX_NUMBER_OF_ENCODERS;
}
{
blocks[CONF_ANALOG_BLOCK].sections = ANALOG_SECTIONS;
blocks[CONF_ANALOG_BLOCK].subsectionType[analogEnabledSection] = BIT_PARAMETER;
blocks[CONF_ANALOG_BLOCK].defaultValue[analogEnabledSection] = 0;
blocks[CONF_ANALOG_BLOCK].sectionParameters[analogEnabledSection] = MAX_NUMBER_OF_ANALOG;
blocks[CONF_ANALOG_BLOCK].subsectionType[analogInvertedSection] = BIT_PARAMETER;
blocks[CONF_ANALOG_BLOCK].defaultValue[analogInvertedSection] = 0;
blocks[CONF_ANALOG_BLOCK].sectionParameters[analogInvertedSection] = MAX_NUMBER_OF_ANALOG;
blocks[CONF_ANALOG_BLOCK].subsectionType[analogTypeSection] = BYTE_PARAMETER;
blocks[CONF_ANALOG_BLOCK].defaultValue[analogTypeSection] = AUTO_INCREMENT;
blocks[CONF_ANALOG_BLOCK].sectionParameters[analogTypeSection] = MAX_NUMBER_OF_ANALOG;
blocks[CONF_ANALOG_BLOCK].subsectionType[analogMIDIidSection] = BYTE_PARAMETER;
blocks[CONF_ANALOG_BLOCK].defaultValue[analogMIDIidSection] = AUTO_INCREMENT;
blocks[CONF_ANALOG_BLOCK].sectionParameters[analogMIDIidSection] = MAX_NUMBER_OF_ANALOG;
blocks[CONF_ANALOG_BLOCK].subsectionType[analogCClowerLimitSection] = BYTE_PARAMETER;
blocks[CONF_ANALOG_BLOCK].defaultValue[analogCClowerLimitSection] = 0;
blocks[CONF_ANALOG_BLOCK].sectionParameters[analogCClowerLimitSection] = MAX_NUMBER_OF_ANALOG;
blocks[CONF_ANALOG_BLOCK].subsectionType[analogCCupperLimitSection] = BYTE_PARAMETER;
blocks[CONF_ANALOG_BLOCK].defaultValue[analogCCupperLimitSection] = 127;
blocks[CONF_ANALOG_BLOCK].sectionParameters[analogCCupperLimitSection] = MAX_NUMBER_OF_ANALOG;
}
{
blocks[CONF_LED_BLOCK].sections = LED_SECTIONS;
blocks[CONF_LED_BLOCK].subsectionType[ledHardwareParameterSection] = BYTE_PARAMETER;
blocks[CONF_LED_BLOCK].defaultValue[ledHardwareParameterSection] = 0;
blocks[CONF_LED_BLOCK].sectionParameters[ledHardwareParameterSection] = LED_HARDWARE_PARAMETERS;
blocks[CONF_LED_BLOCK].subsectionType[ledActivationNoteSection] = BYTE_PARAMETER;
blocks[CONF_LED_BLOCK].defaultValue[ledActivationNoteSection] = 128;
blocks[CONF_LED_BLOCK].sectionParameters[ledActivationNoteSection] = MAX_NUMBER_OF_LEDS;
blocks[CONF_LED_BLOCK].subsectionType[ledStartUpNumberSection] = BYTE_PARAMETER;
blocks[CONF_LED_BLOCK].defaultValue[ledStartUpNumberSection] = MAX_NUMBER_OF_LEDS;
blocks[CONF_LED_BLOCK].sectionParameters[ledStartUpNumberSection] = MAX_NUMBER_OF_LEDS;
blocks[CONF_LED_BLOCK].subsectionType[ledRGBenabledSection] = BIT_PARAMETER;
blocks[CONF_LED_BLOCK].defaultValue[ledRGBenabledSection] = 0;
blocks[CONF_LED_BLOCK].sectionParameters[ledRGBenabledSection] = MAX_NUMBER_OF_LEDS;
}
}<commit_msg>fix incorrect default value for analog type<commit_after>#include "Configuration.h"
#include "../hardware\board\Board.h"
#include "..\interface\settings\MIDIsettings.h"
#include "..\interface\settings\LEDsettings.h"
void Configuration::createMemoryLayout() {
/*
*BLOCK CONTENT DEFINITON*
section number of sections inside block
subsectionType value formatting of parameters inside block
*BIT_PARAMETER 8 parameters per byte
*BYTE_PARAMETER 1 parameter per byte
defaultValue any value 0-127 or AUTO_INCREMENT (next value gets increased by 1)
sectionParameters number of parameters in section
*/
{
blocks[CONF_MIDI_BLOCK].sections = MIDI_SECTIONS;
blocks[CONF_MIDI_BLOCK].subsectionType[midiFeatureSection] = BIT_PARAMETER;
blocks[CONF_MIDI_BLOCK].defaultValue[midiFeatureSection] = 0;
blocks[CONF_MIDI_BLOCK].sectionParameters[midiFeatureSection] = MIDI_FEATURES;
blocks[CONF_MIDI_BLOCK].subsectionType[midiChannelSection] = BYTE_PARAMETER;
blocks[CONF_MIDI_BLOCK].defaultValue[midiChannelSection] = 0x01;
blocks[CONF_MIDI_BLOCK].sectionParameters[midiChannelSection] = MIDI_CHANNELS;
}
{
blocks[CONF_BUTTON_BLOCK].sections = BUTTON_SECTIONS;
blocks[CONF_BUTTON_BLOCK].subsectionType[buttonTypeSection] = BIT_PARAMETER;
blocks[CONF_BUTTON_BLOCK].defaultValue[buttonTypeSection] = 0;
blocks[CONF_BUTTON_BLOCK].sectionParameters[buttonTypeSection] = MAX_NUMBER_OF_BUTTONS;
blocks[CONF_BUTTON_BLOCK].subsectionType[buttonProgramChangeEnabledSection] = BIT_PARAMETER;
blocks[CONF_BUTTON_BLOCK].defaultValue[buttonProgramChangeEnabledSection] = 0;
blocks[CONF_BUTTON_BLOCK].sectionParameters[buttonProgramChangeEnabledSection] = MAX_NUMBER_OF_BUTTONS;
blocks[CONF_BUTTON_BLOCK].subsectionType[buttonMIDIidSection] = BYTE_PARAMETER;
blocks[CONF_BUTTON_BLOCK].defaultValue[buttonMIDIidSection] = AUTO_INCREMENT;
blocks[CONF_BUTTON_BLOCK].sectionParameters[buttonMIDIidSection] = MAX_NUMBER_OF_BUTTONS;
}
{
blocks[CONF_ENCODER_BLOCK].sections = ENCODER_SECTIONS;
blocks[CONF_ENCODER_BLOCK].subsectionType[encoderEnabledSection] = BIT_PARAMETER;
blocks[CONF_ENCODER_BLOCK].defaultValue[encoderEnabledSection] = 0;
blocks[CONF_ENCODER_BLOCK].sectionParameters[encoderEnabledSection] = MAX_NUMBER_OF_ENCODERS;
blocks[CONF_ENCODER_BLOCK].subsectionType[encoderInvertedSection] = BIT_PARAMETER;
blocks[CONF_ENCODER_BLOCK].defaultValue[encoderInvertedSection] = 0;
blocks[CONF_ENCODER_BLOCK].sectionParameters[encoderInvertedSection] = MAX_NUMBER_OF_ENCODERS;
blocks[CONF_ENCODER_BLOCK].subsectionType[encoderEncodingModeSection] = BYTE_PARAMETER;
blocks[CONF_ENCODER_BLOCK].defaultValue[encoderEncodingModeSection] = enc7Fh01h;
blocks[CONF_ENCODER_BLOCK].sectionParameters[encoderEncodingModeSection] = MAX_NUMBER_OF_ENCODERS;
blocks[CONF_ENCODER_BLOCK].subsectionType[encoderMIDIidSection] = BYTE_PARAMETER;
blocks[CONF_ENCODER_BLOCK].defaultValue[encoderMIDIidSection] = AUTO_INCREMENT;
blocks[CONF_ENCODER_BLOCK].sectionParameters[encoderMIDIidSection] = MAX_NUMBER_OF_ENCODERS;
}
{
blocks[CONF_ANALOG_BLOCK].sections = ANALOG_SECTIONS;
blocks[CONF_ANALOG_BLOCK].subsectionType[analogEnabledSection] = BIT_PARAMETER;
blocks[CONF_ANALOG_BLOCK].defaultValue[analogEnabledSection] = 0;
blocks[CONF_ANALOG_BLOCK].sectionParameters[analogEnabledSection] = MAX_NUMBER_OF_ANALOG;
blocks[CONF_ANALOG_BLOCK].subsectionType[analogInvertedSection] = BIT_PARAMETER;
blocks[CONF_ANALOG_BLOCK].defaultValue[analogInvertedSection] = 0;
blocks[CONF_ANALOG_BLOCK].sectionParameters[analogInvertedSection] = MAX_NUMBER_OF_ANALOG;
blocks[CONF_ANALOG_BLOCK].subsectionType[analogTypeSection] = BYTE_PARAMETER;
blocks[CONF_ANALOG_BLOCK].defaultValue[analogTypeSection] = 0;
blocks[CONF_ANALOG_BLOCK].sectionParameters[analogTypeSection] = MAX_NUMBER_OF_ANALOG;
blocks[CONF_ANALOG_BLOCK].subsectionType[analogMIDIidSection] = BYTE_PARAMETER;
blocks[CONF_ANALOG_BLOCK].defaultValue[analogMIDIidSection] = AUTO_INCREMENT;
blocks[CONF_ANALOG_BLOCK].sectionParameters[analogMIDIidSection] = MAX_NUMBER_OF_ANALOG;
blocks[CONF_ANALOG_BLOCK].subsectionType[analogCClowerLimitSection] = BYTE_PARAMETER;
blocks[CONF_ANALOG_BLOCK].defaultValue[analogCClowerLimitSection] = 0;
blocks[CONF_ANALOG_BLOCK].sectionParameters[analogCClowerLimitSection] = MAX_NUMBER_OF_ANALOG;
blocks[CONF_ANALOG_BLOCK].subsectionType[analogCCupperLimitSection] = BYTE_PARAMETER;
blocks[CONF_ANALOG_BLOCK].defaultValue[analogCCupperLimitSection] = 127;
blocks[CONF_ANALOG_BLOCK].sectionParameters[analogCCupperLimitSection] = MAX_NUMBER_OF_ANALOG;
}
{
blocks[CONF_LED_BLOCK].sections = LED_SECTIONS;
blocks[CONF_LED_BLOCK].subsectionType[ledHardwareParameterSection] = BYTE_PARAMETER;
blocks[CONF_LED_BLOCK].defaultValue[ledHardwareParameterSection] = 0;
blocks[CONF_LED_BLOCK].sectionParameters[ledHardwareParameterSection] = LED_HARDWARE_PARAMETERS;
blocks[CONF_LED_BLOCK].subsectionType[ledActivationNoteSection] = BYTE_PARAMETER;
blocks[CONF_LED_BLOCK].defaultValue[ledActivationNoteSection] = 128;
blocks[CONF_LED_BLOCK].sectionParameters[ledActivationNoteSection] = MAX_NUMBER_OF_LEDS;
blocks[CONF_LED_BLOCK].subsectionType[ledStartUpNumberSection] = BYTE_PARAMETER;
blocks[CONF_LED_BLOCK].defaultValue[ledStartUpNumberSection] = MAX_NUMBER_OF_LEDS;
blocks[CONF_LED_BLOCK].sectionParameters[ledStartUpNumberSection] = MAX_NUMBER_OF_LEDS;
blocks[CONF_LED_BLOCK].subsectionType[ledRGBenabledSection] = BIT_PARAMETER;
blocks[CONF_LED_BLOCK].defaultValue[ledRGBenabledSection] = 0;
blocks[CONF_LED_BLOCK].sectionParameters[ledRGBenabledSection] = MAX_NUMBER_OF_LEDS;
}
}<|endoftext|>
|
<commit_before>#include "stdafx.h"
#define PLEXALLOC_DESTRUCTORS
#include "PlexAlloc/Allocator.hpp"
template <typename T>
using PlexAllocator = PlexAlloc::Allocator<T>;
__interface iTestCase
{
void prepare( size_t length );
int run( int inserts );
};
// A test case for STL containers. Because they expose very similar API, a single template implementation is required.
template<class tContainer>
class testStl: public iTestCase
{
tContainer local;
void prepare( size_t length )
{
for( size_t i = 0; i < length; i++ )
local.push_back( 1 );
}
int run( int localInserts )
{
for( int i = 0; i < localInserts; i++ )
local.insert( local.begin(), 1 );
int sum = 0;
for( int i : local )
sum += i;
return sum;
}
};
// ATL containers need special care in terms of API.
class testAtlArray: public iTestCase
{
CAtlArray<int> local;
void prepare( size_t length )
{
for( size_t i = 0; i < length; i++ )
local.Add( 1 );
}
int run( int localInserts )
{
for( int i = 0; i < localInserts; i++ )
local.InsertAt( 0, 1 );
int sum = 0;
for( size_t i = 0; i < local.GetCount(); i++ )
sum += local[ i ];
return sum;
}
};
class testAtlList: public iTestCase
{
CAtlList<int> local;
void prepare( size_t length )
{
for( size_t i = 0; i < length; i++ )
local.AddTail( 1 );
}
int run( int localInserts )
{
for( int i = 0; i < localInserts; i++ )
local.AddHead( 1 );
int sum = 0;
for( POSITION pos = local.GetHeadPosition(); nullptr != pos; )
sum += local.GetNext( pos );
return sum;
}
};
static void run( iTestCase *proc, size_t length, int inserts )
{
using namespace std::chrono;
using stopwatch = high_resolution_clock;
proc->prepare( length );
const stopwatch::time_point t1 = stopwatch::now();
const int res = proc->run( inserts );
const stopwatch::time_point t2 = stopwatch::now();
duration<double> time_span = duration_cast<duration<double>>( t2 - t1 );
printf( "%i\t%.9f\t%i\n", int( length ), time_span.count(), res );
}
int main()
{
const int inserts = 5;
size_t lengths[] = { 100, 1000, 100000, 1000000, 10000000, 100000000 };
using tTest =
// testStl<std::vector<int>>;
// testStl<std::list<int>>;
// testAtlArray;
testAtlList;
// testStl<std::list<int, PlexAllocator<int>>>;
for( size_t l : lengths )
{
tTest coll;
run( &coll, l, inserts );
}
return 0;
}<commit_msg>Minor<commit_after>#include "stdafx.h"
#include "PlexAlloc/Allocator.hpp"
template <typename T>
using PlexAllocator = PlexAlloc::Allocator<T>;
__interface iTestCase
{
void prepare( size_t length );
int run( int inserts );
};
// A test case for STL containers. Because they expose very similar API, a single template implementation is required.
template<class tContainer>
class testStl: public iTestCase
{
tContainer local;
void prepare( size_t length )
{
for( size_t i = 0; i < length; i++ )
local.push_back( 1 );
}
int run( int localInserts )
{
for( int i = 0; i < localInserts; i++ )
local.insert( local.begin(), 1 );
int sum = 0;
for( int i : local )
sum += i;
return sum;
}
};
// ATL containers need special care in terms of API.
class testAtlArray: public iTestCase
{
CAtlArray<int> local;
void prepare( size_t length )
{
for( size_t i = 0; i < length; i++ )
local.Add( 1 );
}
int run( int localInserts )
{
for( int i = 0; i < localInserts; i++ )
local.InsertAt( 0, 1 );
int sum = 0;
for( size_t i = 0; i < local.GetCount(); i++ )
sum += local[ i ];
return sum;
}
};
class testAtlList: public iTestCase
{
CAtlList<int> local;
void prepare( size_t length )
{
for( size_t i = 0; i < length; i++ )
local.AddTail( 1 );
}
int run( int localInserts )
{
for( int i = 0; i < localInserts; i++ )
local.AddHead( 1 );
int sum = 0;
for( POSITION pos = local.GetHeadPosition(); nullptr != pos; )
sum += local.GetNext( pos );
return sum;
}
};
static void run( iTestCase *proc, size_t length, int inserts )
{
using namespace std::chrono;
using stopwatch = high_resolution_clock;
proc->prepare( length );
const stopwatch::time_point t1 = stopwatch::now();
const int res = proc->run( inserts );
const stopwatch::time_point t2 = stopwatch::now();
duration<double> time_span = duration_cast<duration<double>>( t2 - t1 );
printf( "%i\t%.9f\t%i\n", int( length ), time_span.count(), res );
}
int main()
{
const int inserts = 5;
size_t lengths[] = { 100, 1000, 100000, 1000000, 10000000, 100000000 };
using tTest =
// testStl<std::vector<int>>;
// testStl<std::list<int>>;
// testAtlArray;
testAtlList;
// testStl<std::list<int, PlexAllocator<int>>>;
for( size_t l : lengths )
{
tTest coll;
run( &coll, l, inserts );
}
return 0;
}<|endoftext|>
|
<commit_before>#include "PCH.h"
#include "Transform.h"
#include <algorithm>
#include "Math/Vector3.h"
#include "misc/cpp/imgui_stdlib.h"
#include "Engine/Engine.h"
#include "Mathf.h"
#include <SimpleMath.h>
#include "optick.h"
Transform::Transform()
: Component("Transform")
, WorldTransform(DirectX::XMMatrixIdentity())
, Position(0.f, 0.f, 0.f)
, Rotation(0.f, 0.f, 0.f)
, Scale(1.0f, 1.0f, 1.0f)
{
}
Transform::Transform(const std::string& TransformName)
: Component("Transform")
, WorldTransform(DirectX::XMMatrixIdentity())
, Name(std::move(TransformName))
, Position(0.f, 0.f, 0.f)
, Rotation(0.f, 0.f, 0.f)
, Scale(1.0f, 1.0f, 1.0f)
{
}
Transform::~Transform()
{
if (ParentTransform)
{
ParentTransform->RemoveChild(shared_from_this().get());
}
}
void Transform::SetPosition(Vector3 NewPosition)
{
WorldTransform.GetInternalMatrix().Translation((Position - NewPosition).GetInternalVec());
Position = NewPosition;
SetDirty(true);
//UpdateRecursively(this);
}
void Transform::SetScale(Vector3 NewScale)
{
if (NewScale == Vector3())
{
return;
}
Scale = NewScale;
SetDirty(true);
}
void Transform::SetScale(float NewScale)
{
if (NewScale == Scale.x && NewScale == Scale.y && NewScale == Scale.z)
{
return;
}
Scale = Vector3(NewScale);
SetDirty(true);
}
void Transform::Translate(Vector3 NewPosition)
{
if (NewPosition == Vector3())
{
return;
}
SetWorldPosition(Position + NewPosition);
}
Vector3 Transform::Front()
{
//float mat1 = -;// 2, 0);
//float mat2 = -WorldTransform.GetInternalMatrix()(2, 1);
//float mat3 = -WorldTransform.GetInternalMatrix()(2, 2);
return Vector3(WorldTransform.GetInternalMatrix().Forward());
}
Vector3 Transform::Up()
{
return Vector3(WorldTransform.GetInternalMatrix().Up());
}
Vector3& Transform::GetPosition()
{
return Position;
}
void Transform::UpdateRecursively(SharedPtr<Transform> CurrentTransform)
{
OPTICK_EVENT("SceneGraph::UpdateRecursively");
for (SharedPtr<Transform> Child : CurrentTransform->GetChildren())
{
if (Child->m_isDirty)
{
OPTICK_EVENT("SceneGraph::Update::IsDirty");
//Quaternion quat = Quaternion(Child->Rotation);
DirectX::SimpleMath::Matrix id = DirectX::XMMatrixIdentity();
DirectX::SimpleMath::Matrix rot = DirectX::SimpleMath::Matrix::CreateFromQuaternion(DirectX::SimpleMath::Quaternion::CreateFromYawPitchRoll(Child->Rotation[1], Child->Rotation[0], Child->Rotation[2]));// , Child->Rotation.Y(), Child->Rotation.Z());
DirectX::SimpleMath::Matrix scale = DirectX::SimpleMath::Matrix::CreateScale(Child->GetScale().GetInternalVec());
DirectX::SimpleMath::Matrix pos = XMMatrixTranslationFromVector(Child->GetPosition().GetInternalVec());
Child->SetWorldTransform(Matrix4((scale * rot * pos) * CurrentTransform->WorldTransform.GetInternalMatrix()));
}
UpdateRecursively(Child);
}
}
void Transform::UpdateWorldTransform()
{
DirectX::SimpleMath::Matrix id = DirectX::XMMatrixIdentity();
DirectX::SimpleMath::Matrix rot = DirectX::SimpleMath::Matrix::CreateFromQuaternion(DirectX::SimpleMath::Quaternion::CreateFromYawPitchRoll(Rotation[1], Rotation[0], Rotation[2]));// , Child->Rotation.Y(), Child->Rotation.Z());
DirectX::SimpleMath::Matrix scale = DirectX::SimpleMath::Matrix::CreateScale(GetScale().GetInternalVec());
DirectX::SimpleMath::Matrix pos = XMMatrixTranslationFromVector(GetPosition().GetInternalVec());
SetWorldTransform(Matrix4((scale * rot * pos)));
UpdateRecursively(shared_from_this());
}
Vector3 Transform::GetWorldPosition()
{
return WorldTransform.GetPosition();
}
void Transform::SetWorldPosition(const Vector3& NewPosition)
{
DirectX::SimpleMath::Matrix& mat = WorldTransform.GetInternalMatrix();
mat._41 = NewPosition[0];
mat._42 = NewPosition[1];
mat._43 = NewPosition[2];
Position += Vector3(mat._41 - Position[0], mat._42 - Position[1], mat._43 - Position[2]);
SetDirty(true);
}
void Transform::Reset()
{
SetWorldPosition(Vector3());
SetRotation(Vector3());
SetScale(1.f);
}
void Transform::SetWorldTransform(Matrix4& NewWorldTransform, bool InIsDirty)
{
OPTICK_EVENT("Transform::SetWorldTransform");
WorldTransform = std::move(NewWorldTransform);
{
//DirectX::SimpleMath::Quaternion quat;
//DirectX::SimpleMath::Vector3 pos;
//DirectX::SimpleMath::Vector3 scale;
//NewWorldTransform.GetInternalMatrix().Decompose(scale, quat, pos);
//InternalRotation = Quaternion(ParentTransform->GetWorldRotation().GetInternalVec() * Quaternion(quat).GetInternalVec());
//Vector3 rotation = Quaternion::ToEulerAngles(Quaternion(quat));
//Rotation = Vector3(Mathf::Degrees(Rotation.X()), Mathf::Degrees(Rotation.Y()), Mathf::Degrees(Rotation.Z()));
//Position = Vector3(pos);
}
// update local transform
//WorldTransform = std::move(NewWorldTransform);
SetDirty(InIsDirty);
}
const bool Transform::IsDirty() const
{
return m_isDirty;
}
Transform* Transform::GetParent()
{
return GetParentTransform();
}
Matrix4 Transform::GetLocalToWorldMatrix()
{
DirectX::SimpleMath::Matrix id = DirectX::XMMatrixIdentity();
DirectX::SimpleMath::Matrix rot = DirectX::SimpleMath::Matrix::CreateFromYawPitchRoll(Rotation.y, Rotation.x, Rotation.z);// , Child->Rotation.Y(), Child->Rotation.Z());
DirectX::SimpleMath::Matrix scale = DirectX::SimpleMath::Matrix::CreateScale(Scale.GetInternalVec());
DirectX::SimpleMath::Matrix pos = XMMatrixTranslationFromVector(Position.GetInternalVec());
if (ParentTransform)
{
return Matrix4((scale * rot * pos) * GetParentTransform()->WorldTransform.GetInternalMatrix());
}
else
{
return Matrix4(scale * rot * pos);
}
}
Matrix4 Transform::GetWorldToLocalMatrix()
{
DirectX::SimpleMath::Matrix mat;
GetLocalToWorldMatrix().GetInternalMatrix().Invert(mat);
return Matrix4(mat);
}
void Transform::Init()
{
}
#if ME_EDITOR
void Transform::OnEditorInspect()
{
ImGui::InputText("Name", &Name);
Vector3 OldPosition = Position;
HavanaUtils::EditableVector3("Position", Position);
Vector3 OldRotation = Rotation;
HavanaUtils::EditableVector3("Rotation", Rotation);
if (OldRotation != Rotation || OldPosition != Position)
{
SetRotation(Rotation);
}
HavanaUtils::EditableVector3("Scale", Scale);
Vector3 WorldPos = GetWorldPosition();
HavanaUtils::EditableVector3("World Position", WorldPos);
if (WorldPos != GetWorldPosition())
{
SetWorldPosition(WorldPos);
}
if (ImGui::Button("Reset Transform"))
{
Reset();
}
}
#endif
void Transform::SetDirty(bool Dirty)
{
OPTICK_EVENT("Transform::SetDirty");
if (Dirty && (Dirty != m_isDirty))
{
//for (SharedPtr<Transform> Child : GetChildren())
if(ParentTransform)
{
ParentTransform->SetDirty(Dirty);
}
}
m_isDirty = Dirty;
}
Vector3 Transform::GetScale()
{
return Scale;
}
void Transform::LookAt(const Vector3& InDirection)
{
Vector3 worldPos = GetWorldPosition();
WorldTransform = Matrix4(DirectX::SimpleMath::Matrix::CreateLookAt(worldPos.GetInternalVec(), (GetWorldPosition() + InDirection).GetInternalVec(), Vector3::Up.GetInternalVec()).Transpose());
WorldTransform.GetInternalMatrix()._41 = worldPos[0];
WorldTransform.GetInternalMatrix()._42 = worldPos[1];
WorldTransform.GetInternalMatrix()._43 = worldPos[2];
DirectX::SimpleMath::Quaternion quat;
WorldTransform.GetInternalMatrix().Decompose(DirectX::SimpleMath::Vector3(), quat, DirectX::SimpleMath::Vector3());
Quaternion quat2(quat);
Rotation = Quaternion::ToEulerAngles(quat2);
Rotation = Vector3(Mathf::Degrees(Rotation.x), Mathf::Degrees(Rotation.y), Mathf::Degrees(Rotation.z));
InternalRotation = quat2;
SetDirty(true);
}
void Transform::SetRotation(const Vector3& euler)
{
OPTICK_CATEGORY("Transform::Set Rotation", Optick::Category::Scene);
DirectX::SimpleMath::Quaternion quat2 = DirectX::SimpleMath::Quaternion::CreateFromYawPitchRoll(Mathf::Radians(euler.y), Mathf::Radians(euler.x), Mathf::Radians(euler.z));
Quaternion quat(quat2);
InternalRotation = quat;
Rotation = euler;
SetDirty(true);
}
void Transform::SetWorldRotation(Quaternion InRotation)
{
InternalRotation = Quaternion(GetParentTransform()->GetWorldRotation().GetInternalVec() * InternalRotation.GetInternalVec());
Rotation = Quaternion::ToEulerAngles(InternalRotation);
SetDirty(true);
}
const Vector3& Transform::GetRotation() const
{
return Rotation;
}
Quaternion Transform::GetWorldRotation()
{
DirectX::SimpleMath::Quaternion quat;
WorldTransform.GetInternalMatrix().Decompose(DirectX::SimpleMath::Vector3(), quat, DirectX::SimpleMath::Vector3());
Quaternion quat2(quat);
return quat2;
}
Vector3 Transform::GetWorldRotationEuler()
{
return Quaternion::ToEulerAngles(GetWorldRotation());
}
//
//void Transform::SetRotation(glm::quat quat)
//{
// //glm::rotate(Rotation, quat);
// Rotation = glm::eulerAngles(quat);
// SetDirty(true);
//}
void Transform::SetParent(Transform& NewParent)
{
if (ParentTransform)
{
GetParentTransform()->RemoveChild(this);
}
ParentTransform = NewParent.shared_from_this();
GetParentTransform()->Children.push_back(shared_from_this());
SetDirty(true);
}
void Transform::RemoveChild(Transform* TargetTransform)
{
if (Children.size() > 0)
{
Children.erase(std::remove(Children.begin(), Children.end(), TargetTransform->shared_from_this()), Children.end());
TargetTransform->ParentTransform = nullptr;
}
}
Transform* Transform::GetChildByName(const std::string& Name)
{
for (auto child : Children)
{
if (child->Name == Name)
{
return child.get();
}
}
return nullptr;
}
const std::vector<SharedPtr<Transform>>& Transform::GetChildren() const
{
OPTICK_CATEGORY("Transform::GetChildren", Optick::Category::GameLogic);
return Children;
//std::vector<Transform*> children;
//for (auto& child : Children)
//{
// if (child)
// {
// children.push_back(&child->GetComponent<Transform>());
// }
//}
//return children;
}
Transform* Transform::GetParentTransform()
{
if (ParentTransform)
{
return ParentTransform.get();
}
return nullptr;
}
Matrix4 Transform::GetMatrix()
{
return WorldTransform;
}
void Transform::OnSerialize(json& outJson)
{
outJson["Position"] = { Position.x, Position.y, Position.z };
outJson["Rotation"] = { Rotation.x, Rotation.y, Rotation.z };
outJson["Scale"] = { Scale.x, Scale.y, Scale.z };
}
void Transform::OnDeserialize(const json& inJson)
{
SetPosition(Vector3((float)inJson["Position"][0], (float)inJson["Position"][1], (float)inJson["Position"][2]));
SetRotation(Vector3((float)inJson["Rotation"][0], (float)inJson["Rotation"][1], (float)inJson["Rotation"][2]));
if (inJson.find("Scale") != inJson.end())
{
SetScale(Vector3((float)inJson["Scale"][0], (float)inJson["Scale"][1], (float)inJson["Scale"][2]));
}
DirectX::SimpleMath::Matrix id = DirectX::XMMatrixIdentity();
DirectX::SimpleMath::Matrix rot = DirectX::SimpleMath::Matrix::CreateFromQuaternion(DirectX::SimpleMath::Quaternion::CreateFromYawPitchRoll(Rotation[1], Rotation[0], Rotation[2]));// , Child->Rotation.Y(), Child->Rotation.Z());
DirectX::SimpleMath::Matrix scale = DirectX::SimpleMath::Matrix::CreateScale(GetScale().GetInternalVec());
DirectX::SimpleMath::Matrix pos = XMMatrixTranslationFromVector(GetPosition().GetInternalVec());
if (ParentTransform)
{
SetWorldTransform(Matrix4((scale * rot * pos) * GetParentTransform()->WorldTransform.GetInternalMatrix()), false);
}
else
{
SetWorldTransform(Matrix4(scale * rot * pos), false);
}
}
void Transform::SetName(const std::string& name)
{
Name = name;
}
<commit_msg>⚖ Scaling finally updates the transform<commit_after>#include "PCH.h"
#include "Transform.h"
#include <algorithm>
#include "Math/Vector3.h"
#include "misc/cpp/imgui_stdlib.h"
#include "Engine/Engine.h"
#include "Mathf.h"
#include <SimpleMath.h>
#include "optick.h"
Transform::Transform()
: Component("Transform")
, WorldTransform(DirectX::XMMatrixIdentity())
, Position(0.f, 0.f, 0.f)
, Rotation(0.f, 0.f, 0.f)
, Scale(1.0f, 1.0f, 1.0f)
{
}
Transform::Transform(const std::string& TransformName)
: Component("Transform")
, WorldTransform(DirectX::XMMatrixIdentity())
, Name(std::move(TransformName))
, Position(0.f, 0.f, 0.f)
, Rotation(0.f, 0.f, 0.f)
, Scale(1.0f, 1.0f, 1.0f)
{
}
Transform::~Transform()
{
if (ParentTransform)
{
ParentTransform->RemoveChild(shared_from_this().get());
}
}
void Transform::SetPosition(Vector3 NewPosition)
{
WorldTransform.GetInternalMatrix().Translation((Position - NewPosition).GetInternalVec());
Position = NewPosition;
SetDirty(true);
//UpdateRecursively(this);
}
void Transform::SetScale(Vector3 NewScale)
{
if (NewScale == Vector3())
{
return;
}
Scale = NewScale;
SetDirty(true);
}
void Transform::SetScale(float NewScale)
{
if (NewScale == Scale.x && NewScale == Scale.y && NewScale == Scale.z)
{
return;
}
Scale = Vector3(NewScale);
SetDirty(true);
}
void Transform::Translate(Vector3 NewPosition)
{
if (NewPosition == Vector3())
{
return;
}
SetWorldPosition(Position + NewPosition);
}
Vector3 Transform::Front()
{
//float mat1 = -;// 2, 0);
//float mat2 = -WorldTransform.GetInternalMatrix()(2, 1);
//float mat3 = -WorldTransform.GetInternalMatrix()(2, 2);
return Vector3(WorldTransform.GetInternalMatrix().Forward());
}
Vector3 Transform::Up()
{
return Vector3(WorldTransform.GetInternalMatrix().Up());
}
Vector3& Transform::GetPosition()
{
return Position;
}
void Transform::UpdateRecursively(SharedPtr<Transform> CurrentTransform)
{
OPTICK_EVENT("SceneGraph::UpdateRecursively");
for (SharedPtr<Transform> Child : CurrentTransform->GetChildren())
{
if (Child->m_isDirty)
{
OPTICK_EVENT("SceneGraph::Update::IsDirty");
//Quaternion quat = Quaternion(Child->Rotation);
DirectX::SimpleMath::Matrix id = DirectX::XMMatrixIdentity();
DirectX::SimpleMath::Matrix rot = DirectX::SimpleMath::Matrix::CreateFromQuaternion(DirectX::SimpleMath::Quaternion::CreateFromYawPitchRoll(Child->Rotation[1], Child->Rotation[0], Child->Rotation[2]));// , Child->Rotation.Y(), Child->Rotation.Z());
DirectX::SimpleMath::Matrix scale = DirectX::SimpleMath::Matrix::CreateScale(Child->GetScale().GetInternalVec());
DirectX::SimpleMath::Matrix pos = XMMatrixTranslationFromVector(Child->GetPosition().GetInternalVec());
Child->SetWorldTransform(Matrix4((scale * rot * pos) * CurrentTransform->WorldTransform.GetInternalMatrix()));
}
UpdateRecursively(Child);
}
}
void Transform::UpdateWorldTransform()
{
DirectX::SimpleMath::Matrix id = DirectX::XMMatrixIdentity();
DirectX::SimpleMath::Matrix rot = DirectX::SimpleMath::Matrix::CreateFromQuaternion(DirectX::SimpleMath::Quaternion::CreateFromYawPitchRoll(Rotation[1], Rotation[0], Rotation[2]));// , Child->Rotation.Y(), Child->Rotation.Z());
DirectX::SimpleMath::Matrix scale = DirectX::SimpleMath::Matrix::CreateScale(GetScale().GetInternalVec());
DirectX::SimpleMath::Matrix pos = XMMatrixTranslationFromVector(GetPosition().GetInternalVec());
SetWorldTransform(Matrix4((scale * rot * pos)));
UpdateRecursively(shared_from_this());
}
Vector3 Transform::GetWorldPosition()
{
return WorldTransform.GetPosition();
}
void Transform::SetWorldPosition(const Vector3& NewPosition)
{
DirectX::SimpleMath::Matrix& mat = WorldTransform.GetInternalMatrix();
mat._41 = NewPosition[0];
mat._42 = NewPosition[1];
mat._43 = NewPosition[2];
Position += Vector3(mat._41 - Position[0], mat._42 - Position[1], mat._43 - Position[2]);
SetDirty(true);
}
void Transform::Reset()
{
SetWorldPosition(Vector3());
SetRotation(Vector3());
SetScale(1.f);
}
void Transform::SetWorldTransform(Matrix4& NewWorldTransform, bool InIsDirty)
{
OPTICK_EVENT("Transform::SetWorldTransform");
WorldTransform = std::move(NewWorldTransform);
{
//DirectX::SimpleMath::Quaternion quat;
//DirectX::SimpleMath::Vector3 pos;
//DirectX::SimpleMath::Vector3 scale;
//NewWorldTransform.GetInternalMatrix().Decompose(scale, quat, pos);
//InternalRotation = Quaternion(ParentTransform->GetWorldRotation().GetInternalVec() * Quaternion(quat).GetInternalVec());
//Vector3 rotation = Quaternion::ToEulerAngles(Quaternion(quat));
//Rotation = Vector3(Mathf::Degrees(Rotation.X()), Mathf::Degrees(Rotation.Y()), Mathf::Degrees(Rotation.Z()));
//Position = Vector3(pos);
}
// update local transform
//WorldTransform = std::move(NewWorldTransform);
SetDirty(InIsDirty);
}
const bool Transform::IsDirty() const
{
return m_isDirty;
}
Transform* Transform::GetParent()
{
return GetParentTransform();
}
Matrix4 Transform::GetLocalToWorldMatrix()
{
DirectX::SimpleMath::Matrix id = DirectX::XMMatrixIdentity();
DirectX::SimpleMath::Matrix rot = DirectX::SimpleMath::Matrix::CreateFromYawPitchRoll(Rotation.y, Rotation.x, Rotation.z);// , Child->Rotation.Y(), Child->Rotation.Z());
DirectX::SimpleMath::Matrix scale = DirectX::SimpleMath::Matrix::CreateScale(Scale.GetInternalVec());
DirectX::SimpleMath::Matrix pos = XMMatrixTranslationFromVector(Position.GetInternalVec());
if (ParentTransform)
{
return Matrix4((scale * rot * pos) * GetParentTransform()->WorldTransform.GetInternalMatrix());
}
else
{
return Matrix4(scale * rot * pos);
}
}
Matrix4 Transform::GetWorldToLocalMatrix()
{
DirectX::SimpleMath::Matrix mat;
GetLocalToWorldMatrix().GetInternalMatrix().Invert(mat);
return Matrix4(mat);
}
void Transform::Init()
{
}
void Transform::SetDirty(bool Dirty)
{
OPTICK_EVENT("Transform::SetDirty");
if (Dirty && (Dirty != m_isDirty))
{
//for (SharedPtr<Transform> Child : GetChildren())
if(ParentTransform)
{
ParentTransform->SetDirty(Dirty);
}
}
m_isDirty = Dirty;
}
Vector3 Transform::GetScale()
{
return Scale;
}
void Transform::LookAt(const Vector3& InDirection)
{
Vector3 worldPos = GetWorldPosition();
WorldTransform = Matrix4(DirectX::SimpleMath::Matrix::CreateLookAt(worldPos.GetInternalVec(), (GetWorldPosition() + InDirection).GetInternalVec(), Vector3::Up.GetInternalVec()).Transpose());
WorldTransform.GetInternalMatrix()._41 = worldPos[0];
WorldTransform.GetInternalMatrix()._42 = worldPos[1];
WorldTransform.GetInternalMatrix()._43 = worldPos[2];
DirectX::SimpleMath::Quaternion quat;
WorldTransform.GetInternalMatrix().Decompose(DirectX::SimpleMath::Vector3(), quat, DirectX::SimpleMath::Vector3());
Quaternion quat2(quat);
Rotation = Quaternion::ToEulerAngles(quat2);
Rotation = Vector3(Mathf::Degrees(Rotation.x), Mathf::Degrees(Rotation.y), Mathf::Degrees(Rotation.z));
InternalRotation = quat2;
SetDirty(true);
}
void Transform::SetRotation(const Vector3& euler)
{
OPTICK_CATEGORY("Transform::Set Rotation", Optick::Category::Scene);
DirectX::SimpleMath::Quaternion quat2 = DirectX::SimpleMath::Quaternion::CreateFromYawPitchRoll(Mathf::Radians(euler.y), Mathf::Radians(euler.x), Mathf::Radians(euler.z));
Quaternion quat(quat2);
InternalRotation = quat;
Rotation = euler;
SetDirty(true);
}
void Transform::SetWorldRotation(Quaternion InRotation)
{
InternalRotation = Quaternion(GetParentTransform()->GetWorldRotation().GetInternalVec() * InternalRotation.GetInternalVec());
Rotation = Quaternion::ToEulerAngles(InternalRotation);
SetDirty(true);
}
const Vector3& Transform::GetRotation() const
{
return Rotation;
}
Quaternion Transform::GetWorldRotation()
{
DirectX::SimpleMath::Quaternion quat;
WorldTransform.GetInternalMatrix().Decompose(DirectX::SimpleMath::Vector3(), quat, DirectX::SimpleMath::Vector3());
Quaternion quat2(quat);
return quat2;
}
Vector3 Transform::GetWorldRotationEuler()
{
return Quaternion::ToEulerAngles(GetWorldRotation());
}
//
//void Transform::SetRotation(glm::quat quat)
//{
// //glm::rotate(Rotation, quat);
// Rotation = glm::eulerAngles(quat);
// SetDirty(true);
//}
void Transform::SetParent(Transform& NewParent)
{
if (ParentTransform)
{
GetParentTransform()->RemoveChild(this);
}
ParentTransform = NewParent.shared_from_this();
GetParentTransform()->Children.push_back(shared_from_this());
SetDirty(true);
}
void Transform::RemoveChild(Transform* TargetTransform)
{
if (Children.size() > 0)
{
Children.erase(std::remove(Children.begin(), Children.end(), TargetTransform->shared_from_this()), Children.end());
TargetTransform->ParentTransform = nullptr;
}
}
Transform* Transform::GetChildByName(const std::string& Name)
{
for (auto child : Children)
{
if (child->Name == Name)
{
return child.get();
}
}
return nullptr;
}
const std::vector<SharedPtr<Transform>>& Transform::GetChildren() const
{
OPTICK_CATEGORY("Transform::GetChildren", Optick::Category::GameLogic);
return Children;
//std::vector<Transform*> children;
//for (auto& child : Children)
//{
// if (child)
// {
// children.push_back(&child->GetComponent<Transform>());
// }
//}
//return children;
}
Transform* Transform::GetParentTransform()
{
if (ParentTransform)
{
return ParentTransform.get();
}
return nullptr;
}
Matrix4 Transform::GetMatrix()
{
return WorldTransform;
}
void Transform::OnSerialize(json& outJson)
{
outJson["Position"] = { Position.x, Position.y, Position.z };
outJson["Rotation"] = { Rotation.x, Rotation.y, Rotation.z };
outJson["Scale"] = { Scale.x, Scale.y, Scale.z };
}
void Transform::OnDeserialize(const json& inJson)
{
SetPosition(Vector3((float)inJson["Position"][0], (float)inJson["Position"][1], (float)inJson["Position"][2]));
SetRotation(Vector3((float)inJson["Rotation"][0], (float)inJson["Rotation"][1], (float)inJson["Rotation"][2]));
if (inJson.find("Scale") != inJson.end())
{
SetScale(Vector3((float)inJson["Scale"][0], (float)inJson["Scale"][1], (float)inJson["Scale"][2]));
}
DirectX::SimpleMath::Matrix id = DirectX::XMMatrixIdentity();
DirectX::SimpleMath::Matrix rot = DirectX::SimpleMath::Matrix::CreateFromQuaternion(DirectX::SimpleMath::Quaternion::CreateFromYawPitchRoll(Rotation[1], Rotation[0], Rotation[2]));// , Child->Rotation.Y(), Child->Rotation.Z());
DirectX::SimpleMath::Matrix scale = DirectX::SimpleMath::Matrix::CreateScale(GetScale().GetInternalVec());
DirectX::SimpleMath::Matrix pos = XMMatrixTranslationFromVector(GetPosition().GetInternalVec());
if (ParentTransform)
{
SetWorldTransform(Matrix4((scale * rot * pos) * GetParentTransform()->WorldTransform.GetInternalMatrix()), false);
}
else
{
SetWorldTransform(Matrix4(scale * rot * pos), false);
}
}
void Transform::SetName(const std::string& name)
{
Name = name;
}
#if ME_EDITOR
void Transform::OnEditorInspect()
{
ImGui::InputText("Name", &Name);
Vector3 OldPosition = Position;
HavanaUtils::EditableVector3("Position", Position);
Vector3 OldRotation = Rotation;
HavanaUtils::EditableVector3("Rotation", Rotation);
if (OldRotation != Rotation || OldPosition != Position)
{
SetRotation(Rotation);
SetPosition(Position);
}
Vector3 OldScale = Scale;
HavanaUtils::EditableVector3("Scale", Scale);
if (OldScale != Scale)
{
SetScale(Scale);
}
Vector3 WorldPos = GetWorldPosition();
HavanaUtils::EditableVector3("World Position", WorldPos);
if (WorldPos != GetWorldPosition())
{
SetWorldPosition(WorldPos);
}
if (ImGui::Button("Reset Transform"))
{
Reset();
}
}
#endif<|endoftext|>
|
<commit_before>/*ckwg +5
* Copyright 2012-2013 by Kitware, Inc. All Rights Reserved. Please refer to
* KITWARE_LICENSE.TXT for licensing information, or contact General Counsel,
* Kitware, Inc., 28 Corporate Drive, Clifton Park, NY 12065.
*/
#include <python/helpers/python_exceptions.h>
#include <vistk/pipeline/config.h>
#include <vistk/pipeline/process.h>
#include <vistk/pipeline/process_cluster.h>
#include <vistk/python/util/python_gil.h>
#include <boost/python/args.hpp>
#include <boost/python/class.hpp>
#include <boost/python/def.hpp>
#include <boost/python/implicit.hpp>
#include <boost/python/module.hpp>
#include <boost/python/override.hpp>
/**
* \file process_cluster.cxx
*
* \brief Python bindings for \link vistk::process_cluster\endlink.
*/
using namespace boost::python;
class wrap_process_cluster
: public vistk::process_cluster
, public wrapper<vistk::process_cluster>
{
public:
wrap_process_cluster(vistk::config_t const& config);
~wrap_process_cluster();
properties_t _base_properties() const;
vistk::processes_t processes() const;
connections_t input_mappings() const;
connections_t output_mappings() const;
connections_t internal_connections() const;
void _map_config(vistk::config::key_t const& key, name_t const& name_, vistk::config::key_t const& mapped_key);
void _add_process(name_t const& name_, type_t const& type_, vistk::config_t const& config);
void _map_input(port_t const& port, name_t const& name_, port_t const& mapped_port);
void _map_output(port_t const& port, name_t const& name_, port_t const& mapped_port);
void _connect(name_t const& upstream_name, port_t const& upstream_port,
name_t const& downstream_name, port_t const& downstream_port);
properties_t _properties() const;
void _declare_input_port(port_t const& port, port_info_t const& info);
void _declare_input_port_1(port_t const& port,
port_type_t const& type_,
port_flags_t const& flags_,
port_description_t const& description_,
port_frequency_t const& frequency_);
void _declare_output_port(port_t const& port, port_info_t const& info);
void _declare_output_port_1(port_t const& port,
port_type_t const& type_,
port_flags_t const& flags_,
port_description_t const& description_,
port_frequency_t const& frequency_);
void _declare_configuration_key(vistk::config::key_t const& key, conf_info_t const& info);
void _declare_configuration_key_1(vistk::config::key_t const& key,
vistk::config::value_t const& def_,
vistk::config::description_t const& description_);
};
static object cluster_from_process(vistk::process_t const& process);
BOOST_PYTHON_MODULE(process_cluster)
{
class_<wrap_process_cluster, boost::noncopyable>("PythonProcessCluster"
, "The base class for Python process clusters."
, no_init)
.def(init<vistk::config_t>())
.def("name", &vistk::process::name
, "Returns the name of the process.")
.def("type", &vistk::process::type
, "Returns the type of the process.")
.def_readonly("type_any", &vistk::process::type_any)
.def_readonly("type_none", &vistk::process::type_none)
.def_readonly("type_data_dependent", &vistk::process::type_data_dependent)
.def_readonly("type_flow_dependent", &vistk::process::type_flow_dependent)
.def_readonly("flag_output_const", &vistk::process::flag_output_const)
.def_readonly("flag_input_static", &vistk::process::flag_input_static)
.def_readonly("flag_input_mutable", &vistk::process::flag_input_mutable)
.def_readonly("flag_input_nodep", &vistk::process::flag_input_nodep)
.def_readonly("flag_required", &vistk::process::flag_required)
.def("_base_properties", &wrap_process_cluster::_base_properties
, "Base class properties.")
.def("map_config", &wrap_process_cluster::_map_config
, (arg("key"), arg("name"), arg("mapped_key"))
, "Map a configuration value to a process.")
.def("add_process", &wrap_process_cluster::_add_process
, (arg("name"), arg("type"), arg("config") = vistk::config::empty_config())
, "Add a process to the cluster.")
.def("map_input", &wrap_process_cluster::_map_input
, (arg("port"), arg("name"), arg("mapped_port"))
, "Map a port on the cluster to an input port.")
.def("map_output", &wrap_process_cluster::_map_output
, (arg("port"), arg("name"), arg("mapped_port"))
, "Map an output port to a port on the cluster.")
.def("connect", &wrap_process_cluster::_connect
, (arg("upstream_name"), arg("upstream_port"), arg("downstream_name"), arg("downstream_port"))
, "Connect two ports within the cluster.")
.def("_properties", &wrap_process_cluster::_properties, &wrap_process_cluster::_base_properties
, "The properties on the subclass.")
.def("declare_input_port", &wrap_process_cluster::_declare_input_port
, (arg("port"), arg("info"))
, "Declare an input port on the process.")
.def("declare_input_port", &wrap_process_cluster::_declare_input_port_1
, (arg("port"), arg("type"), arg("flags"), arg("description"), arg("frequency") = vistk::process::port_frequency_t(1))
, "Declare an input port on the process.")
.def("declare_output_port", &wrap_process_cluster::_declare_output_port
, (arg("port"), arg("info"))
, "Declare an output port on the process.")
.def("declare_output_port", &wrap_process_cluster::_declare_output_port_1
, (arg("port"), arg("type"), arg("flags"), arg("description"), arg("frequency") = vistk::process::port_frequency_t(1))
, "Declare an output port on the process.")
.def("declare_configuration_key", &wrap_process_cluster::_declare_configuration_key
, (arg("key"), arg("info"))
, "Declare a configuration key for the process.")
.def("declare_configuration_key", &wrap_process_cluster::_declare_configuration_key_1
, (arg("key"), arg("default"), arg("description"))
, "Declare a configuration key for the process.")
.def("processes", &vistk::process_cluster::processes
, "Processes in the cluster.")
.def("input_mappings", &vistk::process_cluster::input_mappings
, "Input mappings for the cluster.")
.def("output_mappings", &vistk::process_cluster::output_mappings
, "Output mappings for the cluster.")
.def("internal_connections", &vistk::process_cluster::internal_connections
, "Connections internal to the cluster.")
;
def("cluster_from_process", cluster_from_process
, (arg("process"))
, "Returns the process as a cluster or None if the process is not a cluster.");
implicitly_convertible<vistk::process_cluster_t, vistk::process_t>();
}
wrap_process_cluster
::wrap_process_cluster(vistk::config_t const& config)
: vistk::process_cluster(config)
{
}
wrap_process_cluster
::~wrap_process_cluster()
{
}
vistk::process::properties_t
wrap_process_cluster
::_base_properties() const
{
return process_cluster::properties();
}
void
wrap_process_cluster
::_map_config(vistk::config::key_t const& key, name_t const& name_, vistk::config::key_t const& mapped_key)
{
map_config(key, name_, mapped_key);
}
void
wrap_process_cluster
::_add_process(name_t const& name_, type_t const& type_, vistk::config_t const& conf)
{
add_process(name_, type_, conf);
}
void
wrap_process_cluster
::_map_input(port_t const& port, name_t const& name_, port_t const& mapped_port)
{
map_input(port, name_, mapped_port);
}
void
wrap_process_cluster
::_map_output(port_t const& port, name_t const& name_, port_t const& mapped_port)
{
map_output(port, name_, mapped_port);
}
void
wrap_process_cluster
::_connect(name_t const& upstream_name, port_t const& upstream_port,
name_t const& downstream_name, port_t const& downstream_port)
{
connect(upstream_name, upstream_port,
downstream_name, downstream_port);
}
vistk::process::properties_t
wrap_process_cluster
::_properties() const
{
{
vistk::python::python_gil const gil;
(void)gil;
override const f = get_override("_properties");
if (f)
{
HANDLE_PYTHON_EXCEPTION(return f())
}
}
return _base_properties();
}
void
wrap_process_cluster
::_declare_input_port(port_t const& port, port_info_t const& info)
{
declare_input_port(port, info);
}
void
wrap_process_cluster
::_declare_input_port_1(port_t const& port,
port_type_t const& type_,
port_flags_t const& flags_,
port_description_t const& description_,
port_frequency_t const& frequency_)
{
declare_input_port(port, type_, flags_, description_, frequency_);
}
void
wrap_process_cluster
::_declare_output_port(port_t const& port, port_info_t const& info)
{
declare_output_port(port, info);
}
void
wrap_process_cluster
::_declare_output_port_1(port_t const& port,
port_type_t const& type_,
port_flags_t const& flags_,
port_description_t const& description_,
port_frequency_t const& frequency_)
{
declare_output_port(port, type_, flags_, description_, frequency_);
}
void
wrap_process_cluster
::_declare_configuration_key(vistk::config::key_t const& key, conf_info_t const& info)
{
declare_configuration_key(key, info);
}
void
wrap_process_cluster
::_declare_configuration_key_1(vistk::config::key_t const& key,
vistk::config::value_t const& def_,
vistk::config::description_t const& description_)
{
declare_configuration_key(key, def_, description_);
}
object
cluster_from_process(vistk::process_t const& process)
{
vistk::process_cluster_t const cluster = boost::dynamic_pointer_cast<vistk::process_cluster>(process);
if (!cluster)
{
return object();
}
return object(cluster);
}
<commit_msg>Add Python bindings for a cluster's _reconfigure<commit_after>/*ckwg +5
* Copyright 2012-2013 by Kitware, Inc. All Rights Reserved. Please refer to
* KITWARE_LICENSE.TXT for licensing information, or contact General Counsel,
* Kitware, Inc., 28 Corporate Drive, Clifton Park, NY 12065.
*/
#include <python/helpers/python_exceptions.h>
#include <vistk/pipeline/config.h>
#include <vistk/pipeline/process.h>
#include <vistk/pipeline/process_cluster.h>
#include <vistk/python/util/python_gil.h>
#include <boost/python/args.hpp>
#include <boost/python/class.hpp>
#include <boost/python/def.hpp>
#include <boost/python/implicit.hpp>
#include <boost/python/module.hpp>
#include <boost/python/override.hpp>
/**
* \file process_cluster.cxx
*
* \brief Python bindings for \link vistk::process_cluster\endlink.
*/
using namespace boost::python;
class wrap_process_cluster
: public vistk::process_cluster
, public wrapper<vistk::process_cluster>
{
public:
wrap_process_cluster(vistk::config_t const& config);
~wrap_process_cluster();
properties_t _base_properties() const;
void _base_reconfigure();
vistk::processes_t processes() const;
connections_t input_mappings() const;
connections_t output_mappings() const;
connections_t internal_connections() const;
void _map_config(vistk::config::key_t const& key, name_t const& name_, vistk::config::key_t const& mapped_key);
void _add_process(name_t const& name_, type_t const& type_, vistk::config_t const& config);
void _map_input(port_t const& port, name_t const& name_, port_t const& mapped_port);
void _map_output(port_t const& port, name_t const& name_, port_t const& mapped_port);
void _connect(name_t const& upstream_name, port_t const& upstream_port,
name_t const& downstream_name, port_t const& downstream_port);
properties_t _properties() const;
void _reconfigure();
void _declare_input_port(port_t const& port, port_info_t const& info);
void _declare_input_port_1(port_t const& port,
port_type_t const& type_,
port_flags_t const& flags_,
port_description_t const& description_,
port_frequency_t const& frequency_);
void _declare_output_port(port_t const& port, port_info_t const& info);
void _declare_output_port_1(port_t const& port,
port_type_t const& type_,
port_flags_t const& flags_,
port_description_t const& description_,
port_frequency_t const& frequency_);
void _declare_configuration_key(vistk::config::key_t const& key, conf_info_t const& info);
void _declare_configuration_key_1(vistk::config::key_t const& key,
vistk::config::value_t const& def_,
vistk::config::description_t const& description_);
};
static object cluster_from_process(vistk::process_t const& process);
BOOST_PYTHON_MODULE(process_cluster)
{
class_<wrap_process_cluster, boost::noncopyable>("PythonProcessCluster"
, "The base class for Python process clusters."
, no_init)
.def(init<vistk::config_t>())
.def("name", &vistk::process::name
, "Returns the name of the process.")
.def("type", &vistk::process::type
, "Returns the type of the process.")
.def_readonly("type_any", &vistk::process::type_any)
.def_readonly("type_none", &vistk::process::type_none)
.def_readonly("type_data_dependent", &vistk::process::type_data_dependent)
.def_readonly("type_flow_dependent", &vistk::process::type_flow_dependent)
.def_readonly("flag_output_const", &vistk::process::flag_output_const)
.def_readonly("flag_input_static", &vistk::process::flag_input_static)
.def_readonly("flag_input_mutable", &vistk::process::flag_input_mutable)
.def_readonly("flag_input_nodep", &vistk::process::flag_input_nodep)
.def_readonly("flag_required", &vistk::process::flag_required)
.def("_base_properties", &wrap_process_cluster::_base_properties
, "Base class properties.")
.def("_base_reconfigure", &wrap_process_cluster::_base_reconfigure
, "Base class reconfigure.")
.def("map_config", &wrap_process_cluster::_map_config
, (arg("key"), arg("name"), arg("mapped_key"))
, "Map a configuration value to a process.")
.def("add_process", &wrap_process_cluster::_add_process
, (arg("name"), arg("type"), arg("config") = vistk::config::empty_config())
, "Add a process to the cluster.")
.def("map_input", &wrap_process_cluster::_map_input
, (arg("port"), arg("name"), arg("mapped_port"))
, "Map a port on the cluster to an input port.")
.def("map_output", &wrap_process_cluster::_map_output
, (arg("port"), arg("name"), arg("mapped_port"))
, "Map an output port to a port on the cluster.")
.def("connect", &wrap_process_cluster::_connect
, (arg("upstream_name"), arg("upstream_port"), arg("downstream_name"), arg("downstream_port"))
, "Connect two ports within the cluster.")
.def("_properties", &wrap_process_cluster::_properties, &wrap_process_cluster::_base_properties
, "The properties on the subclass.")
.def("_reconfigure", &wrap_process_cluster::_reconfigure, &wrap_process_cluster::_base_reconfigure
, "Runtime configuration for subclasses.")
.def("declare_input_port", &wrap_process_cluster::_declare_input_port
, (arg("port"), arg("info"))
, "Declare an input port on the process.")
.def("declare_input_port", &wrap_process_cluster::_declare_input_port_1
, (arg("port"), arg("type"), arg("flags"), arg("description"), arg("frequency") = vistk::process::port_frequency_t(1))
, "Declare an input port on the process.")
.def("declare_output_port", &wrap_process_cluster::_declare_output_port
, (arg("port"), arg("info"))
, "Declare an output port on the process.")
.def("declare_output_port", &wrap_process_cluster::_declare_output_port_1
, (arg("port"), arg("type"), arg("flags"), arg("description"), arg("frequency") = vistk::process::port_frequency_t(1))
, "Declare an output port on the process.")
.def("declare_configuration_key", &wrap_process_cluster::_declare_configuration_key
, (arg("key"), arg("info"))
, "Declare a configuration key for the process.")
.def("declare_configuration_key", &wrap_process_cluster::_declare_configuration_key_1
, (arg("key"), arg("default"), arg("description"))
, "Declare a configuration key for the process.")
.def("processes", &vistk::process_cluster::processes
, "Processes in the cluster.")
.def("input_mappings", &vistk::process_cluster::input_mappings
, "Input mappings for the cluster.")
.def("output_mappings", &vistk::process_cluster::output_mappings
, "Output mappings for the cluster.")
.def("internal_connections", &vistk::process_cluster::internal_connections
, "Connections internal to the cluster.")
;
def("cluster_from_process", cluster_from_process
, (arg("process"))
, "Returns the process as a cluster or None if the process is not a cluster.");
implicitly_convertible<vistk::process_cluster_t, vistk::process_t>();
}
wrap_process_cluster
::wrap_process_cluster(vistk::config_t const& config)
: vistk::process_cluster(config)
{
}
wrap_process_cluster
::~wrap_process_cluster()
{
}
vistk::process::properties_t
wrap_process_cluster
::_base_properties() const
{
return process_cluster::properties();
}
void
wrap_process_cluster
::_base_reconfigure()
{
return process_cluster::_reconfigure();
}
void
wrap_process_cluster
::_map_config(vistk::config::key_t const& key, name_t const& name_, vistk::config::key_t const& mapped_key)
{
map_config(key, name_, mapped_key);
}
void
wrap_process_cluster
::_add_process(name_t const& name_, type_t const& type_, vistk::config_t const& conf)
{
add_process(name_, type_, conf);
}
void
wrap_process_cluster
::_map_input(port_t const& port, name_t const& name_, port_t const& mapped_port)
{
map_input(port, name_, mapped_port);
}
void
wrap_process_cluster
::_map_output(port_t const& port, name_t const& name_, port_t const& mapped_port)
{
map_output(port, name_, mapped_port);
}
void
wrap_process_cluster
::_connect(name_t const& upstream_name, port_t const& upstream_port,
name_t const& downstream_name, port_t const& downstream_port)
{
connect(upstream_name, upstream_port,
downstream_name, downstream_port);
}
vistk::process::properties_t
wrap_process_cluster
::_properties() const
{
{
vistk::python::python_gil const gil;
(void)gil;
override const f = get_override("_properties");
if (f)
{
HANDLE_PYTHON_EXCEPTION(return f())
}
}
return _base_properties();
}
void
wrap_process_cluster
::_reconfigure()
{
{
vistk::python::python_gil const gil;
(void)gil;
override const f = get_override("_reconfigure");
if (f)
{
HANDLE_PYTHON_EXCEPTION(f())
}
}
_base_reconfigure();
}
void
wrap_process_cluster
::_declare_input_port(port_t const& port, port_info_t const& info)
{
declare_input_port(port, info);
}
void
wrap_process_cluster
::_declare_input_port_1(port_t const& port,
port_type_t const& type_,
port_flags_t const& flags_,
port_description_t const& description_,
port_frequency_t const& frequency_)
{
declare_input_port(port, type_, flags_, description_, frequency_);
}
void
wrap_process_cluster
::_declare_output_port(port_t const& port, port_info_t const& info)
{
declare_output_port(port, info);
}
void
wrap_process_cluster
::_declare_output_port_1(port_t const& port,
port_type_t const& type_,
port_flags_t const& flags_,
port_description_t const& description_,
port_frequency_t const& frequency_)
{
declare_output_port(port, type_, flags_, description_, frequency_);
}
void
wrap_process_cluster
::_declare_configuration_key(vistk::config::key_t const& key, conf_info_t const& info)
{
declare_configuration_key(key, info);
}
void
wrap_process_cluster
::_declare_configuration_key_1(vistk::config::key_t const& key,
vistk::config::value_t const& def_,
vistk::config::description_t const& description_)
{
declare_configuration_key(key, def_, description_);
}
object
cluster_from_process(vistk::process_t const& process)
{
vistk::process_cluster_t const cluster = boost::dynamic_pointer_cast<vistk::process_cluster>(process);
if (!cluster)
{
return object();
}
return object(cluster);
}
<|endoftext|>
|
<commit_before>//
// OricMFMDSK.cpp
// Clock Signal
//
// Created by Thomas Harte on 21/11/2016.
// Copyright 2016 Thomas Harte. All rights reserved.
//
#include "OricMFMDSK.hpp"
#include "../../Encodings/MFM/Constants.hpp"
#include "../../Encodings/MFM/Shifter.hpp"
#include "../../Encodings/MFM/Encoder.hpp"
#include "../../Track/PCMTrack.hpp"
#include "../../Track/TrackSerialiser.hpp"
using namespace Storage::Disk;
OricMFMDSK::OricMFMDSK(const std::string &file_name) :
file_(file_name) {
if(!file_.check_signature("MFM_DISK"))
throw Error::InvalidFormat;
head_count_ = file_.get32le();
track_count_ = file_.get32le();
geometry_type_ = file_.get32le();
if(geometry_type_ < 1 || geometry_type_ > 2)
throw Error::InvalidFormat;
}
HeadPosition OricMFMDSK::get_maximum_head_position() {
return HeadPosition(static_cast<int>(track_count_));
}
int OricMFMDSK::get_head_count() {
return static_cast<int>(head_count_);
}
long OricMFMDSK::get_file_offset_for_position(Track::Address address) {
int seek_offset = 0;
switch(geometry_type_) {
case 1:
seek_offset = address.head * static_cast<int>(track_count_) + address.position.as_int();
break;
case 2:
seek_offset = address.position.as_int() * static_cast<int>(track_count_ * head_count_) + address.head;
break;
}
return static_cast<long>(seek_offset) * 6400 + 256;
}
std::shared_ptr<Track> OricMFMDSK::get_track_at_position(Track::Address address) {
PCMSegment segment;
{
std::lock_guard<std::mutex> lock_guard(file_.get_file_access_mutex());
file_.seek(get_file_offset_for_position(address), SEEK_SET);
// The file format omits clock bits. So it's not a genuine MFM capture.
// A consumer must contextually guess when an FB, FC, etc is meant to be a control mark.
std::size_t track_offset = 0;
uint8_t last_header[6] = {0, 0, 0, 0, 0, 0};
std::unique_ptr<Encodings::MFM::Encoder> encoder = Encodings::MFM::GetMFMEncoder(segment.data);
bool did_sync = false;
while(track_offset < 6250) {
uint8_t next_byte = file_.get8();
track_offset++;
switch(next_byte) {
default: {
encoder->add_byte(next_byte);
if(did_sync) {
switch(next_byte) {
default: break;
case 0xfe:
for(int byte = 0; byte < 6; byte++) {
last_header[byte] = file_.get8();
encoder->add_byte(last_header[byte]);
track_offset++;
if(track_offset == 6250) break;
}
break;
case 0xfb:
for(int byte = 0; byte < (128 << last_header[3]) + 2; byte++) {
encoder->add_byte(file_.get8());
track_offset++;
if(track_offset == 6250) break;
}
break;
}
}
did_sync = false;
}
break;
case 0xa1: // a synchronisation mark that implies a sector or header coming
encoder->output_short(Storage::Encodings::MFM::MFMSync);
did_sync = true;
break;
case 0xc2: // an 'ordinary' synchronisation mark
encoder->output_short(Storage::Encodings::MFM::MFMIndexSync);
break;
}
}
}
return std::make_shared<PCMTrack>(segment);
}
void OricMFMDSK::set_tracks(const std::map<Track::Address, std::shared_ptr<Track>> &tracks) {
for(const auto &track : tracks) {
PCMSegment segment = Storage::Disk::track_serialisation(*track.second, Storage::Encodings::MFM::MFMBitLength);
Storage::Encodings::MFM::Shifter shifter;
shifter.set_is_double_density(true);
shifter.set_should_obey_syncs(true);
std::vector<uint8_t> parsed_track;
int size = 0;
int offset = 0;
bool capture_size = false;
for(const auto bit : segment.data) {
shifter.add_input_bit(bit ? 1 : 0);
if(shifter.get_token() == Storage::Encodings::MFM::Shifter::Token::None) continue;
parsed_track.push_back(shifter.get_byte());
if(offset) {
offset--;
if(!offset) {
shifter.set_should_obey_syncs(true);
}
if(capture_size && offset == 2) {
size = parsed_track.back();
capture_size = false;
}
}
if( shifter.get_token() == Storage::Encodings::MFM::Shifter::Token::Data ||
shifter.get_token() == Storage::Encodings::MFM::Shifter::Token::DeletedData) {
offset = 128 << size;
shifter.set_should_obey_syncs(false);
}
if(shifter.get_token() == Storage::Encodings::MFM::Shifter::Token::ID) {
offset = 6;
shifter.set_should_obey_syncs(false);
capture_size = true;
}
}
long file_offset = get_file_offset_for_position(track.first);
std::lock_guard<std::mutex> lock_guard(file_.get_file_access_mutex());
file_.seek(file_offset, SEEK_SET);
std::size_t track_size = std::min(static_cast<std::size_t>(6400), parsed_track.size());
file_.write(parsed_track.data(), track_size);
}
}
bool OricMFMDSK::get_is_read_only() {
return file_.get_is_known_read_only();
}
<commit_msg>Adapts slightly; it would seem that BD-DOS disks really fill up space.<commit_after>//
// OricMFMDSK.cpp
// Clock Signal
//
// Created by Thomas Harte on 21/11/2016.
// Copyright 2016 Thomas Harte. All rights reserved.
//
#include "OricMFMDSK.hpp"
#include "../../Encodings/MFM/Constants.hpp"
#include "../../Encodings/MFM/Shifter.hpp"
#include "../../Encodings/MFM/Encoder.hpp"
#include "../../Track/PCMTrack.hpp"
#include "../../Track/TrackSerialiser.hpp"
using namespace Storage::Disk;
OricMFMDSK::OricMFMDSK(const std::string &file_name) :
file_(file_name) {
if(!file_.check_signature("MFM_DISK"))
throw Error::InvalidFormat;
head_count_ = file_.get32le();
track_count_ = file_.get32le();
geometry_type_ = file_.get32le();
if(geometry_type_ < 1 || geometry_type_ > 2)
throw Error::InvalidFormat;
}
HeadPosition OricMFMDSK::get_maximum_head_position() {
return HeadPosition(static_cast<int>(track_count_));
}
int OricMFMDSK::get_head_count() {
return static_cast<int>(head_count_);
}
long OricMFMDSK::get_file_offset_for_position(Track::Address address) {
int seek_offset = 0;
switch(geometry_type_) {
case 1:
seek_offset = address.head * static_cast<int>(track_count_) + address.position.as_int();
break;
case 2:
seek_offset = address.position.as_int() * static_cast<int>(track_count_ * head_count_) + address.head;
break;
}
return static_cast<long>(seek_offset) * 6400 + 256;
}
std::shared_ptr<Track> OricMFMDSK::get_track_at_position(Track::Address address) {
PCMSegment segment;
{
std::lock_guard<std::mutex> lock_guard(file_.get_file_access_mutex());
file_.seek(get_file_offset_for_position(address), SEEK_SET);
// The file format omits clock bits. So it's not a genuine MFM capture.
// A consumer must contextually guess when an FB, FC, etc is meant to be a control mark.
std::size_t track_offset = 0;
uint8_t last_header[6] = {0, 0, 0, 0, 0, 0};
std::unique_ptr<Encodings::MFM::Encoder> encoder = Encodings::MFM::GetMFMEncoder(segment.data);
bool did_sync = false;
while(track_offset < 6250) {
uint8_t next_byte = file_.get8();
track_offset++;
switch(next_byte) {
default: {
encoder->add_byte(next_byte);
if(did_sync) {
switch(next_byte) {
default: break;
case 0xfe:
for(int byte = 0; byte < 6; byte++) {
last_header[byte] = file_.get8();
encoder->add_byte(last_header[byte]);
++track_offset;
if(track_offset == 6250) break;
}
break;
case 0xfb:
for(int byte = 0; byte < (128 << last_header[3]) + 2; byte++) {
encoder->add_byte(file_.get8());
++track_offset;
// Special exception: don't interrupt a sector body if it seems to
// be about to run over the end of the track. It seems like BD-500
// disks break the usual 6250-byte rule, pushing out to just less
// than 6400 bytes total.
if(track_offset == 6400) break;
}
break;
}
}
did_sync = false;
}
break;
case 0xa1: // a synchronisation mark that implies a sector or header coming
encoder->output_short(Storage::Encodings::MFM::MFMSync);
did_sync = true;
break;
case 0xc2: // an 'ordinary' synchronisation mark
encoder->output_short(Storage::Encodings::MFM::MFMIndexSync);
break;
}
}
}
return std::make_shared<PCMTrack>(segment);
}
void OricMFMDSK::set_tracks(const std::map<Track::Address, std::shared_ptr<Track>> &tracks) {
for(const auto &track : tracks) {
PCMSegment segment = Storage::Disk::track_serialisation(*track.second, Storage::Encodings::MFM::MFMBitLength);
Storage::Encodings::MFM::Shifter shifter;
shifter.set_is_double_density(true);
shifter.set_should_obey_syncs(true);
std::vector<uint8_t> parsed_track;
int size = 0;
int offset = 0;
bool capture_size = false;
for(const auto bit : segment.data) {
shifter.add_input_bit(bit ? 1 : 0);
if(shifter.get_token() == Storage::Encodings::MFM::Shifter::Token::None) continue;
parsed_track.push_back(shifter.get_byte());
if(offset) {
offset--;
if(!offset) {
shifter.set_should_obey_syncs(true);
}
if(capture_size && offset == 2) {
size = parsed_track.back();
capture_size = false;
}
}
if( shifter.get_token() == Storage::Encodings::MFM::Shifter::Token::Data ||
shifter.get_token() == Storage::Encodings::MFM::Shifter::Token::DeletedData) {
offset = 128 << size;
shifter.set_should_obey_syncs(false);
}
if(shifter.get_token() == Storage::Encodings::MFM::Shifter::Token::ID) {
offset = 6;
shifter.set_should_obey_syncs(false);
capture_size = true;
}
}
long file_offset = get_file_offset_for_position(track.first);
std::lock_guard<std::mutex> lock_guard(file_.get_file_access_mutex());
file_.seek(file_offset, SEEK_SET);
std::size_t track_size = std::min(static_cast<std::size_t>(6400), parsed_track.size());
file_.write(parsed_track.data(), track_size);
}
}
bool OricMFMDSK::get_is_read_only() {
return file_.get_is_known_read_only();
}
<|endoftext|>
|
<commit_before><commit_msg>Additional Tests for Free Motion<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 <gtest/gtest.h>
#include <string>
#include <memory>
#include <SurgSim/Framework/Runtime.h>
#include <SurgSim/Physics/PhysicsManager.h>
#include <SurgSim/Physics/Actors/FixedActor.h>
#include <SurgSim/Physics/Actors/RigidActor.h>
#include <SurgSim/Physics/Actors/RigidActorParameters.h>
#include <SurgSim/Physics/Actors/SphereShape.h>
#include <SurgSim/Physics/FreeMotion.h>
#include <SurgSim/Math/Vector.h>
#include <SurgSim/Math/Quaternion.h>
#include <SurgSim/Math/RigidTransform.h>
using SurgSim::Physics::Actor;
using SurgSim::Physics::RigidActor;
using SurgSim::Physics::RigidActorParameters;
using SurgSim::Physics::SphereShape;
using SurgSim::Physics::FreeMotion;
struct FreeMotionTest: public ::testing::Test
{
virtual void SetUp()
{
}
virtual void TearDown()
{
}
};
TEST(FreeMotionTest, RunTest)
{
std::shared_ptr<std::vector<std::shared_ptr<Actor>>> actors =
std::make_shared<std::vector<std::shared_ptr<Actor>>>();
std::shared_ptr<RigidActor> actor = std::make_shared<RigidActor>("TestSphere");
RigidActorParameters params;
params.setDensity(700.0); // Wood
std::shared_ptr<SphereShape> shape = std::make_shared<SphereShape>(0.01); // 1cm Sphere
params.setShapeUsedForMassInertia(shape);
actor->setInitialParameters(params);
actor->setInitialPose(SurgSim::Math::makeRigidTransform(SurgSim::Math::Quaterniond(), Vector3d(0.0,0.0,0.0)));
actors->push_back(actor);
FreeMotion computation(actors);
EXPECT_TRUE(Vector3d(0.0,0.0,0.0).isApprox(actor->getPose().translation()));
computation.update(1.0);
EXPECT_FALSE(Vector3d(0.0,0.0,0.0).isApprox(actor->getPose().translation()));
}
<|endoftext|>
|
<commit_before>#include "stdafx.h"
#include "CppUnitTest.h"
#include "ThreadIds.h"
#include "ReadyEvent.h"
#include "AppFactory.h"
#include "App.h"
using namespace Microsoft::VisualStudio::CppUnitTestFramework;
namespace threadily {
namespace test {
TEST_CLASS(AppExampleUnitTest)
{
public:
/**
* Basically tries to create everything in the system and any linkages in the system
*/
TEST_METHOD(ReadProductsAsync_bug_2017_03_18)
{
auto app = AppFactory::getInstance().create();
// first see if the business exists
waitForAsync(
app->isBusinessesPending,
[&app]() {
app->readBusinessesAsync(0, 10, "Wit");
});
Assert::AreEqual(0, (int)app->businesses->size(), L"Should be 0 businesses in the system");
// Since it doesn't exist, we should make it! First the address
waitForAsync(
app->isCreateBusinessPending,
[&app]() {
app->createBusinessAsync("Witness");
});
auto witness = app->createdBusiness->get();
Assert::AreEqual(std::string("Witness"), witness->name->get());
auto similarToThreadilyBridge = witness->products->subscribe([](std::shared_ptr<Product> newValue, size_t index, threadily::ObservableActionType action) {
});
// Even though we have the business let's check it's product listings anyway
waitForAsync(
witness->isProductsPending,
[&witness]() {
witness->readProductsAsync(0, 20, "");
});
Assert::AreEqual(0, (int)witness->products->size(), L"Should be 0 products for the business in the system");
// create a product
waitForAsync(
witness->isCreateProductPending,
[&witness]() {
witness->createProductAsync("Name");
});
Assert::IsTrue(witness->createdProduct->get() != nullptr, L"Product should not be null after creating it");
// Make sure the product exists
waitForAsync(
witness->isProductsPending,
[&witness]() {
witness->readProductsAsync(0, 20, "");
});
Assert::AreEqual(1, (int)witness->products->size(), L"Should be 1 products for the business in the system");
}
void waitForAsync(std::shared_ptr<threadily::Observable<bool>> isPending, std::function<void()> asyncMethod)
{
threadily::ReadyEvent ready;
auto subscriptionHandle = isPending->subscribe([&ready](bool isPending) {
if (!isPending)
{
ready.finished();
}
});
asyncMethod();
ready.wait();
isPending->unsubscribe(subscriptionHandle);
}
};
}
}<commit_msg>Created unit test<commit_after>#include "stdafx.h"
#include "CppUnitTest.h"
#include "ThreadIds.h"
#include "ReadyEvent.h"
#include "AppFactory.h"
#include "App.h"
using namespace Microsoft::VisualStudio::CppUnitTestFramework;
namespace threadily {
namespace test {
TEST_CLASS(AppExampleUnitTest)
{
public:
/**
* Basically tries to create everything in the system and any linkages in the system
*/
TEST_METHOD(ReadProductsAsync_bug_2017_03_18)
{
auto app = AppFactory::getInstance().create();
// first see if the business exists
waitForAsync(
app->isBusinessesPending,
[&app]() {
app->readBusinessesAsync(0, 10, "Wit");
});
Assert::AreEqual(0, (int)app->businesses->size(), L"Should be 0 businesses in the system");
// Since it doesn't exist, we should make it! First the address
waitForAsync(
app->isCreateBusinessPending,
[&app]() {
app->createBusinessAsync("Witness");
});
auto witness = app->createdBusiness->get();
Assert::AreEqual(std::string("Witness"), witness->name->get());
auto similarToThreadilyBridge = witness->products->subscribe([](std::shared_ptr<Product> newValue, size_t index, threadily::ObservableActionType action) {
});
// Even though we have the business let's check it's product listings anyway
waitForAsync(
witness->isProductsPending,
[&witness]() {
witness->readProductsAsync(0, 20, "");
});
Assert::AreEqual(0, (int)witness->products->size(), L"Should be 0 products for the business in the system");
// create a product
waitForAsync(
witness->isCreateProductPending,
[&witness]() {
witness->createProductAsync("Name");
});
Assert::IsTrue(witness->createdProduct->get() != nullptr, L"Product should not be null after creating it");
// Make sure the product exists
waitForAsync(
witness->isProductsPending,
[&witness]() {
witness->readProductsAsync(0, 20, "");
});
Assert::AreEqual(1, (int)witness->products->size(), L"Should be 1 products for the business in the system");
}
TEST_METHOD(BusinessVectorIncreasesRefCount)
{
auto app = AppFactory::getInstance().create();
// Create a business
waitForAsync(
app->isCreateBusinessPending,
[&app]() {
app->createBusinessAsync("Witness");
});
auto witness = app->createdBusiness->get();
Assert::AreEqual(std::string("Witness"), witness->name->get());
auto oldUseCount = witness.use_count();
// Now query the business populating app->businesses
waitForAsync(
app->isBusinessesPending,
[&app]() {
app->readBusinessesAsync(0, 10, "Wit");
});
Assert::AreEqual(1, (int)app->businesses->size(), L"Should be 1 businesses in the system");
Assert::AreEqual(oldUseCount + 1, witness.use_count(), L"Expected the use count to increase by one as it should now be stored in the businesses listing");
}
void waitForAsync(std::shared_ptr<threadily::Observable<bool>> isPending, std::function<void()> asyncMethod)
{
threadily::ReadyEvent ready;
auto subscriptionHandle = isPending->subscribe([&ready](bool isPending) {
if (!isPending)
{
ready.finished();
}
});
asyncMethod();
ready.wait();
isPending->unsubscribe(subscriptionHandle);
}
};
}
}<|endoftext|>
|
<commit_before>/*
*
* Copyright 2015 gRPC authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
#include <memory>
#include <grpc/grpc.h>
#include <grpc/support/time.h>
#include <grpcpp/channel.h>
#include <grpcpp/client_context.h>
#include <grpcpp/create_channel.h>
#include <grpcpp/generic/async_generic_service.h>
#include <grpcpp/generic/generic_stub.h>
#include <grpcpp/impl/codegen/proto_utils.h>
#include <grpcpp/server.h>
#include <grpcpp/server_builder.h>
#include <grpcpp/server_context.h>
#include <grpcpp/support/slice.h>
#include "src/proto/grpc/testing/echo.grpc.pb.h"
#include "test/core/util/port.h"
#include "test/core/util/test_config.h"
#include "test/cpp/util/byte_buffer_proto_helper.h"
#include <gtest/gtest.h>
using grpc::testing::EchoRequest;
using grpc::testing::EchoResponse;
using std::chrono::system_clock;
namespace grpc {
namespace testing {
namespace {
void* tag(int i) { return (void*)static_cast<intptr_t>(i); }
void verify_ok(CompletionQueue* cq, int i, bool expect_ok) {
bool ok;
void* got_tag;
EXPECT_TRUE(cq->Next(&got_tag, &ok));
EXPECT_EQ(expect_ok, ok);
EXPECT_EQ(tag(i), got_tag);
}
class GenericEnd2endTest : public ::testing::Test {
protected:
GenericEnd2endTest() : server_host_("localhost") {}
void SetUp() override {
int port = grpc_pick_unused_port_or_die();
server_address_ << server_host_ << ":" << port;
// Setup server
ServerBuilder builder;
builder.AddListeningPort(server_address_.str(),
InsecureServerCredentials());
builder.RegisterAsyncGenericService(&generic_service_);
// Include a second call to RegisterAsyncGenericService to make sure that
// we get an error in the log, since it is not allowed to have 2 async
// generic services
builder.RegisterAsyncGenericService(&generic_service_);
srv_cq_ = builder.AddCompletionQueue();
server_ = builder.BuildAndStart();
}
void TearDown() override {
server_->Shutdown();
void* ignored_tag;
bool ignored_ok;
cli_cq_.Shutdown();
srv_cq_->Shutdown();
while (cli_cq_.Next(&ignored_tag, &ignored_ok))
;
while (srv_cq_->Next(&ignored_tag, &ignored_ok))
;
}
void ResetStub() {
std::shared_ptr<Channel> channel =
CreateChannel(server_address_.str(), InsecureChannelCredentials());
generic_stub_.reset(new GenericStub(channel));
}
void server_ok(int i) { verify_ok(srv_cq_.get(), i, true); }
void client_ok(int i) { verify_ok(&cli_cq_, i, true); }
void server_fail(int i) { verify_ok(srv_cq_.get(), i, false); }
void client_fail(int i) { verify_ok(&cli_cq_, i, false); }
void SendRpc(int num_rpcs) {
SendRpc(num_rpcs, false, gpr_inf_future(GPR_CLOCK_MONOTONIC));
}
void SendRpc(int num_rpcs, bool check_deadline, gpr_timespec deadline) {
const grpc::string kMethodName("/grpc.cpp.test.util.EchoTestService/Echo");
for (int i = 0; i < num_rpcs; i++) {
EchoRequest send_request;
EchoRequest recv_request;
EchoResponse send_response;
EchoResponse recv_response;
Status recv_status;
ClientContext cli_ctx;
GenericServerContext srv_ctx;
GenericServerAsyncReaderWriter stream(&srv_ctx);
// The string needs to be long enough to test heap-based slice.
send_request.set_message("Hello world. Hello world. Hello world.");
if (check_deadline) {
cli_ctx.set_deadline(deadline);
}
std::unique_ptr<GenericClientAsyncReaderWriter> call =
generic_stub_->PrepareCall(&cli_ctx, kMethodName, &cli_cq_);
call->StartCall(tag(1));
client_ok(1);
std::unique_ptr<ByteBuffer> send_buffer =
SerializeToByteBuffer(&send_request);
call->Write(*send_buffer, tag(2));
// Send ByteBuffer can be destroyed after calling Write.
send_buffer.reset();
client_ok(2);
call->WritesDone(tag(3));
client_ok(3);
generic_service_.RequestCall(&srv_ctx, &stream, srv_cq_.get(),
srv_cq_.get(), tag(4));
verify_ok(srv_cq_.get(), 4, true);
EXPECT_EQ(server_host_, srv_ctx.host().substr(0, server_host_.length()));
EXPECT_EQ(kMethodName, srv_ctx.method());
if (check_deadline) {
EXPECT_TRUE(gpr_time_similar(deadline, srv_ctx.raw_deadline(),
gpr_time_from_millis(1000, GPR_TIMESPAN)));
}
ByteBuffer recv_buffer;
stream.Read(&recv_buffer, tag(5));
server_ok(5);
EXPECT_TRUE(ParseFromByteBuffer(&recv_buffer, &recv_request));
EXPECT_EQ(send_request.message(), recv_request.message());
send_response.set_message(recv_request.message());
send_buffer = SerializeToByteBuffer(&send_response);
stream.Write(*send_buffer, tag(6));
send_buffer.reset();
server_ok(6);
stream.Finish(Status::OK, tag(7));
server_ok(7);
recv_buffer.Clear();
call->Read(&recv_buffer, tag(8));
client_ok(8);
EXPECT_TRUE(ParseFromByteBuffer(&recv_buffer, &recv_response));
call->Finish(&recv_status, tag(9));
client_ok(9);
EXPECT_EQ(send_response.message(), recv_response.message());
EXPECT_TRUE(recv_status.ok());
}
}
CompletionQueue cli_cq_;
std::unique_ptr<ServerCompletionQueue> srv_cq_;
std::unique_ptr<grpc::testing::EchoTestService::Stub> stub_;
std::unique_ptr<grpc::GenericStub> generic_stub_;
std::unique_ptr<Server> server_;
AsyncGenericService generic_service_;
const grpc::string server_host_;
std::ostringstream server_address_;
};
TEST_F(GenericEnd2endTest, SimpleRpc) {
ResetStub();
SendRpc(1);
}
TEST_F(GenericEnd2endTest, SequentialRpcs) {
ResetStub();
SendRpc(10);
}
TEST_F(GenericEnd2endTest, SequentialUnaryRpcs) {
ResetStub();
const int num_rpcs = 10;
const grpc::string kMethodName("/grpc.cpp.test.util.EchoTestService/Echo");
for (int i = 0; i < num_rpcs; i++) {
EchoRequest send_request;
EchoRequest recv_request;
EchoResponse send_response;
EchoResponse recv_response;
Status recv_status;
ClientContext cli_ctx;
GenericServerContext srv_ctx;
GenericServerAsyncReaderWriter stream(&srv_ctx);
// The string needs to be long enough to test heap-based slice.
send_request.set_message("Hello world. Hello world. Hello world.");
std::unique_ptr<ByteBuffer> cli_send_buffer =
SerializeToByteBuffer(&send_request);
// Use the same cq as server so that events can be polled in time.
std::unique_ptr<GenericClientAsyncResponseReader> call =
generic_stub_->PrepareUnaryCall(&cli_ctx, kMethodName,
*cli_send_buffer.get(), srv_cq_.get());
call->StartCall();
ByteBuffer cli_recv_buffer;
call->Finish(&cli_recv_buffer, &recv_status, tag(1));
generic_service_.RequestCall(&srv_ctx, &stream, srv_cq_.get(),
srv_cq_.get(), tag(4));
server_ok(4);
EXPECT_EQ(server_host_, srv_ctx.host().substr(0, server_host_.length()));
EXPECT_EQ(kMethodName, srv_ctx.method());
ByteBuffer srv_recv_buffer;
stream.Read(&srv_recv_buffer, tag(5));
server_ok(5);
EXPECT_TRUE(ParseFromByteBuffer(&srv_recv_buffer, &recv_request));
EXPECT_EQ(send_request.message(), recv_request.message());
send_response.set_message(recv_request.message());
std::unique_ptr<ByteBuffer> srv_send_buffer =
SerializeToByteBuffer(&send_response);
stream.Write(*srv_send_buffer, tag(6));
server_ok(6);
stream.Finish(Status::OK, tag(7));
server_ok(7);
verify_ok(srv_cq_.get(), 1, true);
EXPECT_TRUE(ParseFromByteBuffer(&cli_recv_buffer, &recv_response));
EXPECT_EQ(send_response.message(), recv_response.message());
EXPECT_TRUE(recv_status.ok());
}
}
// One ping, one pong.
TEST_F(GenericEnd2endTest, SimpleBidiStreaming) {
ResetStub();
const grpc::string kMethodName(
"/grpc.cpp.test.util.EchoTestService/BidiStream");
EchoRequest send_request;
EchoRequest recv_request;
EchoResponse send_response;
EchoResponse recv_response;
Status recv_status;
ClientContext cli_ctx;
GenericServerContext srv_ctx;
GenericServerAsyncReaderWriter srv_stream(&srv_ctx);
cli_ctx.set_compression_algorithm(GRPC_COMPRESS_GZIP);
send_request.set_message("Hello");
std::unique_ptr<GenericClientAsyncReaderWriter> cli_stream =
generic_stub_->PrepareCall(&cli_ctx, kMethodName, &cli_cq_);
cli_stream->StartCall(tag(1));
client_ok(1);
generic_service_.RequestCall(&srv_ctx, &srv_stream, srv_cq_.get(),
srv_cq_.get(), tag(2));
verify_ok(srv_cq_.get(), 2, true);
EXPECT_EQ(server_host_, srv_ctx.host().substr(0, server_host_.length()));
EXPECT_EQ(kMethodName, srv_ctx.method());
std::unique_ptr<ByteBuffer> send_buffer =
SerializeToByteBuffer(&send_request);
cli_stream->Write(*send_buffer, tag(3));
send_buffer.reset();
client_ok(3);
ByteBuffer recv_buffer;
srv_stream.Read(&recv_buffer, tag(4));
server_ok(4);
EXPECT_TRUE(ParseFromByteBuffer(&recv_buffer, &recv_request));
EXPECT_EQ(send_request.message(), recv_request.message());
send_response.set_message(recv_request.message());
send_buffer = SerializeToByteBuffer(&send_response);
srv_stream.Write(*send_buffer, tag(5));
send_buffer.reset();
server_ok(5);
cli_stream->Read(&recv_buffer, tag(6));
client_ok(6);
EXPECT_TRUE(ParseFromByteBuffer(&recv_buffer, &recv_response));
EXPECT_EQ(send_response.message(), recv_response.message());
cli_stream->WritesDone(tag(7));
client_ok(7);
srv_stream.Read(&recv_buffer, tag(8));
server_fail(8);
srv_stream.Finish(Status::OK, tag(9));
server_ok(9);
cli_stream->Finish(&recv_status, tag(10));
client_ok(10);
EXPECT_EQ(send_response.message(), recv_response.message());
EXPECT_TRUE(recv_status.ok());
}
TEST_F(GenericEnd2endTest, Deadline) {
ResetStub();
SendRpc(1, true,
gpr_time_add(gpr_now(GPR_CLOCK_MONOTONIC),
gpr_time_from_seconds(10, GPR_TIMESPAN)));
}
} // namespace
} // namespace testing
} // namespace grpc
int main(int argc, char** argv) {
grpc_test_init(argc, argv);
::testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}
<commit_msg>Confirm that generic API method name is not needed after call creation<commit_after>/*
*
* Copyright 2015 gRPC authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
#include <memory>
#include <grpc/grpc.h>
#include <grpc/support/time.h>
#include <grpcpp/channel.h>
#include <grpcpp/client_context.h>
#include <grpcpp/create_channel.h>
#include <grpcpp/generic/async_generic_service.h>
#include <grpcpp/generic/generic_stub.h>
#include <grpcpp/impl/codegen/proto_utils.h>
#include <grpcpp/server.h>
#include <grpcpp/server_builder.h>
#include <grpcpp/server_context.h>
#include <grpcpp/support/slice.h>
#include "src/proto/grpc/testing/echo.grpc.pb.h"
#include "test/core/util/port.h"
#include "test/core/util/test_config.h"
#include "test/cpp/util/byte_buffer_proto_helper.h"
#include <gtest/gtest.h>
using grpc::testing::EchoRequest;
using grpc::testing::EchoResponse;
using std::chrono::system_clock;
namespace grpc {
namespace testing {
namespace {
void* tag(int i) { return (void*)static_cast<intptr_t>(i); }
void verify_ok(CompletionQueue* cq, int i, bool expect_ok) {
bool ok;
void* got_tag;
EXPECT_TRUE(cq->Next(&got_tag, &ok));
EXPECT_EQ(expect_ok, ok);
EXPECT_EQ(tag(i), got_tag);
}
class GenericEnd2endTest : public ::testing::Test {
protected:
GenericEnd2endTest() : server_host_("localhost") {}
void SetUp() override {
int port = grpc_pick_unused_port_or_die();
server_address_ << server_host_ << ":" << port;
// Setup server
ServerBuilder builder;
builder.AddListeningPort(server_address_.str(),
InsecureServerCredentials());
builder.RegisterAsyncGenericService(&generic_service_);
// Include a second call to RegisterAsyncGenericService to make sure that
// we get an error in the log, since it is not allowed to have 2 async
// generic services
builder.RegisterAsyncGenericService(&generic_service_);
srv_cq_ = builder.AddCompletionQueue();
server_ = builder.BuildAndStart();
}
void TearDown() override {
server_->Shutdown();
void* ignored_tag;
bool ignored_ok;
cli_cq_.Shutdown();
srv_cq_->Shutdown();
while (cli_cq_.Next(&ignored_tag, &ignored_ok))
;
while (srv_cq_->Next(&ignored_tag, &ignored_ok))
;
}
void ResetStub() {
std::shared_ptr<Channel> channel =
CreateChannel(server_address_.str(), InsecureChannelCredentials());
generic_stub_.reset(new GenericStub(channel));
}
void server_ok(int i) { verify_ok(srv_cq_.get(), i, true); }
void client_ok(int i) { verify_ok(&cli_cq_, i, true); }
void server_fail(int i) { verify_ok(srv_cq_.get(), i, false); }
void client_fail(int i) { verify_ok(&cli_cq_, i, false); }
void SendRpc(int num_rpcs) {
SendRpc(num_rpcs, false, gpr_inf_future(GPR_CLOCK_MONOTONIC));
}
void SendRpc(int num_rpcs, bool check_deadline, gpr_timespec deadline) {
const grpc::string kMethodName("/grpc.cpp.test.util.EchoTestService/Echo");
for (int i = 0; i < num_rpcs; i++) {
EchoRequest send_request;
EchoRequest recv_request;
EchoResponse send_response;
EchoResponse recv_response;
Status recv_status;
ClientContext cli_ctx;
GenericServerContext srv_ctx;
GenericServerAsyncReaderWriter stream(&srv_ctx);
// The string needs to be long enough to test heap-based slice.
send_request.set_message("Hello world. Hello world. Hello world.");
if (check_deadline) {
cli_ctx.set_deadline(deadline);
}
// Rather than using the original kMethodName, make a short-lived
// copy to also confirm that we don't refer to this object beyond
// the initial call preparation
const grpc::string* method_name = new grpc::string(kMethodName);
std::unique_ptr<GenericClientAsyncReaderWriter> call =
generic_stub_->PrepareCall(&cli_ctx, *method_name, &cli_cq_);
delete method_name; // Make sure that this is not needed after invocation
call->StartCall(tag(1));
client_ok(1);
std::unique_ptr<ByteBuffer> send_buffer =
SerializeToByteBuffer(&send_request);
call->Write(*send_buffer, tag(2));
// Send ByteBuffer can be destroyed after calling Write.
send_buffer.reset();
client_ok(2);
call->WritesDone(tag(3));
client_ok(3);
generic_service_.RequestCall(&srv_ctx, &stream, srv_cq_.get(),
srv_cq_.get(), tag(4));
verify_ok(srv_cq_.get(), 4, true);
EXPECT_EQ(server_host_, srv_ctx.host().substr(0, server_host_.length()));
EXPECT_EQ(kMethodName, srv_ctx.method());
if (check_deadline) {
EXPECT_TRUE(gpr_time_similar(deadline, srv_ctx.raw_deadline(),
gpr_time_from_millis(1000, GPR_TIMESPAN)));
}
ByteBuffer recv_buffer;
stream.Read(&recv_buffer, tag(5));
server_ok(5);
EXPECT_TRUE(ParseFromByteBuffer(&recv_buffer, &recv_request));
EXPECT_EQ(send_request.message(), recv_request.message());
send_response.set_message(recv_request.message());
send_buffer = SerializeToByteBuffer(&send_response);
stream.Write(*send_buffer, tag(6));
send_buffer.reset();
server_ok(6);
stream.Finish(Status::OK, tag(7));
server_ok(7);
recv_buffer.Clear();
call->Read(&recv_buffer, tag(8));
client_ok(8);
EXPECT_TRUE(ParseFromByteBuffer(&recv_buffer, &recv_response));
call->Finish(&recv_status, tag(9));
client_ok(9);
EXPECT_EQ(send_response.message(), recv_response.message());
EXPECT_TRUE(recv_status.ok());
}
}
CompletionQueue cli_cq_;
std::unique_ptr<ServerCompletionQueue> srv_cq_;
std::unique_ptr<grpc::testing::EchoTestService::Stub> stub_;
std::unique_ptr<grpc::GenericStub> generic_stub_;
std::unique_ptr<Server> server_;
AsyncGenericService generic_service_;
const grpc::string server_host_;
std::ostringstream server_address_;
};
TEST_F(GenericEnd2endTest, SimpleRpc) {
ResetStub();
SendRpc(1);
}
TEST_F(GenericEnd2endTest, SequentialRpcs) {
ResetStub();
SendRpc(10);
}
TEST_F(GenericEnd2endTest, SequentialUnaryRpcs) {
ResetStub();
const int num_rpcs = 10;
const grpc::string kMethodName("/grpc.cpp.test.util.EchoTestService/Echo");
for (int i = 0; i < num_rpcs; i++) {
EchoRequest send_request;
EchoRequest recv_request;
EchoResponse send_response;
EchoResponse recv_response;
Status recv_status;
ClientContext cli_ctx;
GenericServerContext srv_ctx;
GenericServerAsyncReaderWriter stream(&srv_ctx);
// The string needs to be long enough to test heap-based slice.
send_request.set_message("Hello world. Hello world. Hello world.");
std::unique_ptr<ByteBuffer> cli_send_buffer =
SerializeToByteBuffer(&send_request);
// Use the same cq as server so that events can be polled in time.
std::unique_ptr<GenericClientAsyncResponseReader> call =
generic_stub_->PrepareUnaryCall(&cli_ctx, kMethodName,
*cli_send_buffer.get(), srv_cq_.get());
call->StartCall();
ByteBuffer cli_recv_buffer;
call->Finish(&cli_recv_buffer, &recv_status, tag(1));
generic_service_.RequestCall(&srv_ctx, &stream, srv_cq_.get(),
srv_cq_.get(), tag(4));
server_ok(4);
EXPECT_EQ(server_host_, srv_ctx.host().substr(0, server_host_.length()));
EXPECT_EQ(kMethodName, srv_ctx.method());
ByteBuffer srv_recv_buffer;
stream.Read(&srv_recv_buffer, tag(5));
server_ok(5);
EXPECT_TRUE(ParseFromByteBuffer(&srv_recv_buffer, &recv_request));
EXPECT_EQ(send_request.message(), recv_request.message());
send_response.set_message(recv_request.message());
std::unique_ptr<ByteBuffer> srv_send_buffer =
SerializeToByteBuffer(&send_response);
stream.Write(*srv_send_buffer, tag(6));
server_ok(6);
stream.Finish(Status::OK, tag(7));
server_ok(7);
verify_ok(srv_cq_.get(), 1, true);
EXPECT_TRUE(ParseFromByteBuffer(&cli_recv_buffer, &recv_response));
EXPECT_EQ(send_response.message(), recv_response.message());
EXPECT_TRUE(recv_status.ok());
}
}
// One ping, one pong.
TEST_F(GenericEnd2endTest, SimpleBidiStreaming) {
ResetStub();
const grpc::string kMethodName(
"/grpc.cpp.test.util.EchoTestService/BidiStream");
EchoRequest send_request;
EchoRequest recv_request;
EchoResponse send_response;
EchoResponse recv_response;
Status recv_status;
ClientContext cli_ctx;
GenericServerContext srv_ctx;
GenericServerAsyncReaderWriter srv_stream(&srv_ctx);
cli_ctx.set_compression_algorithm(GRPC_COMPRESS_GZIP);
send_request.set_message("Hello");
std::unique_ptr<GenericClientAsyncReaderWriter> cli_stream =
generic_stub_->PrepareCall(&cli_ctx, kMethodName, &cli_cq_);
cli_stream->StartCall(tag(1));
client_ok(1);
generic_service_.RequestCall(&srv_ctx, &srv_stream, srv_cq_.get(),
srv_cq_.get(), tag(2));
verify_ok(srv_cq_.get(), 2, true);
EXPECT_EQ(server_host_, srv_ctx.host().substr(0, server_host_.length()));
EXPECT_EQ(kMethodName, srv_ctx.method());
std::unique_ptr<ByteBuffer> send_buffer =
SerializeToByteBuffer(&send_request);
cli_stream->Write(*send_buffer, tag(3));
send_buffer.reset();
client_ok(3);
ByteBuffer recv_buffer;
srv_stream.Read(&recv_buffer, tag(4));
server_ok(4);
EXPECT_TRUE(ParseFromByteBuffer(&recv_buffer, &recv_request));
EXPECT_EQ(send_request.message(), recv_request.message());
send_response.set_message(recv_request.message());
send_buffer = SerializeToByteBuffer(&send_response);
srv_stream.Write(*send_buffer, tag(5));
send_buffer.reset();
server_ok(5);
cli_stream->Read(&recv_buffer, tag(6));
client_ok(6);
EXPECT_TRUE(ParseFromByteBuffer(&recv_buffer, &recv_response));
EXPECT_EQ(send_response.message(), recv_response.message());
cli_stream->WritesDone(tag(7));
client_ok(7);
srv_stream.Read(&recv_buffer, tag(8));
server_fail(8);
srv_stream.Finish(Status::OK, tag(9));
server_ok(9);
cli_stream->Finish(&recv_status, tag(10));
client_ok(10);
EXPECT_EQ(send_response.message(), recv_response.message());
EXPECT_TRUE(recv_status.ok());
}
TEST_F(GenericEnd2endTest, Deadline) {
ResetStub();
SendRpc(1, true,
gpr_time_add(gpr_now(GPR_CLOCK_MONOTONIC),
gpr_time_from_seconds(10, GPR_TIMESPAN)));
}
} // namespace
} // namespace testing
} // namespace grpc
int main(int argc, char** argv) {
grpc_test_init(argc, argv);
::testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}
<|endoftext|>
|
<commit_before>#include <iostream>
#include <conio.h>
using namespace std;
const int SIZE_A = 7;
const int SIZE_B = 7;
bool binarySearch(int * arr, int size, int num) {
static int start = 0;
int end = size - 1;
int mid;
bool found = false;
while (!found && start <= end) {
mid = (start + end) / 2;
if (num == *(arr + mid)) {
found = true;
} else if (num < *(arr + mid)) {
end = mid - 1;
} else {
start = mid + 1;
}
}
return found;
}
int main()
{
int A[SIZE_A] = { 13, 27, 35, 40, 49, 55, 59 };
int B[SIZE_B] = { 17, 35, 39, 40, 55, 58, 60 };
for (int i = 0; i < SIZE_A; i++) {
if (binarySearch(B, SIZE_B, A[i])) {
cout << A[i] << " ";
}
}
_getch();
return 0;
}
<commit_msg>improve code for common elements in two sorted arrays<commit_after>#include <iostream>
#include <conio.h>
using namespace std;
int main()
{
const int SIZE_A = 7;
const int SIZE_B = 7;
int A[SIZE_A] = { 13, 27, 35, 40, 49, 55, 59 };
int B[SIZE_B] = { 17, 35, 39, 40, 55, 58, 60 };
int i = 0, j = 0;
while (i < SIZE_A && j < SIZE_B) {
if (A[i] < B[j]) {
i++;
} else if (A[i] > B[j]) {
j++;
} else {
cout << A[i] << " ";
i++;
j++;
}
}
_getch();
return 0;
}
<|endoftext|>
|
<commit_before>/*************************************************************************
*
* $RCSfile: backingcomp.hxx,v $
*
* $Revision: 1.6 $
*
* last change: $Author: kz $ $Date: 2005-01-18 15:41:08 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the "License"); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#ifndef __FRAMEWORK_SERVICES_BACKINGCOMP_HXX_
#define __FRAMEWORK_SERVICES_BACKINGCOMP_HXX_
//__________________________________________
// own includes
#ifndef __FRAMEWORK_THREADHELP_THREADHELPBASE_HXX_
#include <threadhelp/threadhelpbase.hxx>
#endif
#ifndef __FRAMEWORK_GENERAL_H_
#include <general.h>
#endif
#ifndef __FRAMEWORK_STDTYPES_H_
#include <stdtypes.h>
#endif
//__________________________________________
// interface includes
#ifndef _COM_SUN_STAR_LANG_XTYPEPROVIDER_HPP_
#include <com/sun/star/lang/XTypeProvider.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_XSERVICEINFO_HPP_
#include <com/sun/star/lang/XServiceInfo.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_XINITIALIZATION_HPP_
#include <com/sun/star/lang/XInitialization.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_XMULTISERVICEFACTORY_HPP_
#include <com/sun/star/lang/XMultiServiceFactory.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_XSINGLESERVICEFACTORY_HPP_
#include <com/sun/star/lang/XSingleServiceFactory.hpp>
#endif
#ifndef _COM_SUN_STAR_AWT_XWINDOW_HPP_
#include <com/sun/star/awt/XWindow.hpp>
#endif
#ifndef _COM_SUN_STAR_AWT_XKEYLISTENER_HPP_
#include <com/sun/star/awt/XKeyListener.hpp>
#endif
#ifndef _COM_SUN_STAR_FAME_XFRAME_HPP_
#include <com/sun/star/frame/XFrame.hpp>
#endif
#ifndef _COM_SUN_STAR_DATATRANSFER_DND_XDROPTARGETELISTENER_HPP_
#include <com/sun/star/datatransfer/dnd/XDropTargetListener.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_XEVENTLISTENER_HPP_
#include <com/sun/star/lang/XEventListener.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_XCOMPONENT_HPP_
#include <com/sun/star/lang/XComponent.hpp>
#endif
//__________________________________________
// other includes
#ifndef _CPPUHELPER_WEAK_HXX_
#include <cppuhelper/weak.hxx>
#endif
#ifndef INCLUDED_SVTOOLS_ACCELERATOREXECUTE_HXX
#include <svtools/acceleratorexecute.hxx>
#endif
//__________________________________________
// definition
namespace framework
{
//__________________________________________
/**
implements the backing component.
This component is a special one, which doesn't provide a controller
nor a model. It supports the following features:
- Drag & Drop
- Key Accelerators
- Simple Menu
- Progress Bar
- Background
*/
class BackingComp : public css::lang::XTypeProvider
, public css::lang::XServiceInfo
, public css::lang::XInitialization
, public css::frame::XController // => XComponent
, public css::awt::XKeyListener // => XEventListener
// attention! Must be the first base class to guarentee right initialize lock ...
, private ThreadHelpBase
, public ::cppu::OWeakObject
{
//______________________________________
// member
private:
/** the global uno service manager.
Must be used to create own needed services. */
css::uno::Reference< css::lang::XMultiServiceFactory > m_xSMGR;
/** reference to the component window. */
css::uno::Reference< css::awt::XWindow > m_xWindow;
/** the owner frame of this component. */
css::uno::Reference< css::frame::XFrame > m_xFrame;
/** helper for drag&drop. */
css::uno::Reference< css::datatransfer::dnd::XDropTargetListener > m_xDropTargetListener;
/** helper, which handle shortcuts for us. */
::svt::AcceleratorExecute* m_pAccExec;
//______________________________________
// interface
public:
BackingComp( const css::uno::Reference< css::lang::XMultiServiceFactory > xSMGR );
virtual ~BackingComp( );
// XInterface
virtual css::uno::Any SAL_CALL queryInterface( const css::uno::Type& aType ) throw(css::uno::RuntimeException);
virtual void SAL_CALL acquire ( ) throw( );
virtual void SAL_CALL release ( ) throw( );
// XTypeProvide
virtual css::uno::Sequence< css::uno::Type > SAL_CALL getTypes () throw(css::uno::RuntimeException);
virtual css::uno::Sequence< sal_Int8 > SAL_CALL getImplementationId() throw(css::uno::RuntimeException);
// XServiceInfo
virtual ::rtl::OUString SAL_CALL getImplementationName ( ) throw(css::uno::RuntimeException);
virtual sal_Bool SAL_CALL supportsService ( const ::rtl::OUString& sServiceName ) throw(css::uno::RuntimeException);
virtual css::uno::Sequence< ::rtl::OUString > SAL_CALL getSupportedServiceNames( ) throw(css::uno::RuntimeException);
// XInitialization
virtual void SAL_CALL initialize( const css::uno::Sequence< css::uno::Any >& lArgs ) throw(css::uno::Exception, css::uno::RuntimeException);
// XController
virtual void SAL_CALL attachFrame ( const css::uno::Reference< css::frame::XFrame >& xFrame ) throw(css::uno::RuntimeException);
virtual sal_Bool SAL_CALL attachModel ( const css::uno::Reference< css::frame::XModel >& xModel ) throw(css::uno::RuntimeException);
virtual sal_Bool SAL_CALL suspend ( sal_Bool bSuspend ) throw(css::uno::RuntimeException);
virtual css::uno::Any SAL_CALL getViewData ( ) throw(css::uno::RuntimeException);
virtual void SAL_CALL restoreViewData( const css::uno::Any& aData ) throw(css::uno::RuntimeException);
virtual css::uno::Reference< css::frame::XModel > SAL_CALL getModel ( ) throw(css::uno::RuntimeException);
virtual css::uno::Reference< css::frame::XFrame > SAL_CALL getFrame ( ) throw(css::uno::RuntimeException);
// XKeyListener
virtual void SAL_CALL keyPressed ( const css::awt::KeyEvent& aEvent ) throw(css::uno::RuntimeException);
virtual void SAL_CALL keyReleased( const css::awt::KeyEvent& aEvent ) throw(css::uno::RuntimeException);
// XEventListener
virtual void SAL_CALL disposing( const css::lang::EventObject& aEvent ) throw(css::uno::RuntimeException);
// XComponent
virtual void SAL_CALL dispose ( ) throw(css::uno::RuntimeException);
virtual void SAL_CALL addEventListener ( const css::uno::Reference< css::lang::XEventListener >& xListener ) throw(css::uno::RuntimeException);
virtual void SAL_CALL removeEventListener( const css::uno::Reference< css::lang::XEventListener >& xListener ) throw(css::uno::RuntimeException);
//______________________________________
// helper
public:
static css::uno::Sequence< ::rtl::OUString > SAL_CALL impl_getStaticSupportedServiceNames( );
static ::rtl::OUString SAL_CALL impl_getStaticImplementationName ( );
static css::uno::Reference< css::uno::XInterface > SAL_CALL impl_createInstance ( const css::uno::Reference< css::lang::XMultiServiceFactory >& xSMGR ) throw( css::uno::Exception );
static css::uno::Reference< css::lang::XSingleServiceFactory > SAL_CALL impl_createFactory ( const css::uno::Reference< css::lang::XMultiServiceFactory >& xSMGR );
};
} // namespace framework
#endif // __FRAMEWORK_SERVICES_BACKINGCOMP_HXX_
<commit_msg>INTEGRATION: CWS ooo19126 (1.6.164); FILE MERGED 2005/09/05 13:05:10 rt 1.6.164.1: #i54170# Change license header: remove SISSL<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: backingcomp.hxx,v $
*
* $Revision: 1.7 $
*
* last change: $Author: rt $ $Date: 2005-09-09 00:28:32 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#ifndef __FRAMEWORK_SERVICES_BACKINGCOMP_HXX_
#define __FRAMEWORK_SERVICES_BACKINGCOMP_HXX_
//__________________________________________
// own includes
#ifndef __FRAMEWORK_THREADHELP_THREADHELPBASE_HXX_
#include <threadhelp/threadhelpbase.hxx>
#endif
#ifndef __FRAMEWORK_GENERAL_H_
#include <general.h>
#endif
#ifndef __FRAMEWORK_STDTYPES_H_
#include <stdtypes.h>
#endif
//__________________________________________
// interface includes
#ifndef _COM_SUN_STAR_LANG_XTYPEPROVIDER_HPP_
#include <com/sun/star/lang/XTypeProvider.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_XSERVICEINFO_HPP_
#include <com/sun/star/lang/XServiceInfo.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_XINITIALIZATION_HPP_
#include <com/sun/star/lang/XInitialization.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_XMULTISERVICEFACTORY_HPP_
#include <com/sun/star/lang/XMultiServiceFactory.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_XSINGLESERVICEFACTORY_HPP_
#include <com/sun/star/lang/XSingleServiceFactory.hpp>
#endif
#ifndef _COM_SUN_STAR_AWT_XWINDOW_HPP_
#include <com/sun/star/awt/XWindow.hpp>
#endif
#ifndef _COM_SUN_STAR_AWT_XKEYLISTENER_HPP_
#include <com/sun/star/awt/XKeyListener.hpp>
#endif
#ifndef _COM_SUN_STAR_FAME_XFRAME_HPP_
#include <com/sun/star/frame/XFrame.hpp>
#endif
#ifndef _COM_SUN_STAR_DATATRANSFER_DND_XDROPTARGETELISTENER_HPP_
#include <com/sun/star/datatransfer/dnd/XDropTargetListener.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_XEVENTLISTENER_HPP_
#include <com/sun/star/lang/XEventListener.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_XCOMPONENT_HPP_
#include <com/sun/star/lang/XComponent.hpp>
#endif
//__________________________________________
// other includes
#ifndef _CPPUHELPER_WEAK_HXX_
#include <cppuhelper/weak.hxx>
#endif
#ifndef INCLUDED_SVTOOLS_ACCELERATOREXECUTE_HXX
#include <svtools/acceleratorexecute.hxx>
#endif
//__________________________________________
// definition
namespace framework
{
//__________________________________________
/**
implements the backing component.
This component is a special one, which doesn't provide a controller
nor a model. It supports the following features:
- Drag & Drop
- Key Accelerators
- Simple Menu
- Progress Bar
- Background
*/
class BackingComp : public css::lang::XTypeProvider
, public css::lang::XServiceInfo
, public css::lang::XInitialization
, public css::frame::XController // => XComponent
, public css::awt::XKeyListener // => XEventListener
// attention! Must be the first base class to guarentee right initialize lock ...
, private ThreadHelpBase
, public ::cppu::OWeakObject
{
//______________________________________
// member
private:
/** the global uno service manager.
Must be used to create own needed services. */
css::uno::Reference< css::lang::XMultiServiceFactory > m_xSMGR;
/** reference to the component window. */
css::uno::Reference< css::awt::XWindow > m_xWindow;
/** the owner frame of this component. */
css::uno::Reference< css::frame::XFrame > m_xFrame;
/** helper for drag&drop. */
css::uno::Reference< css::datatransfer::dnd::XDropTargetListener > m_xDropTargetListener;
/** helper, which handle shortcuts for us. */
::svt::AcceleratorExecute* m_pAccExec;
//______________________________________
// interface
public:
BackingComp( const css::uno::Reference< css::lang::XMultiServiceFactory > xSMGR );
virtual ~BackingComp( );
// XInterface
virtual css::uno::Any SAL_CALL queryInterface( const css::uno::Type& aType ) throw(css::uno::RuntimeException);
virtual void SAL_CALL acquire ( ) throw( );
virtual void SAL_CALL release ( ) throw( );
// XTypeProvide
virtual css::uno::Sequence< css::uno::Type > SAL_CALL getTypes () throw(css::uno::RuntimeException);
virtual css::uno::Sequence< sal_Int8 > SAL_CALL getImplementationId() throw(css::uno::RuntimeException);
// XServiceInfo
virtual ::rtl::OUString SAL_CALL getImplementationName ( ) throw(css::uno::RuntimeException);
virtual sal_Bool SAL_CALL supportsService ( const ::rtl::OUString& sServiceName ) throw(css::uno::RuntimeException);
virtual css::uno::Sequence< ::rtl::OUString > SAL_CALL getSupportedServiceNames( ) throw(css::uno::RuntimeException);
// XInitialization
virtual void SAL_CALL initialize( const css::uno::Sequence< css::uno::Any >& lArgs ) throw(css::uno::Exception, css::uno::RuntimeException);
// XController
virtual void SAL_CALL attachFrame ( const css::uno::Reference< css::frame::XFrame >& xFrame ) throw(css::uno::RuntimeException);
virtual sal_Bool SAL_CALL attachModel ( const css::uno::Reference< css::frame::XModel >& xModel ) throw(css::uno::RuntimeException);
virtual sal_Bool SAL_CALL suspend ( sal_Bool bSuspend ) throw(css::uno::RuntimeException);
virtual css::uno::Any SAL_CALL getViewData ( ) throw(css::uno::RuntimeException);
virtual void SAL_CALL restoreViewData( const css::uno::Any& aData ) throw(css::uno::RuntimeException);
virtual css::uno::Reference< css::frame::XModel > SAL_CALL getModel ( ) throw(css::uno::RuntimeException);
virtual css::uno::Reference< css::frame::XFrame > SAL_CALL getFrame ( ) throw(css::uno::RuntimeException);
// XKeyListener
virtual void SAL_CALL keyPressed ( const css::awt::KeyEvent& aEvent ) throw(css::uno::RuntimeException);
virtual void SAL_CALL keyReleased( const css::awt::KeyEvent& aEvent ) throw(css::uno::RuntimeException);
// XEventListener
virtual void SAL_CALL disposing( const css::lang::EventObject& aEvent ) throw(css::uno::RuntimeException);
// XComponent
virtual void SAL_CALL dispose ( ) throw(css::uno::RuntimeException);
virtual void SAL_CALL addEventListener ( const css::uno::Reference< css::lang::XEventListener >& xListener ) throw(css::uno::RuntimeException);
virtual void SAL_CALL removeEventListener( const css::uno::Reference< css::lang::XEventListener >& xListener ) throw(css::uno::RuntimeException);
//______________________________________
// helper
public:
static css::uno::Sequence< ::rtl::OUString > SAL_CALL impl_getStaticSupportedServiceNames( );
static ::rtl::OUString SAL_CALL impl_getStaticImplementationName ( );
static css::uno::Reference< css::uno::XInterface > SAL_CALL impl_createInstance ( const css::uno::Reference< css::lang::XMultiServiceFactory >& xSMGR ) throw( css::uno::Exception );
static css::uno::Reference< css::lang::XSingleServiceFactory > SAL_CALL impl_createFactory ( const css::uno::Reference< css::lang::XMultiServiceFactory >& xSMGR );
};
} // namespace framework
#endif // __FRAMEWORK_SERVICES_BACKINGCOMP_HXX_
<|endoftext|>
|
<commit_before>#include <string>
#include <vector>
#include <time.h>
#include "../glsl_optimizer.h"
#ifdef _MSC_VER
#include <windows.h>
#include <gl/GL.h>
extern "C" {
typedef char GLcharARB; /* native character */
typedef unsigned int GLhandleARB; /* shader object handle */
#define GL_VERTEX_SHADER_ARB 0x8B31
#define GL_FRAGMENT_SHADER_ARB 0x8B30
#define GL_OBJECT_COMPILE_STATUS_ARB 0x8B81
typedef void (WINAPI * PFNGLDELETEOBJECTARBPROC) (GLhandleARB obj);
typedef GLhandleARB (WINAPI * PFNGLCREATESHADEROBJECTARBPROC) (GLenum shaderType);
typedef void (WINAPI * PFNGLSHADERSOURCEARBPROC) (GLhandleARB shaderObj, GLsizei count, const GLcharARB* *string, const GLint *length);
typedef void (WINAPI * PFNGLCOMPILESHADERARBPROC) (GLhandleARB shaderObj);
typedef void (WINAPI * PFNGLGETINFOLOGARBPROC) (GLhandleARB obj, GLsizei maxLength, GLsizei *length, GLcharARB *infoLog);
typedef void (WINAPI * PFNGLGETOBJECTPARAMETERIVARBPROC) (GLhandleARB obj, GLenum pname, GLint *params);
static PFNGLDELETEOBJECTARBPROC glDeleteObjectARB;
static PFNGLCREATESHADEROBJECTARBPROC glCreateShaderObjectARB;
static PFNGLSHADERSOURCEARBPROC glShaderSourceARB;
static PFNGLCOMPILESHADERARBPROC glCompileShaderARB;
static PFNGLGETINFOLOGARBPROC glGetInfoLogARB;
static PFNGLGETOBJECTPARAMETERIVARBPROC glGetObjectParameterivARB;
}
#else
#include <OpenGL/OpenGL.h>
#include <AGL/agl.h>
#include <dirent.h>
#endif
static bool InitializeOpenGL ()
{
bool hasGLSL = false;
#ifdef _MSC_VER
// setup minimal required GL
HWND wnd = CreateWindowA(
"STATIC",
"GL",
WS_OVERLAPPEDWINDOW | WS_CLIPSIBLINGS | WS_CLIPCHILDREN,
0, 0, 16, 16,
NULL, NULL,
GetModuleHandle(NULL), NULL );
HDC dc = GetDC( wnd );
PIXELFORMATDESCRIPTOR pfd = {
sizeof(PIXELFORMATDESCRIPTOR), 1,
PFD_DRAW_TO_WINDOW | PFD_SUPPORT_OPENGL,
PFD_TYPE_RGBA, 32,
0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0,
16, 0,
0, PFD_MAIN_PLANE, 0, 0, 0, 0
};
int fmt = ChoosePixelFormat( dc, &pfd );
SetPixelFormat( dc, fmt, &pfd );
HGLRC rc = wglCreateContext( dc );
wglMakeCurrent( dc, rc );
#else
GLint attributes[16];
int i = 0;
attributes[i++]=AGL_RGBA;
attributes[i++]=AGL_PIXEL_SIZE;
attributes[i++]=32;
attributes[i++]=AGL_NO_RECOVERY;
attributes[i++]=AGL_NONE;
AGLPixelFormat pixelFormat = aglChoosePixelFormat(NULL,0,attributes);
AGLContext agl = aglCreateContext(pixelFormat, NULL);
aglSetCurrentContext (agl);
#endif
// check if we have GLSL
const char* extensions = (const char*)glGetString(GL_EXTENSIONS);
hasGLSL = strstr(extensions, "GL_ARB_shader_objects") && strstr(extensions, "GL_ARB_vertex_shader") && strstr(extensions, "GL_ARB_fragment_shader");
#ifdef _MSC_VER
if (hasGLSL)
{
glDeleteObjectARB = (PFNGLDELETEOBJECTARBPROC)wglGetProcAddress("glDeleteObjectARB");
glCreateShaderObjectARB = (PFNGLCREATESHADEROBJECTARBPROC)wglGetProcAddress("glCreateShaderObjectARB");
glShaderSourceARB = (PFNGLSHADERSOURCEARBPROC)wglGetProcAddress("glShaderSourceARB");
glCompileShaderARB = (PFNGLCOMPILESHADERARBPROC)wglGetProcAddress("glCompileShaderARB");
glGetInfoLogARB = (PFNGLGETINFOLOGARBPROC)wglGetProcAddress("glGetInfoLogARB");
glGetObjectParameterivARB = (PFNGLGETOBJECTPARAMETERIVARBPROC)wglGetProcAddress("glGetObjectParameterivARB");
}
#endif
return hasGLSL;
}
static bool CheckGLSL (bool vertex, const char* prefix, const char* source)
{
GLhandleARB shader = glCreateShaderObjectARB (vertex ? GL_VERTEX_SHADER_ARB : GL_FRAGMENT_SHADER_ARB);
glShaderSourceARB (shader, 1, &source, NULL);
glCompileShaderARB (shader);
GLint status;
glGetObjectParameterivARB (shader, GL_OBJECT_COMPILE_STATUS_ARB, &status);
bool res = true;
if (status == 0)
{
char log[4096];
GLsizei logLength;
glGetInfoLogARB (shader, sizeof(log), &logLength, log);
printf (" glsl compile error on %s:\n%s\n", prefix, log);
res = false;
}
glDeleteObjectARB (shader);
return res;
}
static bool ReadStringFromFile (const char* pathName, std::string& output)
{
FILE* file = fopen( pathName, "rb" );
if (file == NULL)
return false;
fseek(file, 0, SEEK_END);
int length = ftell(file);
fseek(file, 0, SEEK_SET);
if (length < 0)
{
fclose( file );
return false;
}
output.resize(length);
int readLength = fread(&*output.begin(), 1, length, file);
fclose(file);
if (readLength != length)
{
output.clear();
return false;
}
return true;
}
bool EndsWith (const std::string& str, const std::string& sub)
{
return (str.size() >= sub.size()) && (strncmp (str.c_str()+str.size()-sub.size(), sub.c_str(), sub.size())==0);
}
typedef std::vector<std::string> StringVector;
static StringVector GetFiles (const std::string& folder, const std::string& endsWith)
{
StringVector res;
#ifdef _MSC_VER
WIN32_FIND_DATAA FindFileData;
HANDLE hFind = FindFirstFileA ((folder+"/*"+endsWith).c_str(), &FindFileData);
if (hFind == INVALID_HANDLE_VALUE)
return res;
do {
res.push_back (FindFileData.cFileName);
} while (FindNextFileA (hFind, &FindFileData));
FindClose (hFind);
#else
DIR *dirp;
struct dirent *dp;
if ((dirp = opendir(folder.c_str())) == NULL)
return res;
while ( (dp = readdir(dirp)) )
{
std::string fname = dp->d_name;
if (fname == "." || fname == "..")
continue;
if (!EndsWith (fname, endsWith))
continue;
res.push_back (fname);
}
closedir(dirp);
#endif
return res;
}
static void DeleteFile (const std::string& path)
{
#ifdef _MSC_VER
DeleteFileA (path.c_str());
#else
unlink (path.c_str());
#endif
}
static void MassageVertexForGLES (std::string& s)
{
std::string pre;
pre += "#define gl_Vertex _glesVertex\nattribute highp vec4 _glesVertex;\n";
pre += "#define gl_Normal _glesNormal\nattribute mediump vec3 _glesNormal;\n";
pre += "#define gl_MultiTexCoord0 _glesMultiTexCoord0\nattribute highp vec4 _glesMultiTexCoord0;\n";
pre += "#define gl_MultiTexCoord1 _glesMultiTexCoord1\nattribute highp vec4 _glesMultiTexCoord1;\n";
pre += "#define gl_Color _glesColor\nattribute lowp vec4 _glesColor;\n";
s = pre + s;
}
static void MassageFragmentForGLES (std::string& s)
{
std::string pre;
s = pre + s;
}
static bool TestFile (glslopt_ctx* ctx, bool vertex,
const std::string& inputPath,
const std::string& hirPath,
const std::string& outputPath,
bool gles,
bool doCheckGLSL)
{
std::string input;
if (!ReadStringFromFile (inputPath.c_str(), input))
{
printf (" failed to read input file\n");
return false;
}
if (doCheckGLSL && !CheckGLSL (vertex, "input", input.c_str()))
{
return false;
}
if (gles)
{
if (vertex)
MassageVertexForGLES (input);
else
MassageFragmentForGLES (input);
}
bool res = true;
glslopt_shader_type type = vertex ? kGlslOptShaderVertex : kGlslOptShaderFragment;
glslopt_shader* shader = glslopt_optimize (ctx, type, input.c_str(), 0);
bool optimizeOk = glslopt_get_status(shader);
if (optimizeOk)
{
std::string textHir = glslopt_get_raw_output (shader);
std::string textOpt = glslopt_get_output (shader);
std::string outputHir;
ReadStringFromFile (hirPath.c_str(), outputHir);
std::string outputOpt;
ReadStringFromFile (outputPath.c_str(), outputOpt);
if (textHir != outputHir)
{
// write output
FILE* f = fopen (hirPath.c_str(), "wb");
fwrite (textHir.c_str(), 1, textHir.size(), f);
fclose (f);
printf (" does not match raw output\n");
res = false;
}
if (textOpt != outputOpt)
{
// write output
FILE* f = fopen (outputPath.c_str(), "wb");
fwrite (textOpt.c_str(), 1, textOpt.size(), f);
fclose (f);
printf (" does not match optimized output\n");
res = false;
}
if (res && doCheckGLSL && !CheckGLSL (vertex, "raw", textHir.c_str()))
res = false;
if (res && doCheckGLSL && !CheckGLSL (vertex, "optimized", textOpt.c_str()))
res = false;
}
else
{
printf (" optimize error: %s\n", glslopt_get_log(shader));
res = false;
}
glslopt_shader_delete (shader);
return res;
}
int main (int argc, const char** argv)
{
if (argc < 2)
{
printf ("USAGE: glsloptimizer testfolder\n");
return 1;
}
bool hasOpenGL = InitializeOpenGL ();
glslopt_ctx* ctx[2] = {
glslopt_initialize(true),
glslopt_initialize(false),
};
std::string baseFolder = argv[1];
clock_t time0 = clock();
static const char* kTypeName[2] = { "vertex", "fragment" };
size_t tests = 0;
size_t errors = 0;
for (int type = 0; type < 2; ++type)
{
std::string testFolder = baseFolder + "/" + kTypeName[type];
static const char* kAPIName[2] = { "OpenGL ES 2.0", "OpenGL" };
static const char* kApiIn [2] = {"-inES.txt", "-in.txt"};
static const char* kApiIR [2] = {"-irES.txt", "-ir.txt"};
static const char* kApiOut[2] = {"-outES.txt", "-out.txt"};
for (int api = 0; api < 1; ++api)
{
printf ("** running %s tests for %s...\n", kTypeName[type], kAPIName[api]);
StringVector inputFiles = GetFiles (testFolder, kApiIn[api]);
size_t n = inputFiles.size();
for (size_t i = 0; i < n; ++i)
{
std::string inname = inputFiles[i];
printf ("test %s\n", inname.c_str());
std::string hirname = inname.substr (0,inname.size()-strlen(kApiIn[api])) + kApiIR[api];
std::string outname = inname.substr (0,inname.size()-strlen(kApiIn[api])) + kApiOut[api];
bool ok = TestFile (ctx[api], type==0, testFolder + "/" + inname, testFolder + "/" + hirname, testFolder + "/" + outname, api==0, hasOpenGL);
if (!ok)
{
++errors;
}
++tests;
}
}
}
clock_t time1 = clock();
float timeDelta = float(time1-time0)/CLOCKS_PER_SEC;
if (errors != 0)
printf ("**** %i tests (%.2fsec), %i !!!FAILED!!!\n", tests, timeDelta, errors);
else
printf ("**** %i tests (%.2fsec) succeeded\n", tests, timeDelta);
for (int i = 0; i < 2; ++i)
glslopt_cleanup (ctx[i]);
return errors ? 1 : 0;
}
<commit_msg>tests: whoops, run full tests<commit_after>#include <string>
#include <vector>
#include <time.h>
#include "../glsl_optimizer.h"
#ifdef _MSC_VER
#include <windows.h>
#include <gl/GL.h>
extern "C" {
typedef char GLcharARB; /* native character */
typedef unsigned int GLhandleARB; /* shader object handle */
#define GL_VERTEX_SHADER_ARB 0x8B31
#define GL_FRAGMENT_SHADER_ARB 0x8B30
#define GL_OBJECT_COMPILE_STATUS_ARB 0x8B81
typedef void (WINAPI * PFNGLDELETEOBJECTARBPROC) (GLhandleARB obj);
typedef GLhandleARB (WINAPI * PFNGLCREATESHADEROBJECTARBPROC) (GLenum shaderType);
typedef void (WINAPI * PFNGLSHADERSOURCEARBPROC) (GLhandleARB shaderObj, GLsizei count, const GLcharARB* *string, const GLint *length);
typedef void (WINAPI * PFNGLCOMPILESHADERARBPROC) (GLhandleARB shaderObj);
typedef void (WINAPI * PFNGLGETINFOLOGARBPROC) (GLhandleARB obj, GLsizei maxLength, GLsizei *length, GLcharARB *infoLog);
typedef void (WINAPI * PFNGLGETOBJECTPARAMETERIVARBPROC) (GLhandleARB obj, GLenum pname, GLint *params);
static PFNGLDELETEOBJECTARBPROC glDeleteObjectARB;
static PFNGLCREATESHADEROBJECTARBPROC glCreateShaderObjectARB;
static PFNGLSHADERSOURCEARBPROC glShaderSourceARB;
static PFNGLCOMPILESHADERARBPROC glCompileShaderARB;
static PFNGLGETINFOLOGARBPROC glGetInfoLogARB;
static PFNGLGETOBJECTPARAMETERIVARBPROC glGetObjectParameterivARB;
}
#else
#include <OpenGL/OpenGL.h>
#include <AGL/agl.h>
#include <dirent.h>
#endif
static bool InitializeOpenGL ()
{
bool hasGLSL = false;
#ifdef _MSC_VER
// setup minimal required GL
HWND wnd = CreateWindowA(
"STATIC",
"GL",
WS_OVERLAPPEDWINDOW | WS_CLIPSIBLINGS | WS_CLIPCHILDREN,
0, 0, 16, 16,
NULL, NULL,
GetModuleHandle(NULL), NULL );
HDC dc = GetDC( wnd );
PIXELFORMATDESCRIPTOR pfd = {
sizeof(PIXELFORMATDESCRIPTOR), 1,
PFD_DRAW_TO_WINDOW | PFD_SUPPORT_OPENGL,
PFD_TYPE_RGBA, 32,
0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0,
16, 0,
0, PFD_MAIN_PLANE, 0, 0, 0, 0
};
int fmt = ChoosePixelFormat( dc, &pfd );
SetPixelFormat( dc, fmt, &pfd );
HGLRC rc = wglCreateContext( dc );
wglMakeCurrent( dc, rc );
#else
GLint attributes[16];
int i = 0;
attributes[i++]=AGL_RGBA;
attributes[i++]=AGL_PIXEL_SIZE;
attributes[i++]=32;
attributes[i++]=AGL_NO_RECOVERY;
attributes[i++]=AGL_NONE;
AGLPixelFormat pixelFormat = aglChoosePixelFormat(NULL,0,attributes);
AGLContext agl = aglCreateContext(pixelFormat, NULL);
aglSetCurrentContext (agl);
#endif
// check if we have GLSL
const char* extensions = (const char*)glGetString(GL_EXTENSIONS);
hasGLSL = strstr(extensions, "GL_ARB_shader_objects") && strstr(extensions, "GL_ARB_vertex_shader") && strstr(extensions, "GL_ARB_fragment_shader");
#ifdef _MSC_VER
if (hasGLSL)
{
glDeleteObjectARB = (PFNGLDELETEOBJECTARBPROC)wglGetProcAddress("glDeleteObjectARB");
glCreateShaderObjectARB = (PFNGLCREATESHADEROBJECTARBPROC)wglGetProcAddress("glCreateShaderObjectARB");
glShaderSourceARB = (PFNGLSHADERSOURCEARBPROC)wglGetProcAddress("glShaderSourceARB");
glCompileShaderARB = (PFNGLCOMPILESHADERARBPROC)wglGetProcAddress("glCompileShaderARB");
glGetInfoLogARB = (PFNGLGETINFOLOGARBPROC)wglGetProcAddress("glGetInfoLogARB");
glGetObjectParameterivARB = (PFNGLGETOBJECTPARAMETERIVARBPROC)wglGetProcAddress("glGetObjectParameterivARB");
}
#endif
return hasGLSL;
}
static bool CheckGLSL (bool vertex, const char* prefix, const char* source)
{
GLhandleARB shader = glCreateShaderObjectARB (vertex ? GL_VERTEX_SHADER_ARB : GL_FRAGMENT_SHADER_ARB);
glShaderSourceARB (shader, 1, &source, NULL);
glCompileShaderARB (shader);
GLint status;
glGetObjectParameterivARB (shader, GL_OBJECT_COMPILE_STATUS_ARB, &status);
bool res = true;
if (status == 0)
{
char log[4096];
GLsizei logLength;
glGetInfoLogARB (shader, sizeof(log), &logLength, log);
printf (" glsl compile error on %s:\n%s\n", prefix, log);
res = false;
}
glDeleteObjectARB (shader);
return res;
}
static bool ReadStringFromFile (const char* pathName, std::string& output)
{
FILE* file = fopen( pathName, "rb" );
if (file == NULL)
return false;
fseek(file, 0, SEEK_END);
int length = ftell(file);
fseek(file, 0, SEEK_SET);
if (length < 0)
{
fclose( file );
return false;
}
output.resize(length);
int readLength = fread(&*output.begin(), 1, length, file);
fclose(file);
if (readLength != length)
{
output.clear();
return false;
}
return true;
}
bool EndsWith (const std::string& str, const std::string& sub)
{
return (str.size() >= sub.size()) && (strncmp (str.c_str()+str.size()-sub.size(), sub.c_str(), sub.size())==0);
}
typedef std::vector<std::string> StringVector;
static StringVector GetFiles (const std::string& folder, const std::string& endsWith)
{
StringVector res;
#ifdef _MSC_VER
WIN32_FIND_DATAA FindFileData;
HANDLE hFind = FindFirstFileA ((folder+"/*"+endsWith).c_str(), &FindFileData);
if (hFind == INVALID_HANDLE_VALUE)
return res;
do {
res.push_back (FindFileData.cFileName);
} while (FindNextFileA (hFind, &FindFileData));
FindClose (hFind);
#else
DIR *dirp;
struct dirent *dp;
if ((dirp = opendir(folder.c_str())) == NULL)
return res;
while ( (dp = readdir(dirp)) )
{
std::string fname = dp->d_name;
if (fname == "." || fname == "..")
continue;
if (!EndsWith (fname, endsWith))
continue;
res.push_back (fname);
}
closedir(dirp);
#endif
return res;
}
static void DeleteFile (const std::string& path)
{
#ifdef _MSC_VER
DeleteFileA (path.c_str());
#else
unlink (path.c_str());
#endif
}
static void MassageVertexForGLES (std::string& s)
{
std::string pre;
pre += "#define gl_Vertex _glesVertex\nattribute highp vec4 _glesVertex;\n";
pre += "#define gl_Normal _glesNormal\nattribute mediump vec3 _glesNormal;\n";
pre += "#define gl_MultiTexCoord0 _glesMultiTexCoord0\nattribute highp vec4 _glesMultiTexCoord0;\n";
pre += "#define gl_MultiTexCoord1 _glesMultiTexCoord1\nattribute highp vec4 _glesMultiTexCoord1;\n";
pre += "#define gl_Color _glesColor\nattribute lowp vec4 _glesColor;\n";
s = pre + s;
}
static void MassageFragmentForGLES (std::string& s)
{
std::string pre;
s = pre + s;
}
static bool TestFile (glslopt_ctx* ctx, bool vertex,
const std::string& inputPath,
const std::string& hirPath,
const std::string& outputPath,
bool gles,
bool doCheckGLSL)
{
std::string input;
if (!ReadStringFromFile (inputPath.c_str(), input))
{
printf (" failed to read input file\n");
return false;
}
if (doCheckGLSL && !CheckGLSL (vertex, "input", input.c_str()))
{
return false;
}
if (gles)
{
if (vertex)
MassageVertexForGLES (input);
else
MassageFragmentForGLES (input);
}
bool res = true;
glslopt_shader_type type = vertex ? kGlslOptShaderVertex : kGlslOptShaderFragment;
glslopt_shader* shader = glslopt_optimize (ctx, type, input.c_str(), 0);
bool optimizeOk = glslopt_get_status(shader);
if (optimizeOk)
{
std::string textHir = glslopt_get_raw_output (shader);
std::string textOpt = glslopt_get_output (shader);
std::string outputHir;
ReadStringFromFile (hirPath.c_str(), outputHir);
std::string outputOpt;
ReadStringFromFile (outputPath.c_str(), outputOpt);
if (textHir != outputHir)
{
// write output
FILE* f = fopen (hirPath.c_str(), "wb");
fwrite (textHir.c_str(), 1, textHir.size(), f);
fclose (f);
printf (" does not match raw output\n");
res = false;
}
if (textOpt != outputOpt)
{
// write output
FILE* f = fopen (outputPath.c_str(), "wb");
fwrite (textOpt.c_str(), 1, textOpt.size(), f);
fclose (f);
printf (" does not match optimized output\n");
res = false;
}
if (res && doCheckGLSL && !CheckGLSL (vertex, "raw", textHir.c_str()))
res = false;
if (res && doCheckGLSL && !CheckGLSL (vertex, "optimized", textOpt.c_str()))
res = false;
}
else
{
printf (" optimize error: %s\n", glslopt_get_log(shader));
res = false;
}
glslopt_shader_delete (shader);
return res;
}
int main (int argc, const char** argv)
{
if (argc < 2)
{
printf ("USAGE: glsloptimizer testfolder\n");
return 1;
}
bool hasOpenGL = InitializeOpenGL ();
glslopt_ctx* ctx[2] = {
glslopt_initialize(true),
glslopt_initialize(false),
};
std::string baseFolder = argv[1];
clock_t time0 = clock();
static const char* kTypeName[2] = { "vertex", "fragment" };
size_t tests = 0;
size_t errors = 0;
for (int type = 0; type < 2; ++type)
{
std::string testFolder = baseFolder + "/" + kTypeName[type];
static const char* kAPIName[2] = { "OpenGL ES 2.0", "OpenGL" };
static const char* kApiIn [2] = {"-inES.txt", "-in.txt"};
static const char* kApiIR [2] = {"-irES.txt", "-ir.txt"};
static const char* kApiOut[2] = {"-outES.txt", "-out.txt"};
for (int api = 0; api < 2; ++api)
{
printf ("** running %s tests for %s...\n", kTypeName[type], kAPIName[api]);
StringVector inputFiles = GetFiles (testFolder, kApiIn[api]);
size_t n = inputFiles.size();
for (size_t i = 0; i < n; ++i)
{
std::string inname = inputFiles[i];
printf ("test %s\n", inname.c_str());
std::string hirname = inname.substr (0,inname.size()-strlen(kApiIn[api])) + kApiIR[api];
std::string outname = inname.substr (0,inname.size()-strlen(kApiIn[api])) + kApiOut[api];
bool ok = TestFile (ctx[api], type==0, testFolder + "/" + inname, testFolder + "/" + hirname, testFolder + "/" + outname, api==0, hasOpenGL);
if (!ok)
{
++errors;
}
++tests;
}
}
}
clock_t time1 = clock();
float timeDelta = float(time1-time0)/CLOCKS_PER_SEC;
if (errors != 0)
printf ("**** %i tests (%.2fsec), %i !!!FAILED!!!\n", tests, timeDelta, errors);
else
printf ("**** %i tests (%.2fsec) succeeded\n", tests, timeDelta);
for (int i = 0; i < 2; ++i)
glslopt_cleanup (ctx[i]);
return errors ? 1 : 0;
}
<|endoftext|>
|
<commit_before>#pragma once
#include "boost_defs.hpp"
#include "event_queue.hpp"
#include "modifier_flag_manager.hpp"
#include "stream_utility.hpp"
#include <boost/optional.hpp>
#include <json/json.hpp>
#include <unordered_set>
namespace krbn {
namespace manipulator {
namespace details {
class event_definition {
public:
enum class type {
none,
key_code,
pointing_button,
};
enum class modifier {
any,
caps_lock,
command,
control,
fn,
left_command,
left_control,
left_option,
left_shift,
option,
right_command,
right_control,
right_option,
right_shift,
shift,
end_,
};
virtual ~event_definition(void) {
}
type get_type(void) const {
return type_;
}
boost::optional<key_code> get_key_code(void) const {
if (type_ == type::key_code) {
return key_code_;
}
return boost::none;
}
boost::optional<pointing_button> get_pointing_button(void) const {
if (type_ == type::pointing_button) {
return pointing_button_;
}
return boost::none;
}
boost::optional<event_queue::queued_event::event> to_event(void) const {
switch (type_) {
case type::none:
return boost::none;
case type::key_code:
return event_queue::queued_event::event(key_code_);
case type::pointing_button:
return event_queue::queued_event::event(pointing_button_);
}
}
static std::unordered_set<modifier> make_modifiers(const nlohmann::json& json) {
std::unordered_set<modifier> modifiers;
for (const auto& j : json) {
if (j.is_string()) {
if (j == "any") { modifiers.insert(modifier::any); }
if (j == "caps_lock") { modifiers.insert(modifier::caps_lock); }
if (j == "command") { modifiers.insert(modifier::command); }
if (j == "control") { modifiers.insert(modifier::control); }
if (j == "fn") { modifiers.insert(modifier::fn); }
if (j == "left_command") { modifiers.insert(modifier::left_command); }
if (j == "left_control") { modifiers.insert(modifier::left_control); }
if (j == "left_option") { modifiers.insert(modifier::left_option); }
if (j == "left_shift") { modifiers.insert(modifier::left_shift); }
if (j == "option") { modifiers.insert(modifier::option); }
if (j == "right_command") { modifiers.insert(modifier::right_command); }
if (j == "right_control") { modifiers.insert(modifier::right_control); }
if (j == "right_option") { modifiers.insert(modifier::right_option); }
if (j == "right_shift") { modifiers.insert(modifier::right_shift); }
if (j == "shift") { modifiers.insert(modifier::shift); }
}
}
return modifiers;
}
static std::vector<modifier_flag> get_modifier_flags(modifier modifier) {
switch (modifier) {
case modifier::any:
return {};
case modifier::caps_lock:
return {modifier_flag::caps_lock};
case modifier::command:
return {modifier_flag::left_command, modifier_flag::right_command};
case modifier::control:
return {modifier_flag::left_control, modifier_flag::right_control};
case modifier::fn:
return {modifier_flag::fn};
case modifier::left_command:
return {modifier_flag::left_command};
case modifier::left_control:
return {modifier_flag::left_control};
case modifier::left_option:
return {modifier_flag::left_option};
case modifier::left_shift:
return {modifier_flag::left_shift};
case modifier::option:
return {modifier_flag::left_option, modifier_flag::right_option};
case modifier::right_command:
return {modifier_flag::right_command};
case modifier::right_control:
return {modifier_flag::right_control};
case modifier::right_option:
return {modifier_flag::right_option};
case modifier::right_shift:
return {modifier_flag::right_shift};
case modifier::shift:
return {modifier_flag::left_shift, modifier_flag::right_shift};
case modifier::end_:
return {};
}
}
static modifier get_modifier(modifier_flag modifier_flag) {
switch (modifier_flag) {
case modifier_flag::caps_lock:
return modifier::caps_lock;
case modifier_flag::fn:
return modifier::fn;
case modifier_flag::left_command:
return modifier::left_command;
case modifier_flag::left_control:
return modifier::left_control;
case modifier_flag::left_option:
return modifier::left_option;
case modifier_flag::left_shift:
return modifier::left_shift;
case modifier_flag::right_command:
return modifier::right_command;
case modifier_flag::right_control:
return modifier::right_control;
case modifier_flag::right_option:
return modifier::right_option;
case modifier_flag::right_shift:
return modifier::right_shift;
case modifier_flag::zero:
case modifier_flag::end_:
return modifier::end_;
}
}
protected:
event_definition(const nlohmann::json& json) : type_(type::none) {
// Set type_ and values.
{
const std::string key = "key_code";
if (json.find(key) != std::end(json) && json[key].is_string()) {
const std::string& name = json[key];
if (auto key_code = types::get_key_code(name)) {
type_ = type::key_code;
key_code_ = *key_code;
return;
}
}
}
{
const std::string key = "pointing_button";
if (json.find(key) != std::end(json) && json[key].is_string()) {
if (auto pointing_button = types::get_pointing_button(json[key])) {
type_ = type::pointing_button;
pointing_button_ = *pointing_button;
return;
}
}
}
}
event_definition(key_code key_code) : type_(type::key_code),
key_code_(key_code) {
}
event_definition(pointing_button pointing_button) : type_(type::pointing_button),
pointing_button_(pointing_button) {
}
type type_;
union {
key_code key_code_;
pointing_button pointing_button_;
};
};
class from_event_definition final : public event_definition {
public:
from_event_definition(const nlohmann::json& json) : event_definition(json) {
{
const std::string key = "modifiers";
if (json.find(key) != json.end() && json[key].is_object()) {
auto& modifiers = json[key];
{
const std::string k = "mandatory";
if (modifiers.find(k) != modifiers.end()) {
mandatory_modifiers_ = make_modifiers(modifiers[k]);
}
}
{
const std::string k = "optional";
if (modifiers.find(k) != modifiers.end()) {
optional_modifiers_ = make_modifiers(modifiers[k]);
}
}
}
}
}
from_event_definition(key_code key_code,
std::unordered_set<modifier> mandatory_modifiers,
std::unordered_set<modifier> optional_modifiers) : event_definition(key_code),
mandatory_modifiers_(mandatory_modifiers),
optional_modifiers_(optional_modifiers) {
}
virtual ~from_event_definition(void) {
}
const std::unordered_set<modifier>& get_mandatory_modifiers(void) const {
return mandatory_modifiers_;
}
const std::unordered_set<modifier>& get_optional_modifiers(void) const {
return optional_modifiers_;
}
boost::optional<std::unordered_set<modifier_flag>> test_modifiers(const modifier_flag_manager& modifier_flag_manager) const {
std::unordered_set<modifier_flag> modifier_flags;
// If mandatory_modifiers_ contains modifier::any, return all active modifier_flags.
if (mandatory_modifiers_.find(modifier::any) != std::end(mandatory_modifiers_)) {
for (auto i = static_cast<uint32_t>(modifier_flag::zero) + 1; i != static_cast<uint32_t>(modifier_flag::end_); ++i) {
auto flag = modifier_flag(i);
if (modifier_flag_manager.is_pressed(flag)) {
modifier_flags.insert(flag);
}
}
return modifier_flags;
}
// Check modifier_flag state.
for (int i = 0; i < static_cast<int>(modifier::end_); ++i) {
auto m = modifier(i);
if (mandatory_modifiers_.find(m) != std::end(mandatory_modifiers_)) {
auto pair = test_modifier(modifier_flag_manager, m);
if (!pair.first) {
return boost::none;
}
if (pair.second != modifier_flag::zero) {
modifier_flags.insert(pair.second);
}
}
}
// If optional_modifiers_ does not contain modifier::any, we have to check modifier flags strictly.
if (optional_modifiers_.find(modifier::any) == std::end(optional_modifiers_)) {
std::unordered_set<modifier_flag> extra_modifier_flags;
for (auto m = static_cast<uint32_t>(modifier_flag::zero) + 1; m != static_cast<uint32_t>(modifier_flag::end_); ++m) {
extra_modifier_flags.insert(modifier_flag(m));
}
for (int i = 0; i < static_cast<int>(modifier::end_); ++i) {
auto m = modifier(i);
if (mandatory_modifiers_.find(m) != std::end(mandatory_modifiers_) ||
optional_modifiers_.find(m) != std::end(optional_modifiers_)) {
for (const auto& flag : get_modifier_flags(m)) {
extra_modifier_flags.erase(flag);
}
}
}
for (const auto& flag : extra_modifier_flags) {
if (modifier_flag_manager.is_pressed(flag)) {
return boost::none;
}
}
}
return modifier_flags;
}
static std::pair<bool, modifier_flag> test_modifier(const modifier_flag_manager& modifier_flag_manager,
modifier modifier) {
if (modifier == modifier::any) {
return std::make_pair(true, modifier_flag::zero);
}
auto modifier_flags = get_modifier_flags(modifier);
if (!modifier_flags.empty()) {
for (const auto& m : modifier_flags) {
if (modifier_flag_manager.is_pressed(m)) {
return std::make_pair(true, m);
}
}
}
return std::make_pair(false, modifier_flag::zero);
}
private:
std::unordered_set<modifier> mandatory_modifiers_;
std::unordered_set<modifier> optional_modifiers_;
};
class to_event_definition final : public event_definition {
public:
to_event_definition(const nlohmann::json& json) : event_definition(json) {
{
const std::string key = "modifiers";
if (json.find(key) != json.end()) {
modifiers_ = make_modifiers(json[key]);
}
}
}
to_event_definition(key_code key_code,
std::unordered_set<modifier> modifiers) : event_definition(key_code),
modifiers_(modifiers) {
}
virtual ~to_event_definition(void) {
}
const std::unordered_set<modifier>& get_modifiers(void) const {
return modifiers_;
}
private:
std::unordered_set<modifier> modifiers_;
};
inline std::ostream& operator<<(std::ostream& stream, const event_definition::modifier& value) {
#define KRBN_MANIPULATOR_DETAILS_MODIFIER_OUTPUT(MODIFIER) \
case event_definition::modifier::MODIFIER: \
stream << #MODIFIER; \
break;
switch (value) {
KRBN_MANIPULATOR_DETAILS_MODIFIER_OUTPUT(any);
KRBN_MANIPULATOR_DETAILS_MODIFIER_OUTPUT(caps_lock);
KRBN_MANIPULATOR_DETAILS_MODIFIER_OUTPUT(command);
KRBN_MANIPULATOR_DETAILS_MODIFIER_OUTPUT(control);
KRBN_MANIPULATOR_DETAILS_MODIFIER_OUTPUT(fn);
KRBN_MANIPULATOR_DETAILS_MODIFIER_OUTPUT(left_command);
KRBN_MANIPULATOR_DETAILS_MODIFIER_OUTPUT(left_control);
KRBN_MANIPULATOR_DETAILS_MODIFIER_OUTPUT(left_option);
KRBN_MANIPULATOR_DETAILS_MODIFIER_OUTPUT(left_shift);
KRBN_MANIPULATOR_DETAILS_MODIFIER_OUTPUT(option);
KRBN_MANIPULATOR_DETAILS_MODIFIER_OUTPUT(right_command);
KRBN_MANIPULATOR_DETAILS_MODIFIER_OUTPUT(right_control);
KRBN_MANIPULATOR_DETAILS_MODIFIER_OUTPUT(right_option);
KRBN_MANIPULATOR_DETAILS_MODIFIER_OUTPUT(right_shift);
KRBN_MANIPULATOR_DETAILS_MODIFIER_OUTPUT(shift);
KRBN_MANIPULATOR_DETAILS_MODIFIER_OUTPUT(end_);
}
#undef KRBN_MANIPULATOR_DETAILS_MODIFIER_OUTPUT
return stream;
}
template <template <class T, class A> class container>
inline std::ostream& operator<<(std::ostream& stream, const container<event_definition::modifier, std::allocator<event_definition::modifier>>& values) {
return stream_utility::output_enums(stream, values);
}
template <template <class T, class H, class K, class A> class container>
inline std::ostream& operator<<(std::ostream& stream,
const container<event_definition::modifier,
std::hash<event_definition::modifier>,
std::equal_to<event_definition::modifier>,
std::allocator<event_definition::modifier>>& values) {
return stream_utility::output_enums(stream, values);
}
} // namespace details
} // namespace manipulator
} // namespace krbn
<commit_msg>add error log<commit_after>#pragma once
#include "boost_defs.hpp"
#include "event_queue.hpp"
#include "modifier_flag_manager.hpp"
#include "stream_utility.hpp"
#include <boost/optional.hpp>
#include <json/json.hpp>
#include <unordered_set>
namespace krbn {
namespace manipulator {
namespace details {
class event_definition {
public:
enum class type {
none,
key_code,
pointing_button,
};
enum class modifier {
any,
caps_lock,
command,
control,
fn,
left_command,
left_control,
left_option,
left_shift,
option,
right_command,
right_control,
right_option,
right_shift,
shift,
end_,
};
virtual ~event_definition(void) {
}
type get_type(void) const {
return type_;
}
boost::optional<key_code> get_key_code(void) const {
if (type_ == type::key_code) {
return key_code_;
}
return boost::none;
}
boost::optional<pointing_button> get_pointing_button(void) const {
if (type_ == type::pointing_button) {
return pointing_button_;
}
return boost::none;
}
boost::optional<event_queue::queued_event::event> to_event(void) const {
switch (type_) {
case type::none:
return boost::none;
case type::key_code:
return event_queue::queued_event::event(key_code_);
case type::pointing_button:
return event_queue::queued_event::event(pointing_button_);
}
}
static std::unordered_set<modifier> make_modifiers(const nlohmann::json& json) {
std::unordered_set<modifier> modifiers;
for (const auto& j : json) {
if (j.is_string()) {
const std::string& name = j;
if (name == "any") {
modifiers.insert(modifier::any);
} else if (name == "caps_lock") {
modifiers.insert(modifier::caps_lock);
} else if (name == "command") {
modifiers.insert(modifier::command);
} else if (name == "control") {
modifiers.insert(modifier::control);
} else if (name == "fn") {
modifiers.insert(modifier::fn);
} else if (name == "left_command") {
modifiers.insert(modifier::left_command);
} else if (name == "left_control") {
modifiers.insert(modifier::left_control);
} else if (name == "left_option") {
modifiers.insert(modifier::left_option);
} else if (name == "left_shift") {
modifiers.insert(modifier::left_shift);
} else if (name == "option") {
modifiers.insert(modifier::option);
} else if (name == "right_command") {
modifiers.insert(modifier::right_command);
} else if (name == "right_control") {
modifiers.insert(modifier::right_control);
} else if (name == "right_option") {
modifiers.insert(modifier::right_option);
} else if (name == "right_shift") {
modifiers.insert(modifier::right_shift);
} else if (name == "shift") {
modifiers.insert(modifier::shift);
} else {
logger::get_logger().error("unknown modifier: {0}", name);
}
}
}
return modifiers;
}
static std::vector<modifier_flag> get_modifier_flags(modifier modifier) {
switch (modifier) {
case modifier::any:
return {};
case modifier::caps_lock:
return {modifier_flag::caps_lock};
case modifier::command:
return {modifier_flag::left_command, modifier_flag::right_command};
case modifier::control:
return {modifier_flag::left_control, modifier_flag::right_control};
case modifier::fn:
return {modifier_flag::fn};
case modifier::left_command:
return {modifier_flag::left_command};
case modifier::left_control:
return {modifier_flag::left_control};
case modifier::left_option:
return {modifier_flag::left_option};
case modifier::left_shift:
return {modifier_flag::left_shift};
case modifier::option:
return {modifier_flag::left_option, modifier_flag::right_option};
case modifier::right_command:
return {modifier_flag::right_command};
case modifier::right_control:
return {modifier_flag::right_control};
case modifier::right_option:
return {modifier_flag::right_option};
case modifier::right_shift:
return {modifier_flag::right_shift};
case modifier::shift:
return {modifier_flag::left_shift, modifier_flag::right_shift};
case modifier::end_:
return {};
}
}
static modifier get_modifier(modifier_flag modifier_flag) {
switch (modifier_flag) {
case modifier_flag::caps_lock:
return modifier::caps_lock;
case modifier_flag::fn:
return modifier::fn;
case modifier_flag::left_command:
return modifier::left_command;
case modifier_flag::left_control:
return modifier::left_control;
case modifier_flag::left_option:
return modifier::left_option;
case modifier_flag::left_shift:
return modifier::left_shift;
case modifier_flag::right_command:
return modifier::right_command;
case modifier_flag::right_control:
return modifier::right_control;
case modifier_flag::right_option:
return modifier::right_option;
case modifier_flag::right_shift:
return modifier::right_shift;
case modifier_flag::zero:
case modifier_flag::end_:
return modifier::end_;
}
}
protected:
event_definition(const nlohmann::json& json) : type_(type::none) {
// Set type_ and values.
{
const std::string key = "key_code";
if (json.find(key) != std::end(json) && json[key].is_string()) {
const std::string& name = json[key];
if (auto key_code = types::get_key_code(name)) {
type_ = type::key_code;
key_code_ = *key_code;
return;
}
}
}
{
const std::string key = "pointing_button";
if (json.find(key) != std::end(json) && json[key].is_string()) {
if (auto pointing_button = types::get_pointing_button(json[key])) {
type_ = type::pointing_button;
pointing_button_ = *pointing_button;
return;
}
}
}
}
event_definition(key_code key_code) : type_(type::key_code),
key_code_(key_code) {
}
event_definition(pointing_button pointing_button) : type_(type::pointing_button),
pointing_button_(pointing_button) {
}
type type_;
union {
key_code key_code_;
pointing_button pointing_button_;
};
};
class from_event_definition final : public event_definition {
public:
from_event_definition(const nlohmann::json& json) : event_definition(json) {
{
const std::string key = "modifiers";
if (json.find(key) != json.end() && json[key].is_object()) {
auto& modifiers = json[key];
{
const std::string k = "mandatory";
if (modifiers.find(k) != modifiers.end()) {
mandatory_modifiers_ = make_modifiers(modifiers[k]);
}
}
{
const std::string k = "optional";
if (modifiers.find(k) != modifiers.end()) {
optional_modifiers_ = make_modifiers(modifiers[k]);
}
}
}
}
}
from_event_definition(key_code key_code,
std::unordered_set<modifier> mandatory_modifiers,
std::unordered_set<modifier> optional_modifiers) : event_definition(key_code),
mandatory_modifiers_(mandatory_modifiers),
optional_modifiers_(optional_modifiers) {
}
virtual ~from_event_definition(void) {
}
const std::unordered_set<modifier>& get_mandatory_modifiers(void) const {
return mandatory_modifiers_;
}
const std::unordered_set<modifier>& get_optional_modifiers(void) const {
return optional_modifiers_;
}
boost::optional<std::unordered_set<modifier_flag>> test_modifiers(const modifier_flag_manager& modifier_flag_manager) const {
std::unordered_set<modifier_flag> modifier_flags;
// If mandatory_modifiers_ contains modifier::any, return all active modifier_flags.
if (mandatory_modifiers_.find(modifier::any) != std::end(mandatory_modifiers_)) {
for (auto i = static_cast<uint32_t>(modifier_flag::zero) + 1; i != static_cast<uint32_t>(modifier_flag::end_); ++i) {
auto flag = modifier_flag(i);
if (modifier_flag_manager.is_pressed(flag)) {
modifier_flags.insert(flag);
}
}
return modifier_flags;
}
// Check modifier_flag state.
for (int i = 0; i < static_cast<int>(modifier::end_); ++i) {
auto m = modifier(i);
if (mandatory_modifiers_.find(m) != std::end(mandatory_modifiers_)) {
auto pair = test_modifier(modifier_flag_manager, m);
if (!pair.first) {
return boost::none;
}
if (pair.second != modifier_flag::zero) {
modifier_flags.insert(pair.second);
}
}
}
// If optional_modifiers_ does not contain modifier::any, we have to check modifier flags strictly.
if (optional_modifiers_.find(modifier::any) == std::end(optional_modifiers_)) {
std::unordered_set<modifier_flag> extra_modifier_flags;
for (auto m = static_cast<uint32_t>(modifier_flag::zero) + 1; m != static_cast<uint32_t>(modifier_flag::end_); ++m) {
extra_modifier_flags.insert(modifier_flag(m));
}
for (int i = 0; i < static_cast<int>(modifier::end_); ++i) {
auto m = modifier(i);
if (mandatory_modifiers_.find(m) != std::end(mandatory_modifiers_) ||
optional_modifiers_.find(m) != std::end(optional_modifiers_)) {
for (const auto& flag : get_modifier_flags(m)) {
extra_modifier_flags.erase(flag);
}
}
}
for (const auto& flag : extra_modifier_flags) {
if (modifier_flag_manager.is_pressed(flag)) {
return boost::none;
}
}
}
return modifier_flags;
}
static std::pair<bool, modifier_flag> test_modifier(const modifier_flag_manager& modifier_flag_manager,
modifier modifier) {
if (modifier == modifier::any) {
return std::make_pair(true, modifier_flag::zero);
}
auto modifier_flags = get_modifier_flags(modifier);
if (!modifier_flags.empty()) {
for (const auto& m : modifier_flags) {
if (modifier_flag_manager.is_pressed(m)) {
return std::make_pair(true, m);
}
}
}
return std::make_pair(false, modifier_flag::zero);
}
private:
std::unordered_set<modifier> mandatory_modifiers_;
std::unordered_set<modifier> optional_modifiers_;
};
class to_event_definition final : public event_definition {
public:
to_event_definition(const nlohmann::json& json) : event_definition(json) {
{
const std::string key = "modifiers";
if (json.find(key) != json.end()) {
modifiers_ = make_modifiers(json[key]);
}
}
}
to_event_definition(key_code key_code,
std::unordered_set<modifier> modifiers) : event_definition(key_code),
modifiers_(modifiers) {
}
virtual ~to_event_definition(void) {
}
const std::unordered_set<modifier>& get_modifiers(void) const {
return modifiers_;
}
private:
std::unordered_set<modifier> modifiers_;
};
inline std::ostream& operator<<(std::ostream& stream, const event_definition::modifier& value) {
#define KRBN_MANIPULATOR_DETAILS_MODIFIER_OUTPUT(MODIFIER) \
case event_definition::modifier::MODIFIER: \
stream << #MODIFIER; \
break;
switch (value) {
KRBN_MANIPULATOR_DETAILS_MODIFIER_OUTPUT(any);
KRBN_MANIPULATOR_DETAILS_MODIFIER_OUTPUT(caps_lock);
KRBN_MANIPULATOR_DETAILS_MODIFIER_OUTPUT(command);
KRBN_MANIPULATOR_DETAILS_MODIFIER_OUTPUT(control);
KRBN_MANIPULATOR_DETAILS_MODIFIER_OUTPUT(fn);
KRBN_MANIPULATOR_DETAILS_MODIFIER_OUTPUT(left_command);
KRBN_MANIPULATOR_DETAILS_MODIFIER_OUTPUT(left_control);
KRBN_MANIPULATOR_DETAILS_MODIFIER_OUTPUT(left_option);
KRBN_MANIPULATOR_DETAILS_MODIFIER_OUTPUT(left_shift);
KRBN_MANIPULATOR_DETAILS_MODIFIER_OUTPUT(option);
KRBN_MANIPULATOR_DETAILS_MODIFIER_OUTPUT(right_command);
KRBN_MANIPULATOR_DETAILS_MODIFIER_OUTPUT(right_control);
KRBN_MANIPULATOR_DETAILS_MODIFIER_OUTPUT(right_option);
KRBN_MANIPULATOR_DETAILS_MODIFIER_OUTPUT(right_shift);
KRBN_MANIPULATOR_DETAILS_MODIFIER_OUTPUT(shift);
KRBN_MANIPULATOR_DETAILS_MODIFIER_OUTPUT(end_);
}
#undef KRBN_MANIPULATOR_DETAILS_MODIFIER_OUTPUT
return stream;
}
template <template <class T, class A> class container>
inline std::ostream& operator<<(std::ostream& stream, const container<event_definition::modifier, std::allocator<event_definition::modifier>>& values) {
return stream_utility::output_enums(stream, values);
}
template <template <class T, class H, class K, class A> class container>
inline std::ostream& operator<<(std::ostream& stream,
const container<event_definition::modifier,
std::hash<event_definition::modifier>,
std::equal_to<event_definition::modifier>,
std::allocator<event_definition::modifier>>& values) {
return stream_utility::output_enums(stream, values);
}
} // namespace details
} // namespace manipulator
} // namespace krbn
<|endoftext|>
|
<commit_before>#ifndef TEXTURECUBEMAP_HPP
#define TEXTURECUBEMAP_HPP
#include <memory>
#include "Texture.hpp"
class TextureCubemap : public Texture {
public:
enum cubeFaces {
CUBEMAP_POSITIVE_X = GL_TEXTURE_CUBE_MAP_POSITIVE_X,
CUBEMAP_NEGATIVE_X = GL_TEXTURE_CUBE_MAP_NEGATIVE_X,
CUBEMAP_POSITIVE_Y = GL_TEXTURE_CUBE_MAP_POSITIVE_Y,
CUBEMAP_NEGATIVE_Y = GL_TEXTURE_CUBE_MAP_NEGATIVE_Y,
CUBEMAP_POSITIVE_Z = GL_TEXTURE_CUBE_MAP_POSITIVE_Z,
CUBEMAP_NEGATIVE_Z = GL_TEXTURE_CUBE_MAP_NEGATIVE_Z
};
static TextureCubemap load(
std::vector<std::unique_ptr<std::istream>>& files,
TextureFormat::Format format = TextureFormat::AUTO);
TextureCubemap();
TextureCubemap(
unsigned int size,
TextureFormat::Format format = TextureFormat::RGBA);
void setData(
const void* pixels,
TextureFormat::Format sourceFormat = TextureFormat::RGBA,
TextureFormat::SourceType sourceType = TextureFormat::UNSIGNED_BYTE);
unsigned int getSize() const;
static void bind(const TextureCubemap* tex, unsigned int slot) {
Texture::bind(Texture::TypeCubemap, tex, slot);
}
TextureCubemap(TextureCubemap&& rhs);
TextureCubemap& operator=(TextureCubemap&& rhs);
friend void swap(TextureCubemap& a, TextureCubemap& b);
private:
unsigned int size = 0;
};
#endif // TEXTURECUBEMAP_HPP
<commit_msg>Update TextureCubemap.hpp<commit_after>#ifndef TEXTURECUBEMAP_HPP
#define TEXTURECUBEMAP_HPP
#include <memory>
#include "Texture.hpp"
///
/// \brief TextureCubemap represents a GL Cubemap Texture
///
class TextureCubemap : public Texture {
public:
///
/// \brief The cubeFaces enum
///
enum cubeFaces {
CUBEMAP_POSITIVE_X = GL_TEXTURE_CUBE_MAP_POSITIVE_X,
CUBEMAP_NEGATIVE_X = GL_TEXTURE_CUBE_MAP_NEGATIVE_X,
CUBEMAP_POSITIVE_Y = GL_TEXTURE_CUBE_MAP_POSITIVE_Y,
CUBEMAP_NEGATIVE_Y = GL_TEXTURE_CUBE_MAP_NEGATIVE_Y,
CUBEMAP_POSITIVE_Z = GL_TEXTURE_CUBE_MAP_POSITIVE_Z,
CUBEMAP_NEGATIVE_Z = GL_TEXTURE_CUBE_MAP_NEGATIVE_Z
};
///
/// \brief Loads a new texture from a stream.
///
/// The input stream may be an open file or a user-implemented stream.
///
/// \see Storage
///
static TextureCubemap load(
std::vector<std::unique_ptr<std::istream>>& files,
TextureFormat::Format format = TextureFormat::AUTO);
///
/// \brief Default constructor. Generates an invalid texture with no pixels.
///
/// This constructor will generate a texture of size 0. This texture is not
/// meant for use in rendering.
///
TextureCubemap();
///
/// \brief Size and Format constructor.
///
/// Will create an empty texture with the specified size and format.
/// The cube faces are always square (same width and height).
/// The initial contents of the texture are undefined.
///
/// \param format Can be sized or not.
///
/// \see TextureFormat::Format
///
TextureCubemap(
unsigned int size,
TextureFormat::Format format = TextureFormat::RGBA);
///
/// \brief Sets the content of the texture
///
/// The pixels pointer must hold enough data to fill the texture, otherwise the behaviour is undefined
///
/// \param sourceFormat The format of the pixels pointer
/// \param sourceType The data type of the pixels pointer
///
/// \see TextureFormat::Format
/// \see TextureFormat::SourceType
///
void setData(
const void* pixels,
TextureFormat::Format sourceFormat = TextureFormat::RGBA,
TextureFormat::SourceType sourceType = TextureFormat::UNSIGNED_BYTE);
///
/// \brief Returns the texture size
///
unsigned int getSize() const;
///
/// \brief Bind a texture to any given slot
///
/// Binding this texture will replace whatever texture was previously assigned for this slot
///
static void bind(const TextureCubemap* tex, unsigned int slot) {
Texture::bind(Texture::TypeCubemap, tex, slot);
}
///
/// \brief Move constructor
///
TextureCubemap(TextureCubemap&& rhs);
///
/// \brief Move operator=
///
TextureCubemap& operator=(TextureCubemap&& rhs);
///
/// \brief Swap operator for the TextureCubemap class
///
friend void swap(TextureCubemap& a, TextureCubemap& b);
private:
unsigned int size = 0;
};
///
/// \class TextureCubemap TextureCubemap.hpp <VBE/graphics/TextureCubemap.hpp>
/// \ingroup Graphics
///
#endif // TEXTURECUBEMAP_HPP
<|endoftext|>
|
<commit_before>#include "embeddedLinker.h"
#include <math.h>
#include <QtWidgets/QStyle>
#include <QtWidgets/QGraphicsItem>
#include <QtWidgets/QStyleOptionGraphicsItem>
#include "umllib/edgeElement.h"
#include "umllib/nodeElement.h"
#include "view/editorViewScene.h"
#include "mainwindow/mainWindow.h"
#include "umllib/private/reshapeEdgeCommand.h"
using namespace qReal;
EmbeddedLinker::EmbeddedLinker()
: mEdge(NULL)
, mMaster(NULL)
, mColor(Qt::blue)
, mPressed(false)
{
mSize = SettingsManager::value("EmbeddedLinkerSize").toFloat();
if (mSize > 10) {
mSize *= 0.75;
}
mIndent = SettingsManager::value("EmbeddedLinkerIndent").toFloat();
mIndent *= 0.8;
if (mIndent > 17) {
mIndent *= 0.7;
}
mRectangle = QRectF(-mSize, -mSize, mSize * 2, mSize * 2);
mInnerRectangle = QRectF(-mSize / 2, -mSize / 2, mSize, mSize);
setZValue(300);
setFlag(ItemStacksBehindParent, false);
setAcceptHoverEvents(true);
}
EmbeddedLinker::~EmbeddedLinker()
{
}
NodeElement* EmbeddedLinker::master() const
{
return mMaster;
}
void EmbeddedLinker::setMaster(NodeElement *element)
{
mMaster = element;
setParentItem(element);
}
void EmbeddedLinker::generateColor()
{
int result = 0;
mColor = QColor(result % 192 + 64, result % 128 + 128, result % 64 + 192).darker(0);
}
void EmbeddedLinker::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget*)
{
Q_UNUSED(option);
painter->save();
QBrush brush;
brush.setColor(mColor);
brush.setStyle(Qt::SolidPattern);
painter->setBrush(brush);
painter->setOpacity(0.75);
painter->setPen(mColor);
mSize = SettingsManager::value("EmbeddedLinkerSize").toFloat();
if (mSize > 10) {
mSize *= 0.75;
}
mRectangle = QRectF(-mSize, -mSize, mSize * 2, mSize * 2);
mInnerRectangle = QRectF(-mSize / 2, -mSize / 2, mSize, mSize);
painter->drawEllipse(mRectangle);
painter->setOpacity(0.9);
painter->drawEllipse(mInnerRectangle);
painter->restore();
}
void EmbeddedLinker::setDirected(const bool directed)
{
this->mDirected = directed;
}
void EmbeddedLinker::initTitle()
{
// TODO: It is not Label, it is simply some text on a scene. Refactor this.
// Temporarily commented out.
// EditorManagerInterface const &editorManagerInterface
// = dynamic_cast<EditorViewScene *>(scene())->mainWindow()->editorManager();
// QString edgeTypeFriendly = editorManagerInterface.friendlyName(Id::loadFromString("qrm:/"+ mMaster->id().editor()
// + "/" + mMaster->id().diagram() + "/" + mEdgeType.element()));
// float textWidth = edgeTypeFriendly.size() * 10;
// float rectWidth = mMaster->boundingRect().right() - mMaster->boundingRect().left();
// float rectHeight = mMaster->boundingRect().bottom() - mMaster->boundingRect().top();
// int x = 0;
// int y = 0;
// if (scenePos().y() < mMaster->scenePos().y() + rectHeight/3)
// y = -boundingRect().height() - 10;
// else if (scenePos().y() > mMaster->scenePos().y() + 2*rectHeight/3)
// y = +boundingRect().height() - 10;
// if (scenePos().x() < mMaster->scenePos().x() + rectWidth/3)
// x = -boundingRect().width() - textWidth + 20;
// else if (scenePos().x() > mMaster->scenePos().x() + 2*rectWidth/3)
// x = +boundingRect().width() - 10;
// mTitle = new Label(static_cast<qreal>(x) / boundingRect().width()
// , static_cast<qreal>(y) / boundingRect().height(), edgeTypeFriendly, 0);
// mTitle->init(boundingRect());
// mTitle->setTextWidth(textWidth);
// mTitle->setParentItem(this);
}
void EmbeddedLinker::setEdgeType(const qReal::Id &edgeType)
{
this->mEdgeType = edgeType;
generateColor();
}
qReal::Id EmbeddedLinker::edgeType() const
{
return mEdgeType;
}
bool EmbeddedLinker::isDirected() const
{
return mDirected;
}
void EmbeddedLinker::takePosition(int index, int maxIndex)
{
qreal const pi = 3.141592;
QRectF const bounding = mMaster->boundingRect();
qreal const top = bounding.topLeft().y();
qreal const left = bounding.topLeft().x();
qreal const right = bounding.bottomRight().x();
qreal const bottom = bounding.bottomRight().y();
qreal const height = bottom - top;
qreal const width = right - left;
qreal const angle = 2 * pi * index / maxIndex;
int rW = width;
int rH = height;
if (rW < 150) {
rW *= 1.5;
} else {
rW += 5;
}
if (rH < 150) {
rH *= 1.5;
} else {
rH += 5;
}
// TODO: customize start angle
qreal const px = left + width / 2 + rW * cos(angle) / 2;
qreal const py = bottom - height / 2 + rH * sin(angle) / 2;
// if linker covers master node:
qreal min = py - top;
if (min > bottom - py) {
min = bottom - py;
}
if (min > px - left) {
min = px - left;
}
if (min > right - px) {
min = right - px;
}
qreal fx;
qreal fy;
mIndent = SettingsManager::value("EmbeddedLinkerIndent").toFloat();
mIndent *= 0.8;
if (mIndent > 17) {
mIndent *= 0.7;
}
//obviously, top != left != right != bottom
if ((bottom - py == min) || (py - top == min)) {
fx = px;
fy = bottom - py == min ? bottom + mIndent : top - mIndent;
} else {
fx = right - px == min ? right + mIndent : left - mIndent;
fy = py;
}
setPos(fx, fy);
}
QRectF EmbeddedLinker::boundingRect() const {
return mRectangle;
}
void EmbeddedLinker::mousePressEvent(QGraphicsSceneMouseEvent *event)
{
Q_UNUSED(event)
mPressed = true;
if (event->button() == Qt::LeftButton) {
mEdge = NULL;
}
}
void EmbeddedLinker::mouseMoveEvent(QGraphicsSceneMouseEvent *event)
{
if (mPressed) {
mPressed = false;
EditorViewScene *scene = dynamic_cast<EditorViewScene*>(mMaster->scene());
if (!scene) {
return;
}
QString const type = "qrm:/" + mMaster->id().editor() + "/" +
mMaster->id().diagram() + "/" + mEdgeType.element();
if (scene->mainWindow()->editorManager().hasElement(Id::loadFromString(type))) {
mMaster->setConnectingState(true);
// FIXME: I am raw. return strange pos() and inside me a small trash
Id edgeId = scene->createElement(type, event->scenePos(), true, &mCreateEdgeCommand);
mEdge = dynamic_cast<EdgeElement*>(scene->getElem(edgeId));
}
if (mEdge) {
mMaster->setZValue(1);
mEdge->setSrc(mMaster);
mEdge->setDst(NULL);
mEdge->highlight();
mEdge->tuneForLinker();
mEdge->placeEndTo(mEdge->mapFromScene(mapToScene(event->pos())));
}
}
mEdge->placeEndTo(mEdge->mapFromScene(mapToScene(event->pos())));
}
void EmbeddedLinker::mouseReleaseEvent(QGraphicsSceneMouseEvent *event)
{
hide();
mMaster->selectionState(false);
EditorViewScene* scene = dynamic_cast<EditorViewScene*>(mMaster->scene());
if (!mPressed && scene && mEdge) {
mEdge->hide();
QPointF const &eScenePos = event->scenePos();
NodeElement *under = dynamic_cast<NodeElement*>(scene->itemAt(eScenePos, QTransform()));
mEdge->show();
int result = 0;
commands::CreateElementCommand *createElementFromMenuCommand = NULL;
if (!under) {
result = scene->launchEdgeMenu(mEdge, mMaster, eScenePos, false, &createElementFromMenuCommand);
} else {
bool canBeConnected = false;
foreach(PossibleEdge const &pEdge, mEdge->src()->getPossibleEdges()) {
if (pEdge.first.second.element() == under->id().element()) {
canBeConnected = true;
} else {
// pEdge.second.first is true, if edge can connect items in only one direction.
if (!pEdge.second.first) {
canBeConnected = (pEdge.first.first.element() == under->id().element());
}
}
}
if (under->isContainer()) {
result = scene->launchEdgeMenu(mEdge, mMaster, eScenePos
, canBeConnected, &createElementFromMenuCommand);
} else {
if (!canBeConnected) {
result = -1;
}
}
}
NodeElement *target = dynamic_cast<NodeElement*>(scene->getLastCreated());
if (result == -1) {
mEdge = NULL;
} else if ((result == 1) && target) {
mEdge->setDst(target);
target->storeGeometry();
}
if (result != -1) {
mEdge->connectToPort();
// This will restore edge state after undo/redo
commands::ReshapeEdgeCommand *reshapeEdge = new commands::ReshapeEdgeCommand(mEdge);
reshapeEdge->startTracking();
mEdge->layOut();
reshapeEdge->stopTracking();
reshapeEdge->setUndoEnabled(false);
if (createElementFromMenuCommand) {
createElementFromMenuCommand->addPostAction(reshapeEdge);
mCreateEdgeCommand->addPostAction(createElementFromMenuCommand);
} else {
mCreateEdgeCommand->addPostAction(reshapeEdge);
}
}
}
mPressed = false;
mEdge = NULL;
}
<commit_msg>fix #1015<commit_after>#include "embeddedLinker.h"
#include <math.h>
#include <QtWidgets/QStyle>
#include <QtWidgets/QGraphicsItem>
#include <QtWidgets/QStyleOptionGraphicsItem>
#include "umllib/edgeElement.h"
#include "umllib/nodeElement.h"
#include "view/editorViewScene.h"
#include "mainwindow/mainWindow.h"
#include "umllib/private/reshapeEdgeCommand.h"
using namespace qReal;
EmbeddedLinker::EmbeddedLinker()
: mEdge(NULL)
, mMaster(NULL)
, mColor(Qt::blue)
, mPressed(false)
{
mSize = SettingsManager::value("EmbeddedLinkerSize").toFloat();
if (mSize > 10) {
mSize *= 0.75;
}
mIndent = SettingsManager::value("EmbeddedLinkerIndent").toFloat();
mIndent *= 0.8;
if (mIndent > 17) {
mIndent *= 0.7;
}
mRectangle = QRectF(-mSize, -mSize, mSize * 2, mSize * 2);
mInnerRectangle = QRectF(-mSize / 2, -mSize / 2, mSize, mSize);
setZValue(300);
setFlag(ItemStacksBehindParent, false);
setAcceptHoverEvents(true);
}
EmbeddedLinker::~EmbeddedLinker()
{
}
NodeElement* EmbeddedLinker::master() const
{
return mMaster;
}
void EmbeddedLinker::setMaster(NodeElement *element)
{
mMaster = element;
setParentItem(element);
}
void EmbeddedLinker::generateColor()
{
int result = 0;
mColor = QColor(result % 192 + 64, result % 128 + 128, result % 64 + 192).darker(0);
}
void EmbeddedLinker::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget*)
{
Q_UNUSED(option);
painter->save();
QBrush brush;
brush.setColor(mColor);
brush.setStyle(Qt::SolidPattern);
painter->setBrush(brush);
painter->setOpacity(0.75);
painter->setPen(mColor);
mSize = SettingsManager::value("EmbeddedLinkerSize").toFloat();
if (mSize > 10) {
mSize *= 0.75;
}
mRectangle = QRectF(-mSize, -mSize, mSize * 2, mSize * 2);
mInnerRectangle = QRectF(-mSize / 2, -mSize / 2, mSize, mSize);
painter->drawEllipse(mRectangle);
painter->setOpacity(0.9);
painter->drawEllipse(mInnerRectangle);
painter->restore();
}
void EmbeddedLinker::setDirected(const bool directed)
{
this->mDirected = directed;
}
void EmbeddedLinker::initTitle()
{
// TODO: It is not Label, it is simply some text on a scene. Refactor this.
// Temporarily commented out.
// EditorManagerInterface const &editorManagerInterface
// = dynamic_cast<EditorViewScene *>(scene())->mainWindow()->editorManager();
// QString edgeTypeFriendly = editorManagerInterface.friendlyName(Id::loadFromString("qrm:/"+ mMaster->id().editor()
// + "/" + mMaster->id().diagram() + "/" + mEdgeType.element()));
// float textWidth = edgeTypeFriendly.size() * 10;
// float rectWidth = mMaster->boundingRect().right() - mMaster->boundingRect().left();
// float rectHeight = mMaster->boundingRect().bottom() - mMaster->boundingRect().top();
// int x = 0;
// int y = 0;
// if (scenePos().y() < mMaster->scenePos().y() + rectHeight/3)
// y = -boundingRect().height() - 10;
// else if (scenePos().y() > mMaster->scenePos().y() + 2*rectHeight/3)
// y = +boundingRect().height() - 10;
// if (scenePos().x() < mMaster->scenePos().x() + rectWidth/3)
// x = -boundingRect().width() - textWidth + 20;
// else if (scenePos().x() > mMaster->scenePos().x() + 2*rectWidth/3)
// x = +boundingRect().width() - 10;
// mTitle = new Label(static_cast<qreal>(x) / boundingRect().width()
// , static_cast<qreal>(y) / boundingRect().height(), edgeTypeFriendly, 0);
// mTitle->init(boundingRect());
// mTitle->setTextWidth(textWidth);
// mTitle->setParentItem(this);
}
void EmbeddedLinker::setEdgeType(const qReal::Id &edgeType)
{
this->mEdgeType = edgeType;
generateColor();
}
qReal::Id EmbeddedLinker::edgeType() const
{
return mEdgeType;
}
bool EmbeddedLinker::isDirected() const
{
return mDirected;
}
void EmbeddedLinker::takePosition(int index, int maxIndex)
{
qreal const pi = 3.141592;
QRectF const bounding = mMaster->boundingRect();
qreal const top = bounding.topLeft().y();
qreal const left = bounding.topLeft().x();
qreal const right = bounding.bottomRight().x();
qreal const bottom = bounding.bottomRight().y();
qreal const height = bottom - top;
qreal const width = right - left;
qreal const angle = 2 * pi * index / maxIndex;
int rW = width;
int rH = height;
if (rW < 150) {
rW *= 1.5;
} else {
rW += 5;
}
if (rH < 150) {
rH *= 1.5;
} else {
rH += 5;
}
// TODO: customize start angle
qreal const px = left + width / 2 + rW * cos(angle) / 2;
qreal const py = bottom - height / 2 + rH * sin(angle) / 2;
// if linker covers master node:
qreal min = py - top;
if (min > bottom - py) {
min = bottom - py;
}
if (min > px - left) {
min = px - left;
}
if (min > right - px) {
min = right - px;
}
qreal fx;
qreal fy;
mIndent = SettingsManager::value("EmbeddedLinkerIndent").toFloat();
mIndent *= 0.8;
if (mIndent > 17) {
mIndent *= 0.7;
}
//obviously, top != left != right != bottom
if ((bottom - py == min) || (py - top == min)) {
fx = px;
fy = bottom - py == min ? bottom + mIndent : top - mIndent;
} else {
fx = right - px == min ? right + mIndent : left - mIndent;
fy = py;
}
setPos(fx, fy);
}
QRectF EmbeddedLinker::boundingRect() const {
return mRectangle;
}
void EmbeddedLinker::mousePressEvent(QGraphicsSceneMouseEvent *event)
{
Q_UNUSED(event)
mPressed = true;
if (event->button() == Qt::LeftButton) {
mEdge = NULL;
}
}
void EmbeddedLinker::mouseMoveEvent(QGraphicsSceneMouseEvent *event)
{
if (mPressed) {
mPressed = false;
EditorViewScene *scene = dynamic_cast<EditorViewScene*>(mMaster->scene());
if (!scene) {
return;
}
QString const type = "qrm:/" + mMaster->id().editor() + "/" +
mMaster->id().diagram() + "/" + mEdgeType.element();
if (scene->mainWindow()->editorManager().hasElement(Id::loadFromString(type))) {
mMaster->setConnectingState(true);
// FIXME: I am raw. return strange pos() and inside me a small trash
Id edgeId = scene->createElement(type, event->scenePos(), true, &mCreateEdgeCommand, false);
mCreateEdgeCommand->redo();
mEdge = dynamic_cast<EdgeElement*>(scene->getElem(edgeId));
}
if (mEdge) {
mMaster->setZValue(1);
mEdge->setSrc(mMaster);
mEdge->setDst(NULL);
mEdge->highlight();
mEdge->tuneForLinker();
mEdge->placeEndTo(mEdge->mapFromScene(mapToScene(event->pos())));
}
}
mEdge->placeEndTo(mEdge->mapFromScene(mapToScene(event->pos())));
}
void EmbeddedLinker::mouseReleaseEvent(QGraphicsSceneMouseEvent *event)
{
hide();
mMaster->selectionState(false);
EditorViewScene* scene = dynamic_cast<EditorViewScene*>(mMaster->scene());
if (!mPressed && scene && mEdge) {
mEdge->hide();
QPointF const &eScenePos = event->scenePos();
NodeElement *under = dynamic_cast<NodeElement*>(scene->itemAt(eScenePos, QTransform()));
mEdge->show();
int result = 0;
commands::CreateElementCommand *createElementFromMenuCommand = NULL;
if (!under) {
result = scene->launchEdgeMenu(mEdge, mMaster, eScenePos, false, &createElementFromMenuCommand);
} else {
bool canBeConnected = false;
foreach(PossibleEdge const &pEdge, mEdge->src()->getPossibleEdges()) {
if (pEdge.first.second.element() == under->id().element()) {
canBeConnected = true;
} else {
// pEdge.second.first is true, if edge can connect items in only one direction.
if (!pEdge.second.first) {
canBeConnected = (pEdge.first.first.element() == under->id().element());
}
}
}
if (under->isContainer()) {
result = scene->launchEdgeMenu(mEdge, mMaster, eScenePos
, canBeConnected, &createElementFromMenuCommand);
} else {
if (!canBeConnected) {
result = -1;
}
}
}
NodeElement *target = dynamic_cast<NodeElement*>(scene->getLastCreated());
if (result == -1) {
mEdge = NULL;
} else if ((result == 1) && target) {
mEdge->setDst(target);
target->storeGeometry();
}
if (result != -1) {
mEdge->connectToPort();
// This will restore edge state after undo/redo
commands::ReshapeEdgeCommand *reshapeEdge = new commands::ReshapeEdgeCommand(mEdge);
reshapeEdge->startTracking();
mEdge->layOut();
reshapeEdge->stopTracking();
reshapeEdge->setUndoEnabled(false);
if (createElementFromMenuCommand) {
createElementFromMenuCommand->addPostAction(reshapeEdge);
createElementFromMenuCommand->addPreAction(mCreateEdgeCommand);
} else {
mCreateEdgeCommand->undo();
mCreateEdgeCommand->addPostAction(reshapeEdge);
mEdge->controller()->execute(mCreateEdgeCommand);
}
}
}
mPressed = false;
mEdge = NULL;
}
<|endoftext|>
|
<commit_before>#include "positiontracker.h"
#include <cmath>
PositionTracker::PositionTracker()
: LOnGPSData(this),
LOnMotionCommand(this),
LOnIMUData(this)
{
}
Position PositionTracker::GetPosition()
{
return _current_estimate;
}
Position PositionTracker::UpdateWithMeasurement(Position S, Position Measurement)
{
Position result;
result.Latitude.SetValue( ( S.Latitude.Value()*Measurement.Latitude.Variance() + Measurement.Latitude.Value()*S.Latitude.Variance() ) / (S.Latitude.Variance()+Measurement.Latitude.Variance()) );
result.Longitude.SetValue( ( S.Longitude.Value()*Measurement.Longitude.Variance() + Measurement.Longitude.Value()*S.Longitude.Variance() ) / (S.Longitude.Variance()+Measurement.Longitude.Variance()) );
result.Heading.SetValue( ( S.Heading.Value()*Measurement.Heading.Variance() + Measurement.Heading.Value()*S.Heading.Variance() ) / (S.Heading.Variance()+Measurement.Heading.Variance()) );
result.Latitude.SetVariance( 1.0 / (1.0/S.Latitude.Variance() + 1.0 / Measurement.Latitude.Variance()) );
result.Longitude.SetVariance( 1.0 / (1.0/S.Longitude.Variance() + 1.0 / Measurement.Longitude.Variance()) );
result.Heading.SetVariance( 1.0 / (1.0/S.Heading.Variance() + 1.0 / Measurement.Heading.Variance()) );
return result;
}
Position PositionTracker::UpdateWithMotion(Position S, Position Delta)
{
Position result;
result.Latitude.SetValue(S.Latitude.Value() + Delta.Latitude.Value());
result.Longitude.SetValue(S.Longitude.Value() + Delta.Longitude.Value());
result.Heading.SetValue(S.Heading.Value() + Delta.Heading.Value());
result.Latitude.SetVariance(S.Latitude.Variance() + Delta.Latitude.Variance());
result.Longitude.SetVariance(S.Longitude.Variance() + Delta.Longitude.Variance());
result.Heading.SetVariance(S.Heading.Variance() + Delta.Heading.Variance());
return result;
}
Position PositionTracker::DelaFromMotionCommand(MotorCommand cmd)
{
using namespace std;
double V = ( cmd.leftVel + cmd.rightVel ) / 2.0;
double W;
double t = cmd.millis / 1000.0;
double R = V/W;
Position delta;
double theta = _current_estimate.Heading.Value() * M_PI/180.0;
double thetaPrime = (_current_estimate.Heading.Value() + W*t) * M_PI/180.0;
delta.Heading.SetValue(W*t);
delta.Latitude.SetValue(R*(cos(theta) - cos(thetaPrime)));
delta.Longitude.SetValue(R*(sin(thetaPrime) - sin(theta)));
// TODO - handle variances
return delta;
}
void PositionTracker::OnGPSData(GPSData data)
{
Position measurement;
measurement.Latitude.SetValue(data.Lat());
measurement.Longitude.SetValue(data.Long());
// TODO - make sure the GPS actually outputs heading data
measurement.Heading.SetValue(data.Heading());
// TODO - handle variances
_current_estimate = UpdateWithMeasurement(_current_estimate, measurement);
}
void PositionTracker::OnIMUData(IMUData data)
{
}
void PositionTracker::OnMotionCommand(MotorCommand cmd)
{
_current_estimate = UpdateWithMotion(_current_estimate, DelaFromMotionCommand(cmd));
}
<commit_msg>Corrects spelling error in positiontracker.cpp<commit_after>#include "positiontracker.h"
#include <cmath>
PositionTracker::PositionTracker()
: LOnGPSData(this),
LOnMotionCommand(this),
LOnIMUData(this)
{
}
Position PositionTracker::GetPosition()
{
return _current_estimate;
}
Position PositionTracker::UpdateWithMeasurement(Position S, Position Measurement)
{
Position result;
result.Latitude.SetValue( ( S.Latitude.Value()*Measurement.Latitude.Variance() + Measurement.Latitude.Value()*S.Latitude.Variance() ) / (S.Latitude.Variance()+Measurement.Latitude.Variance()) );
result.Longitude.SetValue( ( S.Longitude.Value()*Measurement.Longitude.Variance() + Measurement.Longitude.Value()*S.Longitude.Variance() ) / (S.Longitude.Variance()+Measurement.Longitude.Variance()) );
result.Heading.SetValue( ( S.Heading.Value()*Measurement.Heading.Variance() + Measurement.Heading.Value()*S.Heading.Variance() ) / (S.Heading.Variance()+Measurement.Heading.Variance()) );
result.Latitude.SetVariance( 1.0 / (1.0/S.Latitude.Variance() + 1.0 / Measurement.Latitude.Variance()) );
result.Longitude.SetVariance( 1.0 / (1.0/S.Longitude.Variance() + 1.0 / Measurement.Longitude.Variance()) );
result.Heading.SetVariance( 1.0 / (1.0/S.Heading.Variance() + 1.0 / Measurement.Heading.Variance()) );
return result;
}
Position PositionTracker::UpdateWithMotion(Position S, Position Delta)
{
Position result;
result.Latitude.SetValue(S.Latitude.Value() + Delta.Latitude.Value());
result.Longitude.SetValue(S.Longitude.Value() + Delta.Longitude.Value());
result.Heading.SetValue(S.Heading.Value() + Delta.Heading.Value());
result.Latitude.SetVariance(S.Latitude.Variance() + Delta.Latitude.Variance());
result.Longitude.SetVariance(S.Longitude.Variance() + Delta.Longitude.Variance());
result.Heading.SetVariance(S.Heading.Variance() + Delta.Heading.Variance());
return result;
}
Position PositionTracker::DeltaFromMotionCommand(MotorCommand cmd)
{
using namespace std;
double V = ( cmd.leftVel + cmd.rightVel ) / 2.0;
// TODO - Calculate omega
double W;
double t = cmd.millis / 1000.0;
double R = V/W;
Position delta;
double theta = _current_estimate.Heading.Value() * M_PI/180.0;
double thetaPrime = (_current_estimate.Heading.Value() + W*t) * M_PI/180.0;
delta.Heading.SetValue(W*t);
delta.Latitude.SetValue(R*(cos(theta) - cos(thetaPrime)));
delta.Longitude.SetValue(R*(sin(thetaPrime) - sin(theta)));
// TODO - handle variances
return delta;
}
void PositionTracker::OnGPSData(GPSData data)
{
Position measurement;
measurement.Latitude.SetValue(data.Lat());
measurement.Longitude.SetValue(data.Long());
// TODO - make sure the GPS actually outputs heading data
measurement.Heading.SetValue(data.Heading());
// TODO - handle variances
_current_estimate = UpdateWithMeasurement(_current_estimate, measurement);
}
void PositionTracker::OnIMUData(IMUData data)
{
}
void PositionTracker::OnMotionCommand(MotorCommand cmd)
{
_current_estimate = UpdateWithMotion(_current_estimate, DeltaFromMotionCommand(cmd));
}
<|endoftext|>
|
<commit_before>/*=========================================================================
Program: Medical Imaging & Interaction Toolkit
Language: C++
Date: $Date: 2009-02-10 18:08:54 +0100 (Di, 10 Feb 2009) $
Version: $Revision: 16228 $
Copyright (c) German Cancer Research Center, Division of Medical and
Biological Informatics. All rights reserved.
See MITKCopyright.txt or http://www.mitk.org/copyright.html 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 "mitkNavigationDataPlayer.h"
//for the pause
#include <itksys/SystemTools.hxx>
#include <mitkTimeStamp.h>
#include <fstream>
mitk::NavigationDataPlayer::NavigationDataPlayer() : mitk::NavigationDataPlayerBase()
{
m_NumberOfOutputs = 0;
m_Pause = false;
m_Playing = false;
m_Stream = NULL;
m_PlayerMode = NormalFile;
m_FileName = "";
m_FileVersion = 1;
m_Playing = false;
m_Pause = false;
m_NumberOfOutputs = 0;
m_StartPlayingTimeStamp = 0.0;
m_PauseTimeStamp = 0.0;
m_parentElement = NULL;
m_currentNode = NULL;
m_StreamEnd = false;
m_StreamSetOutsideFromClass = false;
//To get a start time
mitk::TimeStamp::GetInstance()->Start(this);
}
mitk::NavigationDataPlayer::~NavigationDataPlayer()
{
StopPlaying();
delete m_parentElement;
}
void mitk::NavigationDataPlayer::GenerateData()
{
//Only produce new output if the player is started
if (!m_Playing)
{
//The output is not valid anymore
for (unsigned int index = 0; index < m_NumberOfOutputs; index++)
{
mitk::NavigationData* output = this->GetOutput(index);
assert(output);
mitk::NavigationData::Pointer nd = mitk::NavigationData::New();
mitk::NavigationData::PositionType position;
mitk::NavigationData::OrientationType orientation(0.0,0.0,0.0,0.0);
position.Fill(0.0);
nd->SetPosition(position);
nd->SetOrientation(orientation);
nd->SetDataValid(false);
output->Graft(nd);
}
return;
}
//first of all get current time
TimeStampType now = mitk::TimeStamp::GetInstance()->GetElapsed();
//now we make a little time arithmetic
//to get the elapsed time since the start of the player
TimeStampType timeSinceStart = now - m_StartPlayingTimeStamp;
//init the vectors
std::vector< NavigationData::Pointer > nextCandidates;
std::vector< NavigationData::Pointer > lastCandidates;
std::vector< NavigationData::TimeStampType > currentTimeOfData;
for (unsigned int index=0; index < m_NumberOfOutputs; index++)
{
nextCandidates.push_back(m_NextToPlayNavigationData.at(index));
lastCandidates.push_back(m_NextToPlayNavigationData.at(index));
currentTimeOfData.push_back(timeSinceStart + m_StartTimeOfData.at(index));
}
if (m_NextToPlayNavigationData.size() != m_NumberOfOutputs)
{
std::cout << "Mismatch in data" << std::endl;
return;
}
// Now we try to find next NavigationData in the stream:
// This means we step through the stream of NavigationDatas until we find
// a NavigationData which has a current timestamp (currentTimeOfData) greater
// then the current playing time. Then we store the data in
// m_NextToPlayNavigationData and take the last data (lastCandidates) for the
// output of this filter.
//
// The loop will stop when a suitable NavigationData is found or we reach EOF.
// The timestamps of each recorded NavigationData should be equal
// therefore we take always the time from the first.
while( nextCandidates[0]->GetTimeStamp() < currentTimeOfData[0])
{
for (unsigned int index=0; index < m_NumberOfOutputs; index++)
{
lastCandidates[index] = nextCandidates.at(index);
switch(m_FileVersion)
{
case 1:
nextCandidates[index] = ReadVersion1();
break;
default: //this case should not happen! therefore the return at this point
return;
break;
}
//check if the input stream delivered a correct NavigationData object
for (unsigned int i = 0; i < m_NumberOfOutputs; i++)
{
if (nextCandidates.at(index).IsNull())
{
m_StreamEnd = true;
StopPlaying();
return; //the case if no NavigationData is found, e.g. EOF, bad stream
}
}
}
}
//Now lastCandidates stores the new output and nextCandidates is stored to the m_NextToPlay vector
for (unsigned int index = 0; index < m_NumberOfOutputs; index++)
{
mitk::NavigationData* output = this->GetOutput(index);
assert(output);
output->Graft(lastCandidates.at(index));
m_NextToPlayNavigationData[index] = nextCandidates.at(index);
}
}
void mitk::NavigationDataPlayer::UpdateOutputInformation()
{
this->Modified(); // make sure that we need to be updated
Superclass::UpdateOutputInformation();
}
void mitk::NavigationDataPlayer::InitPlayer()
{
if (m_Stream == NULL)
{
StreamInvalid("Playing not possible. Wrong file name or path?");
return;
}
if (!m_Stream->good())
{
StreamInvalid("Playing not possible. Stream is not good!");
return;
}
m_FileVersion = GetFileVersion(m_Stream); //first get the file version
//check if we have a valid version
if (m_FileVersion < 1)
{
StreamInvalid("Playing not possible. Stream is not good!");
return;
}
//now read the number of Tracked Tools
if(m_NumberOfOutputs == 0){m_NumberOfOutputs = GetNumberOfNavigationDatas(m_Stream);}
//with the information about the tracked tool number we can generate the output
if (m_NumberOfOutputs > 0)
{
//Generate the output only if there are changes to the amount of outputs
//This happens when the player is stopped and start again with different file
if (this->GetNumberOfOutputs() != m_NumberOfOutputs) {SetNumberOfOutputs(m_NumberOfOutputs);}
//initialize the player with first data
GetFirstData();
//set stream valid
m_ErrorMessage = "";
m_StreamValid = true;
}
else
{
StreamInvalid("The input stream seems to have NavigationData incompatible format");
return;
}
}
unsigned int mitk::NavigationDataPlayer::GetFileVersion(std::istream* stream)
{
if (stream==NULL)
{
std::cout << "No input stream set!" << std::endl;
return 0;
}
if (!stream->good())
{
std::cout << "Stream not good!" << std::endl;
return 0;
}
int version = 1;
TiXmlDeclaration* dec = new TiXmlDeclaration();
*stream >> *dec;
if(strcmp(dec->Version(),"") == 0){
std::cout << "The input stream seems to have XML incompatible format" << std::endl;
return 0;
}
m_parentElement = new TiXmlElement("");
*stream >> *m_parentElement; //2nd line this is the file version
std::string tempValue = m_parentElement->Value();
if(tempValue != "Version")
{
if(tempValue == "Data"){
m_parentElement->QueryIntAttribute("version",&version);
}
}
else
{
m_parentElement->QueryIntAttribute("Ver",&version);
}
if (version > 0)
return version;
else
return 0;
}
unsigned int mitk::NavigationDataPlayer::GetNumberOfNavigationDatas(std::istream* stream)
{
if (stream == NULL)
{
std::cout << "No input stream set!" << std::endl;
return 0;
}
if (!stream->good())
{
std::cout << "Stream not good!" << std::endl;
return 0;
}
//If something has changed in a future version of the XML definition e.g. navigationcount or addional parameters
//catch this here with a select case block (see GenerateData() method)
int numberOfTools = 0;
std::string tempValue = m_parentElement->Value();
if(tempValue == "Version"){
*stream >> *m_parentElement;
}
m_parentElement->QueryIntAttribute("ToolCount",&numberOfTools);
if (numberOfTools > 0)
return numberOfTools;
return 0;
}
mitk::NavigationData::Pointer mitk::NavigationDataPlayer::ReadVersion1()
{
if (m_Stream == NULL)
{
m_Playing = false;
std::cout << "Playing not possible. Wrong file name or path? " << std::endl;
return NULL;
}
if (!m_Stream->good())
{
m_Playing = false;
std::cout << "Playing not possible. Stream is not good!" << std::endl;
return NULL;
}
/*TiXmlElement* elem = new TiXmlElement("");
m_currentNode = m_parentElement->IterateChildren(m_currentNode);
if(m_currentNode)
{
elem = m_currentNode->ToElement();
}*/
TiXmlElement* elem;
m_currentNode = m_parentElement->IterateChildren(m_currentNode);
bool delElem;
if(m_currentNode)
{
elem = m_currentNode->ToElement();
delElem = false;
}
else
{
elem = new TiXmlElement("");
delElem = true;
}
mitk::NavigationData::Pointer nd = this->ReadNavigationData(elem);
if(delElem)
delete elem;
return nd;
}
void mitk::NavigationDataPlayer::StartPlaying()
{
if (m_Stream == NULL)
{
m_Playing = false;
//Perhaps the SetStream method was not called so we do this when a FileName is set with SetStream(PlayerMode)
if (m_FileName != "")
{
//The PlayerMode is initialized with LastSetStream
//SetStream also calls InitPlayer()
SetStream(m_PlayerMode);
}
//now check again
if (m_Stream == NULL)
{
StopPlaying();
std::cout << "Playing not possible. Wrong file name or path? " << std::endl;
return;
}
}
if (!m_Playing && m_Stream->good())
{
m_Playing = true; //starts the player
m_StartPlayingTimeStamp = mitk::TimeStamp::GetInstance()->GetElapsed();
}
else
{
std::cout << "Player already started or stream is not good" << std::endl;
StopPlaying();
}
}
void mitk::NavigationDataPlayer::StopPlaying()
{
//re init all data!! for playing again with different data
//only PlayerMode and FileName are not changed
m_Pause = false;
m_Playing = false;
if (!m_StreamSetOutsideFromClass)
{delete m_Stream;}
m_Stream = NULL;
m_FileVersion = 1;
m_Playing = false;
m_Pause = false;
m_StartPlayingTimeStamp = 0.0;
m_PauseTimeStamp = 0.0;
m_NextToPlayNavigationData.clear();
m_StartTimeOfData.clear();
}
void mitk::NavigationDataPlayer::GetFirstData()
{
//Here we read the first lines of input (dependend on the number of inputs)
for (unsigned int index=0; index < m_NumberOfOutputs; index++)
{
//Here we init the vector for later use
m_NextToPlayNavigationData.push_back(NULL);
m_StartTimeOfData.push_back(0.0);
mitk::NavigationData::Pointer nd = this->GetOutput(index);
switch(m_FileVersion)
{
case 1:
m_NextToPlayNavigationData[index] = ReadVersion1();
//check if there is valid data in it
if (m_NextToPlayNavigationData[index].IsNull())
{
m_StreamEnd = true;
StopPlaying();
std::cout << "XML File is corrupt or has no NavigationData" << std::endl;
return;
}
//Have a look it the output was set already without this check the pipline will disconnect after a start/stop cycle
if (nd.IsNull())
this->SetNthOutput(index, m_NextToPlayNavigationData[index]);
m_StartTimeOfData[index] = m_NextToPlayNavigationData[index]->GetTimeStamp();
break;
default: //this case should not happen! therefore the return at this point
return;
break;
}
}
}
void mitk::NavigationDataPlayer::Pause()
{
//player runs and pause was called -> pause the player
if(m_Playing && !m_Pause)
{
m_Playing = false;
m_Pause = true;
m_PauseTimeStamp = mitk::TimeStamp::GetInstance()->GetElapsed();
}
else
{
std::cout << "Player is either not started or already is paused" << std::endl;
}
}
void mitk::NavigationDataPlayer::Resume()
{
//player is in pause mode -> play at the last position
if(!m_Playing && m_Pause)
{
m_Playing = true;
m_Pause = false;
mitk::NavigationData::TimeStampType now = mitk::TimeStamp::GetInstance()->GetElapsed();
// in this case m_StartPlayingTimeStamp is set to the total elapsed time with NO playback
m_StartPlayingTimeStamp = now - (m_PauseTimeStamp - m_StartPlayingTimeStamp);
}
else
{
std::cout << "Player is not paused!" << std::endl;
}
}
void mitk::NavigationDataPlayer::SetStream( PlayerMode /*mode*/ )
{
m_Stream = NULL;
if (!itksys::SystemTools::FileExists(m_FileName.c_str()))
{
std::cout << "File dont exist!" << std::endl;
return;
}
switch(m_PlayerMode)
{
case NormalFile:
m_Stream = new std::ifstream(m_FileName.c_str());
m_StreamSetOutsideFromClass = false;
break;
case ZipFile:
m_Stream = NULL;
std::cout << "Sorry no ZipFile support yet";
break;
default:
m_Stream = NULL;
break;
}
this->Modified();
InitPlayer();
}
void mitk::NavigationDataPlayer::SetStream( std::istream* stream )
{
if (!stream->good())
{
m_StreamEnd = true;
std::cout << "The stream is not good" << std::endl;
return;
}
m_Stream = stream;
m_StreamSetOutsideFromClass = true;
this->Modified();
InitPlayer();
}
bool mitk::NavigationDataPlayer::IsAtEnd()
{
return this->m_StreamEnd;
}
void mitk::NavigationDataPlayer::StreamInvalid(std::string message)
{
m_StreamEnd = true;
StopPlaying();
m_ErrorMessage = message;
m_StreamValid = false;
MITK_ERROR << m_ErrorMessage;
return;
}<commit_msg>replaced std::cout by MITK_ERROR messages<commit_after>/*=========================================================================
Program: Medical Imaging & Interaction Toolkit
Language: C++
Date: $Date: 2009-02-10 18:08:54 +0100 (Di, 10 Feb 2009) $
Version: $Revision: 16228 $
Copyright (c) German Cancer Research Center, Division of Medical and
Biological Informatics. All rights reserved.
See MITKCopyright.txt or http://www.mitk.org/copyright.html 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 "mitkNavigationDataPlayer.h"
//for the pause
#include <itksys/SystemTools.hxx>
#include <mitkTimeStamp.h>
#include <fstream>
mitk::NavigationDataPlayer::NavigationDataPlayer() : mitk::NavigationDataPlayerBase()
{
m_NumberOfOutputs = 0;
m_Pause = false;
m_Playing = false;
m_Stream = NULL;
m_PlayerMode = NormalFile;
m_FileName = "";
m_FileVersion = 1;
m_Playing = false;
m_Pause = false;
m_NumberOfOutputs = 0;
m_StartPlayingTimeStamp = 0.0;
m_PauseTimeStamp = 0.0;
m_parentElement = NULL;
m_currentNode = NULL;
m_StreamEnd = false;
m_StreamSetOutsideFromClass = false;
//To get a start time
mitk::TimeStamp::GetInstance()->Start(this);
}
mitk::NavigationDataPlayer::~NavigationDataPlayer()
{
StopPlaying();
delete m_parentElement;
}
void mitk::NavigationDataPlayer::GenerateData()
{
//Only produce new output if the player is started
if (!m_Playing)
{
//The output is not valid anymore
for (unsigned int index = 0; index < m_NumberOfOutputs; index++)
{
mitk::NavigationData* output = this->GetOutput(index);
assert(output);
mitk::NavigationData::Pointer nd = mitk::NavigationData::New();
mitk::NavigationData::PositionType position;
mitk::NavigationData::OrientationType orientation(0.0,0.0,0.0,0.0);
position.Fill(0.0);
nd->SetPosition(position);
nd->SetOrientation(orientation);
nd->SetDataValid(false);
output->Graft(nd);
}
return;
}
//first of all get current time
TimeStampType now = mitk::TimeStamp::GetInstance()->GetElapsed();
//now we make a little time arithmetic
//to get the elapsed time since the start of the player
TimeStampType timeSinceStart = now - m_StartPlayingTimeStamp;
//init the vectors
std::vector< NavigationData::Pointer > nextCandidates;
std::vector< NavigationData::Pointer > lastCandidates;
std::vector< NavigationData::TimeStampType > currentTimeOfData;
for (unsigned int index=0; index < m_NumberOfOutputs; index++)
{
nextCandidates.push_back(m_NextToPlayNavigationData.at(index));
lastCandidates.push_back(m_NextToPlayNavigationData.at(index));
currentTimeOfData.push_back(timeSinceStart + m_StartTimeOfData.at(index));
}
if (m_NextToPlayNavigationData.size() != m_NumberOfOutputs)
{
MITK_ERROR << "Mismatch in data";
return;
}
// Now we try to find next NavigationData in the stream:
// This means we step through the stream of NavigationDatas until we find
// a NavigationData which has a current timestamp (currentTimeOfData) greater
// then the current playing time. Then we store the data in
// m_NextToPlayNavigationData and take the last data (lastCandidates) for the
// output of this filter.
//
// The loop will stop when a suitable NavigationData is found or we reach EOF.
// The timestamps of each recorded NavigationData should be equal
// therefore we take always the time from the first.
while( nextCandidates[0]->GetTimeStamp() < currentTimeOfData[0])
{
for (unsigned int index=0; index < m_NumberOfOutputs; index++)
{
lastCandidates[index] = nextCandidates.at(index);
switch(m_FileVersion)
{
case 1:
nextCandidates[index] = ReadVersion1();
break;
default: //this case should not happen! therefore the return at this point
return;
break;
}
//check if the input stream delivered a correct NavigationData object
for (unsigned int i = 0; i < m_NumberOfOutputs; i++)
{
if (nextCandidates.at(index).IsNull())
{
m_StreamEnd = true;
StopPlaying();
return; //the case if no NavigationData is found, e.g. EOF, bad stream
}
}
}
}
//Now lastCandidates stores the new output and nextCandidates is stored to the m_NextToPlay vector
for (unsigned int index = 0; index < m_NumberOfOutputs; index++)
{
mitk::NavigationData* output = this->GetOutput(index);
assert(output);
output->Graft(lastCandidates.at(index));
m_NextToPlayNavigationData[index] = nextCandidates.at(index);
}
}
void mitk::NavigationDataPlayer::UpdateOutputInformation()
{
this->Modified(); // make sure that we need to be updated
Superclass::UpdateOutputInformation();
}
void mitk::NavigationDataPlayer::InitPlayer()
{
if (m_Stream == NULL)
{
StreamInvalid("C1: Playing not possible. Wrong file name or path?");
return;
}
if (!m_Stream->good())
{
StreamInvalid("C2: Playing not possible. Stream is not good!");
return;
}
m_FileVersion = GetFileVersion(m_Stream); //first get the file version
//check if we have a valid version
if (m_FileVersion < 1)
{
StreamInvalid("C3: Playing not possible. Invalid file version!");
return;
}
//now read the number of Tracked Tools
if(m_NumberOfOutputs == 0){m_NumberOfOutputs = GetNumberOfNavigationDatas(m_Stream);}
//with the information about the tracked tool number we can generate the output
if (m_NumberOfOutputs > 0)
{
//Generate the output only if there are changes to the amount of outputs
//This happens when the player is stopped and start again with different file
if (this->GetNumberOfOutputs() != m_NumberOfOutputs) {SetNumberOfOutputs(m_NumberOfOutputs);}
//initialize the player with first data
GetFirstData();
//set stream valid
m_ErrorMessage = "";
m_StreamValid = true;
}
else
{
StreamInvalid("The input stream seems to have NavigationData incompatible format");
return;
}
}
unsigned int mitk::NavigationDataPlayer::GetFileVersion(std::istream* stream)
{
if (stream==NULL)
{
MITK_ERROR << "D1: No input stream set!";
return 0;
}
if (!stream->good())
{
MITK_ERROR << "D2: Stream not good!";
return 0;
}
int version = 1;
TiXmlDeclaration* dec = new TiXmlDeclaration();
*stream >> *dec;
if(strcmp(dec->Version(),"") == 0){
MITK_ERROR << "D3: The input stream seems to have XML incompatible format";
return 0;
}
m_parentElement = new TiXmlElement("");
*stream >> *m_parentElement; //2nd line this is the file version
std::string tempValue = m_parentElement->Value();
if(tempValue != "Version")
{
if(tempValue == "Data"){
m_parentElement->QueryIntAttribute("version",&version);
}
}
else
{
m_parentElement->QueryIntAttribute("Ver",&version);
}
if (version > 0)
return version;
else
return 0;
}
unsigned int mitk::NavigationDataPlayer::GetNumberOfNavigationDatas(std::istream* stream)
{
if (stream == NULL)
{
MITK_ERROR << "No input stream set!";
return 0;
}
if (!stream->good())
{
MITK_ERROR << "Stream not good!";
return 0;
}
//If something has changed in a future version of the XML definition e.g. navigationcount or addional parameters
//catch this here with a select case block (see GenerateData() method)
int numberOfTools = 0;
std::string tempValue = m_parentElement->Value();
if(tempValue == "Version"){
*stream >> *m_parentElement;
}
m_parentElement->QueryIntAttribute("ToolCount",&numberOfTools);
if (numberOfTools > 0)
return numberOfTools;
return 0;
}
mitk::NavigationData::Pointer mitk::NavigationDataPlayer::ReadVersion1()
{
if (m_Stream == NULL)
{
m_Playing = false;
MITK_ERROR << "Playing not possible. Wrong file name or path? ";
return NULL;
}
if (!m_Stream->good())
{
m_Playing = false;
MITK_ERROR << "Playing not possible. Stream is not good!";
return NULL;
}
/*TiXmlElement* elem = new TiXmlElement("");
m_currentNode = m_parentElement->IterateChildren(m_currentNode);
if(m_currentNode)
{
elem = m_currentNode->ToElement();
}*/
TiXmlElement* elem;
m_currentNode = m_parentElement->IterateChildren(m_currentNode);
bool delElem;
if(m_currentNode)
{
elem = m_currentNode->ToElement();
delElem = false;
}
else
{
elem = new TiXmlElement("");
delElem = true;
}
mitk::NavigationData::Pointer nd = this->ReadNavigationData(elem);
if(delElem)
delete elem;
return nd;
}
void mitk::NavigationDataPlayer::StartPlaying()
{
if (m_Stream == NULL)
{
m_Playing = false;
//Perhaps the SetStream method was not called so we do this when a FileName is set with SetStream(PlayerMode)
if (m_FileName != "")
{
//The PlayerMode is initialized with LastSetStream
//SetStream also calls InitPlayer()
SetStream(m_PlayerMode);
}
//now check again
if (m_Stream == NULL)
{
StopPlaying();
MITK_ERROR << "Playing not possible. Wrong file name or path?";
return;
}
}
if (!m_Playing && m_Stream->good())
{
m_Playing = true; //starts the player
m_StartPlayingTimeStamp = mitk::TimeStamp::GetInstance()->GetElapsed();
}
else
{
MITK_ERROR << "Player already started or stream is not good!";
StopPlaying();
}
}
void mitk::NavigationDataPlayer::StopPlaying()
{
//re init all data!! for playing again with different data
//only PlayerMode and FileName are not changed
m_Pause = false;
m_Playing = false;
if (!m_StreamSetOutsideFromClass)
{delete m_Stream;}
m_Stream = NULL;
m_FileVersion = 1;
m_Playing = false;
m_Pause = false;
m_StartPlayingTimeStamp = 0.0;
m_PauseTimeStamp = 0.0;
m_NextToPlayNavigationData.clear();
m_StartTimeOfData.clear();
}
void mitk::NavigationDataPlayer::GetFirstData()
{
//Here we read the first lines of input (dependend on the number of inputs)
for (unsigned int index=0; index < m_NumberOfOutputs; index++)
{
//Here we init the vector for later use
m_NextToPlayNavigationData.push_back(NULL);
m_StartTimeOfData.push_back(0.0);
mitk::NavigationData::Pointer nd = this->GetOutput(index);
switch(m_FileVersion)
{
case 1:
m_NextToPlayNavigationData[index] = ReadVersion1();
//check if there is valid data in it
if (m_NextToPlayNavigationData[index].IsNull())
{
m_StreamEnd = true;
StopPlaying();
MITK_ERROR << "XML File is corrupt or has no NavigationData" << std::endl;
return;
}
//Have a look it the output was set already without this check the pipline will disconnect after a start/stop cycle
if (nd.IsNull())
this->SetNthOutput(index, m_NextToPlayNavigationData[index]);
m_StartTimeOfData[index] = m_NextToPlayNavigationData[index]->GetTimeStamp();
break;
default: //this case should not happen! therefore the return at this point
return;
break;
}
}
}
void mitk::NavigationDataPlayer::Pause()
{
//player runs and pause was called -> pause the player
if(m_Playing && !m_Pause)
{
m_Playing = false;
m_Pause = true;
m_PauseTimeStamp = mitk::TimeStamp::GetInstance()->GetElapsed();
}
else
{
MITK_ERROR << "Player is either not started or already is paused" << std::endl;
}
}
void mitk::NavigationDataPlayer::Resume()
{
//player is in pause mode -> play at the last position
if(!m_Playing && m_Pause)
{
m_Playing = true;
m_Pause = false;
mitk::NavigationData::TimeStampType now = mitk::TimeStamp::GetInstance()->GetElapsed();
// in this case m_StartPlayingTimeStamp is set to the total elapsed time with NO playback
m_StartPlayingTimeStamp = now - (m_PauseTimeStamp - m_StartPlayingTimeStamp);
}
else
{
MITK_ERROR << "Player is not paused!" << std::endl;
}
}
void mitk::NavigationDataPlayer::SetStream( PlayerMode /*mode*/ )
{
m_Stream = NULL;
if (!itksys::SystemTools::FileExists(m_FileName.c_str()))
{
MITK_ERROR << "File dont exist!" << std::endl;
return;
}
switch(m_PlayerMode)
{
case NormalFile:
m_Stream = new std::ifstream(m_FileName.c_str());
m_StreamSetOutsideFromClass = false;
break;
case ZipFile:
m_Stream = NULL;
MITK_ERROR << "Sorry no ZipFile support yet";
break;
default:
m_Stream = NULL;
break;
}
this->Modified();
InitPlayer();
}
void mitk::NavigationDataPlayer::SetStream( std::istream* stream )
{
if (!stream->good())
{
m_StreamEnd = true;
MITK_ERROR << "The stream is not good";
return;
}
m_Stream = stream;
m_StreamSetOutsideFromClass = true;
this->Modified();
InitPlayer();
}
bool mitk::NavigationDataPlayer::IsAtEnd()
{
return this->m_StreamEnd;
}
void mitk::NavigationDataPlayer::StreamInvalid(std::string message)
{
m_StreamEnd = true;
StopPlaying();
m_ErrorMessage = message;
m_StreamValid = false;
MITK_ERROR << m_ErrorMessage;
return;
}<|endoftext|>
|
<commit_before>// -------------------------------------------------------------------------
// @FileName : NFCLoginLogicModule.cpp
// @Author : LvSheng.Huang
// @Date : 2013-01-02
// @Module : NFCLoginLogicModule
// @Desc :
// -------------------------------------------------------------------------
#include "NFLoginLogicPlugin.h"
#include "NFCLoginLogicModule.h"
bool NFCLoginLogicModule::Init()
{
return true;
}
bool NFCLoginLogicModule::Shut()
{
return true;
}
void NFCLoginLogicModule::OnLoginProcess(const int nSockIndex, const int nMsgID, const char* msg, const uint32_t nLen)
{
NFINetModule* pNetModule = m_pLoginNet_ServerModule->GetNetModule();
NFGUID nPlayerID;
NFMsg::ReqAccountLogin xMsg;
if (!pNetModule->ReceivePB(nSockIndex, nMsgID, msg, nLen, xMsg, nPlayerID))
{
return;
}
NetObject* pNetObject = pNetModule->GetNet()->GetNetObject(nSockIndex);
if (pNetObject)
{
if (pNetObject->GetConnectKeyState() == 0)
{
//int nState = m_pLoginLogicModule->OnLoginProcess(pNetObject->GetClientID(), xMsg.account(), xMsg.password());
int nState = 0;
if (0 != nState)
{
std::ostringstream strLog;
strLog << "Check password failed, Account = " << xMsg.account() << " Password = " << xMsg.password();
m_pLogModule->LogNormal(NFILogModule::NLL_ERROR_NORMAL, NFGUID(0, nSockIndex), strLog, __FUNCTION__, __LINE__);
NFMsg::AckEventResult xMsg;
xMsg.set_event_code(NFMsg::EGEC_ACCOUNTPWD_INVALID);
pNetModule->SendMsgPB(NFMsg::EGameMsgID::EGMI_ACK_LOGIN, xMsg, nSockIndex);
return;
}
pNetObject->SetConnectKeyState(1);
pNetObject->SetAccount(xMsg.account());
NFMsg::AckEventResult xData;
xData.set_event_code(NFMsg::EGEC_ACCOUNT_SUCCESS);
pNetModule->SendMsgPB(NFMsg::EGameMsgID::EGMI_ACK_LOGIN, xData, nSockIndex);
m_pLogModule->LogNormal(NFILogModule::NLL_INFO_NORMAL, NFGUID(0, nSockIndex), "Login successed :", xMsg.account().c_str());
}
}
}
bool NFCLoginLogicModule::ReadyExecute()
{
NFINetModule* pNetModule = m_pLoginNet_ServerModule->GetNetModule();
pNetModule->RemoveReceiveCallBack(NFMsg::EGMI_REQ_LOGIN);
pNetModule->AddReceiveCallBack(NFMsg::EGMI_REQ_LOGIN, this, &NFCLoginLogicModule::OnLoginProcess);
return true;
}
bool NFCLoginLogicModule::Execute()
{
return true;
}
bool NFCLoginLogicModule::AfterInit()
{
m_pLoginNet_ServerModule = pPluginManager->FindModule<NFILoginNet_ServerModule>();
return true;
}
<commit_msg>fix NFCLoginLogicModule m_pLogModule not Init<commit_after>// -------------------------------------------------------------------------
// @FileName : NFCLoginLogicModule.cpp
// @Author : LvSheng.Huang
// @Date : 2013-01-02
// @Module : NFCLoginLogicModule
// @Desc :
// -------------------------------------------------------------------------
#include "NFLoginLogicPlugin.h"
#include "NFCLoginLogicModule.h"
bool NFCLoginLogicModule::Init()
{
return true;
}
bool NFCLoginLogicModule::Shut()
{
return true;
}
void NFCLoginLogicModule::OnLoginProcess(const int nSockIndex, const int nMsgID, const char* msg, const uint32_t nLen)
{
NFINetModule* pNetModule = m_pLoginNet_ServerModule->GetNetModule();
NFGUID nPlayerID;
NFMsg::ReqAccountLogin xMsg;
if (!pNetModule->ReceivePB(nSockIndex, nMsgID, msg, nLen, xMsg, nPlayerID))
{
return;
}
NetObject* pNetObject = pNetModule->GetNet()->GetNetObject(nSockIndex);
if (pNetObject)
{
if (pNetObject->GetConnectKeyState() == 0)
{
//int nState = m_pLoginLogicModule->OnLoginProcess(pNetObject->GetClientID(), xMsg.account(), xMsg.password());
int nState = 0;
if (0 != nState)
{
std::ostringstream strLog;
strLog << "Check password failed, Account = " << xMsg.account() << " Password = " << xMsg.password();
m_pLogModule->LogNormal(NFILogModule::NLL_ERROR_NORMAL, NFGUID(0, nSockIndex), strLog, __FUNCTION__, __LINE__);
NFMsg::AckEventResult xMsg;
xMsg.set_event_code(NFMsg::EGEC_ACCOUNTPWD_INVALID);
pNetModule->SendMsgPB(NFMsg::EGameMsgID::EGMI_ACK_LOGIN, xMsg, nSockIndex);
return;
}
pNetObject->SetConnectKeyState(1);
pNetObject->SetAccount(xMsg.account());
NFMsg::AckEventResult xData;
xData.set_event_code(NFMsg::EGEC_ACCOUNT_SUCCESS);
pNetModule->SendMsgPB(NFMsg::EGameMsgID::EGMI_ACK_LOGIN, xData, nSockIndex);
m_pLogModule->LogNormal(NFILogModule::NLL_INFO_NORMAL, NFGUID(0, nSockIndex), "Login successed :", xMsg.account().c_str());
}
}
}
bool NFCLoginLogicModule::ReadyExecute()
{
NFINetModule* pNetModule = m_pLoginNet_ServerModule->GetNetModule();
pNetModule->RemoveReceiveCallBack(NFMsg::EGMI_REQ_LOGIN);
pNetModule->AddReceiveCallBack(NFMsg::EGMI_REQ_LOGIN, this, &NFCLoginLogicModule::OnLoginProcess);
return true;
}
bool NFCLoginLogicModule::Execute()
{
return true;
}
bool NFCLoginLogicModule::AfterInit()
{
m_pLoginNet_ServerModule = pPluginManager->FindModule<NFILoginNet_ServerModule>();
m_pLogModule = pPluginManager->FindModule<NFILogModule>();
return true;
}
<|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
#include "etl/impl/transpose.hpp"
#include "etl/impl/fft.hpp"
/*!
* \file inplace_assignable.hpp
* \brief Use CRTP technique to inject inplace operations into expressions and value classes.
*/
namespace etl {
/*!
* \brief CRTP class to inject inplace operations to matrix and vector structures.
*
* This CRTP class injects inplace FFT, Transposition, flipping and scaling.
*/
template <typename D>
struct inplace_assignable {
using derived_t = D; ///< The derived type
/*!
* \brief Returns a reference to the derived object, i.e. the object using the CRTP injector.
* \return a reference to the derived object.
*/
derived_t& as_derived() noexcept {
return *static_cast<derived_t*>(this);
}
/*!
* \brief Scale the matrix by the factor e, in place.
*
* \param e The scaling factor.
*/
template <typename E>
derived_t& scale_inplace(E&& e) {
as_derived() *= e;
return as_derived();
}
/*!
* \brief Flip the matrix horizontally and vertically, in place.
*/
derived_t& fflip_inplace() {
static_assert(etl_traits<derived_t>::dimensions() <= 2, "Impossible to fflip a matrix of D > 2");
if (etl_traits<derived_t>::dimensions() == 2) {
std::reverse(as_derived().begin(), as_derived().end());
}
return as_derived();
}
/*!
* \brief Transpose each sub 2D matrix in place.
*/
template <typename S = D, cpp_enable_if((etl_traits<S>::dimensions() > 3))>
derived_t& deep_transpose_inplace() {
decltype(auto) mat = as_derived();
for (std::size_t i = 0; i < etl::dim<0>(mat); ++i) {
mat(i).deep_transpose_inplace();
}
return mat;
}
/*!
* \brief Transpose each sub 2D matrix in place.
*/
template <typename S = D, cpp_enable_if((etl_traits<S>::dimensions() == 3))>
derived_t& deep_transpose_inplace() {
decltype(auto) mat = as_derived();
for (std::size_t i = 0; i < etl::dim<0>(mat); ++i) {
mat(i).transpose_inplace();
}
return mat;
}
/*!
* \brief Transpose the matrix in place.
*
* Only square fast matrix can be transpose in place, dyn matrix don't have any limitation.
*/
template <typename S = D, cpp_disable_if(is_dyn_matrix<S>::value)>
derived_t& transpose_inplace() {
static_assert(etl_traits<derived_t>::dimensions() == 2, "Only 2D matrix can be transposed");
cpp_assert(etl::dim<0>(as_derived()) == etl::dim<1>(as_derived()), "Only square fast matrices can be tranposed inplace");
detail::inplace_square_transpose<derived_t>::apply(as_derived());
return as_derived();
}
/*!
* \brief Transpose the matrix in place.
*
* Only square fast matrix can be transpose in place, dyn matrix don't have any limitation.
*/
template <typename S = D, cpp_enable_if(is_dyn_matrix<S>::value)>
derived_t& transpose_inplace() {
static_assert(etl_traits<derived_t>::dimensions() == 2, "Only 2D matrix can be transposed");
decltype(auto) mat = as_derived();
if (etl::dim<0>(mat) == etl::dim<1>(mat)) {
detail::inplace_square_transpose<derived_t>::apply(mat);
} else {
detail::inplace_rectangular_transpose<derived_t>::apply(mat);
using std::swap;
swap(mat.unsafe_dimension_access(0), mat.unsafe_dimension_access(1));
}
return mat;
}
/*!
* \brief Perform inplace 1D FFT of the vector.
*/
derived_t& fft_inplace() {
static_assert(is_complex<derived_t>::value, "Only complex vector can use inplace FFT");
static_assert(etl_traits<derived_t>::dimensions() == 1, "Only vector can use fft_inplace, use fft2_inplace for matrices");
decltype(auto) mat = as_derived();
detail::fft1_impl<derived_t, derived_t>::apply(mat, mat);
mat.gpu_copy_from_if_necessary();
return mat;
}
/*!
* \brief Perform many inplace 1D FFT of the matrix.
*
* This function considers the first dimension as being batches of 1D FFT.
*/
derived_t& fft_many_inplace() {
static_assert(is_complex<derived_t>::value, "Only complex vector can use inplace FFT");
static_assert(etl_traits<derived_t>::dimensions() > 1, "Only matrix of dimensions > 1 can use fft_many_inplace");
decltype(auto) mat = as_derived();
detail::fft1_many_impl<derived_t, derived_t>::apply(mat, mat);
mat.gpu_copy_from_if_necessary();
return mat;
}
/*!
* \brief Perform inplace 1D Inverse FFT of the vector.
*/
derived_t& ifft_inplace() {
static_assert(is_complex<derived_t>::value, "Only complex vector can use inplace IFFT");
static_assert(etl_traits<derived_t>::dimensions() == 1, "Only vector can use ifft_inplace, use ifft2_inplace for matrices");
decltype(auto) mat = as_derived();
detail::ifft1_impl<derived_t, derived_t>::apply(mat, mat);
mat.gpu_copy_from_if_necessary();
return mat;
}
/*!
* \brief Perform inplace 2D FFT of the matrix.
*/
derived_t& fft2_inplace() {
static_assert(is_complex<derived_t>::value, "Only complex vector can use inplace FFT");
static_assert(etl_traits<derived_t>::dimensions() == 2, "Only matrix can use fft2_inplace, use fft_inplace for vectors");
decltype(auto) mat = as_derived();
detail::fft2_impl<derived_t, derived_t>::apply(mat, mat);
mat.gpu_copy_from_if_necessary();
return mat;
}
/*!
* \brief Perform many inplace 2D FFT of the matrix.
*
* This function considers the first dimension as being batches of 2D FFT.
*/
derived_t& fft2_many_inplace() {
static_assert(is_complex<derived_t>::value, "Only complex vector can use inplace FFT");
static_assert(etl_traits<derived_t>::dimensions() > 2, "Only matrix of dimensions > 2 can use fft2_many_inplace");
decltype(auto) mat = as_derived();
detail::fft2_many_impl<derived_t, derived_t>::apply(mat, mat);
mat.gpu_copy_from_if_necessary();
return mat;
}
/*!
* \brief Perform inplace 2D Inverse FFT of the matrix.
*/
derived_t& ifft2_inplace() {
static_assert(is_complex<derived_t>::value, "Only complex vector can use inplace IFFT");
static_assert(etl_traits<derived_t>::dimensions() == 2, "Only vector can use ifft_inplace, use ifft2_inplace for matrices");
decltype(auto) mat = as_derived();
detail::ifft2_impl<derived_t, derived_t>::apply(mat, mat);
mat.gpu_copy_from_if_necessary();
return mat;
}
};
} //end of namespace etl
<commit_msg>Improve deep transposition capabitilies<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
#include "etl/impl/transpose.hpp"
#include "etl/impl/fft.hpp"
/*!
* \file inplace_assignable.hpp
* \brief Use CRTP technique to inject inplace operations into expressions and value classes.
*/
namespace etl {
/*!
* \brief CRTP class to inject inplace operations to matrix and vector structures.
*
* This CRTP class injects inplace FFT, Transposition, flipping and scaling.
*/
template <typename D>
struct inplace_assignable {
using derived_t = D; ///< The derived type
/*!
* \brief Returns a reference to the derived object, i.e. the object using the CRTP injector.
* \return a reference to the derived object.
*/
derived_t& as_derived() noexcept {
return *static_cast<derived_t*>(this);
}
/*!
* \brief Scale the matrix by the factor e, in place.
*
* \param e The scaling factor.
*/
template <typename E>
derived_t& scale_inplace(E&& e) {
as_derived() *= e;
return as_derived();
}
/*!
* \brief Flip the matrix horizontally and vertically, in place.
*/
derived_t& fflip_inplace() {
static_assert(etl_traits<derived_t>::dimensions() <= 2, "Impossible to fflip a matrix of D > 2");
if (etl_traits<derived_t>::dimensions() == 2) {
std::reverse(as_derived().begin(), as_derived().end());
}
return as_derived();
}
/*!
* \brief Transpose each sub 2D matrix in place.
*/
template <typename S = D, cpp_enable_if(is_dyn_matrix<S>::value && (etl_traits<S>::dimensions() > 3))>
derived_t& deep_transpose_inplace() {
decltype(auto) mat = as_derived();
for (std::size_t i = 0; i < etl::dim<0>(mat); ++i) {
mat(i).direct_deep_transpose_inplace();
}
static constexpr const std::size_t d = etl_traits<S>::dimensions();
using std::swap;
swap(mat.unsafe_dimension_access(d - 1), mat.unsafe_dimension_access(d - 2));
return mat;
}
/*!
* \brief Transpose each sub 2D matrix in place.
*/
template <typename S = D, cpp_enable_if(is_dyn_matrix<S>::value && (etl_traits<S>::dimensions() == 3))>
derived_t& deep_transpose_inplace() {
decltype(auto) mat = as_derived();
for (std::size_t i = 0; i < etl::dim<0>(mat); ++i) {
mat(i).direct_transpose_inplace();
}
static constexpr const std::size_t d = etl_traits<S>::dimensions();
using std::swap;
swap(mat.unsafe_dimension_access(d - 1), mat.unsafe_dimension_access(d - 2));
return mat;
}
/*!
* \brief Transpose each sub 2D matrix in place.
*/
template <typename S = D, cpp_enable_if(!is_dyn_matrix<S>::value && (etl_traits<S>::dimensions() > 3))>
derived_t& deep_transpose_inplace() {
decltype(auto) mat = as_derived();
for (std::size_t i = 0; i < etl::dim<0>(mat); ++i) {
mat(i).deep_transpose_inplace();
}
return mat;
}
/*!
* \brief Transpose each sub 2D matrix in place.
*/
template <typename S = D, cpp_enable_if(!is_dyn_matrix<S>::value && (etl_traits<S>::dimensions() == 3))>
derived_t& deep_transpose_inplace() {
decltype(auto) mat = as_derived();
for (std::size_t i = 0; i < etl::dim<0>(mat); ++i) {
mat(i).transpose_inplace();
}
return mat;
}
/*!
* \brief Transpose each sub 2D matrix in place.
*/
template <typename S = D, cpp_enable_if((etl_traits<S>::dimensions() > 3))>
derived_t& direct_deep_transpose_inplace() {
decltype(auto) mat = as_derived();
for (std::size_t i = 0; i < etl::dim<0>(mat); ++i) {
mat(i).direct_deep_transpose_inplace();
}
return mat;
}
/*!
* \brief Transpose each sub 2D matrix in place.
*/
template <typename S = D, cpp_enable_if((etl_traits<S>::dimensions() == 3))>
derived_t& direct_deep_transpose_inplace() {
decltype(auto) mat = as_derived();
for (std::size_t i = 0; i < etl::dim<0>(mat); ++i) {
mat(i).direct_transpose_inplace();
}
return mat;
}
/*!
* \brief Transpose the matrix in place.
*
* Only square fast matrix can be transpose in place, dyn matrix don't have any limitation.
*/
template <typename S = D, cpp_disable_if(is_dyn_matrix<S>::value)>
derived_t& transpose_inplace() {
static_assert(etl_traits<derived_t>::dimensions() == 2, "Only 2D matrix can be transposed");
cpp_assert(etl::dim<0>(as_derived()) == etl::dim<1>(as_derived()), "Only square fast matrices can be tranposed inplace");
detail::inplace_square_transpose<derived_t>::apply(as_derived());
return as_derived();
}
/*!
* \brief Transpose the matrix in place.
*
* Only square fast matrix can be transpose in place, dyn matrix don't have any limitation.
*/
template <typename S = D, cpp_enable_if(is_dyn_matrix<S>::value)>
derived_t& transpose_inplace() {
static_assert(etl_traits<derived_t>::dimensions() == 2, "Only 2D matrix can be transposed");
decltype(auto) mat = as_derived();
if (etl::dim<0>(mat) == etl::dim<1>(mat)) {
detail::inplace_square_transpose<derived_t>::apply(mat);
} else {
detail::inplace_rectangular_transpose<derived_t>::apply(mat);
using std::swap;
swap(mat.unsafe_dimension_access(0), mat.unsafe_dimension_access(1));
}
return mat;
}
/*!
* \brief Transpose the matrix in place.
*
* Only square fast matrix can be transpose in place, dyn matrix don't have any limitation.
*/
derived_t& direct_transpose_inplace() {
static_assert(etl_traits<derived_t>::dimensions() == 2, "Only 2D matrix can be transposed");
decltype(auto) mat = as_derived();
if (etl::dim<0>(mat) == etl::dim<1>(mat)) {
detail::inplace_square_transpose<derived_t>::apply(mat);
} else {
detail::inplace_rectangular_transpose<derived_t>::apply(mat);
}
return mat;
}
/*!
* \brief Perform inplace 1D FFT of the vector.
*/
derived_t& fft_inplace() {
static_assert(is_complex<derived_t>::value, "Only complex vector can use inplace FFT");
static_assert(etl_traits<derived_t>::dimensions() == 1, "Only vector can use fft_inplace, use fft2_inplace for matrices");
decltype(auto) mat = as_derived();
detail::fft1_impl<derived_t, derived_t>::apply(mat, mat);
mat.gpu_copy_from_if_necessary();
return mat;
}
/*!
* \brief Perform many inplace 1D FFT of the matrix.
*
* This function considers the first dimension as being batches of 1D FFT.
*/
derived_t& fft_many_inplace() {
static_assert(is_complex<derived_t>::value, "Only complex vector can use inplace FFT");
static_assert(etl_traits<derived_t>::dimensions() > 1, "Only matrix of dimensions > 1 can use fft_many_inplace");
decltype(auto) mat = as_derived();
detail::fft1_many_impl<derived_t, derived_t>::apply(mat, mat);
mat.gpu_copy_from_if_necessary();
return mat;
}
/*!
* \brief Perform inplace 1D Inverse FFT of the vector.
*/
derived_t& ifft_inplace() {
static_assert(is_complex<derived_t>::value, "Only complex vector can use inplace IFFT");
static_assert(etl_traits<derived_t>::dimensions() == 1, "Only vector can use ifft_inplace, use ifft2_inplace for matrices");
decltype(auto) mat = as_derived();
detail::ifft1_impl<derived_t, derived_t>::apply(mat, mat);
mat.gpu_copy_from_if_necessary();
return mat;
}
/*!
* \brief Perform inplace 2D FFT of the matrix.
*/
derived_t& fft2_inplace() {
static_assert(is_complex<derived_t>::value, "Only complex vector can use inplace FFT");
static_assert(etl_traits<derived_t>::dimensions() == 2, "Only matrix can use fft2_inplace, use fft_inplace for vectors");
decltype(auto) mat = as_derived();
detail::fft2_impl<derived_t, derived_t>::apply(mat, mat);
mat.gpu_copy_from_if_necessary();
return mat;
}
/*!
* \brief Perform many inplace 2D FFT of the matrix.
*
* This function considers the first dimension as being batches of 2D FFT.
*/
derived_t& fft2_many_inplace() {
static_assert(is_complex<derived_t>::value, "Only complex vector can use inplace FFT");
static_assert(etl_traits<derived_t>::dimensions() > 2, "Only matrix of dimensions > 2 can use fft2_many_inplace");
decltype(auto) mat = as_derived();
detail::fft2_many_impl<derived_t, derived_t>::apply(mat, mat);
mat.gpu_copy_from_if_necessary();
return mat;
}
/*!
* \brief Perform inplace 2D Inverse FFT of the matrix.
*/
derived_t& ifft2_inplace() {
static_assert(is_complex<derived_t>::value, "Only complex vector can use inplace IFFT");
static_assert(etl_traits<derived_t>::dimensions() == 2, "Only vector can use ifft_inplace, use ifft2_inplace for matrices");
decltype(auto) mat = as_derived();
detail::ifft2_impl<derived_t, derived_t>::apply(mat, mat);
mat.gpu_copy_from_if_necessary();
return mat;
}
};
} //end of namespace etl
<|endoftext|>
|
<commit_before>/*
* The MIT License (MIT)
*
* Copyright (c) 2015 Microsoft Corporation
*
* -=- Robust Distributed System Nucleus (rDSN) -=-
*
* 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.
*/
/*
* Description:
* Replication testing framework.
*
* Revision history:
* Nov., 2015, @qinzuoyan (Zuoyan Qin), first version
* xxxx-xx-xx, author, fix bug about xxx
*/
# include "checker.h"
# include "injector.h"
# include "case.h"
# include "client.h"
# include "simple_kv.server.impl.h"
# ifdef __TITLE__
# undef __TITLE__
# endif
# define __TITLE__ "simple_kv.main"
void dsn_app_registration()
{
// register services
dsn::register_app<dsn::replication::replication_service_app>("replica");
dsn::register_app<dsn::service::meta_service_app>("meta");
dsn::register_app<dsn::replication::test::simple_kv_client_app>("client");
dsn::register_app_with_type_1_replication_support< ::dsn::replication::test::simple_kv_service_impl>("simple_kv");
//dsn::replication::register_replica_provider<dsn::replication::test::simple_kv_service_impl>("simple_kv");
dsn::tools::register_toollet<dsn::replication::test::test_injector>("test_injector");
dsn::replication::test::install_checkers();
}
int main(int argc, char** argv)
{
if (argc != 3)
{
std::cerr << "USGAE: " << argv[0] << " <config-file> <case-input>" << std::endl;
std::cerr << " e.g.: " << argv[0] << " case-000.ini case-000.act" << std::endl;
return -1;
}
dsn::replication::test::g_case_input = argv[2];
dsn_app_registration();
// specify what services and tools will run in config file, then run
dsn_run(argc - 1, argv, false);
while (!dsn::replication::test::g_done)
{
std::this_thread::sleep_for(std::chrono::milliseconds(1));
}
ddebug("=== exiting ...");
dsn::replication::test::test_checker::instance().exit();
if (dsn::replication::test::g_fail)
{
#ifndef ENABLE_GCOV
dsn_exit(-1);
#endif
return -1;
}
#ifndef ENABLE_GCOV
dsn_exit(0);
#endif
return 0;
}
<commit_msg>register replica as frameworks instead of normal apps<commit_after>/*
* The MIT License (MIT)
*
* Copyright (c) 2015 Microsoft Corporation
*
* -=- Robust Distributed System Nucleus (rDSN) -=-
*
* 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.
*/
/*
* Description:
* Replication testing framework.
*
* Revision history:
* Nov., 2015, @qinzuoyan (Zuoyan Qin), first version
* xxxx-xx-xx, author, fix bug about xxx
*/
# include "checker.h"
# include "injector.h"
# include "case.h"
# include "client.h"
# include "simple_kv.server.impl.h"
# ifdef __TITLE__
# undef __TITLE__
# endif
# define __TITLE__ "simple_kv.main"
void dsn_app_registration()
{
// register services
dsn::register_layer2_framework< ::dsn::replication::replication_service_app>("replica", DSN_L2_REPLICATION_FRAMEWORK_TYPE_1);
dsn::register_app<dsn::service::meta_service_app>("meta");
dsn::register_app<dsn::replication::test::simple_kv_client_app>("client");
dsn::register_app_with_type_1_replication_support< ::dsn::replication::test::simple_kv_service_impl>("simple_kv");
//dsn::replication::register_replica_provider<dsn::replication::test::simple_kv_service_impl>("simple_kv");
dsn::tools::register_toollet<dsn::replication::test::test_injector>("test_injector");
dsn::replication::test::install_checkers();
}
int main(int argc, char** argv)
{
if (argc != 3)
{
std::cerr << "USGAE: " << argv[0] << " <config-file> <case-input>" << std::endl;
std::cerr << " e.g.: " << argv[0] << " case-000.ini case-000.act" << std::endl;
return -1;
}
dsn::replication::test::g_case_input = argv[2];
dsn_app_registration();
// specify what services and tools will run in config file, then run
dsn_run(argc - 1, argv, false);
while (!dsn::replication::test::g_done)
{
std::this_thread::sleep_for(std::chrono::milliseconds(1));
}
ddebug("=== exiting ...");
dsn::replication::test::test_checker::instance().exit();
if (dsn::replication::test::g_fail)
{
#ifndef ENABLE_GCOV
dsn_exit(-1);
#endif
return -1;
}
#ifndef ENABLE_GCOV
dsn_exit(0);
#endif
return 0;
}
<|endoftext|>
|
<commit_before>#ifndef _GRL_VREP_ROBOT_ARM_DRIVER_HPP_
#define _GRL_VREP_ROBOT_ARM_DRIVER_HPP_
#include <iostream>
#include <memory>
#include <array>
#include <boost/log/trivial.hpp>
#include <boost/exception/all.hpp>
#include <boost/algorithm/string.hpp>
#include "grl/vrep/Vrep.hpp"
#include "v_repLib.h"
namespace grl { namespace vrep {
class VrepRobotArmDriver : public std::enable_shared_from_this<VrepRobotArmDriver> {
public:
enum ParamIndex {
JointNames,
RobotTipName,
RobotTargetName,
RobotTargetBaseName,
RobotIkGroup
};
/// @todo allow default params
typedef std::tuple<
std::vector<std::string>,
std::string,
std::string,
std::string
> Params;
static const Params defaultParams()
{
std::vector<std::string> jointNames{
"LBR_iiwa_14_R820_joint1" , // Joint1Handle,
"LBR_iiwa_14_R820_joint2" , // Joint2Handle,
"LBR_iiwa_14_R820_joint3" , // Joint3Handle,
"LBR_iiwa_14_R820_joint4" , // Joint4Handle,
"LBR_iiwa_14_R820_joint5" , // Joint5Handle,
"LBR_iiwa_14_R820_joint6" , // Joint6Handle,
"LBR_iiwa_14_R820_joint7" // Joint7Handle,
};
return std::make_tuple(
jointNames , // JointNames
"RobotMillTip" , // RobotTipName,
"RobotMillTipTarget" , // RobotTargetName,
"Robotiiwa" // RobotTargetBaseName,
);
}
/// unique tag type so State never
/// conflicts with a similar tuple
struct JointStateTag{};
enum JointStateIndex {
JointPosition,
JointForce,
JointTargetPosition,
JointLowerPositionLimit,
JointUpperPositionLimit,
JointMatrix,
JointStateTagIndex
};
typedef std::vector<float> JointScalar;
/// @see http://www.coppeliarobotics.com/helpFiles/en/apiFunctions.htm#simGetJointMatrix for data layout information
typedef std::array<float,12> TransformationMatrix;
typedef std::vector<TransformationMatrix> TransformationMatrices;
typedef std::tuple<
JointScalar, // jointPosition
// JointScalar // JointVelocity // no velocity yet
JointScalar, // jointForce
JointScalar, // jointTargetPosition
JointScalar, // JointLowerPositionLimit
JointScalar, // JointUpperPositionLimit
TransformationMatrices, // jointTransformation
JointStateTag // JointStateTag unique identifying type so tuple doesn't conflict
> State;
VrepRobotArmDriver(Params params = defaultParams())
: params_(params)
{
}
/// @todo create a function that calls simGetObjectHandle and throws an exception when it fails
/// @todo throw an exception if any of the handles is -1
void construct() {
jointHandle.clear();
getHandleFromParam<JointNames>(params_,std::back_inserter(jointHandle)); //Obtain Joint Handles
robotTip = getHandleFromParam<RobotTipName> (params_); //Obtain RobotTip handle
target = getHandleFromParam<RobotTargetName> (params_);
targetBase = getHandleFromParam<RobotTargetBaseName> (params_);
allHandlesSet = true;
}
/// @return 0 if ok 1 if problem
/// @todo handle cyclic joints (see isCyclic below & simGetJointInterval)
bool getState(State& state){
if(!allHandlesSet) return false;
std::get<JointPosition> (state).resize(jointHandle.size());
std::get<JointForce> (state).resize(jointHandle.size());
std::get<JointTargetPosition>(state).resize(jointHandle.size());
std::get<JointMatrix> (state).resize(jointHandle.size());
enum limit {
lower
,upper
,numLimits
};
simBool isCyclic;
float jointAngleInterval[2]; // min,max
for (int i=0 ; i < jointHandle.size() ; i++)
{
int currentJointHandle = jointHandle[i];
simGetJointPosition(currentJointHandle,&std::get<JointPosition>(state)[i]); //retrieves the intrinsic position of a joint (Angle for revolute joint)
simGetJointForce(currentJointHandle,&std::get<JointForce>(state)[i]); //retrieves the force or torque applied to a joint along/about its active axis. This function retrieves meaningful information only if the joint is prismatic or revolute, and is dynamically enabled.
simGetJointTargetPosition(currentJointHandle,&std::get<JointTargetPosition>(state)[i]); //retrieves the target position of a joint
simGetJointMatrix(currentJointHandle,&std::get<JointMatrix>(state)[i][0]); //retrieves the intrinsic transformation matrix of a joint (the transformation caused by the joint movement)
simGetJointInterval(currentJointHandle,&isCyclic,jointAngleInterval);
std::get<JointLowerPositionLimit>(state)[i] = jointAngleInterval[lower];
std::get<JointUpperPositionLimit>(state)[i] = jointAngleInterval[upper];
}
// BOOST_LOG_TRIVIAL(info) << "simJointPostition = " << simJointPosition << std::endl;
// BOOST_LOG_TRIVIAL(info) << "simJointForce = " << simJointForce << std::endl;
// BOOST_LOG_TRIVIAL(info) << "simJointTargetPostition = " << simJointTargetPosition << std::endl;
// BOOST_LOG_TRIVIAL(info) << "simJointTransformationMatrix = " << simJointTransformationMatrix << std::endl;
//
// float simTipPosition[3];
// float simTipOrientation[3];
//
// simGetObjectPosition(target, targetBase, simTipPosition);
// simGetObjectOrientation(target, targetBase, simTipOrientation);
//
// for (int i = 0 ; i < 3 ; i++)
// {
// BOOST_LOG_TRIVIAL(info) << "simTipPosition[" << i << "] = " << simTipPosition[i] << std::endl;
// BOOST_LOG_TRIVIAL(info) << "simTipOrientation[" << i << "] = " << simTipOrientation[i] << std::endl;
//
// }
// Send updated position to the real arm based on simulation
return false;
}
bool setState(State& state) {
// Step 1
////////////////////////////////////////////////////
// call the functions here and just print joint angles out
// or display something on the screens
///////////////////
// call our object to get the latest real kuka state
// then use the functions below to set the simulation state
// to match
/////////////////// assuming given real joint position (angles), forces, target position and target velocity
// setting the simulation variables to data from real robot (here they have been assumed given)
for (int i=0 ; i < 7 ; i++)
{
//simSetJointPosition(jointHandle[i],realJointPosition[i]); //Sets the intrinsic position of a joint. May have no effect depending on the joint mode
//simSetJointTargetPosition(jointHandle[i],realJointTargetPosition[i]); //Sets the target position of a joint if the joint is in torque/force mode (also make sure that the joint's motor and position control are enabled
//simSetJointForce(jointHandle[i],realJointForce[i]); //Sets the maximum force or torque that a joint can exert. This function has no effect when the joint is not dynamically enabled
//simSetJointTargetVelocity(jointHandle[i],realJointTargetVelocity[i]); //Sets the intrinsic target velocity of a non-spherical joint. This command makes only sense when the joint mode is: (a) motion mode: the joint's motion handling feature must be enabled (simHandleJoint must be called (is called by default in the main script), and the joint motion properties must be set in the joint settings dialog), (b) torque/force mode: the dynamics functionality and the joint motor have to be enabled (position control should however be disabled)
}
return true;
}
const std::vector<int>& getJointHandles()
{
return jointHandle;
}
private:
Params params_;
std::vector<int> jointHandle = {}; // {-1,-1,-1,-1,-1,-1,-1}; //global variables defined
int robotTip = -1; //Obtain RobotTip handle
int target = -1;
int targetBase = -1;
volatile bool allHandlesSet = false;
};
}} // grl::vrep
#endif // _GRL_VREP_ROBOT_ARM_DRIVER_HPP_<commit_msg>VrepRobotArmDriver.hpp now stores handles in a tuple just like string params.<commit_after>#ifndef _GRL_VREP_ROBOT_ARM_DRIVER_HPP_
#define _GRL_VREP_ROBOT_ARM_DRIVER_HPP_
#include <iostream>
#include <memory>
#include <array>
#include <boost/log/trivial.hpp>
#include <boost/exception/all.hpp>
#include <boost/algorithm/string.hpp>
#include "grl/vrep/Vrep.hpp"
#include "v_repLib.h"
namespace grl { namespace vrep {
class VrepRobotArmDriver : public std::enable_shared_from_this<VrepRobotArmDriver> {
public:
enum ParamIndex {
JointNames,
RobotTipName,
RobotTargetName,
RobotTargetBaseName,
RobotIkGroup
};
/// @todo allow default params
typedef std::tuple<
std::vector<std::string>,
std::string,
std::string,
std::string
> Params;
typedef std::tuple<
std::vector<int>,
int,
int,
int
> VrepHandleParams;
static const Params defaultParams()
{
std::vector<std::string> jointNames{
"LBR_iiwa_14_R820_joint1" , // Joint1Handle,
"LBR_iiwa_14_R820_joint2" , // Joint2Handle,
"LBR_iiwa_14_R820_joint3" , // Joint3Handle,
"LBR_iiwa_14_R820_joint4" , // Joint4Handle,
"LBR_iiwa_14_R820_joint5" , // Joint5Handle,
"LBR_iiwa_14_R820_joint6" , // Joint6Handle,
"LBR_iiwa_14_R820_joint7" // Joint7Handle,
};
return std::make_tuple(
jointNames , // JointNames
"RobotMillTip" , // RobotTipName,
"RobotMillTipTarget" , // RobotTargetName,
"Robotiiwa" // RobotTargetBaseName,
);
}
/// unique tag type so State never
/// conflicts with a similar tuple
struct JointStateTag{};
enum JointStateIndex {
JointPosition,
JointForce,
JointTargetPosition,
JointLowerPositionLimit,
JointUpperPositionLimit,
JointMatrix,
JointStateTagIndex
};
typedef std::vector<float> JointScalar;
/// @see http://www.coppeliarobotics.com/helpFiles/en/apiFunctions.htm#simGetJointMatrix for data layout information
typedef std::array<float,12> TransformationMatrix;
typedef std::vector<TransformationMatrix> TransformationMatrices;
typedef std::tuple<
JointScalar, // jointPosition
// JointScalar // JointVelocity // no velocity yet
JointScalar, // jointForce
JointScalar, // jointTargetPosition
JointScalar, // JointLowerPositionLimit
JointScalar, // JointUpperPositionLimit
TransformationMatrices, // jointTransformation
JointStateTag // JointStateTag unique identifying type so tuple doesn't conflict
> State;
VrepRobotArmDriver(Params params = defaultParams())
: params_(params)
{
}
/// @todo create a function that calls simGetObjectHandle and throws an exception when it fails
/// @todo throw an exception if any of the handles is -1
void construct() {
std::vector<int> jointHandle;
getHandleFromParam<JointNames>(params_,std::back_inserter(jointHandle));
handleParams_ =
std::make_tuple(
std::move(jointHandle) //Obtain Joint Handles
,getHandleFromParam<RobotTipName> (params_) //Obtain RobotTip handle
,getHandleFromParam<RobotTargetName> (params_)
,getHandleFromParam<RobotTargetBaseName> (params_)
);
allHandlesSet = true;
}
/// @return 0 if ok 1 if problem
/// @todo handle cyclic joints (see isCyclic below & simGetJointInterval)
bool getState(State& state){
if(!allHandlesSet) return false;
const std::vector<int>& jointHandle = std::get<JointNames>(handleParams_);
std::get<JointPosition> (state).resize(jointHandle.size());
std::get<JointForce> (state).resize(jointHandle.size());
std::get<JointTargetPosition> (state).resize(jointHandle.size());
std::get<JointMatrix> (state).resize(jointHandle.size());
std::get<JointLowerPositionLimit> (state).resize(jointHandle.size());
std::get<JointUpperPositionLimit> (state).resize(jointHandle.size());
enum limit {
lower
,upper
,numLimits
};
simBool isCyclic;
float jointAngleInterval[2]; // min,max
for (int i=0 ; i < jointHandle.size() ; i++)
{
int currentJointHandle = jointHandle[i];
simGetJointPosition(currentJointHandle,&std::get<JointPosition>(state)[i]); //retrieves the intrinsic position of a joint (Angle for revolute joint)
simGetJointForce(currentJointHandle,&std::get<JointForce>(state)[i]); //retrieves the force or torque applied to a joint along/about its active axis. This function retrieves meaningful information only if the joint is prismatic or revolute, and is dynamically enabled.
simGetJointTargetPosition(currentJointHandle,&std::get<JointTargetPosition>(state)[i]); //retrieves the target position of a joint
simGetJointMatrix(currentJointHandle,&std::get<JointMatrix>(state)[i][0]); //retrieves the intrinsic transformation matrix of a joint (the transformation caused by the joint movement)
simGetJointInterval(currentJointHandle,&isCyclic,jointAngleInterval);
std::get<JointLowerPositionLimit>(state)[i] = jointAngleInterval[lower];
std::get<JointUpperPositionLimit>(state)[i] = jointAngleInterval[upper];
}
// BOOST_LOG_TRIVIAL(info) << "simJointPostition = " << simJointPosition << std::endl;
// BOOST_LOG_TRIVIAL(info) << "simJointForce = " << simJointForce << std::endl;
// BOOST_LOG_TRIVIAL(info) << "simJointTargetPostition = " << simJointTargetPosition << std::endl;
// BOOST_LOG_TRIVIAL(info) << "simJointTransformationMatrix = " << simJointTransformationMatrix << std::endl;
//
// float simTipPosition[3];
// float simTipOrientation[3];
//
// simGetObjectPosition(target, targetBase, simTipPosition);
// simGetObjectOrientation(target, targetBase, simTipOrientation);
//
// for (int i = 0 ; i < 3 ; i++)
// {
// BOOST_LOG_TRIVIAL(info) << "simTipPosition[" << i << "] = " << simTipPosition[i] << std::endl;
// BOOST_LOG_TRIVIAL(info) << "simTipOrientation[" << i << "] = " << simTipOrientation[i] << std::endl;
//
// }
// Send updated position to the real arm based on simulation
return false;
}
bool setState(State& state) {
// Step 1
////////////////////////////////////////////////////
// call the functions here and just print joint angles out
// or display something on the screens
///////////////////
// call our object to get the latest real kuka state
// then use the functions below to set the simulation state
// to match
/////////////////// assuming given real joint position (angles), forces, target position and target velocity
// setting the simulation variables to data from real robot (here they have been assumed given)
for (int i=0 ; i < 7 ; i++)
{
//simSetJointPosition(jointHandle[i],realJointPosition[i]); //Sets the intrinsic position of a joint. May have no effect depending on the joint mode
//simSetJointTargetPosition(jointHandle[i],realJointTargetPosition[i]); //Sets the target position of a joint if the joint is in torque/force mode (also make sure that the joint's motor and position control are enabled
//simSetJointForce(jointHandle[i],realJointForce[i]); //Sets the maximum force or torque that a joint can exert. This function has no effect when the joint is not dynamically enabled
//simSetJointTargetVelocity(jointHandle[i],realJointTargetVelocity[i]); //Sets the intrinsic target velocity of a non-spherical joint. This command makes only sense when the joint mode is: (a) motion mode: the joint's motion handling feature must be enabled (simHandleJoint must be called (is called by default in the main script), and the joint motion properties must be set in the joint settings dialog), (b) torque/force mode: the dynamics functionality and the joint motor have to be enabled (position control should however be disabled)
}
return true;
}
/// @todo deal with !allHandlesSet()
const std::vector<int>& getJointHandles()
{
return std::get<JointNames>(handleParams_);
}
const Params & getParams(){
return params_;
}
const VrepHandleParams & getVrepHandleParams(){
return handleParams_;
}
private:
Params params_;
VrepHandleParams handleParams_;
volatile bool allHandlesSet = false;
};
}} // grl::vrep
#endif // _GRL_VREP_ROBOT_ARM_DRIVER_HPP_<|endoftext|>
|
<commit_before>/*****************************************************************************
*
* This file is part of Mapnik (c++ mapping toolkit)
*
* Copyright (C) 2016 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_TRANSFORM_EXPRESSION_HPP
#define MAPNIK_TRANSFORM_EXPRESSION_HPP
// mapnik
#include <mapnik/config.hpp>
#include <mapnik/attribute.hpp>
#include <mapnik/value/types.hpp>
#include <mapnik/expression_node_types.hpp>
#include <mapnik/expression_node.hpp>
#include <mapnik/util/variant.hpp>
#pragma GCC diagnostic push
#include <mapnik/warning_ignore.hpp>
#include <boost/optional.hpp>
#include <boost/fusion/include/at.hpp>
#include <boost/fusion/include/vector.hpp>
#pragma GCC diagnostic pop
//
#include <boost/utility/value_init.hpp>
// stl
#include <vector>
#include <memory>
namespace mapnik {
struct identity_node {};
struct matrix_node
{
expr_node a_;
expr_node b_;
expr_node c_;
expr_node d_;
expr_node e_;
expr_node f_;
matrix_node() = default;
template <typename T>
explicit matrix_node(T const& m)
: a_(m.sx), b_(m.shy), c_(m.shx), d_(m.sy), e_(m.tx), f_(m.ty) {}
matrix_node(expr_node const& a, expr_node const& b, expr_node const& c,
expr_node const& d, expr_node const& e, expr_node const& f)
: a_(a), b_(b), c_(c), d_(d), e_(e), f_(f) {}
};
struct translate_node
{
expr_node tx_;
expr_node ty_;
translate_node() = default;
translate_node(expr_node const& tx,
boost::optional<expr_node> const& ty)
: tx_(tx)
, ty_(ty ? expr_node(*ty) : value_null()) {}
};
struct scale_node
{
expr_node sx_;
expr_node sy_;
scale_node() = default;
scale_node(expr_node const& sx,
boost::optional<expr_node> const& sy)
: sx_(sx)
, sy_(sy ? expr_node(*sy) : value_null()) {}
};
struct rotate_node
{
using coords_type = boost::fusion::vector2<expr_node, expr_node>;
expr_node angle_;
expr_node cx_;
expr_node cy_;
rotate_node() = default;
explicit rotate_node(expr_node const& angle)
: angle_(angle) {}
rotate_node(expr_node const& angle,
expr_node const& cx, expr_node const& cy)
: angle_(angle), cx_(cx), cy_(cy) {}
rotate_node(expr_node const& angle,
boost::optional<expr_node> const& cx,
boost::optional<expr_node> const& cy)
: angle_(angle)
, cx_(cx ? expr_node(*cx) : value_null())
, cy_(cy ? expr_node(*cy) : value_null()) {}
rotate_node(expr_node const& angle,
boost::optional<coords_type> const& center)
: angle_(angle)
{
if (center)
{
cx_ = boost::fusion::at_c<0>(*center);
cy_ = boost::fusion::at_c<1>(*center);
}
}
};
struct skewX_node
{
expr_node angle_;
skewX_node() = default;
skewX_node(expr_node const& angle)
: angle_(angle) {}
};
struct skewY_node
{
expr_node angle_;
skewY_node() = default;
skewY_node(expr_node const& angle)
: angle_(angle) {}
};
namespace detail {
// boost::spirit::traits::clear<T>(T& val) [with T = boost::variant<...>]
// attempts to assign to the variant's current value a default-constructed
// value of the same type, which not only requires that each value-type is
// default-constructible, but also makes little sense with our variant of
// transform nodes...
using transform_variant = mapnik::util::variant< identity_node,
matrix_node,
translate_node,
scale_node,
rotate_node,
skewX_node,
skewY_node >;
// ... thus we wrap the variant-type in a distinct type and provide
// a custom clear overload, which resets the value to identity_node
struct transform_node
{
transform_variant base_;
transform_node()
: base_() {}
template <typename T>
transform_node(boost::value_initialized<T> const&)
: base_() {}
template <typename T>
transform_node(T const& val)
: base_(val) {}
template <typename T>
transform_node& operator= (T const& val)
{
base_ = val;
return *this;
}
transform_variant const& operator* () const
{
return base_;
}
transform_variant& operator* ()
{
return base_;
}
};
inline void clear(transform_node& val)
{
val.base_ = identity_node();
}
namespace {
struct is_null_transform_node
{
bool operator() (value const& val) const
{
return val.is_null();
}
bool operator() (value_null const&) const
{
return true;
}
template <typename T>
bool operator() (T const&) const
{
return false;
}
bool operator() (detail::transform_variant const& var) const
{
return util::apply_visitor(*this, var);
}
};
}
template <typename T>
bool is_null_node (T const& node)
{
return util::apply_visitor(is_null_transform_node(), node);
}
} // namespace detail
using transform_node = detail::transform_node;
using transform_list = std::vector<transform_node>;
using transform_list_ptr = std::shared_ptr<transform_list>;
MAPNIK_DECL std::string to_expression_string(transform_node const& node);
MAPNIK_DECL std::string to_expression_string(transform_list const& list);
} // namespace mapnik
#endif // MAPNIK_TRANSFORM_EXPRESSION_HPP
<commit_msg>Revert "add ```template <typename T>" - oops we don't need this in master!<commit_after>/*****************************************************************************
*
* This file is part of Mapnik (c++ mapping toolkit)
*
* Copyright (C) 2016 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_TRANSFORM_EXPRESSION_HPP
#define MAPNIK_TRANSFORM_EXPRESSION_HPP
// mapnik
#include <mapnik/config.hpp>
#include <mapnik/attribute.hpp>
#include <mapnik/value/types.hpp>
#include <mapnik/expression_node_types.hpp>
#include <mapnik/expression_node.hpp>
#include <mapnik/util/variant.hpp>
#pragma GCC diagnostic push
#include <mapnik/warning_ignore.hpp>
#include <boost/optional.hpp>
#include <boost/fusion/include/at.hpp>
#include <boost/fusion/include/vector.hpp>
#pragma GCC diagnostic pop
// stl
#include <vector>
#include <memory>
namespace mapnik {
struct identity_node {};
struct matrix_node
{
expr_node a_;
expr_node b_;
expr_node c_;
expr_node d_;
expr_node e_;
expr_node f_;
matrix_node() = default;
template <typename T>
explicit matrix_node(T const& m)
: a_(m.sx), b_(m.shy), c_(m.shx), d_(m.sy), e_(m.tx), f_(m.ty) {}
matrix_node(expr_node const& a, expr_node const& b, expr_node const& c,
expr_node const& d, expr_node const& e, expr_node const& f)
: a_(a), b_(b), c_(c), d_(d), e_(e), f_(f) {}
};
struct translate_node
{
expr_node tx_;
expr_node ty_;
translate_node() = default;
translate_node(expr_node const& tx,
boost::optional<expr_node> const& ty)
: tx_(tx)
, ty_(ty ? expr_node(*ty) : value_null()) {}
};
struct scale_node
{
expr_node sx_;
expr_node sy_;
scale_node() = default;
scale_node(expr_node const& sx,
boost::optional<expr_node> const& sy)
: sx_(sx)
, sy_(sy ? expr_node(*sy) : value_null()) {}
};
struct rotate_node
{
using coords_type = boost::fusion::vector2<expr_node, expr_node>;
expr_node angle_;
expr_node cx_;
expr_node cy_;
rotate_node() = default;
explicit rotate_node(expr_node const& angle)
: angle_(angle) {}
rotate_node(expr_node const& angle,
expr_node const& cx, expr_node const& cy)
: angle_(angle), cx_(cx), cy_(cy) {}
rotate_node(expr_node const& angle,
boost::optional<expr_node> const& cx,
boost::optional<expr_node> const& cy)
: angle_(angle)
, cx_(cx ? expr_node(*cx) : value_null())
, cy_(cy ? expr_node(*cy) : value_null()) {}
rotate_node(expr_node const& angle,
boost::optional<coords_type> const& center)
: angle_(angle)
{
if (center)
{
cx_ = boost::fusion::at_c<0>(*center);
cy_ = boost::fusion::at_c<1>(*center);
}
}
};
struct skewX_node
{
expr_node angle_;
skewX_node() = default;
skewX_node(expr_node const& angle)
: angle_(angle) {}
};
struct skewY_node
{
expr_node angle_;
skewY_node() = default;
skewY_node(expr_node const& angle)
: angle_(angle) {}
};
namespace detail {
// boost::spirit::traits::clear<T>(T& val) [with T = boost::variant<...>]
// attempts to assign to the variant's current value a default-constructed
// value of the same type, which not only requires that each value-type is
// default-constructible, but also makes little sense with our variant of
// transform nodes...
using transform_variant = mapnik::util::variant< identity_node,
matrix_node,
translate_node,
scale_node,
rotate_node,
skewX_node,
skewY_node >;
// ... thus we wrap the variant-type in a distinct type and provide
// a custom clear overload, which resets the value to identity_node
struct transform_node
{
transform_variant base_;
transform_node()
: base_() {}
template <typename T>
transform_node(T const& val)
: base_(val) {}
template <typename T>
transform_node& operator= (T const& val)
{
base_ = val;
return *this;
}
transform_variant const& operator* () const
{
return base_;
}
transform_variant& operator* ()
{
return base_;
}
};
inline void clear(transform_node& val)
{
val.base_ = identity_node();
}
namespace {
struct is_null_transform_node
{
bool operator() (value const& val) const
{
return val.is_null();
}
bool operator() (value_null const&) const
{
return true;
}
template <typename T>
bool operator() (T const&) const
{
return false;
}
bool operator() (detail::transform_variant const& var) const
{
return util::apply_visitor(*this, var);
}
};
}
template <typename T>
bool is_null_node (T const& node)
{
return util::apply_visitor(is_null_transform_node(), node);
}
} // namespace detail
using transform_node = detail::transform_node;
using transform_list = std::vector<transform_node>;
using transform_list_ptr = std::shared_ptr<transform_list>;
MAPNIK_DECL std::string to_expression_string(transform_node const& node);
MAPNIK_DECL std::string to_expression_string(transform_list const& list);
} // namespace mapnik
#endif // MAPNIK_TRANSFORM_EXPRESSION_HPP
<|endoftext|>
|
<commit_before>/*
1. Treat each edge id as a cluster, unordered map from edgeId to a set
2. also store size of each cluster which will 0 in the begining
// $ g++ -std=c++0x -O3 -o calcDensityForDiffThresh calcDensityForDiffThresh.cpp
// $ ./calcDensityForDiffThresh networkEdgeIdMap.csv network.jaccs sortedjaccs.csv Nthresholds threshDensity.csv
*/
#include <math.h>
#include <ctime>
#include <cstdlib>
#include <fstream>
#include <iostream>
#include <unordered_map>
#include <set>
#include <map>
#include <utility> // for pairs
#include <algorithm> // for swap
using namespace std;
int main (int argc, char const *argv[]){
//************* make sure args are present:
if (argc != 6){
cout << "ERROR: something wrong with the inputs" << endl;
cout << "usage:\n " << argv[0] << " networkEdgeIdMap.csv network.jaccs sortedjaccs.csv "
<< " Nthresholds threshDensity.csv" << endl;
exit(1);
}
// Nthresholds is the total thresholds user wants us to try
int nThresh = atoi(argv[4]);
int gapBetweenthresh = 0;
float threshold = 0;
float D = 0.0;
int mc, nc;
int M = 0, Mns = 0;
double wSum = 0.0;
float highestD=0.0;
float highestDThr = 0.0;
//************* got the args
clock_t begin = clock();
//************* start load edgelist
ifstream inFile;
inFile.open( argv[1] );
if (!inFile) {
cout << "ERROR: unable to open input file" << endl;
exit(1); // terminate with error
}
// store edge ids in a map
// each edge id will be a cluster of it's own in the begining
// each cluster will be og size 1
unordered_map< int, pair<int,int> > idEdgePairMap;
unordered_map< int, set<int > > index2cluster; // O(log n) access too slow?
unordered_map< int, unordered_map< int, set<int > >::iterator > edge2iter;
int ni, nj, edgeId, index = 0;
while (inFile >> ni >> nj >> edgeId){
idEdgePairMap[ edgeId ] = make_pair(ni,nj);
index2cluster[ index ].insert(edgeId); // build cluster index to set of edge-pairs map
edge2iter[edgeId] = index2cluster.find(index);
index++;
}
inFile.close(); inFile.clear();
cout << "There were " << index2cluster.size() << " edges." << endl;
/// end reading edge ids -----
//----- ----- ----- -----
ifstream sortedjaccFile;
sortedjaccFile.open( argv[3] );
if (!sortedjaccFile) {
cout << "ERROR: unable to open sortedjaccFile file" << endl;
exit(1); // terminate with error
}
int totalThresh = 0;
int edgeId1,edgeId2;
float jacc;
// Count totalines in the file, we are setting
while ( sortedjaccFile >> jacc ) {
if(jacc>0 && jacc<=1.0)
totalThresh++;
}
sortedjaccFile.close(); sortedjaccFile.clear();
cout << "Done counting totalines in the file, \nTotal unique Jaccs = " << totalThresh << endl;
if(totalThresh==0){
cout << "ERROR: there are 0 Jaccs!!!" << endl;
exit(1); // terminate with error
}
// now we want gap between two consecutive thresholds
// we want to consider
gapBetweenthresh = totalThresh/nThresh;
if(totalThresh < nThresh)
gapBetweenthresh = totalThresh;
set<float> thresholdSet;
set<float> ::reverse_iterator thIt;
// ----------------------------
totalThresh = -1;
sortedjaccFile.open( argv[3] );
while ( sortedjaccFile >> jacc ){
totalThresh++;
if(totalThresh%gapBetweenthresh!=0){
continue;
}
thresholdSet.insert(jacc);
}
sortedjaccFile.close(); sortedjaccFile.clear();
thresholdSet.insert(1.1);
cout << "Done with thresholdSet creation." << endl;
// ---------------------------
ifstream jaccFile;
jaccFile.open(argv[2]);
// read first line
jaccFile >> edgeId1 >> edgeId2 >> jacc ;
// open the outputfile
unordered_map< int, set< int> >::iterator iter_i,iter_j;
set<int>::iterator iterS;
FILE * threshDensityFile = fopen( argv[5], "w" );
fclose(threshDensityFile);
fprintf( threshDensityFile, "thresh D\n" );
long long done = 0;
float percDone = 0.01;
clock_t lastBegin = clock();
for(thIt = thresholdSet.rbegin(); thIt!=thresholdSet.rend(); thIt++){
threshold = *thIt;
if (threshold < 0.0 || threshold > 1.1){
cout << "ERROR: specified threshold not in [0,1]" << endl;
exit(1);
}
do{
if( jacc < threshold )
break;
iter_i = edge2iter[ edgeId1 ];
iter_j = edge2iter[ edgeId2 ];
if ( iter_i != iter_j ) {
// always merge smaller cluster into bigger:
if ( (*iter_j).second.size() > (*iter_i).second.size() ){ // !!!!!!
swap(iter_i, iter_j);
}
// merge cluster j into i and update index for all elements in j:
for (iterS = iter_j->second.begin(); iterS != iter_j->second.end(); iterS++){
iter_i->second.insert( *iterS );
edge2iter[ *iterS ] = iter_i;
}
// delete cluster j:
index2cluster.erase(iter_j);
}
}while ( jaccFile >> edgeId1 >> edgeId2 >> jacc );
// all done clustering, write to file (and calculated partition density):
M = 0, Mns = 0;
wSum = 0.0;
set< int >::iterator S;
set<int> clusterNodes;
unordered_map< int, set< int > >::iterator it;
for ( it = index2cluster.begin(); it != index2cluster.end(); it++ ) {
clusterNodes.clear();
for (S = it->second.begin(); S != it->second.end(); S++ ){
//fprintf( clustersFile, "%i ", *S ); // this leaves a trailing space...!
clusterNodes.insert(idEdgePairMap[*S].first);
clusterNodes.insert(idEdgePairMap[*S].second);
}
mc = it->second.size();
nc = clusterNodes.size();
M += mc;
if (nc > 2) {
Mns += mc;
wSum += mc * (mc - (nc-1.0)) / ((nc-2.0)*(nc-1.0));
}
}
threshDensityFile = fopen( argv[5], "a" );
D = 2.0 * wSum / M;
if (isinf(D)){
fprintf( threshDensityFile, "\nERROR: D == -inf \n\n");
fclose(threshDensityFile);
exit(1);
}
//*************
fprintf( threshDensityFile, "%.6f %.6f \n", threshold, D);
fclose(threshDensityFile);
if(D > highestD){
highestD = D;
highestDThr = threshold;
}
done++;
if((float)done/(float)thresholdSet.size() >= percDone){
cout << percDone*100 << " pc done.\n" << endl;
percDone += 0.01;
}
cout << "Time taken = " << double(clock() - lastBegin)/ CLOCKS_PER_SEC << " seconds. "<< endl;
lastBegin = clock();
}
jaccFile.close(); jaccFile.clear();
fprintf( threshDensityFile, "\n highest D=%.6f at thresh:%.6f.\n", highestD, highestDThr);
fclose(threshDensityFile);
cout << "Time taken = " << double(clock() - begin)/ CLOCKS_PER_SEC << " seconds. "<< endl;
return 0;
}
<commit_msg>Update createSortedJaccsFile.cpp<commit_after>/*
// $ g++ -O3 -o createSortedJaccsFile createSortedJaccsFile.cpp
// $ ./createSortedJaccsFile network.jaccs newSortedNewtwork.jaccs sortedJaccs.csv
*/
#include <math.h>
#include <ctime>
#include <cstdlib>
#include <fstream>
#include <iostream>
#include <set>
#include <map>
#include <utility> // for pairs
#include <algorithm> // for swap
#define MIN_DIFF_BW_JACCS 0.0001
using namespace std;
int main (int argc, char const *argv[]){
//************* make sure args are present:
if (argc != 4){
cout << "ERROR: something wrong with the inputs" << endl;
cout << "usage:\n " << argv[0] << " network.jaccs newSortedNewtwork.jaccs sortedJaccs.csv" << endl;
exit(1);
}
//************* got the args
clock_t begin = clock();
ifstream jaccFile;
jaccFile.open( argv[1] );
if (!jaccFile) {
cout << "ERROR: unable to open jaccards file" << endl;
exit(1); // terminate with error
}
set<pair<float, pair<int, int> > > jaccsEdgeEdgeSet;
int edgeId1,edgeId2;
float jacc;
set<float> thresholdSet;
// read each line from the jacc file
while ( jaccFile >> edgeId1 >> edgeId2 >> jacc ) {
// if this value of jacc does exists
// then add inser the value
jaccsEdgeEdgeSet.insert(make_pair(jacc, make_pair(edgeId1, edgeId2)));
if(thresholdSet.count(jacc) == 0)
thresholdSet.insert(jacc);
}
jaccFile.close();jaccFile.clear();
cout << "Done with thresholdSet creation. total unique jaccs:" << thresholdSet.size() << endl;
// create the file
// if exists then overwrite everything
FILE * sortedJaccsFile = fopen( argv[3], "w" );
set<float> ::reverse_iterator thIt;
for(thIt = thresholdSet.rbegin(); thIt!=thresholdSet.rend(); thIt++){
jacc = *thIt;
// open the file
fprintf( sortedJaccsFile, "%.6f \n", jacc);
}
fclose(sortedJaccsFile);
thresholdSet.clear();
cout << "Done writing unique jaccs! ";
clock_t end1 = clock();
cout << "Time taken = " << double(end1 - begin)/ CLOCKS_PER_SEC << " seconds. "<< endl;
//------------------------
// Create a file with sorted in on-increasing order jaccs with:
// < edgeId edgeId jaccs > on each line
long long done = 0;
float percDone = 0.01;
FILE * sortedNewNWJaccsFile = fopen( argv[2], "w" );
set<pair<float, pair<int, int> > >::reverse_iterator jaccsEdgeEdgeSetIt;
for(jaccsEdgeEdgeSetIt = jaccsEdgeEdgeSet.rbegin();
jaccsEdgeEdgeSetIt!=jaccsEdgeEdgeSet.rend(); jaccsEdgeEdgeSetIt++){
jacc = (*jaccsEdgeEdgeSetIt).first;
edgeId1 = (*jaccsEdgeEdgeSetIt).second.first;
edgeId2 = (*jaccsEdgeEdgeSetIt).second.second;
// open the file
fprintf( sortedNewNWJaccsFile, "%lld %lld %.6f\n", edgeId1, edgeId2, jacc);
done++;
if((float)done/(float)jaccsEdgeEdgeSet.size() >= percDone){
cout << percDone*100 << " pc done.\n" << endl;
percDone += 0.01;
}
}
fclose(sortedNewNWJaccsFile);
jaccsEdgeEdgeSet.clear();
cout << "Done writing sorted New NW JaccsFile! ";
cout << "Time taken = " << double(clock() - end1)/ CLOCKS_PER_SEC << " seconds. "<< endl;
cout << "Total Time taken = " << double(clock() - begin)/ CLOCKS_PER_SEC << " seconds. "<< endl;
return 0;
}
<|endoftext|>
|
<commit_before>#pragma once
#include <memory>
#include "VectorIndexer.hpp"
namespace Rendering
{
namespace Manager
{
template <typename BufferType>
class BufferPool final
{
public:
BufferPool() = default;
DISALLOW_ASSIGN_COPY(BufferPool<BufferType>);
void Add(const std::string& file, const std::string& key, const BufferType& bufferData)
{
_buffers.Add(file + ":" + key, bufferData);
}
//auto Find(const std::string& file, const std::string& key)
//{
// std::string findKey = file + ":" + key;
// return _buffers.Find(findKey);
//}
bool Has(const std::string& file, const std::string& key) const
{
return _buffers.GetIndexer().Has(file + ":" + key);
}
void DeleteBuffer(const std::string& file, const std::string& key)
{
uint findIndex = _buffers.GetIndexer().Find(file + ":" + key);
if (findIndex != decltype(_buffers.GetIndexer())::FailIndex())
_buffers.Delete(findIndex);
}
void Destroy()
{
_buffers.DeleteAll();
}
private:
Core::VectorMap<std::string, BufferType> _buffers;
};
}
}<commit_msg>BufferPool - Find 추가<commit_after>#pragma once
#include <memory>
#include "VectorIndexer.hpp"
namespace Rendering
{
namespace Manager
{
template <typename BufferType>
class BufferPool final
{
public:
BufferPool() = default;
DISALLOW_ASSIGN_COPY(BufferPool<BufferType>);
void Add(const std::string& file, const std::string& key, const BufferType& bufferData)
{
_buffers.Add(file + ":" + key, bufferData);
}
auto Find(const std::string& file, const std::string& key)
{
std::string findKey = file + ":" + key;
return _buffers.Find(findKey);
}
bool Has(const std::string& file, const std::string& key) const
{
return _buffers.GetIndexer().Has(file + ":" + key);
}
void DeleteBuffer(const std::string& file, const std::string& key)
{
uint findIndex = _buffers.GetIndexer().Find(file + ":" + key);
auto failIdx = Core::VectorMap<std::string, BufferType>::IndexyerType::FailIndex();
if (findIndex != failIdx)
_buffers.Delete(findIndex);
}
void Destroy()
{
_buffers.DeleteAll();
}
private:
Core::VectorMap<std::string, BufferType> _buffers;
};
}
}<|endoftext|>
|
<commit_before>/*=========================================================================
Program: Insight Segmentation & Registration Toolkit (ITK)
Module:
Language: C++
Date:
Version:
Copyright (c) 2000 National Library of Medicine
All rights reserved.
See COPYRIGHT.txt for copyright details.
=========================================================================*/
#if defined(_MSC_VER)
#pragma warning ( disable : 4786 )
#endif
#include <iostream>
// This file has been generated by BuildHeaderTest.tcl
// Test to include each header file for Insight
#include "itkAntiAliasBinaryImageFilter.txx"
#include "itkBalloonForce3DFilter.txx"
#include "itkBalloonForceFilter.txx"
#include "itkBinaryMask3DMeshSource.txx"
#include "itkBinaryMinMaxCurvatureFlowFunction.txx"
#include "itkBinaryMinMaxCurvatureFlowImageFilter.txx"
#include "itkCannySegmentationLevelSetFunction.txx"
#include "itkCannySegmentationLevelSetImageFilter.txx"
#include "itkClassifierBase.txx"
#include "itkConnectedRegionsMeshFilter.txx"
#include "itkCurvatureFlowFunction.txx"
#include "itkCurvatureFlowImageFilter.txx"
#include "itkDeformableMesh3DFilter.txx"
#include "itkDeformableMeshFilter.txx"
#include "itkDemonsRegistrationFilter.txx"
#include "itkDemonsRegistrationFunction.txx"
#include "itkExtensionVelocitiesImageFilter.txx"
#include "itkFEMRegistrationFilter.txx"
#include "itkFastMarchingExtensionImageFilter.txx"
#include "itkFastMarchingImageFilter.txx"
#include "itkGeodesicActiveContourImageFilter.txx"
#include "itkGibbsPriorFilter.txx"
#include "itkGradientVectorFlowImageFilter.txx"
#include "itkHistogramMatchingImageFilter.txx"
#include "itkHybridFilter.txx"
#include "itkImageClassifierBase.txx"
#include "itkImageGaussianModelEstimator.txx"
#include "itkImageKmeansModelEstimator.txx"
#include "itkImageModelEstimatorBase.txx"
#include "itkImageMomentsCalculator.txx"
#include "itkImageRegistrationMethod.txx"
#include "itkImageToImageMetric.txx"
#include "itkKLMRegionGrowImageFilter.txx"
#include "itkKalmanLinearEstimator.h"
#include "itkLaplacianSegmentationLevelSetFunction.txx"
#include "itkLaplacianSegmentationLevelSetImageFilter.txx"
#include "itkLevelSetImageFilter.txx"
#include "itkLevelSetNeighborhoodExtractor.txx"
#include "itkLevelSetVelocityNeighborhoodExtractor.txx"
#include "itkMRASlabIdentifier.txx"
#include "itkMRFImageFilter.txx"
#include "itkMRIBiasFieldCorrectionFilter.txx"
#include "itkMattesMutualInformationImageToImageMetric.txx"
#include "itkMeanSquaresImageToImageMetric.txx"
#include "itkMeanSquaresPointSetToImageMetric.txx"
#include "itkMinMaxCurvatureFlowFunction.txx"
#include "itkMinMaxCurvatureFlowImageFilter.txx"
#include "itkMultiResolutionImageRegistrationMethod.txx"
#include "itkMultiResolutionPDEDeformableRegistration.txx"
#include "itkMultiResolutionPyramidImageFilter.txx"
#include "itkMutualInformationImageToImageMetric.txx"
#include "itkNormalizedCorrelationImageToImageMetric.txx"
#include "itkNormalizedCorrelationPointSetToImageMetric.txx"
#include "itkOtsuThresholdImageCalculator.txx"
#include "itkPDEDeformableRegistrationFilter.txx"
#include "itkPDEDeformableRegistrationFunction.h"
#include "itkPatternIntensityImageToImageMetric.txx"
#include "itkPatternIntensityPointSetToImageMetric.txx"
#include "itkRGBGibbsPriorFilter.txx"
#include "itkRecursiveMultiResolutionPyramidImageFilter.txx"
#include "itkRegionGrowImageFilter.txx"
#include "itkRegistrationMethod.txx"
#include "itkReinitializeLevelSetImageFilter.txx"
#include "itkSegmentationLevelSetImageFilter.txx"
#include "itkShapeDetectionLevelSetFilter.txx"
#include "itkSimpleFuzzyConnectednessImageFilterBase.txx"
#include "itkSimpleFuzzyConnectednessRGBImageFilter.txx"
#include "itkSimpleFuzzyConnectednessScalarImageFilter.txx"
#include "itkSphereMeshSource.txx"
#include "itkThresholdSegmentationLevelSetFunction.txx"
#include "itkThresholdSegmentationLevelSetImageFilter.txx"
#include "itkVectorFuzzyConnectednessImageFilter.txx"
#include "itkVoronoiDiagram2D.txx"
#include "itkVoronoiDiagram2DGenerator.txx"
#include "itkVoronoiPartitioningImageFilter.txx"
#include "itkVoronoiSegmentationImageFilter.txx"
#include "itkVoronoiSegmentationImageFilterBase.txx"
#include "itkVoronoiSegmentationRGBImageFilter.txx"
#include "itkWatershedBoundary.txx"
#include "itkWatershedBoundaryResolver.txx"
#include "itkWatershedEquivalenceRelabeler.txx"
#include "itkWatershedEquivalencyTable.txx"
#include "itkWatershedImageFilter.txx"
#include "itkWatershedMiniPipelineProgressCommand.h"
#include "itkWatershedOneWayEquivalencyTable.txx"
#include "itkWatershedRelabeler.txx"
#include "itkWatershedSegmentTable.txx"
#include "itkWatershedSegmentTree.txx"
#include "itkWatershedSegmentTreeGenerator.txx"
#include "itkWatershedSegmenter.txx"
int main ( int , char* )
{
return 0;
}
<commit_msg>ENH: Updated to latest headers<commit_after>/*=========================================================================
Program: Insight Segmentation & Registration Toolkit (ITK)
Module:
Language: C++
Date:
Version:
Copyright (c) 2000 National Library of Medicine
All rights reserved.
See COPYRIGHT.txt for copyright details.
=========================================================================*/
#if defined(_MSC_VER)
#pragma warning ( disable : 4786 )
#endif
#include <iostream>
// This file has been generated by BuildHeaderTest.tcl
// Test to include each header file for Insight
#include "itkAntiAliasBinaryImageFilter.txx"
#include "itkBalloonForce3DFilter.txx"
#include "itkBalloonForceFilter.txx"
#include "itkBinaryMask3DMeshSource.txx"
#include "itkBinaryMinMaxCurvatureFlowFunction.txx"
#include "itkBinaryMinMaxCurvatureFlowImageFilter.txx"
#include "itkCannySegmentationLevelSetFunction.txx"
#include "itkCannySegmentationLevelSetImageFilter.txx"
#include "itkClassifierBase.txx"
#include "itkConnectedRegionsMeshFilter.txx"
#include "itkCurvatureFlowFunction.txx"
#include "itkCurvatureFlowImageFilter.txx"
#include "itkDeformableMesh3DFilter.txx"
#include "itkDeformableMeshFilter.txx"
#include "itkDemonsRegistrationFilter.txx"
#include "itkDemonsRegistrationFunction.txx"
#include "itkExtensionVelocitiesImageFilter.txx"
#include "itkFEMRegistrationFilter.txx"
#include "itkFastMarchingExtensionImageFilter.txx"
#include "itkFastMarchingImageFilter.txx"
#include "itkGeodesicActiveContourImageFilter.txx"
#include "itkGibbsPriorFilter.txx"
#include "itkGradientVectorFlowImageFilter.txx"
#include "itkHistogramMatchingImageFilter.txx"
#include "itkHybridFilter.txx"
#include "itkImageClassifierBase.txx"
#include "itkImageGaussianModelEstimator.txx"
#include "itkImageKmeansModelEstimator.txx"
#include "itkImageModelEstimatorBase.txx"
#include "itkImageMomentsCalculator.txx"
#include "itkImageRegistrationMethod.h"
#include "itkImageToImageMetric.txx"
#include "itkKLMRegionGrowImageFilter.txx"
#include "itkKalmanLinearEstimator.h"
#include "itkLaplacianSegmentationLevelSetFunction.txx"
#include "itkLaplacianSegmentationLevelSetImageFilter.txx"
#include "itkLevelSetImageFilter.txx"
#include "itkLevelSetNeighborhoodExtractor.txx"
#include "itkLevelSetVelocityNeighborhoodExtractor.txx"
#include "itkMRASlabIdentifier.txx"
#include "itkMRFImageFilter.txx"
#include "itkMRIBiasFieldCorrectionFilter.txx"
#include "itkMattesMutualInformationImageToImageMetric.txx"
#include "itkMeanSquaresImageToImageMetric.txx"
#include "itkMeanSquaresPointSetToImageMetric.txx"
#include "itkMinMaxCurvatureFlowFunction.txx"
#include "itkMinMaxCurvatureFlowImageFilter.txx"
#include "itkMultiResolutionImageRegistrationMethod.txx"
#include "itkMultiResolutionPDEDeformableRegistration.txx"
#include "itkMultiResolutionPyramidImageFilter.txx"
#include "itkMutualInformationImageToImageMetric.txx"
#include "itkNormalizedCorrelationImageToImageMetric.txx"
#include "itkNormalizedCorrelationPointSetToImageMetric.txx"
#include "itkOtsuThresholdImageCalculator.txx"
#include "itkPDEDeformableRegistrationFilter.txx"
#include "itkPDEDeformableRegistrationFunction.h"
#include "itkPatternIntensityImageToImageMetric.txx"
#include "itkPatternIntensityPointSetToImageMetric.txx"
#include "itkRGBGibbsPriorFilter.txx"
#include "itkRecursiveMultiResolutionPyramidImageFilter.txx"
#include "itkRegionGrowImageFilter.txx"
#include "itkRegistrationMethod.txx"
#include "itkReinitializeLevelSetImageFilter.txx"
#include "itkSegmentationLevelSetImageFilter.txx"
#include "itkShapeDetectionLevelSetFilter.txx"
#include "itkSimpleFuzzyConnectednessImageFilterBase.txx"
#include "itkSimpleFuzzyConnectednessRGBImageFilter.txx"
#include "itkSimpleFuzzyConnectednessScalarImageFilter.txx"
#include "itkSphereMeshSource.txx"
#include "itkThresholdSegmentationLevelSetFunction.txx"
#include "itkThresholdSegmentationLevelSetImageFilter.txx"
#include "itkVectorFuzzyConnectednessImageFilter.txx"
#include "itkVoronoiDiagram2D.txx"
#include "itkVoronoiDiagram2DGenerator.txx"
#include "itkVoronoiPartitioningImageFilter.txx"
#include "itkVoronoiSegmentationImageFilter.txx"
#include "itkVoronoiSegmentationImageFilterBase.txx"
#include "itkVoronoiSegmentationRGBImageFilter.txx"
#include "itkWatershedBoundary.txx"
#include "itkWatershedBoundaryResolver.txx"
#include "itkWatershedEquivalenceRelabeler.txx"
#include "itkWatershedEquivalencyTable.txx"
#include "itkWatershedImageFilter.txx"
#include "itkWatershedMiniPipelineProgressCommand.h"
#include "itkWatershedOneWayEquivalencyTable.txx"
#include "itkWatershedRelabeler.txx"
#include "itkWatershedSegmentTable.txx"
#include "itkWatershedSegmentTree.txx"
#include "itkWatershedSegmentTreeGenerator.txx"
#include "itkWatershedSegmenter.txx"
int main ( int , char* )
{
return 0;
}
<|endoftext|>
|
<commit_before>/*=========================================================================
Program: Insight Segmentation & Registration Toolkit
Module: itkKdTreeTest1.cxx
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) Insight Software Consortium. All rights reserved.
See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notices for more information.
=========================================================================*/
#if defined(_MSC_VER)
#pragma warning ( disable : 4786 )
#endif
#include "itkVector.h"
#include "itkMersenneTwisterRandomVariateGenerator.h"
#include "itkListSample.h"
#include "itkKdTree.h"
#include "itkKdTreeGenerator.h"
#include "itkEuclideanDistance.h"
#include <fstream>
int itkKdTreeTest1(int argc , char * argv [] )
{
if( argc < 5 )
{
std::cerr << "Missing parameters" << std::endl;
std::cerr << "Usage: " << std::endl;
std::cerr << argv[0] << " numberOfDataPoints numberOfTestPoints bucketSize graphvizDotOutputFile" << std::endl;
return EXIT_FAILURE;
}
// Random number generator
typedef itk::Statistics::MersenneTwisterRandomVariateGenerator NumberGeneratorType;
NumberGeneratorType::Pointer randomNumberGenerator = NumberGeneratorType::New();
randomNumberGenerator->Initialize();
typedef itk::Array< double > MeasurementVectorType ;
typedef itk::Statistics::ListSample< MeasurementVectorType > SampleType ;
const SampleType::MeasurementVectorSizeType measurementVectorSize = 2;
SampleType::Pointer sample = SampleType::New() ;
sample->SetMeasurementVectorSize( measurementVectorSize );
//
// Generate a sample of random points
//
const unsigned int numberOfDataPoints = atoi( argv[1] );
MeasurementVectorType mv( measurementVectorSize ) ;
for (unsigned int i = 0 ; i < numberOfDataPoints ; ++i )
{
mv[0] = randomNumberGenerator->GetNormalVariate( 0.0, 1.0 );
mv[1] = randomNumberGenerator->GetNormalVariate( 0.0, 1.0 );
sample->PushBack( mv ) ;
}
typedef itk::Statistics::KdTreeGenerator< SampleType > TreeGeneratorType ;
TreeGeneratorType::Pointer treeGenerator = TreeGeneratorType::New() ;
const unsigned int bucketSize = atoi( argv[3] );
treeGenerator->SetSample( sample ) ;
treeGenerator->SetBucketSize( bucketSize );
treeGenerator->Update() ;
typedef TreeGeneratorType::KdTreeType TreeType ;
typedef TreeType::NearestNeighbors NeighborsType ;
typedef TreeType::KdTreeNodeType NodeType ;
TreeType::Pointer tree = treeGenerator->GetOutput() ;
MeasurementVectorType queryPoint( measurementVectorSize ) ;
MeasurementVectorType origin( measurementVectorSize ) ;
unsigned int numberOfNeighbors = 1 ;
TreeType::InstanceIdentifierVectorType neighbors ;
MeasurementVectorType result( measurementVectorSize ) ;
MeasurementVectorType test_point( measurementVectorSize ) ;
MeasurementVectorType min_point( measurementVectorSize ) ;
unsigned int numberOfFailedPoints = 0;
const unsigned int numberOfTestPoints = atoi( argv[2] );
//
// Check that for every point in the sample, its closest point is itself.
//
typedef itk::Statistics::EuclideanDistance< MeasurementVectorType > DistanceMetricType;
DistanceMetricType::Pointer distanceMetric = DistanceMetricType::New();
bool testFailed = false;
for( unsigned int k = 0; k < sample->Size(); k++ )
{
queryPoint = sample->GetMeasurementVector(k);
for ( unsigned int i = 0 ; i < sample->GetMeasurementVectorSize() ; ++i )
{
origin[i] = queryPoint[i];
}
distanceMetric->SetOrigin( origin );
unsigned int numberOfNeighbors = 1;
TreeType::InstanceIdentifierVectorType neighbors;
tree->Search( queryPoint, numberOfNeighbors, neighbors ) ;
for ( unsigned int i = 0 ; i < numberOfNeighbors ; ++i )
{
const double distance =
distanceMetric->Evaluate( tree->GetMeasurementVector( neighbors[i] ));
if( distance > vnl_math::eps )
{
std::cout << "kd-tree knn search result:" << std::endl
<< "query point = [" << queryPoint << "]" << std::endl
<< "k = " << numberOfNeighbors << std::endl;
std::cout << "measurement vector : distance" << std::endl;
std::cout << "[" << tree->GetMeasurementVector( neighbors[i] )
<< "] : "
<< distance << std::endl;
testFailed = true;
}
}
}
if( testFailed )
{
std::cout << "Points failed to find themselves as closest-point" << std::endl;
}
//
// Generate a second sample of random points
// and use them to query the tree
//
for (unsigned int j = 0 ; j < numberOfTestPoints ; ++j )
{
double min_dist = itk::NumericTraits< double >::max();
queryPoint[0] = randomNumberGenerator->GetNormalVariate( 0.0, 1.0 );
queryPoint[1] = randomNumberGenerator->GetNormalVariate( 0.0, 1.0 );
tree->Search( queryPoint, numberOfNeighbors, neighbors ) ;
//
// The first neighbor should be the closest point.
//
result = tree->GetMeasurementVector( neighbors[0] );
//
// Compute the distance to the "presumed" nearest neighbor
//
double result_dist = sqrt(
(result[0] - queryPoint[0]) *
(result[0] - queryPoint[0]) +
(result[1] - queryPoint[1]) *
(result[1] - queryPoint[1])
);
//
// Compute the distance to all other points, to verify
// whether the first neighbor was the closest one or not.
//
for( unsigned int i = 0 ; i < numberOfDataPoints; ++i )
{
test_point = tree->GetMeasurementVector( i );
const double dist = sqrt(
(test_point[0] - queryPoint[0]) *
(test_point[0] - queryPoint[0]) +
(test_point[1] - queryPoint[1]) *
(test_point[1] - queryPoint[1])
);
if( dist < min_dist )
{
min_dist = dist;
min_point = test_point;
}
}
if( min_dist < result_dist )
{
std::cerr << "Problem found " << std::endl;
std::cerr << "Query point " << queryPoint << std::endl;
std::cerr << "Reported closest point " << result
<< " distance " << result_dist << std::endl;
std::cerr << "Actual closest point " << min_point
<< " distance " << min_dist << std::endl;
std::cerr << std::endl;
std::cerr << "Test FAILED." << std::endl;
numberOfFailedPoints++;
}
}
//
// Plot out the tree structure to the console in the format used by Graphviz dot
//
std::ofstream plotFile;
plotFile.open( argv[4] );
tree->PlotTree( plotFile );
plotFile.close();
if( numberOfFailedPoints )
{
std::cerr << numberOfFailedPoints << " failed out of "
<< numberOfTestPoints << " points " << std::endl;
return EXIT_FAILURE;
}
std::cout << "Test PASSED." << std::endl;
return EXIT_SUCCESS;
}
<commit_msg>ENH: Making optional the generation of the Graphviz-dot plot of the KdTree.<commit_after>/*=========================================================================
Program: Insight Segmentation & Registration Toolkit
Module: itkKdTreeTest1.cxx
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) Insight Software Consortium. All rights reserved.
See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notices for more information.
=========================================================================*/
#if defined(_MSC_VER)
#pragma warning ( disable : 4786 )
#endif
#include "itkVector.h"
#include "itkMersenneTwisterRandomVariateGenerator.h"
#include "itkListSample.h"
#include "itkKdTree.h"
#include "itkKdTreeGenerator.h"
#include "itkEuclideanDistance.h"
#include <fstream>
int itkKdTreeTest1(int argc , char * argv [] )
{
if( argc < 4 )
{
std::cerr << "Missing parameters" << std::endl;
std::cerr << "Usage: " << std::endl;
std::cerr << argv[0] << " numberOfDataPoints numberOfTestPoints bucketSize [graphvizDotOutputFile]" << std::endl;
return EXIT_FAILURE;
}
// Random number generator
typedef itk::Statistics::MersenneTwisterRandomVariateGenerator NumberGeneratorType;
NumberGeneratorType::Pointer randomNumberGenerator = NumberGeneratorType::New();
randomNumberGenerator->Initialize();
typedef itk::Array< double > MeasurementVectorType ;
typedef itk::Statistics::ListSample< MeasurementVectorType > SampleType ;
const SampleType::MeasurementVectorSizeType measurementVectorSize = 2;
SampleType::Pointer sample = SampleType::New() ;
sample->SetMeasurementVectorSize( measurementVectorSize );
//
// Generate a sample of random points
//
const unsigned int numberOfDataPoints = atoi( argv[1] );
MeasurementVectorType mv( measurementVectorSize ) ;
for (unsigned int i = 0 ; i < numberOfDataPoints ; ++i )
{
mv[0] = randomNumberGenerator->GetNormalVariate( 0.0, 1.0 );
mv[1] = randomNumberGenerator->GetNormalVariate( 0.0, 1.0 );
sample->PushBack( mv ) ;
}
typedef itk::Statistics::KdTreeGenerator< SampleType > TreeGeneratorType ;
TreeGeneratorType::Pointer treeGenerator = TreeGeneratorType::New() ;
const unsigned int bucketSize = atoi( argv[3] );
treeGenerator->SetSample( sample ) ;
treeGenerator->SetBucketSize( bucketSize );
treeGenerator->Update() ;
typedef TreeGeneratorType::KdTreeType TreeType ;
typedef TreeType::NearestNeighbors NeighborsType ;
typedef TreeType::KdTreeNodeType NodeType ;
TreeType::Pointer tree = treeGenerator->GetOutput() ;
MeasurementVectorType queryPoint( measurementVectorSize ) ;
MeasurementVectorType origin( measurementVectorSize ) ;
unsigned int numberOfNeighbors = 1 ;
TreeType::InstanceIdentifierVectorType neighbors ;
MeasurementVectorType result( measurementVectorSize ) ;
MeasurementVectorType test_point( measurementVectorSize ) ;
MeasurementVectorType min_point( measurementVectorSize ) ;
unsigned int numberOfFailedPoints = 0;
const unsigned int numberOfTestPoints = atoi( argv[2] );
//
// Check that for every point in the sample, its closest point is itself.
//
typedef itk::Statistics::EuclideanDistance< MeasurementVectorType > DistanceMetricType;
DistanceMetricType::Pointer distanceMetric = DistanceMetricType::New();
bool testFailed = false;
for( unsigned int k = 0; k < sample->Size(); k++ )
{
queryPoint = sample->GetMeasurementVector(k);
for ( unsigned int i = 0 ; i < sample->GetMeasurementVectorSize() ; ++i )
{
origin[i] = queryPoint[i];
}
distanceMetric->SetOrigin( origin );
unsigned int numberOfNeighbors = 1;
TreeType::InstanceIdentifierVectorType neighbors;
tree->Search( queryPoint, numberOfNeighbors, neighbors ) ;
for ( unsigned int i = 0 ; i < numberOfNeighbors ; ++i )
{
const double distance =
distanceMetric->Evaluate( tree->GetMeasurementVector( neighbors[i] ));
if( distance > vnl_math::eps )
{
std::cout << "kd-tree knn search result:" << std::endl
<< "query point = [" << queryPoint << "]" << std::endl
<< "k = " << numberOfNeighbors << std::endl;
std::cout << "measurement vector : distance" << std::endl;
std::cout << "[" << tree->GetMeasurementVector( neighbors[i] )
<< "] : "
<< distance << std::endl;
testFailed = true;
}
}
}
if( testFailed )
{
std::cout << "Points failed to find themselves as closest-point" << std::endl;
}
//
// Generate a second sample of random points
// and use them to query the tree
//
for (unsigned int j = 0 ; j < numberOfTestPoints ; ++j )
{
double min_dist = itk::NumericTraits< double >::max();
queryPoint[0] = randomNumberGenerator->GetNormalVariate( 0.0, 1.0 );
queryPoint[1] = randomNumberGenerator->GetNormalVariate( 0.0, 1.0 );
tree->Search( queryPoint, numberOfNeighbors, neighbors ) ;
//
// The first neighbor should be the closest point.
//
result = tree->GetMeasurementVector( neighbors[0] );
//
// Compute the distance to the "presumed" nearest neighbor
//
double result_dist = sqrt(
(result[0] - queryPoint[0]) *
(result[0] - queryPoint[0]) +
(result[1] - queryPoint[1]) *
(result[1] - queryPoint[1])
);
//
// Compute the distance to all other points, to verify
// whether the first neighbor was the closest one or not.
//
for( unsigned int i = 0 ; i < numberOfDataPoints; ++i )
{
test_point = tree->GetMeasurementVector( i );
const double dist = sqrt(
(test_point[0] - queryPoint[0]) *
(test_point[0] - queryPoint[0]) +
(test_point[1] - queryPoint[1]) *
(test_point[1] - queryPoint[1])
);
if( dist < min_dist )
{
min_dist = dist;
min_point = test_point;
}
}
if( min_dist < result_dist )
{
std::cerr << "Problem found " << std::endl;
std::cerr << "Query point " << queryPoint << std::endl;
std::cerr << "Reported closest point " << result
<< " distance " << result_dist << std::endl;
std::cerr << "Actual closest point " << min_point
<< " distance " << min_dist << std::endl;
std::cerr << std::endl;
std::cerr << "Test FAILED." << std::endl;
numberOfFailedPoints++;
}
}
if( argc > 4 )
{
//
// Plot out the tree structure to the console in the format used by Graphviz dot
//
std::ofstream plotFile;
plotFile.open( argv[4] );
tree->PlotTree( plotFile );
plotFile.close();
}
if( numberOfFailedPoints )
{
std::cerr << numberOfFailedPoints << " failed out of "
<< numberOfTestPoints << " points " << std::endl;
return EXIT_FAILURE;
}
std::cout << "Test PASSED." << std::endl;
return EXIT_SUCCESS;
}
<|endoftext|>
|
<commit_before><commit_msg>coverity#1247641 Uncaught exception<commit_after><|endoftext|>
|
<commit_before>#define BOOST_TEST_STATIC_LINK
#define BOOST_TEST_MODULE FIXED_POINT_LIB_COMMON_USE_CASES
#include <boost/test/unit_test.hpp>
#include <boost/random.hpp>
#include <limits>
#include <string>
#include <sstream>
#include <iomanip>
#include <stdexcept>
#include "./../../fixed_point_lib/src/number.hpp"
namespace utils { namespace unit_tests {
namespace {
using utils::S_number;
using utils::U_number;
using utils::SOU_number;
using utils::UOU_number;
boost::mt19937 rng;
typedef boost::variate_generator<boost::mt19937&, boost::uniform_real<double> >
generator;
typedef boost::uniform_real<double> var;
}
BOOST_AUTO_TEST_SUITE(Summation)
// FIXED-POINT SUMMATION PRECISION TESTS
//////////////////////////////////////////////////////////////////////////
/// idea of tests 'commonCheck1' and 'commonCheck2':
/// 1. common checks for fixed-point accuracy and result sign inference
/// 2. number of accurate decimal numbers in fractional part is determined
/// as floor(log(10, 2^(f + 1) - 1)) - 1. Last number is errored by left
/// non-captured digits.
BOOST_AUTO_TEST_CASE(commonCheck1)
{
typedef S_number<28, 13>::type type1;
typedef U_number<37, 15>::type type2;
var v0(static_cast<double>(std::numeric_limits<type1>::min()),
static_cast<double>(std::numeric_limits<type1>::max()));
double const u0 = generator(rng, v0)();
var v1(static_cast<double>(std::numeric_limits<type2>::min()),
static_cast<double>(std::numeric_limits<type1>::max()) - u0);
double const u1 = generator(rng, v1)();
type1 const a(u0);
type1 const b(u1);
type1::sum_type const result = a + b;
std::stringstream message_stream;
message_stream
<< std::setprecision(5)
<< u0
<< " + "
<< u1
<< ": summation was made with unexpected rounding error";
double const error = static_cast<double>(result) - (u0 + u1);
BOOST_CHECK_MESSAGE(std::fabs(static_cast<double>(result) - (u0 + u1)) < 1E-3,
message_stream.str());
}
BOOST_AUTO_TEST_CASE(commonCheck2)
{
typedef U_number<56, 34>::type type1;
typedef S_number<56, 57>::type type2;
type1 const a(13.5462);
type2 const b(0.00343);
type1::sum_type const result = a + b;
BOOST_CHECK_MESSAGE(std::fabs(static_cast<double>(result) - 13.54963) < 1E-5,
"summation was made with illegal rounding error");
}
// POSITIVE/NEGATIVE OVERFLOW EVENTS HANDLING
//////////////////////////////////////////////////////////////////////////
BOOST_AUTO_TEST_CASE(positiveOverflow)
{
typedef SOU_number<8, 3>::type type;
type const a(31.9);
type const b(0.2);
try {
type const c(a + b);
BOOST_FAIL("Overflow event was not captured");
}
catch (std::overflow_error e){};
}
BOOST_AUTO_TEST_CASE(negativeOverflow)
{
}
// SAME TYPE FIXED-POINT NUMBERS BUILDS AN ADDITIVE ABELIAN GROUP
//////////////////////////////////////////////////////////////////////////
// idea of tests 'unitCheck' and 'commutativityCheck'
// checks if the additive abelian group laws are satisifed
BOOST_AUTO_TEST_CASE(unitCheck)
{
typedef S_number<43, 23>::type type;
type const unit(0.0), a(32.435), b(-23.123), c(0.034);
std::string const message("summation does not have unit");
BOOST_CHECK_MESSAGE((type(a + unit) == type(unit + a)) && (type(unit + a) == type(a)), message);
BOOST_CHECK_MESSAGE((type(b + unit) == type(unit + b)) && (type(unit + b) == type(b)), message);
BOOST_CHECK_MESSAGE((type(c + unit) == type(unit + c)) && (type(unit + c) == type(c)), message);
}
BOOST_AUTO_TEST_CASE(commutativityCheck)
{
typedef S_number<27, 27>::type type;
type const a(0.0023), b(0.095), c(0.9998);
std::string const message("summation does not satisfy commutativity law");
BOOST_CHECK_MESSAGE(a + b == b + a, message);
BOOST_CHECK_MESSAGE(b + c == c + b, message);
BOOST_CHECK_MESSAGE(a + c == c + a, message);
}
BOOST_AUTO_TEST_SUITE_END()
}}
<commit_msg>sum_cases.cpp: std random<commit_after>#define BOOST_TEST_STATIC_LINK
#define BOOST_TEST_MODULE FIXED_POINT_LIB_COMMON_USE_CASES
#include <boost/test/unit_test.hpp>
#include <boost/foreach.hpp>
#include <boost/range/irange.hpp>
#include <limits>
#include <string>
#include <sstream>
#include <iomanip>
#include <stdexcept>
#include "./../../fixed_point_lib/src/number.hpp"
namespace utils { namespace unit_tests {
namespace {
using utils::S_number;
using utils::U_number;
using utils::SOU_number;
using utils::UOU_number;
}
#define fmin(type) double(std::numeric_limits<type>::min())
#define fmax(type) double(std::numeric_limits<type>::max())
#define iterations 10000
double r(double low, double high)
{
return low + std::rand() / (double(RAND_MAX) / (high - low));
}
BOOST_AUTO_TEST_SUITE(Summation)
// FIXED-POINT SUMMATION PRECISION TESTS
//////////////////////////////////////////////////////////////////////////
/// idea of tests 'commonCheck1' and 'commonCheck2':
/// 1. common checks for fixed-point accuracy
/// 2. number of accurate decimal numbers in fractional part is determined
/// as floor(log(10, 2^(f + 1) - 1)) - 1. Last number is errored by left
/// non-captured digits.
BOOST_AUTO_TEST_CASE(commonCheck1)
{
typedef U_number<28, 13>::type type1;
typedef U_number<37, 15>::type type2;
std::srand(static_cast<unsigned int>(std::time(0)));
BOOST_FOREACH(size_t it, boost::irange<size_t>(0, iterations, 1)) {
double const u1 = r(fmin(type1), fmax(type1));
double const u2 = r(fmin(type2), fmax(type1) - u1);
type1 const a(u1);
type2 const b(u2);
type1::sum_type const result = a + b;
std::stringstream message_stream;
message_stream
<< std::setprecision(5)
<< u1
<< " + "
<< u2
<< ": summation was made with unexpected rounding error";
BOOST_CHECK_MESSAGE(std::fabs(double(result) - (u1 + u2)) < 1E-3,
message_stream.str());
}
}
BOOST_AUTO_TEST_CASE(commonCheck2)
{
typedef U_number<56, 34>::type type1;
typedef S_number<56, 57>::type type2;
type1 const a(13.5462);
type2 const b(0.00343);
type1::sum_type const result = a + b;
BOOST_CHECK_MESSAGE(std::fabs(static_cast<double>(result) - 13.54963) < 1E-5,
"summation was made with illegal rounding error");
}
// POSITIVE/NEGATIVE OVERFLOW EVENTS HANDLING
//////////////////////////////////////////////////////////////////////////
BOOST_AUTO_TEST_CASE(positiveOverflow)
{
typedef SOU_number<8, 3>::type type;
type const a(31.9);
type const b(0.2);
try {
type const c(a + b);
BOOST_FAIL("Overflow event was not captured");
}
catch (std::overflow_error e){};
}
BOOST_AUTO_TEST_CASE(negativeOverflow)
{
}
// SAME TYPE FIXED-POINT NUMBERS BUILDS AN ADDITIVE ABELIAN GROUP
//////////////////////////////////////////////////////////////////////////
// idea of tests 'unitCheck' and 'commutativityCheck'
// checks if the additive abelian group laws are satisifed
BOOST_AUTO_TEST_CASE(unitCheck)
{
typedef S_number<43, 23>::type type;
type const unit(0.0), a(32.435), b(-23.123), c(0.034);
std::string const message("summation does not have unit");
BOOST_CHECK_MESSAGE((type(a + unit) == type(unit + a)) && (type(unit + a) == type(a)), message);
BOOST_CHECK_MESSAGE((type(b + unit) == type(unit + b)) && (type(unit + b) == type(b)), message);
BOOST_CHECK_MESSAGE((type(c + unit) == type(unit + c)) && (type(unit + c) == type(c)), message);
}
BOOST_AUTO_TEST_CASE(commutativityCheck)
{
typedef S_number<27, 27>::type type;
type const a(0.0023), b(0.095), c(0.9998);
std::string const message("summation does not satisfy commutativity law");
BOOST_CHECK_MESSAGE(a + b == b + a, message);
BOOST_CHECK_MESSAGE(b + c == c + b, message);
BOOST_CHECK_MESSAGE(a + c == c + a, message);
}
BOOST_AUTO_TEST_SUITE_END()
}}
<|endoftext|>
|
<commit_before>/* Copyright 2019 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#include "tensorflow/compiler/xla/service/all_reduce_simplifier.h"
#include <vector>
#include "tensorflow/compiler/xla/literal_util.h"
#include "tensorflow/compiler/xla/service/hlo_computation.h"
#include "tensorflow/compiler/xla/service/hlo_instruction.h"
#include "tensorflow/compiler/xla/service/hlo_opcode.h"
#include "tensorflow/compiler/xla/service/hlo_replication_analysis.h"
#include "tensorflow/compiler/xla/shape_util.h"
#include "tensorflow/compiler/xla/statusor.h"
namespace xla {
StatusOr<bool> AllReduceSimplifier::Run(HloModule* module) {
TF_ASSIGN_OR_RETURN(
auto replication,
HloReplicationAnalysis::Run(module, /*cross_partition_spmd=*/false));
std::vector<std::pair<HloInstruction*, int64_t>> all_reduces_to_replace;
// Returns the size of a replica group if all groups have the same size, or -1
// if they have different sizes.
auto get_replica_group_size =
[this](const HloInstruction* all_reduce) -> int64_t {
if (all_reduce->replica_groups().empty()) {
return replica_count_;
}
int64_t replica_group_size = -1;
for (const auto& group : all_reduce->replica_groups()) {
if (replica_group_size == -1) {
replica_group_size = group.replica_ids_size();
} else if (replica_group_size != group.replica_ids_size()) {
return -1;
}
}
return replica_group_size;
};
for (auto computation : module->computations()) {
for (HloInstruction* inst : computation->MakeInstructionPostOrder()) {
if (!inst->shape().IsArray()) {
// We currently do not change tuple-shaped all-reduce.
// Until XLA will support Token fed AllReduce(), the PyTorch client code
// uses a fake data token (constant) which relies on this pass to not
// optimize out (being fed within a tuple input).
continue;
}
if (!inst->IsCrossReplicaAllReduce()) {
continue;
}
int64_t group_size = get_replica_group_size(inst);
if (group_size == -1) {
continue;
}
if (replication->HloInstructionIsReplicatedAt(inst->operand(0), {}) ||
group_size == 1) {
all_reduces_to_replace.push_back({inst, group_size});
}
}
}
bool changed = false;
for (auto all_reduce_and_group_size : all_reduces_to_replace) {
auto all_reduce = all_reduce_and_group_size.first;
const int64_t replica_group_size = all_reduce_and_group_size.second;
if (replica_group_size == 1) {
TF_RETURN_IF_ERROR(all_reduce->parent()->ReplaceInstruction(
all_reduce, all_reduce->mutable_operand(0)));
changed = true;
continue;
}
if (all_reduce->to_apply()->instruction_count() != 3 ||
all_reduce->to_apply()->num_parameters() != 2) {
continue;
}
HloInstruction* replacement;
switch (all_reduce->to_apply()->root_instruction()->opcode()) {
case HloOpcode::kAdd: {
// Create the multiplier:
// broadcast(convert_to_matching_type(s32 group size))
auto multiplier =
all_reduce->parent()->AddInstruction(HloInstruction::CreateConstant(
LiteralUtil::CreateR0<int32_t>(replica_group_size)));
if (all_reduce->shape().element_type() != S32) {
multiplier = all_reduce->parent()->AddInstruction(
HloInstruction::CreateConvert(
ShapeUtil::ChangeElementType(
multiplier->shape(), all_reduce->shape().element_type()),
multiplier));
}
if (all_reduce->shape().rank() > 0) {
multiplier = all_reduce->parent()->AddInstruction(
HloInstruction::CreateBroadcast(all_reduce->shape(), multiplier,
{}));
}
replacement =
all_reduce->parent()->AddInstruction(HloInstruction::CreateBinary(
all_reduce->shape(), HloOpcode::kMultiply,
all_reduce->mutable_operand(0), multiplier));
break;
}
case HloOpcode::kMinimum:
case HloOpcode::kMaximum:
case HloOpcode::kOr:
case HloOpcode::kAnd:
replacement = all_reduce->mutable_operand(0);
break;
default:
continue;
}
VLOG(2) << "Replacing " << all_reduce->ToString() << " with "
<< replacement->ToString();
TF_RETURN_IF_ERROR(all_reduce->ReplaceAllUsesWith(replacement));
changed = true;
}
return changed;
}
} // namespace xla
<commit_msg>[XLA:ALL_REDUCE_SIMPLIFIER] Remove trivial AllGather and ReduceScatter<commit_after>/* Copyright 2019 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#include "tensorflow/compiler/xla/service/all_reduce_simplifier.h"
#include <vector>
#include "tensorflow/compiler/xla/literal_util.h"
#include "tensorflow/compiler/xla/service/hlo_computation.h"
#include "tensorflow/compiler/xla/service/hlo_instruction.h"
#include "tensorflow/compiler/xla/service/hlo_opcode.h"
#include "tensorflow/compiler/xla/service/hlo_replication_analysis.h"
#include "tensorflow/compiler/xla/shape_util.h"
#include "tensorflow/compiler/xla/statusor.h"
namespace xla {
StatusOr<bool> AllReduceSimplifier::Run(HloModule* module) {
TF_ASSIGN_OR_RETURN(
auto replication,
HloReplicationAnalysis::Run(module, /*cross_partition_spmd=*/false));
std::vector<std::pair<HloInstruction*, int64_t>> all_reduces_to_replace;
// Returns the size of a replica group if all groups have the same size, or -1
// if they have different sizes.
auto get_replica_group_size =
[this](const HloInstruction* all_reduce) -> int64_t {
if (all_reduce->replica_groups().empty()) {
return replica_count_;
}
int64_t replica_group_size = -1;
for (const auto& group : all_reduce->replica_groups()) {
if (replica_group_size == -1) {
replica_group_size = group.replica_ids_size();
} else if (replica_group_size != group.replica_ids_size()) {
return -1;
}
}
return replica_group_size;
};
bool changed = false;
for (auto computation : module->computations()) {
for (HloInstruction* inst : computation->MakeInstructionPostOrder()) {
// AllGather and ReduceScatter with the same input and output shape
if ((inst->opcode() == HloOpcode::kAllGather ||
inst->opcode() == HloOpcode::kReduceScatter) &&
ShapeUtil::Compatible(inst->shape(), inst->operand(0)->shape())) {
changed = true;
TF_RETURN_IF_ERROR(
computation->ReplaceInstruction(inst, inst->mutable_operand(0)));
}
}
}
for (auto computation : module->computations()) {
for (HloInstruction* inst : computation->MakeInstructionPostOrder()) {
if (!inst->shape().IsArray()) {
// We currently do not change tuple-shaped all-reduce.
// Until XLA will support Token fed AllReduce(), the PyTorch client code
// uses a fake data token (constant) which relies on this pass to not
// optimize out (being fed within a tuple input).
continue;
}
if (!inst->IsCrossReplicaAllReduce()) {
continue;
}
int64_t group_size = get_replica_group_size(inst);
if (group_size == -1) {
continue;
}
if (replication->HloInstructionIsReplicatedAt(inst->operand(0), {}) ||
group_size == 1) {
all_reduces_to_replace.push_back({inst, group_size});
}
}
}
for (auto all_reduce_and_group_size : all_reduces_to_replace) {
auto all_reduce = all_reduce_and_group_size.first;
const int64_t replica_group_size = all_reduce_and_group_size.second;
if (replica_group_size == 1) {
TF_RETURN_IF_ERROR(all_reduce->parent()->ReplaceInstruction(
all_reduce, all_reduce->mutable_operand(0)));
changed = true;
continue;
}
if (all_reduce->to_apply()->instruction_count() != 3 ||
all_reduce->to_apply()->num_parameters() != 2) {
continue;
}
HloInstruction* replacement;
switch (all_reduce->to_apply()->root_instruction()->opcode()) {
case HloOpcode::kAdd: {
// Create the multiplier:
// broadcast(convert_to_matching_type(s32 group size))
auto multiplier =
all_reduce->parent()->AddInstruction(HloInstruction::CreateConstant(
LiteralUtil::CreateR0<int32_t>(replica_group_size)));
if (all_reduce->shape().element_type() != S32) {
multiplier = all_reduce->parent()->AddInstruction(
HloInstruction::CreateConvert(
ShapeUtil::ChangeElementType(
multiplier->shape(), all_reduce->shape().element_type()),
multiplier));
}
if (all_reduce->shape().rank() > 0) {
multiplier = all_reduce->parent()->AddInstruction(
HloInstruction::CreateBroadcast(all_reduce->shape(), multiplier,
{}));
}
replacement =
all_reduce->parent()->AddInstruction(HloInstruction::CreateBinary(
all_reduce->shape(), HloOpcode::kMultiply,
all_reduce->mutable_operand(0), multiplier));
break;
}
case HloOpcode::kMinimum:
case HloOpcode::kMaximum:
case HloOpcode::kOr:
case HloOpcode::kAnd:
replacement = all_reduce->mutable_operand(0);
break;
default:
continue;
}
VLOG(2) << "Replacing " << all_reduce->ToString() << " with "
<< replacement->ToString();
TF_RETURN_IF_ERROR(all_reduce->ReplaceAllUsesWith(replacement));
changed = true;
}
return changed;
}
} // namespace xla
<|endoftext|>
|
<commit_before>///
/// @file calculator.hpp
/// @brief calculator::eval(const std::string&) evaluates an integer
/// arithmetic expression and returns the result. If an error
/// occurs a calculator::error exception is thrown.
/// <https://github.com/kimwalisch/calculator>
/// @author Kim Walisch, <kim.walisch@gmail.com>
/// @copyright Copyright (C) 2013 Kim Walisch
/// @date November 30, 2013
/// @license BSD 2-Clause, http://opensource.org/licenses/BSD-2-Clause
/// @version 1.0 patched: `^' is raise to power instead of XOR.
///
/// == Supported operators ==
///
/// OPERATOR NAME ASSOCIATIVITY PRECEDENCE
///
/// | Bitwise Inclusive OR Left 4
/// & Bitwise AND Left 6
/// << Shift Left Left 9
/// >> Shift Right Left 9
/// + Addition Left 10
/// - Subtraction Left 10
/// * Multiplication Left 20
/// / Division Left 20
/// % Modulo Left 20
/// ^, ** Raise to power Right 30
/// e, E Scientific notation Right 40
/// ~ Unary complement Left 99
///
/// The operator precedence has been set according to (uses the C and
/// C++ operator precedence): http://en.wikipedia.org/wiki/Order_of_operations
/// Operators with higher precedence are evaluated before operators
/// with relatively lower precedence. Unary operators are set to have
/// the highest precedence, this is not strictly correct for the power
/// operator e.g. "-3**2" = 9 but a lot of software tools (Bash shell,
/// Microsoft Excel, GNU bc, ...) use the same convention.
///
/// == Examples of valid expressions ==
///
/// "65536 >> 15" = 2
/// "2**16" = 65536
/// "(0 + 0xDf234 - 1000)*3/2%999" = 828
/// "-(2**2**2**2)" = -65536
/// "(0 + ~(0xDF234 & 1000) *3) /-2" = 817
/// "(2**16) + (1 << 16) >> 0X5" = 4096
/// "5*-(2**(9+7))/3+5*(1 & 0xFf123)" = -109221
///
/// == About the algorithm used ==
///
/// calculator::eval(std::string&) relies on the ExpressionParser
/// class which is a simple C++ operator precedence parser with infix
/// notation for integer arithmetic expressions.
/// ExpressionParser has its roots in a JavaScript parser published
/// at: http://stackoverflow.com/questions/28256/equation-expression-parser-with-precedence/114961#114961
/// The same author has also published an article about his operator
/// precedence algorithm at PerlMonks:
/// http://www.perlmonks.org/?node_id=554516
///
#ifndef CALCULATOR_HPP
#define CALCULATOR_HPP
#include <stdexcept>
#include <string>
#include <sstream>
#include <stack>
#include <cstddef>
#include <cctype>
namespace calculator
{
/// calculator::eval() throws a calculator::error if it fails
/// to evaluate the expression string.
///
class error : public std::runtime_error
{
public:
error(const std::string& expr, const std::string& message)
: std::runtime_error(message),
expr_(expr)
{ }
#if __cplusplus >= 201103L
~error() { }
#else
~error() throw() { }
#endif
std::string expression() const
{
return expr_;
}
private:
std::string expr_;
};
template <typename T>
class ExpressionParser
{
public:
/// Evaluate an integer arithmetic expression and return its result.
/// @throw error if parsing fails.
///
T eval(const std::string& expr)
{
T result = 0;
index_ = 0;
expr_ = expr;
try
{
result = parseExpr();
if (!isEnd())
unexpected();
}
catch (const calculator::error&)
{
while(!stack_.empty())
stack_.pop();
throw;
}
return result;
}
/// Get the integer value of a character.
T eval(char c)
{
std::string expr(1, c);
return eval(expr);
}
private:
enum
{
OPERATOR_NULL,
OPERATOR_BITWISE_OR, /// |
OPERATOR_BITWISE_XOR, /// ^
OPERATOR_BITWISE_AND, /// &
OPERATOR_BITWISE_SHL, /// <<
OPERATOR_BITWISE_SHR, /// >>
OPERATOR_ADDITION, /// +
OPERATOR_SUBTRACTION, /// -
OPERATOR_MULTIPLICATION, /// *
OPERATOR_DIVISION, /// /
OPERATOR_MODULO, /// %
OPERATOR_POWER, /// **
OPERATOR_EXPONENT /// e, E
};
struct Operator
{
/// Operator, one of the OPERATOR_* enum definitions
int op;
int precedence;
/// 'L' = left or 'R' = right
int associativity;
Operator(int opr, int prec, int assoc) :
op(opr),
precedence(prec),
associativity(assoc)
{ }
};
struct OperatorValue
{
Operator op;
T value;
OperatorValue(const Operator& opr, T val) :
op(opr),
value(val)
{ }
int getPrecedence() const
{
return op.precedence;
}
bool isNull() const
{
return op.op == OPERATOR_NULL;
}
};
/// Expression string
std::string expr_;
/// Current expression index, incremented whilst parsing
std::size_t index_;
/// The current operator and its left value
/// are pushed onto the stack if the operator on
/// top of the stack has lower precedence.
std::stack<OperatorValue> stack_;
/// Exponentiation by squaring, x^n.
static T pow(T x, T n)
{
T res = 1;
while (n != 0)
{
if (n % 2 != 0)
{
res *= x;
n -= 1;
}
x *= x;
n /= 2;
}
return res;
}
T checkZero(T value) const
{
if (value == 0)
{
std::string divOperators("/%");
std::size_t division = expr_.find_last_of(divOperators, index_ - 2);
std::ostringstream msg;
msg << "Parser error: division by 0";
if (division != std::string::npos)
msg << " (error token is \""
<< expr_.substr(division, expr_.size() - division)
<< "\")";
throw calculator::error(expr_, msg.str());
}
return value;
}
T calculate(T v1, T v2, const Operator& op) const
{
switch (op.op)
{
case OPERATOR_BITWISE_OR: return v1 | v2;
case OPERATOR_BITWISE_XOR: return v1 ^ v2;
case OPERATOR_BITWISE_AND: return v1 & v2;
case OPERATOR_BITWISE_SHL: return v1 << v2;
case OPERATOR_BITWISE_SHR: return v1 >> v2;
case OPERATOR_ADDITION: return v1 + v2;
case OPERATOR_SUBTRACTION: return v1 - v2;
case OPERATOR_MULTIPLICATION: return v1 * v2;
case OPERATOR_DIVISION: return v1 / checkZero(v2);
case OPERATOR_MODULO: return v1 % checkZero(v2);
case OPERATOR_POWER: return pow(v1, v2);
case OPERATOR_EXPONENT: return v1 * pow(10, v2);
default: return 0;
}
}
bool isEnd() const
{
return index_ >= expr_.size();
}
/// Returns the character at the current expression index or
/// 0 if the end of the expression is reached.
///
char getCharacter() const
{
if (!isEnd())
return expr_[index_];
return 0;
}
/// Parse str at the current expression index.
/// @throw error if parsing fails.
///
void expect(const std::string& str)
{
if (expr_.compare(index_, str.size(), str) != 0)
unexpected();
index_ += str.size();
}
void unexpected() const
{
std::ostringstream msg;
msg << "Syntax error: unexpected token \""
<< expr_.substr(index_, expr_.size() - index_)
<< "\" at index "
<< index_;
throw calculator::error(expr_, msg.str());
}
/// Eat all white space characters at the
/// current expression index.
///
void eatSpaces()
{
while (std::isspace(getCharacter()) != 0)
index_++;
}
/// Parse a binary operator at the current expression index.
/// @return Operator with precedence and associativity.
///
Operator parseOp()
{
eatSpaces();
switch (getCharacter())
{
case '|': index_++; return Operator(OPERATOR_BITWISE_OR, 4, 'L');
case '&': index_++; return Operator(OPERATOR_BITWISE_AND, 6, 'L');
case '<': expect("<<"); return Operator(OPERATOR_BITWISE_SHL, 9, 'L');
case '>': expect(">>"); return Operator(OPERATOR_BITWISE_SHR, 9, 'L');
case '+': index_++; return Operator(OPERATOR_ADDITION, 10, 'L');
case '-': index_++; return Operator(OPERATOR_SUBTRACTION, 10, 'L');
case '/': index_++; return Operator(OPERATOR_DIVISION, 20, 'L');
case '%': index_++; return Operator(OPERATOR_MODULO, 20, 'L');
case '*': index_++; if (getCharacter() != '*')
return Operator(OPERATOR_MULTIPLICATION, 20, 'L');
index_++; return Operator(OPERATOR_POWER, 30, 'R');
case '^': index_++; return Operator(OPERATOR_POWER, 30, 'R');
case 'e': index_++; return Operator(OPERATOR_EXPONENT, 40, 'R');
case 'E': index_++; return Operator(OPERATOR_EXPONENT, 40, 'R');
default : return Operator(OPERATOR_NULL, 0, 'L');
}
}
static T toInteger(char c)
{
if (c >= '0' && c <= '9') return c -'0';
if (c >= 'a' && c <= 'f') return c -'a' + 0xa;
if (c >= 'A' && c <= 'F') return c -'A' + 0xa;
T noDigit = 0xf + 1;
return noDigit;
}
T getInteger() const
{
return toInteger(getCharacter());
}
T parseDecimal()
{
T value = 0;
for (T d; (d = getInteger()) <= 9; index_++)
value = value * 10 + d;
return value;
}
T parseHex()
{
index_ = index_ + 2;
T value = 0;
for (T h; (h = getInteger()) <= 0xf; index_++)
value = value * 0x10 + h;
return value;
}
bool isHex() const
{
if (index_ + 2 < expr_.size())
{
char x = expr_[index_ + 1];
char h = expr_[index_ + 2];
return (std::tolower(x) == 'x' && toInteger(h) <= 0xf);
}
return false;
}
/// Parse an integer value at the current expression index.
/// The unary `+', `-' and `~' operators and opening
/// parentheses `(' cause recursion.
///
T parseValue()
{
T val = 0;
eatSpaces();
switch (getCharacter())
{
case '0': if (isHex())
{
val = parseHex();
break;
}
case '1': case '2': case '3': case '4': case '5':
case '6': case '7': case '8': case '9':
val = parseDecimal();
break;
case '(': index_++;
val = parseExpr();
eatSpaces();
if (getCharacter() != ')')
{
if (!isEnd())
unexpected();
throw calculator::error(expr_, "Syntax error: `)' expected at end of expression");
}
index_++; break;
case '~': index_++; val = ~parseValue(); break;
case '+': index_++; val = parseValue(); break;
case '-': index_++; val = parseValue() * static_cast<T>(-1);
break;
default : if (!isEnd())
unexpected();
throw calculator::error(expr_, "Syntax error: value expected at end of expression");
}
return val;
}
/// Parse all operations of the current parenthesis
/// level and the levels above, when done
/// return the result (value).
///
T parseExpr()
{
stack_.push(OperatorValue(Operator(OPERATOR_NULL, 0, 'L'), 0));
// first parse value on the left
T value = parseValue();
while (!stack_.empty())
{
// parse an operator (+, -, *, ...)
Operator op(parseOp());
while (op.precedence < stack_.top().getPrecedence() || (
op.precedence == stack_.top().getPrecedence() &&
op.associativity == 'L'))
{
// end reached
if (stack_.top().isNull())
{
stack_.pop();
return value;
}
// do the calculation ("reduce"), producing a new value
value = calculate(stack_.top().value, value, stack_.top().op);
stack_.pop();
}
// store on stack_ and continue parsing ("shift")
stack_.push(OperatorValue(op, value));
// parse value on the right
value = parseValue();
}
return 0;
}
};
template <typename T>
inline T eval(const std::string& expression)
{
ExpressionParser<T> parser;
return parser.eval(expression);
}
template <typename T>
inline T eval(char c)
{
ExpressionParser<T> parser;
return parser.eval(c);
}
inline int eval(const std::string& expression)
{
return eval<int>(expression);
}
inline int eval(char c)
{
return eval<int>(c);
}
} // namespace calculator
#endif
<commit_msg>Silence GCC 7 compiler warning<commit_after>///
/// @file calculator.hpp
/// @brief calculator::eval(const std::string&) evaluates an integer
/// arithmetic expression and returns the result. If an error
/// occurs a calculator::error exception is thrown.
/// <https://github.com/kimwalisch/calculator>
/// @author Kim Walisch, <kim.walisch@gmail.com>
/// @copyright Copyright (C) 2013 Kim Walisch
/// @date November 30, 2013
/// @license BSD 2-Clause, http://opensource.org/licenses/BSD-2-Clause
/// @version 1.0 patched: `^' is raise to power instead of XOR.
///
/// == Supported operators ==
///
/// OPERATOR NAME ASSOCIATIVITY PRECEDENCE
///
/// | Bitwise Inclusive OR Left 4
/// & Bitwise AND Left 6
/// << Shift Left Left 9
/// >> Shift Right Left 9
/// + Addition Left 10
/// - Subtraction Left 10
/// * Multiplication Left 20
/// / Division Left 20
/// % Modulo Left 20
/// ^, ** Raise to power Right 30
/// e, E Scientific notation Right 40
/// ~ Unary complement Left 99
///
/// The operator precedence has been set according to (uses the C and
/// C++ operator precedence): http://en.wikipedia.org/wiki/Order_of_operations
/// Operators with higher precedence are evaluated before operators
/// with relatively lower precedence. Unary operators are set to have
/// the highest precedence, this is not strictly correct for the power
/// operator e.g. "-3**2" = 9 but a lot of software tools (Bash shell,
/// Microsoft Excel, GNU bc, ...) use the same convention.
///
/// == Examples of valid expressions ==
///
/// "65536 >> 15" = 2
/// "2**16" = 65536
/// "(0 + 0xDf234 - 1000)*3/2%999" = 828
/// "-(2**2**2**2)" = -65536
/// "(0 + ~(0xDF234 & 1000) *3) /-2" = 817
/// "(2**16) + (1 << 16) >> 0X5" = 4096
/// "5*-(2**(9+7))/3+5*(1 & 0xFf123)" = -109221
///
/// == About the algorithm used ==
///
/// calculator::eval(std::string&) relies on the ExpressionParser
/// class which is a simple C++ operator precedence parser with infix
/// notation for integer arithmetic expressions.
/// ExpressionParser has its roots in a JavaScript parser published
/// at: http://stackoverflow.com/questions/28256/equation-expression-parser-with-precedence/114961#114961
/// The same author has also published an article about his operator
/// precedence algorithm at PerlMonks:
/// http://www.perlmonks.org/?node_id=554516
///
#ifndef CALCULATOR_HPP
#define CALCULATOR_HPP
#include <stdexcept>
#include <string>
#include <sstream>
#include <stack>
#include <cstddef>
#include <cctype>
namespace calculator
{
/// calculator::eval() throws a calculator::error if it fails
/// to evaluate the expression string.
///
class error : public std::runtime_error
{
public:
error(const std::string& expr, const std::string& message)
: std::runtime_error(message),
expr_(expr)
{ }
#if __cplusplus >= 201103L
~error() { }
#else
~error() throw() { }
#endif
std::string expression() const
{
return expr_;
}
private:
std::string expr_;
};
template <typename T>
class ExpressionParser
{
public:
/// Evaluate an integer arithmetic expression and return its result.
/// @throw error if parsing fails.
///
T eval(const std::string& expr)
{
T result = 0;
index_ = 0;
expr_ = expr;
try
{
result = parseExpr();
if (!isEnd())
unexpected();
}
catch (const calculator::error&)
{
while(!stack_.empty())
stack_.pop();
throw;
}
return result;
}
/// Get the integer value of a character.
T eval(char c)
{
std::string expr(1, c);
return eval(expr);
}
private:
enum
{
OPERATOR_NULL,
OPERATOR_BITWISE_OR, /// |
OPERATOR_BITWISE_XOR, /// ^
OPERATOR_BITWISE_AND, /// &
OPERATOR_BITWISE_SHL, /// <<
OPERATOR_BITWISE_SHR, /// >>
OPERATOR_ADDITION, /// +
OPERATOR_SUBTRACTION, /// -
OPERATOR_MULTIPLICATION, /// *
OPERATOR_DIVISION, /// /
OPERATOR_MODULO, /// %
OPERATOR_POWER, /// **
OPERATOR_EXPONENT /// e, E
};
struct Operator
{
/// Operator, one of the OPERATOR_* enum definitions
int op;
int precedence;
/// 'L' = left or 'R' = right
int associativity;
Operator(int opr, int prec, int assoc) :
op(opr),
precedence(prec),
associativity(assoc)
{ }
};
struct OperatorValue
{
Operator op;
T value;
OperatorValue(const Operator& opr, T val) :
op(opr),
value(val)
{ }
int getPrecedence() const
{
return op.precedence;
}
bool isNull() const
{
return op.op == OPERATOR_NULL;
}
};
/// Expression string
std::string expr_;
/// Current expression index, incremented whilst parsing
std::size_t index_;
/// The current operator and its left value
/// are pushed onto the stack if the operator on
/// top of the stack has lower precedence.
std::stack<OperatorValue> stack_;
/// Exponentiation by squaring, x^n.
static T pow(T x, T n)
{
T res = 1;
while (n != 0)
{
if (n % 2 != 0)
{
res *= x;
n -= 1;
}
x *= x;
n /= 2;
}
return res;
}
T checkZero(T value) const
{
if (value == 0)
{
std::string divOperators("/%");
std::size_t division = expr_.find_last_of(divOperators, index_ - 2);
std::ostringstream msg;
msg << "Parser error: division by 0";
if (division != std::string::npos)
msg << " (error token is \""
<< expr_.substr(division, expr_.size() - division)
<< "\")";
throw calculator::error(expr_, msg.str());
}
return value;
}
T calculate(T v1, T v2, const Operator& op) const
{
switch (op.op)
{
case OPERATOR_BITWISE_OR: return v1 | v2;
case OPERATOR_BITWISE_XOR: return v1 ^ v2;
case OPERATOR_BITWISE_AND: return v1 & v2;
case OPERATOR_BITWISE_SHL: return v1 << v2;
case OPERATOR_BITWISE_SHR: return v1 >> v2;
case OPERATOR_ADDITION: return v1 + v2;
case OPERATOR_SUBTRACTION: return v1 - v2;
case OPERATOR_MULTIPLICATION: return v1 * v2;
case OPERATOR_DIVISION: return v1 / checkZero(v2);
case OPERATOR_MODULO: return v1 % checkZero(v2);
case OPERATOR_POWER: return pow(v1, v2);
case OPERATOR_EXPONENT: return v1 * pow(10, v2);
default: return 0;
}
}
bool isEnd() const
{
return index_ >= expr_.size();
}
/// Returns the character at the current expression index or
/// 0 if the end of the expression is reached.
///
char getCharacter() const
{
if (!isEnd())
return expr_[index_];
return 0;
}
/// Parse str at the current expression index.
/// @throw error if parsing fails.
///
void expect(const std::string& str)
{
if (expr_.compare(index_, str.size(), str) != 0)
unexpected();
index_ += str.size();
}
void unexpected() const
{
std::ostringstream msg;
msg << "Syntax error: unexpected token \""
<< expr_.substr(index_, expr_.size() - index_)
<< "\" at index "
<< index_;
throw calculator::error(expr_, msg.str());
}
/// Eat all white space characters at the
/// current expression index.
///
void eatSpaces()
{
while (std::isspace(getCharacter()) != 0)
index_++;
}
/// Parse a binary operator at the current expression index.
/// @return Operator with precedence and associativity.
///
Operator parseOp()
{
eatSpaces();
switch (getCharacter())
{
case '|': index_++; return Operator(OPERATOR_BITWISE_OR, 4, 'L');
case '&': index_++; return Operator(OPERATOR_BITWISE_AND, 6, 'L');
case '<': expect("<<"); return Operator(OPERATOR_BITWISE_SHL, 9, 'L');
case '>': expect(">>"); return Operator(OPERATOR_BITWISE_SHR, 9, 'L');
case '+': index_++; return Operator(OPERATOR_ADDITION, 10, 'L');
case '-': index_++; return Operator(OPERATOR_SUBTRACTION, 10, 'L');
case '/': index_++; return Operator(OPERATOR_DIVISION, 20, 'L');
case '%': index_++; return Operator(OPERATOR_MODULO, 20, 'L');
case '*': index_++; if (getCharacter() != '*')
return Operator(OPERATOR_MULTIPLICATION, 20, 'L');
index_++; return Operator(OPERATOR_POWER, 30, 'R');
case '^': index_++; return Operator(OPERATOR_POWER, 30, 'R');
case 'e': index_++; return Operator(OPERATOR_EXPONENT, 40, 'R');
case 'E': index_++; return Operator(OPERATOR_EXPONENT, 40, 'R');
default : return Operator(OPERATOR_NULL, 0, 'L');
}
}
static T toInteger(char c)
{
if (c >= '0' && c <= '9') return c -'0';
if (c >= 'a' && c <= 'f') return c -'a' + 0xa;
if (c >= 'A' && c <= 'F') return c -'A' + 0xa;
T noDigit = 0xf + 1;
return noDigit;
}
T getInteger() const
{
return toInteger(getCharacter());
}
T parseDecimal()
{
T value = 0;
for (T d; (d = getInteger()) <= 9; index_++)
value = value * 10 + d;
return value;
}
T parseHex()
{
index_ = index_ + 2;
T value = 0;
for (T h; (h = getInteger()) <= 0xf; index_++)
value = value * 0x10 + h;
return value;
}
bool isHex() const
{
if (index_ + 2 < expr_.size())
{
char x = expr_[index_ + 1];
char h = expr_[index_ + 2];
return (std::tolower(x) == 'x' && toInteger(h) <= 0xf);
}
return false;
}
/// Parse an integer value at the current expression index.
/// The unary `+', `-' and `~' operators and opening
/// parentheses `(' cause recursion.
///
T parseValue()
{
T val = 0;
eatSpaces();
switch (getCharacter())
{
case '0': if (isHex())
val = parseHex();
else
val = parseDecimal();
break;
case '1': case '2': case '3': case '4': case '5':
case '6': case '7': case '8': case '9':
val = parseDecimal();
break;
case '(': index_++;
val = parseExpr();
eatSpaces();
if (getCharacter() != ')')
{
if (!isEnd())
unexpected();
throw calculator::error(expr_, "Syntax error: `)' expected at end of expression");
}
index_++; break;
case '~': index_++; val = ~parseValue(); break;
case '+': index_++; val = parseValue(); break;
case '-': index_++; val = parseValue() * static_cast<T>(-1);
break;
default : if (!isEnd())
unexpected();
throw calculator::error(expr_, "Syntax error: value expected at end of expression");
}
return val;
}
/// Parse all operations of the current parenthesis
/// level and the levels above, when done
/// return the result (value).
///
T parseExpr()
{
stack_.push(OperatorValue(Operator(OPERATOR_NULL, 0, 'L'), 0));
// first parse value on the left
T value = parseValue();
while (!stack_.empty())
{
// parse an operator (+, -, *, ...)
Operator op(parseOp());
while (op.precedence < stack_.top().getPrecedence() || (
op.precedence == stack_.top().getPrecedence() &&
op.associativity == 'L'))
{
// end reached
if (stack_.top().isNull())
{
stack_.pop();
return value;
}
// do the calculation ("reduce"), producing a new value
value = calculate(stack_.top().value, value, stack_.top().op);
stack_.pop();
}
// store on stack_ and continue parsing ("shift")
stack_.push(OperatorValue(op, value));
// parse value on the right
value = parseValue();
}
return 0;
}
};
template <typename T>
inline T eval(const std::string& expression)
{
ExpressionParser<T> parser;
return parser.eval(expression);
}
template <typename T>
inline T eval(char c)
{
ExpressionParser<T> parser;
return parser.eval(c);
}
inline int eval(const std::string& expression)
{
return eval<int>(expression);
}
inline int eval(char c)
{
return eval<int>(c);
}
} // namespace calculator
#endif
<|endoftext|>
|
<commit_before>/*
*
* Copyright 2015 gRPC authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
#include <grpc/support/port_platform.h>
#include "src/core/lib/gpr/string.h"
#include <ctype.h>
#include <limits.h>
#include <stddef.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include "absl/strings/str_cat.h"
#include <grpc/support/alloc.h>
#include <grpc/support/log.h>
#include <grpc/support/string_util.h>
#include "src/core/lib/gpr/useful.h"
char* gpr_strdup(const char* src) {
char* dst;
size_t len;
if (!src) {
return nullptr;
}
len = strlen(src) + 1;
dst = static_cast<char*>(gpr_malloc(len));
memcpy(dst, src, len);
return dst;
}
std::string gpr_format_timespec(gpr_timespec tm) {
char time_buffer[35];
char ns_buffer[11]; // '.' + 9 digits of precision
struct tm* tm_info = localtime((const time_t*)&tm.tv_sec);
strftime(time_buffer, sizeof(time_buffer), "%Y-%m-%dT%H:%M:%S", tm_info);
snprintf(ns_buffer, 11, ".%09d", tm.tv_nsec);
// This loop trims off trailing zeros by inserting a null character that the
// right point. We iterate in chunks of three because we want 0, 3, 6, or 9
// fractional digits.
for (int i = 7; i >= 1; i -= 3) {
if (ns_buffer[i] == '0' && ns_buffer[i + 1] == '0' &&
ns_buffer[i + 2] == '0') {
ns_buffer[i] = '\0';
// Edge case in which all fractional digits were 0.
if (i == 1) {
ns_buffer[0] = '\0';
}
} else {
break;
}
}
return absl::StrCat(time_buffer, ns_buffer, "Z");
}
struct dump_out {
size_t capacity;
size_t length;
char* data;
};
static dump_out dump_out_create(void) {
dump_out r = {0, 0, nullptr};
return r;
}
static void dump_out_append(dump_out* out, char c) {
if (out->length == out->capacity) {
out->capacity = GPR_MAX(8, 2 * out->capacity);
out->data = static_cast<char*>(gpr_realloc(out->data, out->capacity));
}
out->data[out->length++] = c;
}
static void hexdump(dump_out* out, const char* buf, size_t len) {
static const char* hex = "0123456789abcdef";
const uint8_t* const beg = reinterpret_cast<const uint8_t*>(buf);
const uint8_t* const end = beg + len;
const uint8_t* cur;
for (cur = beg; cur != end; ++cur) {
if (cur != beg) dump_out_append(out, ' ');
dump_out_append(out, hex[*cur >> 4]);
dump_out_append(out, hex[*cur & 0xf]);
}
}
static void asciidump(dump_out* out, const char* buf, size_t len) {
const uint8_t* const beg = reinterpret_cast<const uint8_t*>(buf);
const uint8_t* const end = beg + len;
const uint8_t* cur;
int out_was_empty = (out->length == 0);
if (!out_was_empty) {
dump_out_append(out, ' ');
dump_out_append(out, '\'');
}
for (cur = beg; cur != end; ++cur) {
dump_out_append(out, (isprint(*cur) ? *(char*)cur : '.'));
}
if (!out_was_empty) {
dump_out_append(out, '\'');
}
}
char* gpr_dump_return_len(const char* buf, size_t len, uint32_t flags,
size_t* out_len) {
dump_out out = dump_out_create();
if (flags & GPR_DUMP_HEX) {
hexdump(&out, buf, len);
}
if (flags & GPR_DUMP_ASCII) {
asciidump(&out, buf, len);
}
dump_out_append(&out, 0);
*out_len = out.length;
return out.data;
}
char* gpr_dump(const char* buf, size_t len, uint32_t flags) {
size_t unused;
return gpr_dump_return_len(buf, len, flags, &unused);
}
int gpr_parse_bytes_to_uint32(const char* buf, size_t len, uint32_t* result) {
uint32_t out = 0;
uint32_t new_val;
size_t i;
if (len == 0) return 0; /* must have some bytes */
for (i = 0; i < len; i++) {
if (buf[i] < '0' || buf[i] > '9') return 0; /* bad char */
new_val = 10 * out + static_cast<uint32_t>(buf[i] - '0');
if (new_val < out) return 0; /* overflow */
out = new_val;
}
*result = out;
return 1;
}
void gpr_reverse_bytes(char* str, int len) {
char *p1, *p2;
for (p1 = str, p2 = str + len - 1; p2 > p1; ++p1, --p2) {
char temp = *p1;
*p1 = *p2;
*p2 = temp;
}
}
int gpr_ltoa(long value, char* string) {
long sign;
int i = 0;
if (value == 0) {
string[0] = '0';
string[1] = 0;
return 1;
}
sign = value < 0 ? -1 : 1;
while (value) {
string[i++] = static_cast<char>('0' + sign * (value % 10));
value /= 10;
}
if (sign < 0) string[i++] = '-';
gpr_reverse_bytes(string, i);
string[i] = 0;
return i;
}
int int64_ttoa(int64_t value, char* string) {
int64_t sign;
int i = 0;
if (value == 0) {
string[0] = '0';
string[1] = 0;
return 1;
}
sign = value < 0 ? -1 : 1;
while (value) {
string[i++] = static_cast<char>('0' + sign * (value % 10));
value /= 10;
}
if (sign < 0) string[i++] = '-';
gpr_reverse_bytes(string, i);
string[i] = 0;
return i;
}
int gpr_parse_nonnegative_int(const char* value) {
char* end;
long result = strtol(value, &end, 0);
if (*end != '\0' || result < 0 || result > INT_MAX) return -1;
return static_cast<int>(result);
}
char* gpr_leftpad(const char* str, char flag, size_t length) {
const size_t str_length = strlen(str);
const size_t out_length = str_length > length ? str_length : length;
char* out = static_cast<char*>(gpr_malloc(out_length + 1));
memset(out, flag, out_length - str_length);
memcpy(out + out_length - str_length, str, str_length);
out[out_length] = 0;
return out;
}
char* gpr_strjoin(const char** strs, size_t nstrs, size_t* final_length) {
return gpr_strjoin_sep(strs, nstrs, "", final_length);
}
char* gpr_strjoin_sep(const char** strs, size_t nstrs, const char* sep,
size_t* final_length) {
const size_t sep_len = strlen(sep);
size_t out_length = 0;
size_t i;
char* out;
for (i = 0; i < nstrs; i++) {
out_length += strlen(strs[i]);
}
out_length += 1; /* null terminator */
if (nstrs > 0) {
out_length += sep_len * (nstrs - 1); /* separators */
}
out = static_cast<char*>(gpr_malloc(out_length));
out_length = 0;
for (i = 0; i < nstrs; i++) {
const size_t slen = strlen(strs[i]);
if (i != 0) {
memcpy(out + out_length, sep, sep_len);
out_length += sep_len;
}
memcpy(out + out_length, strs[i], slen);
out_length += slen;
}
out[out_length] = 0;
if (final_length != nullptr) {
*final_length = out_length;
}
return out;
}
int gpr_strincmp(const char* a, const char* b, size_t n) {
int ca, cb;
do {
ca = tolower(*a);
cb = tolower(*b);
++a;
++b;
--n;
} while (ca == cb && ca != 0 && cb != 0 && n != 0);
return ca - cb;
}
int gpr_stricmp(const char* a, const char* b) {
return gpr_strincmp(a, b, SIZE_MAX);
}
static void add_string_to_split(const char* beg, const char* end, char*** strs,
size_t* nstrs, size_t* capstrs) {
char* out =
static_cast<char*>(gpr_malloc(static_cast<size_t>(end - beg) + 1));
memcpy(out, beg, static_cast<size_t>(end - beg));
out[end - beg] = 0;
if (*nstrs == *capstrs) {
*capstrs = GPR_MAX(8, 2 * *capstrs);
*strs = static_cast<char**>(gpr_realloc(*strs, sizeof(*strs) * *capstrs));
}
(*strs)[*nstrs] = out;
++*nstrs;
}
void gpr_string_split(const char* input, const char* sep, char*** strs,
size_t* nstrs) {
const char* next;
*strs = nullptr;
*nstrs = 0;
size_t capstrs = 0;
while ((next = strstr(input, sep))) {
add_string_to_split(input, next, strs, nstrs, &capstrs);
input = next + strlen(sep);
}
add_string_to_split(input, input + strlen(input), strs, nstrs, &capstrs);
}
void* gpr_memrchr(const void* s, int c, size_t n) {
if (s == nullptr) return nullptr;
char* b = (char*)s;
size_t i;
for (i = 0; i < n; i++) {
if (b[n - i - 1] == c) {
return &b[n - i - 1];
}
}
return nullptr;
}
bool gpr_parse_bool_value(const char* s, bool* dst) {
const char* kTrue[] = {"1", "t", "true", "y", "yes"};
const char* kFalse[] = {"0", "f", "false", "n", "no"};
static_assert(sizeof(kTrue) == sizeof(kFalse), "true_false_equal");
if (s == nullptr) {
return false;
}
for (size_t i = 0; i < GPR_ARRAY_SIZE(kTrue); ++i) {
if (gpr_stricmp(s, kTrue[i]) == 0) {
*dst = true;
return true;
} else if (gpr_stricmp(s, kFalse[i]) == 0) {
*dst = false;
return true;
}
}
return false; // didn't match a legal input
}
<commit_msg>Hard code the base of the string to decimal<commit_after>/*
*
* Copyright 2015 gRPC authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
#include <grpc/support/port_platform.h>
#include "src/core/lib/gpr/string.h"
#include <ctype.h>
#include <limits.h>
#include <stddef.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include "absl/strings/str_cat.h"
#include <grpc/support/alloc.h>
#include <grpc/support/log.h>
#include <grpc/support/string_util.h>
#include "src/core/lib/gpr/useful.h"
char* gpr_strdup(const char* src) {
char* dst;
size_t len;
if (!src) {
return nullptr;
}
len = strlen(src) + 1;
dst = static_cast<char*>(gpr_malloc(len));
memcpy(dst, src, len);
return dst;
}
std::string gpr_format_timespec(gpr_timespec tm) {
char time_buffer[35];
char ns_buffer[11]; // '.' + 9 digits of precision
struct tm* tm_info = localtime((const time_t*)&tm.tv_sec);
strftime(time_buffer, sizeof(time_buffer), "%Y-%m-%dT%H:%M:%S", tm_info);
snprintf(ns_buffer, 11, ".%09d", tm.tv_nsec);
// This loop trims off trailing zeros by inserting a null character that the
// right point. We iterate in chunks of three because we want 0, 3, 6, or 9
// fractional digits.
for (int i = 7; i >= 1; i -= 3) {
if (ns_buffer[i] == '0' && ns_buffer[i + 1] == '0' &&
ns_buffer[i + 2] == '0') {
ns_buffer[i] = '\0';
// Edge case in which all fractional digits were 0.
if (i == 1) {
ns_buffer[0] = '\0';
}
} else {
break;
}
}
return absl::StrCat(time_buffer, ns_buffer, "Z");
}
struct dump_out {
size_t capacity;
size_t length;
char* data;
};
static dump_out dump_out_create(void) {
dump_out r = {0, 0, nullptr};
return r;
}
static void dump_out_append(dump_out* out, char c) {
if (out->length == out->capacity) {
out->capacity = GPR_MAX(8, 2 * out->capacity);
out->data = static_cast<char*>(gpr_realloc(out->data, out->capacity));
}
out->data[out->length++] = c;
}
static void hexdump(dump_out* out, const char* buf, size_t len) {
static const char* hex = "0123456789abcdef";
const uint8_t* const beg = reinterpret_cast<const uint8_t*>(buf);
const uint8_t* const end = beg + len;
const uint8_t* cur;
for (cur = beg; cur != end; ++cur) {
if (cur != beg) dump_out_append(out, ' ');
dump_out_append(out, hex[*cur >> 4]);
dump_out_append(out, hex[*cur & 0xf]);
}
}
static void asciidump(dump_out* out, const char* buf, size_t len) {
const uint8_t* const beg = reinterpret_cast<const uint8_t*>(buf);
const uint8_t* const end = beg + len;
const uint8_t* cur;
int out_was_empty = (out->length == 0);
if (!out_was_empty) {
dump_out_append(out, ' ');
dump_out_append(out, '\'');
}
for (cur = beg; cur != end; ++cur) {
dump_out_append(out, (isprint(*cur) ? *(char*)cur : '.'));
}
if (!out_was_empty) {
dump_out_append(out, '\'');
}
}
char* gpr_dump_return_len(const char* buf, size_t len, uint32_t flags,
size_t* out_len) {
dump_out out = dump_out_create();
if (flags & GPR_DUMP_HEX) {
hexdump(&out, buf, len);
}
if (flags & GPR_DUMP_ASCII) {
asciidump(&out, buf, len);
}
dump_out_append(&out, 0);
*out_len = out.length;
return out.data;
}
char* gpr_dump(const char* buf, size_t len, uint32_t flags) {
size_t unused;
return gpr_dump_return_len(buf, len, flags, &unused);
}
int gpr_parse_bytes_to_uint32(const char* buf, size_t len, uint32_t* result) {
uint32_t out = 0;
uint32_t new_val;
size_t i;
if (len == 0) return 0; /* must have some bytes */
for (i = 0; i < len; i++) {
if (buf[i] < '0' || buf[i] > '9') return 0; /* bad char */
new_val = 10 * out + static_cast<uint32_t>(buf[i] - '0');
if (new_val < out) return 0; /* overflow */
out = new_val;
}
*result = out;
return 1;
}
void gpr_reverse_bytes(char* str, int len) {
char *p1, *p2;
for (p1 = str, p2 = str + len - 1; p2 > p1; ++p1, --p2) {
char temp = *p1;
*p1 = *p2;
*p2 = temp;
}
}
int gpr_ltoa(long value, char* string) {
long sign;
int i = 0;
if (value == 0) {
string[0] = '0';
string[1] = 0;
return 1;
}
sign = value < 0 ? -1 : 1;
while (value) {
string[i++] = static_cast<char>('0' + sign * (value % 10));
value /= 10;
}
if (sign < 0) string[i++] = '-';
gpr_reverse_bytes(string, i);
string[i] = 0;
return i;
}
int int64_ttoa(int64_t value, char* string) {
int64_t sign;
int i = 0;
if (value == 0) {
string[0] = '0';
string[1] = 0;
return 1;
}
sign = value < 0 ? -1 : 1;
while (value) {
string[i++] = static_cast<char>('0' + sign * (value % 10));
value /= 10;
}
if (sign < 0) string[i++] = '-';
gpr_reverse_bytes(string, i);
string[i] = 0;
return i;
}
int gpr_parse_nonnegative_int(const char* value) {
char* end;
long result = strtol(value, &end, 10);
if (*end != '\0' || result < 0 || result > INT_MAX) return -1;
return static_cast<int>(result);
}
char* gpr_leftpad(const char* str, char flag, size_t length) {
const size_t str_length = strlen(str);
const size_t out_length = str_length > length ? str_length : length;
char* out = static_cast<char*>(gpr_malloc(out_length + 1));
memset(out, flag, out_length - str_length);
memcpy(out + out_length - str_length, str, str_length);
out[out_length] = 0;
return out;
}
char* gpr_strjoin(const char** strs, size_t nstrs, size_t* final_length) {
return gpr_strjoin_sep(strs, nstrs, "", final_length);
}
char* gpr_strjoin_sep(const char** strs, size_t nstrs, const char* sep,
size_t* final_length) {
const size_t sep_len = strlen(sep);
size_t out_length = 0;
size_t i;
char* out;
for (i = 0; i < nstrs; i++) {
out_length += strlen(strs[i]);
}
out_length += 1; /* null terminator */
if (nstrs > 0) {
out_length += sep_len * (nstrs - 1); /* separators */
}
out = static_cast<char*>(gpr_malloc(out_length));
out_length = 0;
for (i = 0; i < nstrs; i++) {
const size_t slen = strlen(strs[i]);
if (i != 0) {
memcpy(out + out_length, sep, sep_len);
out_length += sep_len;
}
memcpy(out + out_length, strs[i], slen);
out_length += slen;
}
out[out_length] = 0;
if (final_length != nullptr) {
*final_length = out_length;
}
return out;
}
int gpr_strincmp(const char* a, const char* b, size_t n) {
int ca, cb;
do {
ca = tolower(*a);
cb = tolower(*b);
++a;
++b;
--n;
} while (ca == cb && ca != 0 && cb != 0 && n != 0);
return ca - cb;
}
int gpr_stricmp(const char* a, const char* b) {
return gpr_strincmp(a, b, SIZE_MAX);
}
static void add_string_to_split(const char* beg, const char* end, char*** strs,
size_t* nstrs, size_t* capstrs) {
char* out =
static_cast<char*>(gpr_malloc(static_cast<size_t>(end - beg) + 1));
memcpy(out, beg, static_cast<size_t>(end - beg));
out[end - beg] = 0;
if (*nstrs == *capstrs) {
*capstrs = GPR_MAX(8, 2 * *capstrs);
*strs = static_cast<char**>(gpr_realloc(*strs, sizeof(*strs) * *capstrs));
}
(*strs)[*nstrs] = out;
++*nstrs;
}
void gpr_string_split(const char* input, const char* sep, char*** strs,
size_t* nstrs) {
const char* next;
*strs = nullptr;
*nstrs = 0;
size_t capstrs = 0;
while ((next = strstr(input, sep))) {
add_string_to_split(input, next, strs, nstrs, &capstrs);
input = next + strlen(sep);
}
add_string_to_split(input, input + strlen(input), strs, nstrs, &capstrs);
}
void* gpr_memrchr(const void* s, int c, size_t n) {
if (s == nullptr) return nullptr;
char* b = (char*)s;
size_t i;
for (i = 0; i < n; i++) {
if (b[n - i - 1] == c) {
return &b[n - i - 1];
}
}
return nullptr;
}
bool gpr_parse_bool_value(const char* s, bool* dst) {
const char* kTrue[] = {"1", "t", "true", "y", "yes"};
const char* kFalse[] = {"0", "f", "false", "n", "no"};
static_assert(sizeof(kTrue) == sizeof(kFalse), "true_false_equal");
if (s == nullptr) {
return false;
}
for (size_t i = 0; i < GPR_ARRAY_SIZE(kTrue); ++i) {
if (gpr_stricmp(s, kTrue[i]) == 0) {
*dst = true;
return true;
} else if (gpr_stricmp(s, kFalse[i]) == 0) {
*dst = false;
return true;
}
}
return false; // didn't match a legal input
}
<|endoftext|>
|
<commit_before>/*
** Author(s):
** - Laurent LEC <llec@aldebaran-robotics.com>
**
** Copyright (C) 2012 Aldebaran Robotics
*/
#include <iostream>
#include <string>
#include <map>
#include <event2/util.h>
#include <event2/event.h>
#include <event2/buffer.h>
#include <event2/bufferevent.h>
#include <event2/listener.h>
#include <event2/thread.h>
#include <qi/os.hpp>
#include <qimessaging/session.hpp>
#include <qimessaging/transport_socket.hpp>
#include <qimessaging/object.hpp>
#include <qi/log.hpp>
#ifdef _WIN32
#include <winsock2.h> // for socket
#include <WS2tcpip.h> // for socklen_t
#else
#include <pthread.h>
#include <arpa/inet.h>
#endif
size_t socket_read(struct bufferevent *bev,
void *data,
size_t size)
{
struct evbuffer *input = bufferevent_get_input(bev);
return evbuffer_remove(input, data, size);;
}
bool socket_write(struct bufferevent *bev,
const void *data,
size_t size)
{
evbuffer *evb = evbuffer_new();
evbuffer_add(evb, data, size);
return bufferevent_write_buffer(bev, evb) == 0;
}
void readcb(struct bufferevent *bev, void* context)
{
std::cout << "readcb" << std::endl;
char buffer[1024];
size_t read = socket_read(bev, buffer, sizeof(buffer));
socket_write(bev, buffer, read);
}
void writecb(struct bufferevent *bev, void* context)
{
std::cout << "writecb" << std::endl;
}
void eventcb(struct bufferevent *bev, short events, void *context)
{
std::cout << "eventcb" << std::endl;
if (events & BEV_EVENT_CONNECTED)
{
qiLogInfo("qimessaging.TransportSocket") << "BEV_EVENT_CONNECTED" << std::endl;
}
else if (events & BEV_EVENT_EOF)
{
qiLogInfo("qimessaging.TransportSocket") << "BEV_EVENT_EOF" << std::endl;
}
else if (events & BEV_EVENT_ERROR)
{
bufferevent_free(bev);
qiLogError("qimessaging.TransportSocket") << "BEV_EVENT_ERROR" << std::endl;
}
else if (events & BEV_EVENT_TIMEOUT)
{
qiLogError("qimessaging.TransportSocket") << "BEV_EVENT_TIMEOUT" << std::endl;
}
}
void accept(int fd, struct event_base *base)
{
std::cout << "accept" << std::endl;
bufferevent *bev = bufferevent_socket_new(base, fd, BEV_OPT_CLOSE_ON_FREE);
bufferevent_setcb(bev, readcb, writecb, eventcb, 0);
bufferevent_enable(bev, EV_READ | EV_WRITE);
}
void accept_cb(struct evconnlistener *listener,
evutil_socket_t fd,
struct sockaddr *a,
int slen,
void *p)
{
std::cout << "accept_cb" << std::endl;
struct event_base *base = evconnlistener_get_base(listener);
accept(fd, base);
}
int start_server(const qi::Url &url, struct event_base *base)
{
struct evconnlistener *listener;
static struct sockaddr_storage listen_on_addr;
memset(&listen_on_addr, 0, sizeof(listen_on_addr));
int socklen = sizeof(listen_on_addr);
struct sockaddr_in *sin = reinterpret_cast<struct sockaddr_in *>(&listen_on_addr);
socklen = sizeof(struct sockaddr_in);
sin->sin_port = htons(url.port());
sin->sin_family = AF_INET;
if ((sin->sin_addr.s_addr = inet_addr(url.host().c_str())) == INADDR_NONE)
{
qiLogError("qimessaging.transportserver") << "Provided IP is not valid" << std::endl;
return false;
}
listener = evconnlistener_new_bind(base,
accept_cb,
0,
LEV_OPT_CLOSE_ON_FREE | LEV_OPT_CLOSE_ON_EXEC | LEV_OPT_REUSEABLE,
-1,
(struct sockaddr*)&listen_on_addr,
socklen);
return 0;
}
void *network_thread(void *arg)
{
event_base_dispatch(reinterpret_cast<struct event_base *>(arg));
return 0;
}
static void errorcb(struct bufferevent *bev,
short error,
void *context)
{
std::cout << "errorcb" << std::endl;
}
void *network_thread2(void *arg)
{
struct event_base *base = reinterpret_cast<struct event_base *>(arg);
/* hack to keep the loop running */
struct bufferevent *bev = bufferevent_socket_new(base, -1, BEV_OPT_CLOSE_ON_FREE | BEV_OPT_THREADSAFE);
bufferevent_setcb(bev, 0, 0, errorcb, 0);
bufferevent_enable(bev, EV_READ | EV_WRITE);
event_base_dispatch(reinterpret_cast<struct event_base *>(arg));
std::cout << "exit" << std::endl;
return 0;
}
int main()
{
std::cout << "Starting..." << std::endl;
#ifdef _WIN32
// libevent does not call WSAStartup
WSADATA WSAData;
// TODO: handle return code
::WSAStartup(MAKEWORD(1, 0), &WSAData);
#endif
#ifdef EVTHREAD_USE_WINDOWS_THREADS_IMPLEMENTED
evthread_use_windows_threads();
#endif
#ifdef EVTHREAD_USE_PTHREADS_IMPLEMENTED
evthread_use_pthreads();
#endif
pthread_t server_thread;
struct event_base *server_base = event_base_new();
qi::Url server_url("tcp://127.0.0.1:9571");
start_server(server_url, server_base);
pthread_create(&server_thread, 0, network_thread, server_base);
pthread_t client_thread;
struct event_base *client_base = event_base_new();
qi::Url client_url("tcp://127.0.0.1:5555");
pthread_create(&client_thread, 0, network_thread2, client_base);
// test send
sleep(1); // wait for the thread to start
struct bufferevent *bev = bufferevent_socket_new(client_base, -1, BEV_OPT_CLOSE_ON_FREE | BEV_OPT_THREADSAFE);
bufferevent_setcb(bev, readcb, writecb, eventcb, 0);
bufferevent_socket_connect_hostname(bev, 0, AF_INET,
client_url.host().c_str(), client_url.port());
socket_write(bev, "CHICHE", 6);
pthread_join(client_thread, 0);
pthread_join(server_thread, 0);
return 0;
}
<commit_msg>Use boost::thread instead of pthread.<commit_after>/*
** Author(s):
** - Laurent LEC <llec@aldebaran-robotics.com>
**
** Copyright (C) 2012 Aldebaran Robotics
*/
#include <iostream>
#include <string>
#include <map>
#include <event2/util.h>
#include <event2/event.h>
#include <event2/buffer.h>
#include <event2/bufferevent.h>
#include <event2/listener.h>
#include <event2/thread.h>
#include <qi/os.hpp>
#include <qimessaging/session.hpp>
#include <qimessaging/transport_socket.hpp>
#include <qimessaging/object.hpp>
#include <qi/log.hpp>
#include <boost/thread.hpp>
#ifdef _WIN32
#include <winsock2.h> // for socket
#include <WS2tcpip.h> // for socklen_t
#else
#include <arpa/inet.h>
#endif
size_t socket_read(struct bufferevent *bev,
void *data,
size_t size)
{
struct evbuffer *input = bufferevent_get_input(bev);
return evbuffer_remove(input, data, size);;
}
bool socket_write(struct bufferevent *bev,
const void *data,
size_t size)
{
evbuffer *evb = evbuffer_new();
evbuffer_add(evb, data, size);
return bufferevent_write_buffer(bev, evb) == 0;
}
void readcb(struct bufferevent *bev, void* context)
{
std::cout << "readcb" << std::endl;
char buffer[1024];
size_t read = socket_read(bev, buffer, sizeof(buffer));
socket_write(bev, buffer, read);
}
void writecb(struct bufferevent *bev, void* context)
{
std::cout << "writecb" << std::endl;
}
void eventcb(struct bufferevent *bev, short events, void *context)
{
std::cout << "eventcb" << std::endl;
if (events & BEV_EVENT_CONNECTED)
{
qiLogInfo("qimessaging.TransportSocket") << "BEV_EVENT_CONNECTED" << std::endl;
}
else if (events & BEV_EVENT_EOF)
{
qiLogInfo("qimessaging.TransportSocket") << "BEV_EVENT_EOF" << std::endl;
}
else if (events & BEV_EVENT_ERROR)
{
bufferevent_free(bev);
qiLogError("qimessaging.TransportSocket") << "BEV_EVENT_ERROR" << std::endl;
}
else if (events & BEV_EVENT_TIMEOUT)
{
qiLogError("qimessaging.TransportSocket") << "BEV_EVENT_TIMEOUT" << std::endl;
}
}
void accept(int fd, struct event_base *base)
{
std::cout << "accept" << std::endl;
bufferevent *bev = bufferevent_socket_new(base, fd, BEV_OPT_CLOSE_ON_FREE);
bufferevent_setcb(bev, readcb, writecb, eventcb, 0);
bufferevent_enable(bev, EV_READ | EV_WRITE);
}
void accept_cb(struct evconnlistener *listener,
evutil_socket_t fd,
struct sockaddr *a,
int slen,
void *p)
{
std::cout << "accept_cb" << std::endl;
struct event_base *base = evconnlistener_get_base(listener);
accept(fd, base);
}
int start_server(const qi::Url &url, struct event_base *base)
{
struct evconnlistener *listener;
static struct sockaddr_storage listen_on_addr;
memset(&listen_on_addr, 0, sizeof(listen_on_addr));
int socklen = sizeof(listen_on_addr);
struct sockaddr_in *sin = reinterpret_cast<struct sockaddr_in *>(&listen_on_addr);
socklen = sizeof(struct sockaddr_in);
sin->sin_port = htons(url.port());
sin->sin_family = AF_INET;
if ((sin->sin_addr.s_addr = inet_addr(url.host().c_str())) == INADDR_NONE)
{
qiLogError("qimessaging.transportserver") << "Provided IP is not valid" << std::endl;
return false;
}
listener = evconnlistener_new_bind(base,
accept_cb,
0,
LEV_OPT_CLOSE_ON_FREE | LEV_OPT_CLOSE_ON_EXEC | LEV_OPT_REUSEABLE,
-1,
(struct sockaddr*)&listen_on_addr,
socklen);
return 0;
}
void *network_thread(void *arg)
{
event_base_dispatch(reinterpret_cast<struct event_base *>(arg));
return 0;
}
static void errorcb(struct bufferevent *bev,
short error,
void *context)
{
std::cout << "errorcb" << std::endl;
}
void *network_thread2(void *arg)
{
struct event_base *base = reinterpret_cast<struct event_base *>(arg);
/* hack to keep the loop running */
struct bufferevent *bev = bufferevent_socket_new(base, -1, BEV_OPT_CLOSE_ON_FREE | BEV_OPT_THREADSAFE);
bufferevent_setcb(bev, 0, 0, errorcb, 0);
bufferevent_enable(bev, EV_READ | EV_WRITE);
event_base_dispatch(reinterpret_cast<struct event_base *>(arg));
std::cout << "exit" << std::endl;
return 0;
}
int main()
{
std::cout << "Starting..." << std::endl;
#ifdef _WIN32
// libevent does not call WSAStartup
WSADATA WSAData;
// TODO: handle return code
::WSAStartup(MAKEWORD(1, 0), &WSAData);
#endif
#ifdef EVTHREAD_USE_WINDOWS_THREADS_IMPLEMENTED
evthread_use_windows_threads();
#endif
#ifdef EVTHREAD_USE_PTHREADS_IMPLEMENTED
evthread_use_pthreads();
#endif
struct event_base *server_base = event_base_new();
qi::Url server_url("tcp://127.0.0.1:9571");
start_server(server_url, server_base);
boost::thread server_thread(network_thread, server_base);
struct event_base *client_base = event_base_new();
qi::Url client_url("tcp://127.0.0.1:5555");
boost::thread client_thread(network_thread2, client_base);
// test send
qi::os::sleep(1); // wait for the thread to start
struct bufferevent *bev = bufferevent_socket_new(client_base, -1, BEV_OPT_CLOSE_ON_FREE | BEV_OPT_THREADSAFE);
bufferevent_setcb(bev, readcb, writecb, eventcb, 0);
bufferevent_socket_connect_hostname(bev, 0, AF_INET,
client_url.host().c_str(), client_url.port());
socket_write(bev, "CHICHE", 6);
client_thread.join();
server_thread.join();
return 0;
}
<|endoftext|>
|
<commit_before>/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <activemq/concurrent/Mutex.h>
using namespace activemq::concurrent;
////////////////////////////////////////////////////////////////////////////////
Mutex::Mutex()
{
#ifdef AMQCPP_USE_PTHREADS
pthread_mutexattr_t attr;
pthread_mutexattr_init(&attr);
pthread_mutex_init(&mutex, &attr);
pthread_mutexattr_destroy(&attr);
#else
InitializeCriticalSection(&mutex);
#endif
lock_owner = 0;
lock_count = 0;
}
////////////////////////////////////////////////////////////////////////////////
Mutex::~Mutex()
{
// Unlock the mutex.
unlock();
#ifdef AMQCPP_USE_PTHREADS
pthread_mutex_destroy(&mutex);
#else
DeleteCriticalSection(&mutex);
#endif
}
////////////////////////////////////////////////////////////////////////////////
void Mutex::lock() throw( exceptions::ActiveMQException )
{
if(isLockOwner())
{
lock_count++;
}
else
{
#ifdef AMQCPP_USE_PTHREADS
pthread_mutex_lock(&mutex);
#else
EnterCriticalSection(&mutex);
#endif
lock_count = 1;
lock_owner = Thread::getId();
}
}
////////////////////////////////////////////////////////////////////////////////
void Mutex::unlock() throw( exceptions::ActiveMQException )
{
if(lock_owner == 0)
{
return;
}
if(!isLockOwner())
{
throw exceptions::ActiveMQException(
__FILE__, __LINE__,
"Mutex::unlock - Failed, not Lock Owner!" );
}
lock_count--;
if(lock_count == 0)
{
lock_owner = 0;
#ifdef AMQCPP_USE_PTHREADS
pthread_mutex_unlock(&mutex);
#else
LeaveCriticalSection(&mutex);
#endif
}
}
////////////////////////////////////////////////////////////////////////////////
void Mutex::wait() throw( exceptions::ActiveMQException )
{
// Delegate to the timed version
wait( WAIT_INFINITE );
}
////////////////////////////////////////////////////////////////////////////////
void Mutex::wait( unsigned long millisecs )
throw( exceptions::ActiveMQException )
{
if(!isLockOwner())
{
throw exceptions::ActiveMQException(
__FILE__, __LINE__,
"Mutex::wait - Failed, not Lock Owner!");
}
// Save the current owner and Lock count as we are going to
// unlock and release for someone else to lock on potentially.
// When we come back and re-lock we want to restore to the
// state we were in before.
unsigned long lock_owner = this->lock_owner;
int lock_count = this->lock_count;
this->lock_count = 0;
this->lock_owner = 0;
#ifdef AMQCPP_USE_PTHREADS
// Create this threads wait event
pthread_cond_t waitEvent;
pthread_cond_init(&waitEvent, NULL);
// Store the event in the queue so that a notify can
// call it and wake up the thread.
eventQ.push_back(&waitEvent);
int returnValue = 0;
if(millisecs != WAIT_INFINITE)
{
timeval now = {0,0};
gettimeofday(&now, NULL);
timespec wait = {0,0};
wait.tv_sec = now.tv_sec + (millisecs / 1000);
wait.tv_nsec = (now.tv_usec * 1000) + ((millisecs % 1000) * 1000000);
if(wait.tv_nsec > 1000000000)
{
wait.tv_sec++;
wait.tv_nsec -= 1000000000;
}
returnValue = pthread_cond_timedwait(&waitEvent, &mutex, &wait);
}
else
{
returnValue = pthread_cond_wait(&waitEvent, &mutex);
}
// If the wait did not succeed for any reason, remove it
// from the queue.
if( returnValue != 0 ){
std::list<pthread_cond_t*>::iterator iter = eventQ.begin();
for( ; iter != eventQ.end(); ++iter ){
if( *iter == &waitEvent ){
eventQ.erase(iter);
break;
}
}
}
// Destroy our wait event now, the notify method will have removed it
// from the event queue.
pthread_cond_destroy(&waitEvent);
#else
// Create the event to wait on
HANDLE waitEvent = CreateEvent( NULL, false, false, NULL );
if(waitEvent == NULL)
{
throw exceptions::ActiveMQException(
__FILE__, __LINE__,
"Mutex::Mutex - Failed Creating Event." );
}
eventQ.push_back( waitEvent );
// Release the Lock
LeaveCriticalSection( &mutex );
// Wait for a signal
WaitForSingleObject( waitEvent, millisecs );
// Reaquire the Lock
EnterCriticalSection( &mutex );
// Clean up the event, the notif methods will have
// already poped it from the queue.
CloseHandle( waitEvent );
#endif
// restore the owner
this->lock_owner = lock_owner;
this->lock_count = lock_count;
}
////////////////////////////////////////////////////////////////////////////////
void Mutex::notify() throw( exceptions::ActiveMQException )
{
if( !isLockOwner() )
{
throw exceptions::ActiveMQException(
__FILE__, __LINE__,
"Mutex::Notify - Failed, not Lock Owner!" );
}
if( !eventQ.empty() )
{
#ifdef AMQCPP_USE_PTHREADS
pthread_cond_signal( eventQ.front() );
eventQ.pop_front();
#else
SetEvent( eventQ.front() );
eventQ.pop_front();
#endif
}
}
////////////////////////////////////////////////////////////////////////////////
void Mutex::notifyAll() throw( exceptions::ActiveMQException )
{
if(!isLockOwner())
{
throw exceptions::ActiveMQException(
__FILE__, __LINE__,
"Mutex::NotifyAll - Failed, not Lock Owner!" );
}
#ifdef AMQCPP_USE_PTHREADS
while(!eventQ.empty())
{
pthread_cond_signal( eventQ.front() );
eventQ.pop_front();
}
#else
while(!eventQ.empty())
{
SetEvent( eventQ.front() );
eventQ.pop_front();
}
#endif
}
<commit_msg>[AMQCPP-49] fixing build of Mutex.cpp<commit_after>/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <activemq/concurrent/Mutex.h>
using namespace activemq;
using namespace activemq::concurrent;
////////////////////////////////////////////////////////////////////////////////
Mutex::Mutex()
{
#ifdef AMQCPP_USE_PTHREADS
pthread_mutexattr_t attr;
pthread_mutexattr_init(&attr);
pthread_mutex_init(&mutex, &attr);
pthread_mutexattr_destroy(&attr);
#else
InitializeCriticalSection(&mutex);
#endif
lock_owner = 0;
lock_count = 0;
}
////////////////////////////////////////////////////////////////////////////////
Mutex::~Mutex()
{
// Unlock the mutex.
unlock();
#ifdef AMQCPP_USE_PTHREADS
pthread_mutex_destroy(&mutex);
#else
DeleteCriticalSection(&mutex);
#endif
}
////////////////////////////////////////////////////////////////////////////////
void Mutex::lock() throw( exceptions::ActiveMQException )
{
if(isLockOwner())
{
lock_count++;
}
else
{
#ifdef AMQCPP_USE_PTHREADS
pthread_mutex_lock(&mutex);
#else
EnterCriticalSection(&mutex);
#endif
lock_count = 1;
lock_owner = Thread::getId();
}
}
////////////////////////////////////////////////////////////////////////////////
void Mutex::unlock() throw( exceptions::ActiveMQException )
{
if(lock_owner == 0)
{
return;
}
if(!isLockOwner())
{
throw exceptions::ActiveMQException(
__FILE__, __LINE__,
"Mutex::unlock - Failed, not Lock Owner!" );
}
lock_count--;
if(lock_count == 0)
{
lock_owner = 0;
#ifdef AMQCPP_USE_PTHREADS
pthread_mutex_unlock(&mutex);
#else
LeaveCriticalSection(&mutex);
#endif
}
}
////////////////////////////////////////////////////////////////////////////////
void Mutex::wait() throw( exceptions::ActiveMQException )
{
// Delegate to the timed version
wait( WAIT_INFINITE );
}
////////////////////////////////////////////////////////////////////////////////
void Mutex::wait( unsigned long millisecs )
throw( exceptions::ActiveMQException )
{
if(!isLockOwner())
{
throw exceptions::ActiveMQException(
__FILE__, __LINE__,
"Mutex::wait - Failed, not Lock Owner!");
}
// Save the current owner and Lock count as we are going to
// unlock and release for someone else to lock on potentially.
// When we come back and re-lock we want to restore to the
// state we were in before.
unsigned long lock_owner = this->lock_owner;
int lock_count = this->lock_count;
this->lock_count = 0;
this->lock_owner = 0;
#ifdef AMQCPP_USE_PTHREADS
// Create this threads wait event
pthread_cond_t waitEvent;
pthread_cond_init(&waitEvent, NULL);
// Store the event in the queue so that a notify can
// call it and wake up the thread.
eventQ.push_back(&waitEvent);
int returnValue = 0;
if(millisecs != WAIT_INFINITE)
{
timeval now = {0,0};
gettimeofday(&now, NULL);
timespec wait = {0,0};
wait.tv_sec = now.tv_sec + (millisecs / 1000);
wait.tv_nsec = (now.tv_usec * 1000) + ((millisecs % 1000) * 1000000);
if(wait.tv_nsec > 1000000000)
{
wait.tv_sec++;
wait.tv_nsec -= 1000000000;
}
returnValue = pthread_cond_timedwait(&waitEvent, &mutex, &wait);
}
else
{
returnValue = pthread_cond_wait(&waitEvent, &mutex);
}
// If the wait did not succeed for any reason, remove it
// from the queue.
if( returnValue != 0 ){
std::list<pthread_cond_t*>::iterator iter = eventQ.begin();
for( ; iter != eventQ.end(); ++iter ){
if( *iter == &waitEvent ){
eventQ.erase(iter);
break;
}
}
}
// Destroy our wait event now, the notify method will have removed it
// from the event queue.
pthread_cond_destroy(&waitEvent);
#else
// Create the event to wait on
HANDLE waitEvent = CreateEvent( NULL, false, false, NULL );
if(waitEvent == NULL)
{
throw exceptions::ActiveMQException(
__FILE__, __LINE__,
"Mutex::Mutex - Failed Creating Event." );
}
eventQ.push_back( waitEvent );
// Release the Lock
LeaveCriticalSection( &mutex );
// Wait for a signal
WaitForSingleObject( waitEvent, millisecs );
// Reaquire the Lock
EnterCriticalSection( &mutex );
// Clean up the event, the notif methods will have
// already poped it from the queue.
CloseHandle( waitEvent );
#endif
// restore the owner
this->lock_owner = lock_owner;
this->lock_count = lock_count;
}
////////////////////////////////////////////////////////////////////////////////
void Mutex::notify() throw( exceptions::ActiveMQException )
{
if( !isLockOwner() )
{
throw exceptions::ActiveMQException(
__FILE__, __LINE__,
"Mutex::Notify - Failed, not Lock Owner!" );
}
if( !eventQ.empty() )
{
#ifdef AMQCPP_USE_PTHREADS
pthread_cond_signal( eventQ.front() );
eventQ.pop_front();
#else
SetEvent( eventQ.front() );
eventQ.pop_front();
#endif
}
}
////////////////////////////////////////////////////////////////////////////////
void Mutex::notifyAll() throw( exceptions::ActiveMQException )
{
if(!isLockOwner())
{
throw exceptions::ActiveMQException(
__FILE__, __LINE__,
"Mutex::NotifyAll - Failed, not Lock Owner!" );
}
#ifdef AMQCPP_USE_PTHREADS
while(!eventQ.empty())
{
pthread_cond_signal( eventQ.front() );
eventQ.pop_front();
}
#else
while(!eventQ.empty())
{
SetEvent( eventQ.front() );
eventQ.pop_front();
}
#endif
}
<|endoftext|>
|
<commit_before>/*
* The Apache Software License, Version 1.1
*
*
* Copyright (c) 1999-2001 The Apache Software 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.
*
* 3. The end-user documentation included with the redistribution,
* if any, must include the following acknowledgment:
* "This product includes software developed by the
* Apache Software Foundation (http://www.apache.org/)."
* Alternately, this acknowledgment may appear in the software itself,
* if and wherever such third-party acknowledgments normally appear.
*
* 4. The names "Xalan" and "Apache Software Foundation" must
* not be used to endorse or promote products derived from this
* software without prior written permission. For written
* permission, please contact apache@apache.org.
*
* 5. Products derived from this software may not be called "Apache",
* nor may "Apache" appear in their name, without prior written
* permission of the Apache Software Foundation.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED 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 APACHE SOFTWARE FOUNDATION OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
* USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation and was
* originally based on software copyright (c) 1999, International
* Business Machines, Inc., http://www.ibm.com. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*/
#include <iostream>
#include <strstream>
#include <stdio.h>
#include <direct.h>
#if !defined(XALAN_NO_NAMESPACES)
using std::cerr;
using std::cout;
using std::cin;
using std::endl;
using std::ifstream;
using std::ios_base;
using std::ostrstream;
using std::string;
#endif
// XERCES HEADERS...
// Are included by HarnessInit.hpp
// XALAN HEADERS...
// Are included by FileUtility.hpp
// HARNESS HEADERS...
#include <XMLFileReporter.hpp>
#include <FileUtility.hpp>
#include <HarnessInit.hpp>
#if defined(XALAN_NO_NAMESPACES)
typedef map<XalanDOMString, XalanDOMString, less<XalanDOMString> > Hashtable;
#else
typedef std::map<XalanDOMString, XalanDOMString> Hashtable;
#endif
// This is here for memory leak testing.
#if !defined(NDEBUG) && defined(_MSC_VER)
#include <crtdbg.h>
#endif
const char* const excludeStylesheets[] =
{
"sorterr06.xsl",
0
};
FileUtility h;
void
setHelp()
{
h.args.help << endl
<< "errortests dir [-sub -out]"
<< endl
<< endl
<< "dir (location of conformance directory)"
<< endl
<< "-sub dir (specific directory)"
<< endl
<< "-out dir (base directory for output)"
<< endl;
}
inline bool
checkForExclusion(XalanDOMString currentFile)
{
for (int i=0; excludeStylesheets[i] != 0; i++)
{
if (equals(currentFile, XalanDOMString(excludeStylesheets[i])))
{
return true;
}
}
return false;
}
int
main(int argc,
const char* argv[])
{
#if !defined(NDEBUG) && defined(_MSC_VER)
_CrtSetDbgFlag(_CrtSetDbgFlag(_CRTDBG_REPORT_FLAG) | _CRTDBG_LEAK_CHECK_DF);
_CrtSetReportMode(_CRT_WARN, _CRTDBG_MODE_FILE);
_CrtSetReportFile(_CRT_WARN, _CRTDBG_FILE_STDERR);
#endif
HarnessInit xmlPlatformUtils;
XalanTransformer::initialize();
{
int theResult;
bool setGold = false;
// Set the program help string, then get the command line parameters.
//
setHelp();
if (h.getParams(argc, argv, "ERR-RESULTS", setGold) == true)
{
//
// Call the static initializers for xerces and xalan, and create a transformer
//
XalanTransformer xalan;
XalanSourceTreeDOMSupport domSupport;
XalanSourceTreeParserLiaison parserLiaison(domSupport);
domSupport.setParserLiaison(&parserLiaison);
// Generate Unique Run id and processor info
const XalanDOMString UniqRunid = h.generateUniqRunid();
// Defined basic constants for file manipulation and open results file
const XalanDOMString resultFilePrefix("cpperr");
const XalanDOMString resultsFile(h.args.output + resultFilePrefix + UniqRunid + XMLSuffix);
XMLFileReporter logFile(resultsFile);
logFile.logTestFileInit("Error Testing:");
// Get the list of Directories that are below conf
bool foundDir = false; // Flag indicates directory found. Used in conjunction with -sub cmd-line arg.
const FileNameVectorType dirs = h.getDirectoryNames(h.args.base);
for(FileNameVectorType::size_type j = 0; j < dirs.size(); ++j)
{
// If conformance directory structure does not exist, it needs to be created.
const XalanDOMString confSubdir = h.args.output + dirs[j];
h.checkAndCreateDir(confSubdir);
// Set up to get files from the associated error directories
const XalanDOMString currentDir(dirs[j] + XalanDOMString("\\err"));
const XalanDOMString subErrDir(h.args.sub + XalanDOMString("\\err"));
// Run specific category of files from given directory
if (length(h.args.sub) > 0 && !equals(currentDir, subErrDir))
{
continue;
}
// Check that output directory is there.
const XalanDOMString theOutputDir = h.args.output + currentDir;
h.checkAndCreateDir(theOutputDir);
// Indicate that directory was processed and get test files from the directory
foundDir = true;
logFile.logTestCaseInit(currentDir);
const FileNameVectorType files = h.getTestFileNames(h.args.base, currentDir, false);
for(FileNameVectorType::size_type i = 0; i < files.size(); i++)
{
Hashtable attrs;
const XalanDOMString currentFile(files[i]);
h.data.testOrFile = currentFile;
if (checkForExclusion(currentFile))
continue;
const XalanDOMString theXSLFile= h.args.base + currentDir + pathSep + currentFile;
const XalanDOMString theXMLFile = h.generateFileName(theXSLFile,"xml");
XalanDOMString theGoldFile = h.args.gold + currentDir + pathSep + currentFile;
theGoldFile = h.generateFileName(theGoldFile, "out");
const XalanDOMString outbase = h.args.output + currentDir + pathSep + currentFile;
const XalanDOMString theOutputFile = h.generateFileName(outbase, "out");
const XSLTInputSource xslInputSource(c_wstr(theXSLFile));
const XSLTInputSource xmlInputSource(c_wstr(theXMLFile));
const XSLTInputSource goldInputSource(c_wstr(theGoldFile));
const XSLTResultTarget resultFile(theOutputFile);
// Parsing(compile) the XSL stylesheet and report the results..
//
const XalanCompiledStylesheet* compiledSS = 0;
try
{
cout << endl << "PARSING STYLESHEET FOR: " << currentFile << endl;
xalan.compileStylesheet(xslInputSource, compiledSS);
if (compiledSS == 0 )
{
cout << "FAILED to parse stylesheet for " << currentFile << endl;
cout << "Reason: " << xalan.getLastError() << endl;
logFile.logErrorResult(currentFile, XalanDOMString(xalan.getLastError()));
continue;
}
}
catch(...)
{
cerr << "Exception caught!!!" << endl << endl;
}
// Parsing the input XML and report the results..
//
cout << "PARSING SOURCE XML FOR: " << currentFile << endl;
const XalanParsedSource* parsedSource = 0;
xalan.parseSource(xmlInputSource, parsedSource);
if (parsedSource == 0)
{
cout << "Failed to PARSE source document for " << currentFile << endl;
continue;
}
// Perform One transform using parsed stylesheet and parsed xml source, report results...
//
theResult = 0;
cout << "TRANSFORMING: " << currentFile << endl;
theResult = xalan.transform(*parsedSource, compiledSS, resultFile);
if (theResult != 0)
{
cout << "FAILED to transform stylesheet for " << currentFile << endl;
cout << "Reason: " << xalan.getLastError() << endl;
logFile.logErrorResult(currentFile, XalanDOMString(xalan.getLastError()));
}
else
{
logFile.logCheckPass(currentFile);
}
parserLiaison.reset();
xalan.destroyParsedSource(parsedSource);
xalan.destroyStylesheet(compiledSS);
}
logFile.logTestCaseClose("Done", "Pass");
}
// Check to see if -sub cmd-line directory was processed correctly.
if (!foundDir)
{
cout << "Specified test directory: \"" << c_str(TranscodeToLocalCodePage(h.args.sub)) << "\" not found" << endl;
}
h.reportPassFail(logFile, UniqRunid);
logFile.logTestFileClose("Conformance ", "Done");
logFile.close();
}
}
XalanTransformer::terminate();
return 0;
}
<commit_msg>Updated to run from new directory conferr.<commit_after>/*
* The Apache Software License, Version 1.1
*
*
* Copyright (c) 1999-2001 The Apache Software 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.
*
* 3. The end-user documentation included with the redistribution,
* if any, must include the following acknowledgment:
* "This product includes software developed by the
* Apache Software Foundation (http://www.apache.org/)."
* Alternately, this acknowledgment may appear in the software itself,
* if and wherever such third-party acknowledgments normally appear.
*
* 4. The names "Xalan" and "Apache Software Foundation" must
* not be used to endorse or promote products derived from this
* software without prior written permission. For written
* permission, please contact apache@apache.org.
*
* 5. Products derived from this software may not be called "Apache",
* nor may "Apache" appear in their name, without prior written
* permission of the Apache Software Foundation.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED 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 APACHE SOFTWARE FOUNDATION OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
* USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation and was
* originally based on software copyright (c) 1999, International
* Business Machines, Inc., http://www.ibm.com. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*/
#include <iostream>
#include <strstream>
#include <stdio.h>
#include <direct.h>
#if !defined(XALAN_NO_NAMESPACES)
using std::cerr;
using std::cout;
using std::cin;
using std::endl;
using std::ifstream;
using std::ios_base;
using std::ostrstream;
using std::string;
#endif
// XERCES HEADERS...
// Are included by HarnessInit.hpp
// XALAN HEADERS...
// Are included by FileUtility.hpp
// HARNESS HEADERS...
#include <XMLFileReporter.hpp>
#include <FileUtility.hpp>
#include <HarnessInit.hpp>
#if defined(XALAN_NO_NAMESPACES)
typedef map<XalanDOMString, XalanDOMString, less<XalanDOMString> > Hashtable;
#else
typedef std::map<XalanDOMString, XalanDOMString> Hashtable;
#endif
// This is here for memory leak testing.
#if !defined(NDEBUG) && defined(_MSC_VER)
#include <crtdbg.h>
#endif
const char* const excludeStylesheets[] =
{
"sorterr06.xsl",
0
};
FileUtility h;
void
setHelp()
{
h.args.help << endl
<< "errortests dir [-sub -out]"
<< endl
<< endl
<< "dir (location of conformance directory)"
<< endl
<< "-sub dir (specific directory)"
<< endl
<< "-out dir (base directory for output)"
<< endl;
}
inline bool
checkForExclusion(XalanDOMString currentFile)
{
for (int i=0; excludeStylesheets[i] != 0; i++)
{
if (equals(currentFile, XalanDOMString(excludeStylesheets[i])))
{
return true;
}
}
return false;
}
int
main(int argc,
const char* argv[])
{
#if !defined(NDEBUG) && defined(_MSC_VER)
_CrtSetDbgFlag(_CrtSetDbgFlag(_CRTDBG_REPORT_FLAG) | _CRTDBG_LEAK_CHECK_DF);
_CrtSetReportMode(_CRT_WARN, _CRTDBG_MODE_FILE);
_CrtSetReportFile(_CRT_WARN, _CRTDBG_FILE_STDERR);
#endif
HarnessInit xmlPlatformUtils;
XalanTransformer::initialize();
{
int theResult;
bool setGold = false;
// Set the program help string, then get the command line parameters.
//
setHelp();
if (h.getParams(argc, argv, "ERR-RESULTS", setGold) == true)
{
//
// Call the static initializers for xerces and xalan, and create a transformer
//
XalanTransformer xalan;
XalanSourceTreeDOMSupport domSupport;
XalanSourceTreeParserLiaison parserLiaison(domSupport);
domSupport.setParserLiaison(&parserLiaison);
// Generate Unique Run id and processor info
const XalanDOMString UniqRunid = h.generateUniqRunid();
// Defined basic constants for file manipulation and open results file
const XalanDOMString resultFilePrefix("cpperr");
const XalanDOMString resultsFile(h.args.output + resultFilePrefix + UniqRunid + XMLSuffix);
XMLFileReporter logFile(resultsFile);
logFile.logTestFileInit("Error Testing:");
// Get the list of Directories that are below conf
bool foundDir = false; // Flag indicates directory found. Used in conjunction with -sub cmd-line arg.
const FileNameVectorType dirs = h.getDirectoryNames(h.args.base);
for(FileNameVectorType::size_type j = 0; j < dirs.size(); ++j)
{
// If conformance directory structure does not exist, it needs to be created.
const XalanDOMString confSubdir = h.args.output + dirs[j];
h.checkAndCreateDir(confSubdir);
// Set up to get files from the associated error directories
const XalanDOMString currentDir(dirs[j]);
const XalanDOMString subErrDir(h.args.sub);
// Run specific category of files from given directory
if (length(h.args.sub) > 0 && !equals(currentDir, subErrDir))
{
continue;
}
// Check that output directory is there.
const XalanDOMString theOutputDir = h.args.output + currentDir;
h.checkAndCreateDir(theOutputDir);
// Indicate that directory was processed and get test files from the directory
foundDir = true;
logFile.logTestCaseInit(currentDir);
const FileNameVectorType files = h.getTestFileNames(h.args.base, currentDir, false);
for(FileNameVectorType::size_type i = 0; i < files.size(); i++)
{
Hashtable attrs;
const XalanDOMString currentFile(files[i]);
h.data.testOrFile = currentFile;
if (checkForExclusion(currentFile))
continue;
const XalanDOMString theXSLFile= h.args.base + currentDir + pathSep + currentFile;
const XalanDOMString theXMLFile = h.generateFileName(theXSLFile,"xml");
XalanDOMString theGoldFile = h.args.gold + currentDir + pathSep + currentFile;
theGoldFile = h.generateFileName(theGoldFile, "out");
const XalanDOMString outbase = h.args.output + currentDir + pathSep + currentFile;
const XalanDOMString theOutputFile = h.generateFileName(outbase, "out");
const XSLTInputSource xslInputSource(c_wstr(theXSLFile));
const XSLTInputSource xmlInputSource(c_wstr(theXMLFile));
const XSLTInputSource goldInputSource(c_wstr(theGoldFile));
const XSLTResultTarget resultFile(theOutputFile);
// Parsing(compile) the XSL stylesheet and report the results..
//
const XalanCompiledStylesheet* compiledSS = 0;
try
{
cout << endl << "PARSING STYLESHEET FOR: " << currentFile << endl;
xalan.compileStylesheet(xslInputSource, compiledSS);
if (compiledSS == 0 )
{
cout << "FAILED to parse stylesheet for " << currentFile << endl;
cout << "Reason: " << xalan.getLastError() << endl;
logFile.logErrorResult(currentFile, XalanDOMString(xalan.getLastError()));
continue;
}
}
catch(...)
{
cerr << "Exception caught!!!" << endl << endl;
}
// Parsing the input XML and report the results..
//
cout << "PARSING SOURCE XML FOR: " << currentFile << endl;
const XalanParsedSource* parsedSource = 0;
xalan.parseSource(xmlInputSource, parsedSource);
if (parsedSource == 0)
{
cout << "Failed to PARSE source document for " << currentFile << endl;
continue;
}
// Perform One transform using parsed stylesheet and parsed xml source, report results...
//
theResult = 0;
cout << "TRANSFORMING: " << currentFile << endl;
theResult = xalan.transform(*parsedSource, compiledSS, resultFile);
if (theResult != 0)
{
cout << "FAILED to transform stylesheet for " << currentFile << endl;
cout << "Reason: " << xalan.getLastError() << endl;
logFile.logErrorResult(currentFile, XalanDOMString(xalan.getLastError()));
}
else
{
logFile.logCheckPass(currentFile);
}
parserLiaison.reset();
xalan.destroyParsedSource(parsedSource);
xalan.destroyStylesheet(compiledSS);
}
logFile.logTestCaseClose("Done", "Pass");
}
// Check to see if -sub cmd-line directory was processed correctly.
if (!foundDir)
{
cout << "Specified test directory: \"" << c_str(TranscodeToLocalCodePage(h.args.sub)) << "\" not found" << endl;
}
h.reportPassFail(logFile, UniqRunid);
logFile.logTestFileClose("Conformance ", "Done");
logFile.close();
}
}
XalanTransformer::terminate();
return 0;
}
<|endoftext|>
|
<commit_before>/*******************************************************************************
FILE : computed_field_binaryThresholdFilter.c
LAST MODIFIED : 9 September 2006
DESCRIPTION :
Wraps itk::MeanImageFilter
==============================================================================*/
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
* http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is cmgui.
*
* The Initial Developer of the Original Code is
* Auckland Uniservices Ltd, Auckland, New Zealand.
* Portions created by the Initial Developer are Copyright (C) 2005
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
extern "C" {
#include "computed_field/computed_field.h"
}
#include "computed_field/computed_field_private.hpp"
#include "image_processing/computed_field_ImageFilter.hpp"
extern "C" {
#include "general/debug.h"
#include "general/mystring.h"
#include "user_interface/message.h"
}
namespace CMISS {
int Computed_field_ImageFilter::evaluate_cache_at_location(
Field_location* location)
/*******************************************************************************
LAST MODIFIED : 7 September 2006
DESCRIPTION :
Evaluate the fields cache at the location
==============================================================================*/
{
int return_code;
ENTER(Computed_field_meanImageFilter::evaluate_cache_at_location);
if (field && location)
{
return_code = functor->update_and_evaluate_filter(location);
}
else
{
display_message(ERROR_MESSAGE,
"Computed_field_meanImageFilter::evaluate_cache_at_location. "
"Invalid argument(s)");
return_code = 0;
}
LEAVE;
return (return_code);
} /* Computed_field_meanImageFilter::evaluate_cache_at_location */
} // namespace CMISS
<commit_msg>Fix up header comment.<commit_after>/*******************************************************************************
FILE : computed_field_ImageFilter.cpp
LAST MODIFIED : 9 September 2006
DESCRIPTION :
Wraps itk::MeanImageFilter
==============================================================================*/
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
* http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is cmgui.
*
* The Initial Developer of the Original Code is
* Auckland Uniservices Ltd, Auckland, New Zealand.
* Portions created by the Initial Developer are Copyright (C) 2005
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
extern "C" {
#include "computed_field/computed_field.h"
}
#include "computed_field/computed_field_private.hpp"
#include "image_processing/computed_field_ImageFilter.hpp"
extern "C" {
#include "general/debug.h"
#include "general/mystring.h"
#include "user_interface/message.h"
}
namespace CMISS {
int Computed_field_ImageFilter::evaluate_cache_at_location(
Field_location* location)
/*******************************************************************************
LAST MODIFIED : 7 September 2006
DESCRIPTION :
Evaluate the fields cache at the location
==============================================================================*/
{
int return_code;
ENTER(Computed_field_meanImageFilter::evaluate_cache_at_location);
if (field && location)
{
return_code = functor->update_and_evaluate_filter(location);
}
else
{
display_message(ERROR_MESSAGE,
"Computed_field_meanImageFilter::evaluate_cache_at_location. "
"Invalid argument(s)");
return_code = 0;
}
LEAVE;
return (return_code);
} /* Computed_field_meanImageFilter::evaluate_cache_at_location */
} // namespace CMISS
<|endoftext|>
|
<commit_before>//
// detail/initializer.hpp
// ~~~~~~~~~~~~~~~~~~~~~~
//
// Copyright (c) 2014 Rick Yang (rick68 at gmail dot com)
//
// This Source Code Form is subject to the terms of the Mozilla
// Public License v. 2.0. If a copy of the MPL was not distributed
// with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
//
#ifndef EIGENJS_DETAIL_INITIALIZER_HPP
#define EIGENJS_DETAIL_INITIALIZER_HPP
#include <v8.h>
namespace EigenJS {
namespace detail {
struct initializer {
typedef v8::Local<v8::FunctionTemplate> function_template_type;
initializer(function_template_type& function_template)
: function_template_(function_template)
{}
template <typename T>
void operator()(T& definition) {
definition(function_template_);
}
function_template_type& function_template_;
};
} // detail
} // namespace EigenJS
#endif // EIGENJS_DETAIL_INITIALIZER_HPP
<commit_msg>src: suit to principle of least privilege<commit_after>//
// detail/initializer.hpp
// ~~~~~~~~~~~~~~~~~~~~~~
//
// Copyright (c) 2014 Rick Yang (rick68 at gmail dot com)
//
// This Source Code Form is subject to the terms of the Mozilla
// Public License v. 2.0. If a copy of the MPL was not distributed
// with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
//
#ifndef EIGENJS_DETAIL_INITIALIZER_HPP
#define EIGENJS_DETAIL_INITIALIZER_HPP
#include <v8.h>
namespace EigenJS {
namespace detail {
struct initializer {
typedef v8::Local<v8::FunctionTemplate> function_template_type;
initializer(function_template_type& function_template)
: function_template_(function_template)
{}
template <typename T>
void operator()(T& definition) const {
definition(function_template_);
}
private:
function_template_type& function_template_;
};
} // detail
} // namespace EigenJS
#endif // EIGENJS_DETAIL_INITIALIZER_HPP
<|endoftext|>
|
<commit_before>/*
* Copyright 2013 Google Inc.
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include "SkDocument.h"
#include "SkPDFDocument.h"
#include "SkPDFDevice.h"
class SkDocument_PDF : public SkDocument {
public:
SkDocument_PDF(SkWStream* stream, void (*doneProc)(SkWStream*,bool),
SkPicture::EncodeBitmap encoder,
SkScalar rasterDpi)
: SkDocument(stream, doneProc)
, fEncoder(encoder)
, fRasterDpi(rasterDpi) {
fDoc = SkNEW(SkPDFDocument);
fCanvas = NULL;
fDevice = NULL;
}
virtual ~SkDocument_PDF() {
// subclasses must call close() in their destructors
this->close();
}
protected:
virtual SkCanvas* onBeginPage(SkScalar width, SkScalar height,
const SkRect& trimBox) SK_OVERRIDE {
SkASSERT(NULL == fCanvas);
SkASSERT(NULL == fDevice);
SkISize mediaBoxSize;
mediaBoxSize.set(SkScalarRoundToInt(width), SkScalarRoundToInt(height));
fDevice = SkNEW_ARGS(SkPDFDevice, (mediaBoxSize, mediaBoxSize, SkMatrix::I()));
if (fEncoder) {
fDevice->setDCTEncoder(fEncoder);
}
if (fRasterDpi != 0) {
fDevice->setRasterDpi(fRasterDpi);
}
fCanvas = SkNEW_ARGS(SkCanvas, (fDevice));
fCanvas->translate(trimBox.x(), trimBox.y());
fCanvas->clipRect(SkRect::MakeWH(trimBox.width(), trimBox.height()));
return fCanvas;
}
virtual void onEndPage() SK_OVERRIDE {
SkASSERT(fCanvas);
SkASSERT(fDevice);
fCanvas->flush();
fDoc->appendPage(fDevice);
fCanvas->unref();
fDevice->unref();
fCanvas = NULL;
fDevice = NULL;
}
virtual bool onClose(SkWStream* stream) SK_OVERRIDE {
SkASSERT(NULL == fCanvas);
SkASSERT(NULL == fDevice);
bool success = fDoc->emitPDF(stream);
SkDELETE(fDoc);
fDoc = NULL;
return success;
}
virtual void onAbort() SK_OVERRIDE {
SkDELETE(fDoc);
fDoc = NULL;
}
private:
SkPDFDocument* fDoc;
SkPDFDevice* fDevice;
SkCanvas* fCanvas;
SkPicture::EncodeBitmap fEncoder;
SkScalar fRasterDpi;
};
///////////////////////////////////////////////////////////////////////////////
SkDocument* SkDocument::CreatePDF(SkWStream* stream, void (*done)(SkWStream*,bool),
SkPicture::EncodeBitmap enc,
SkScalar dpi) {
return stream ? SkNEW_ARGS(SkDocument_PDF, (stream, done, enc, dpi)) : NULL;
}
static void delete_wstream(SkWStream* stream, bool aborted) {
SkDELETE(stream);
}
SkDocument* SkDocument::CreatePDF(const char path[],
SkPicture::EncodeBitmap enc,
SkScalar dpi) {
SkFILEWStream* stream = SkNEW_ARGS(SkFILEWStream, (path));
if (!stream->isValid()) {
SkDELETE(stream);
return NULL;
}
return SkNEW_ARGS(SkDocument_PDF, (stream, delete_wstream, enc, dpi));
}
<commit_msg>Simplify canvas calls in SkDocument_PDF<commit_after>/*
* Copyright 2013 Google Inc.
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include "SkDocument.h"
#include "SkPDFDocument.h"
#include "SkPDFDevice.h"
class SkDocument_PDF : public SkDocument {
public:
SkDocument_PDF(SkWStream* stream, void (*doneProc)(SkWStream*,bool),
SkPicture::EncodeBitmap encoder,
SkScalar rasterDpi)
: SkDocument(stream, doneProc)
, fEncoder(encoder)
, fRasterDpi(rasterDpi) {
fDoc = SkNEW(SkPDFDocument);
fCanvas = NULL;
fDevice = NULL;
}
virtual ~SkDocument_PDF() {
// subclasses must call close() in their destructors
this->close();
}
protected:
virtual SkCanvas* onBeginPage(SkScalar width, SkScalar height,
const SkRect& trimBox) SK_OVERRIDE {
SkASSERT(NULL == fCanvas);
SkASSERT(NULL == fDevice);
SkISize mediaBoxSize;
mediaBoxSize.set(SkScalarRoundToInt(width), SkScalarRoundToInt(height));
fDevice = SkNEW_ARGS(SkPDFDevice, (mediaBoxSize, mediaBoxSize, SkMatrix::I()));
if (fEncoder) {
fDevice->setDCTEncoder(fEncoder);
}
if (fRasterDpi != 0) {
fDevice->setRasterDpi(fRasterDpi);
}
fCanvas = SkNEW_ARGS(SkCanvas, (fDevice));
fCanvas->clipRect(trimBox);
fCanvas->translate(trimBox.x(), trimBox.y());
return fCanvas;
}
virtual void onEndPage() SK_OVERRIDE {
SkASSERT(fCanvas);
SkASSERT(fDevice);
fCanvas->flush();
fDoc->appendPage(fDevice);
fCanvas->unref();
fDevice->unref();
fCanvas = NULL;
fDevice = NULL;
}
virtual bool onClose(SkWStream* stream) SK_OVERRIDE {
SkASSERT(NULL == fCanvas);
SkASSERT(NULL == fDevice);
bool success = fDoc->emitPDF(stream);
SkDELETE(fDoc);
fDoc = NULL;
return success;
}
virtual void onAbort() SK_OVERRIDE {
SkDELETE(fDoc);
fDoc = NULL;
}
private:
SkPDFDocument* fDoc;
SkPDFDevice* fDevice;
SkCanvas* fCanvas;
SkPicture::EncodeBitmap fEncoder;
SkScalar fRasterDpi;
};
///////////////////////////////////////////////////////////////////////////////
SkDocument* SkDocument::CreatePDF(SkWStream* stream, void (*done)(SkWStream*,bool),
SkPicture::EncodeBitmap enc,
SkScalar dpi) {
return stream ? SkNEW_ARGS(SkDocument_PDF, (stream, done, enc, dpi)) : NULL;
}
static void delete_wstream(SkWStream* stream, bool aborted) {
SkDELETE(stream);
}
SkDocument* SkDocument::CreatePDF(const char path[],
SkPicture::EncodeBitmap enc,
SkScalar dpi) {
SkFILEWStream* stream = SkNEW_ARGS(SkFILEWStream, (path));
if (!stream->isValid()) {
SkDELETE(stream);
return NULL;
}
return SkNEW_ARGS(SkDocument_PDF, (stream, delete_wstream, enc, dpi));
}
<|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 "otbVectorDataSetField.h"
#include <iostream>
#include "otbVectorData.h"
#include "otbVectorDataFileWriter.h"
#include "otbVectorDataFileReader.h"
namespace otb
{
int VectorDataSetField::Describe(ApplicationDescriptor* descriptor)
{
descriptor->SetName("VectorDataSetField");
descriptor->SetDescription("Set a specified field to a specified value on all features of a vector data");
descriptor->AddOption("Input","Input vector data","in",1,true,ApplicationDescriptor::FileName);
descriptor->AddOption("Output","Output vector data","out",1,true,ApplicationDescriptor::FileName);
descriptor->AddOption("Field","Field name","fn",1,true,ApplicationDescriptor::String);
descriptor->AddOption("Value","Field value","fv",1,true,ApplicationDescriptor::String);
return EXIT_SUCCESS;
}
int VectorDataSetField::Execute(otb::ApplicationOptionsResult* parseResult)
{
try
{
typedef otb::VectorData<> VectorDataType;
typedef otb::VectorDataFileReader<VectorDataType> ReaderVectorType;
ReaderVectorType::Pointer reader = ReaderVectorType::New();
reader->SetFileName(parseResult->GetParameterString("Input"));
reader->Update();
typedef VectorDataType::DataTreeType DataTreeType;
typedef itk::PreOrderTreeIterator<DataTreeType> TreeIteratorType;
TreeIteratorType it(reader->GetOutput()->GetDataTree());
for (it.GoToBegin(); !it.IsAtEnd(); ++it)
{
it.Get()->SetFieldAsString(parseResult->GetParameterString("Field"), parseResult->GetParameterString("Value"));
}
typedef otb::VectorDataFileWriter<VectorDataType> WriterVectorType;
WriterVectorType::Pointer writerVector = WriterVectorType::New();
writerVector->SetFileName(parseResult->GetParameterString("Output"));
writerVector->SetInput(reader->GetOutput());
writerVector->Update();
}
catch ( itk::ExceptionObject & err )
{
std::cout << "Following otbException caught :" << std::endl;
std::cout << err << std::endl;
return EXIT_FAILURE;
}
catch ( std::bad_alloc & err )
{
std::cout << "Exception bad_alloc : "<<(char*)err.what()<< std::endl;
return EXIT_FAILURE;
}
catch ( ... )
{
std::cout << "Unknown Exception found !" << std::endl;
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}
}
<commit_msg>STYLE<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 "otbVectorDataSetField.h"
#include <iostream>
#include "otbVectorData.h"
#include "otbVectorDataFileWriter.h"
#include "otbVectorDataFileReader.h"
namespace otb
{
int VectorDataSetField::Describe(ApplicationDescriptor* descriptor)
{
descriptor->SetName("VectorDataSetField");
descriptor->SetDescription("Set a specified field to a specified value on all features of a vector data");
descriptor->AddOption("Input","Input vector data","in", 1, true, ApplicationDescriptor::FileName);
descriptor->AddOption("Output","Output vector data","out", 1, true, ApplicationDescriptor::FileName);
descriptor->AddOption("Field","Field name","fn", 1, true, ApplicationDescriptor::String);
descriptor->AddOption("Value","Field value","fv", 1, true, ApplicationDescriptor::String);
return EXIT_SUCCESS;
}
int VectorDataSetField::Execute(otb::ApplicationOptionsResult* parseResult)
{
try
{
typedef otb::VectorData<> VectorDataType;
typedef otb::VectorDataFileReader<VectorDataType> ReaderVectorType;
ReaderVectorType::Pointer reader = ReaderVectorType::New();
reader->SetFileName(parseResult->GetParameterString("Input"));
reader->Update();
typedef VectorDataType::DataTreeType DataTreeType;
typedef itk::PreOrderTreeIterator<DataTreeType> TreeIteratorType;
TreeIteratorType it(reader->GetOutput()->GetDataTree());
for (it.GoToBegin(); !it.IsAtEnd(); ++it)
{
it.Get()->SetFieldAsString(parseResult->GetParameterString("Field"), parseResult->GetParameterString("Value"));
}
typedef otb::VectorDataFileWriter<VectorDataType> WriterVectorType;
WriterVectorType::Pointer writerVector = WriterVectorType::New();
writerVector->SetFileName(parseResult->GetParameterString("Output"));
writerVector->SetInput(reader->GetOutput());
writerVector->Update();
}
catch ( itk::ExceptionObject & err )
{
std::cout << "Following otbException caught :" << std::endl;
std::cout << err << std::endl;
return EXIT_FAILURE;
}
catch ( std::bad_alloc & err )
{
std::cout << "Exception bad_alloc : "<<(char*)err.what()<< std::endl;
return EXIT_FAILURE;
}
catch ( ... )
{
std::cout << "Unknown Exception found !" << std::endl;
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}
}
<|endoftext|>
|
<commit_before>/**************************************************************************
* Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. *
* *
* Author: The ALICE Off-line Project. *
* Contributors are mentioned in the code where appropriate. *
* *
* Permission to use, copy, modify and distribute this software and its *
* documentation strictly for non-commercial purposes is hereby granted *
* without fee, provided that the above copyright notice appears in all *
* copies and that both the copyright notice and this permission notice *
* appear in the supporting documentation. The authors make no claims *
* about the suitability of this software for any purpose. It is *
* provided "as is" without express or implied warranty. *
**************************************************************************/
//
// Class AliVZEROLogicalSignal
// ---------------------------
// Describes a logical signal in the electronics.
// Use it to generate observation windows
// which are used by AliVZEROTriggerSimulator class
//
#include "AliLog.h"
#include "AliVZEROLogicalSignal.h"
ClassImp(AliVZEROLogicalSignal)
//_____________________________________________________________________________
AliVZEROLogicalSignal::AliVZEROLogicalSignal() : TObject(), fStart(0.), fStop(0.)
{
// Default constructor
}
//_____________________________________________________________________________
AliVZEROLogicalSignal::AliVZEROLogicalSignal(Float_t start, Float_t stop) : TObject(), fStart(start), fStop(stop)
{
// Constructor using start and stop time
if(fStart>fStop) AliError("Logical Signal has a Start time AFTER the Stop time");
if(fStart==fStop) AliWarning("Logical Signal has a zero width");
}
//_____________________________________________________________________________
AliVZEROLogicalSignal::AliVZEROLogicalSignal(UShort_t profilClock, UInt_t delay) : TObject(), fStart(0.), fStop(0.)
{
// Constructor using the profilClock and delay parameters comming from the FEE
Bool_t word;
Bool_t up=kFALSE;
Bool_t down=kFALSE;
for(int i=0 ; i<5 ; i++) {
word = (profilClock >> i) & 0x1;
if(word&&!up) {
fStart = 5. * i;
up = kTRUE;
}
if(!word&&up&&!down) {
fStop = 5. * i;
down = kTRUE;
}
}
if(!down) fStop = 25.;
fStart += delay*10.e-2; // Add 10 ps par register unit
fStop += delay*10.e-2;
}
//_____________________________________________________________________________
AliVZEROLogicalSignal::AliVZEROLogicalSignal(const AliVZEROLogicalSignal &signal) :
TObject(), fStart(signal.fStart),
fStop(signal.fStop)
{
// Copy constructor
}
//_____________________________________________________________________________
AliVZEROLogicalSignal::~AliVZEROLogicalSignal(){
// Destructor
}
//_____________________________________________________________________________
AliVZEROLogicalSignal& AliVZEROLogicalSignal::operator =
(const AliVZEROLogicalSignal& signal)
{
// Operator =
fStart = signal.fStart;
fStop = signal.fStop;
return *this;
}
//_____________________________________________________________________________
AliVZEROLogicalSignal AliVZEROLogicalSignal::operator|(const AliVZEROLogicalSignal& signal) const
{
// Perform the Logical OR of two signals: C = A or B
if((fStart>signal.fStop) || (signal.fStart>fStop))
AliError(Form("Both signal do not superpose in time.\n Start(A) = %f Stop(A) = %f\n Start(B) = %f Stop(B) = %f",fStart, fStop, signal.fStart,signal.fStop));
AliVZEROLogicalSignal result;
if(fStart<signal.fStart) result.fStart = fStart;
else result.fStart = signal.fStart;
if(fStop>signal.fStop) result.fStop = fStop;
else result.fStop = signal.fStop;
return result;
}
//_____________________________________________________________________________
AliVZEROLogicalSignal AliVZEROLogicalSignal::operator&(const AliVZEROLogicalSignal& signal) const
{
// Perform the Logical AND of two signals: C = A and B
if((fStart>signal.fStop) || (signal.fStart>fStop))
AliError(Form("Both signal do not superpose in time.\n Start(A) = %f Stop(A) = %f\n Start(B) = %f Stop(B) = %f",fStart, fStop, signal.fStart,signal.fStop));
AliVZEROLogicalSignal result;
if(fStart>signal.fStart) result.fStart = fStart;
else result.fStart = signal.fStart;
if(fStop<signal.fStop) result.fStop = fStop;
else result.fStop = signal.fStop;
return result;
}
//_____________________________________________________________________________
Bool_t AliVZEROLogicalSignal::IsInCoincidence(Float_t time) const
{
// Check if a signal arriving at the time "time" is in coincidence with the logical signal
Bool_t result = kFALSE;
if((time>fStart) && (time<fStop)) result = kTRUE;
return result;
}
<commit_msg>Coverity<commit_after>/**************************************************************************
* Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. *
* *
* Author: The ALICE Off-line Project. *
* Contributors are mentioned in the code where appropriate. *
* *
* Permission to use, copy, modify and distribute this software and its *
* documentation strictly for non-commercial purposes is hereby granted *
* without fee, provided that the above copyright notice appears in all *
* copies and that both the copyright notice and this permission notice *
* appear in the supporting documentation. The authors make no claims *
* about the suitability of this software for any purpose. It is *
* provided "as is" without express or implied warranty. *
**************************************************************************/
//
// Class AliVZEROLogicalSignal
// ---------------------------
// Describes a logical signal in the electronics.
// Use it to generate observation windows
// which are used by AliVZEROTriggerSimulator class
//
#include "AliLog.h"
#include "AliVZEROLogicalSignal.h"
ClassImp(AliVZEROLogicalSignal)
//_____________________________________________________________________________
AliVZEROLogicalSignal::AliVZEROLogicalSignal() : TObject(), fStart(0.), fStop(0.)
{
// Default constructor
}
//_____________________________________________________________________________
AliVZEROLogicalSignal::AliVZEROLogicalSignal(Float_t start, Float_t stop) : TObject(), fStart(start), fStop(stop)
{
// Constructor using start and stop time
if(fStart>fStop) AliError("Logical Signal has a Start time AFTER the Stop time");
if(fStart==fStop) AliWarning("Logical Signal has a zero width");
}
//_____________________________________________________________________________
AliVZEROLogicalSignal::AliVZEROLogicalSignal(UShort_t profilClock, UInt_t delay) : TObject(), fStart(0.), fStop(0.)
{
// Constructor using the profilClock and delay parameters comming from the FEE
Bool_t word;
Bool_t up=kFALSE;
Bool_t down=kFALSE;
for(int i=0 ; i<5 ; i++) {
word = (profilClock >> i) & 0x1;
if(word&&!up) {
fStart = 5. * i;
up = kTRUE;
}
if(!word&&up&&!down) {
fStop = 5. * i;
down = kTRUE;
}
}
if(!down) fStop = 25.;
fStart += delay*10.e-2; // Add 10 ps par register unit
fStop += delay*10.e-2;
}
//_____________________________________________________________________________
AliVZEROLogicalSignal::AliVZEROLogicalSignal(const AliVZEROLogicalSignal &signal) :
TObject(), fStart(signal.fStart),
fStop(signal.fStop)
{
// Copy constructor
}
//_____________________________________________________________________________
AliVZEROLogicalSignal::~AliVZEROLogicalSignal(){
// Destructor
}
//_____________________________________________________________________________
AliVZEROLogicalSignal& AliVZEROLogicalSignal::operator =
(const AliVZEROLogicalSignal& signal)
{
// Operator =
if(&signal == this) return *this;
fStart = signal.fStart;
fStop = signal.fStop;
return *this;
}
//_____________________________________________________________________________
AliVZEROLogicalSignal AliVZEROLogicalSignal::operator|(const AliVZEROLogicalSignal& signal) const
{
// Perform the Logical OR of two signals: C = A or B
if((fStart>signal.fStop) || (signal.fStart>fStop))
AliError(Form("Both signal do not superpose in time.\n Start(A) = %f Stop(A) = %f\n Start(B) = %f Stop(B) = %f",fStart, fStop, signal.fStart,signal.fStop));
AliVZEROLogicalSignal result;
if(fStart<signal.fStart) result.fStart = fStart;
else result.fStart = signal.fStart;
if(fStop>signal.fStop) result.fStop = fStop;
else result.fStop = signal.fStop;
return result;
}
//_____________________________________________________________________________
AliVZEROLogicalSignal AliVZEROLogicalSignal::operator&(const AliVZEROLogicalSignal& signal) const
{
// Perform the Logical AND of two signals: C = A and B
if((fStart>signal.fStop) || (signal.fStart>fStop))
AliError(Form("Both signal do not superpose in time.\n Start(A) = %f Stop(A) = %f\n Start(B) = %f Stop(B) = %f",fStart, fStop, signal.fStart,signal.fStop));
AliVZEROLogicalSignal result;
if(fStart>signal.fStart) result.fStart = fStart;
else result.fStart = signal.fStart;
if(fStop<signal.fStop) result.fStop = fStop;
else result.fStop = signal.fStop;
return result;
}
//_____________________________________________________________________________
Bool_t AliVZEROLogicalSignal::IsInCoincidence(Float_t time) const
{
// Check if a signal arriving at the time "time" is in coincidence with the logical signal
Bool_t result = kFALSE;
if((time>fStart) && (time<fStop)) result = kTRUE;
return result;
}
<|endoftext|>
|
<commit_before>//==============================================================================
// Single cell simulation view information solvers widget
//==============================================================================
#include "cellmlfileruntime.h"
#include "cellmlfilevariable.h"
#include "singlecellsimulationviewinformationsolverswidget.h"
//==============================================================================
namespace OpenCOR {
namespace SingleCellSimulationView {
//==============================================================================
SingleCellSimulationViewInformationSolversWidgetData::SingleCellSimulationViewInformationSolversWidgetData() :
needSolver(true),
solversProperty(Core::Property()),
solversListProperty(Core::Property()),
solversProperties(QMap<QString, Core::Properties>())
{
}
//==============================================================================
SingleCellSimulationViewInformationSolversWidget::SingleCellSimulationViewInformationSolversWidget(QWidget *pParent) :
PropertyEditorWidget(true, pParent),
mOdeSolverData(SingleCellSimulationViewInformationSolversWidgetData()),
mDaeSolverData(SingleCellSimulationViewInformationSolversWidgetData()),
mNlaSolverData(SingleCellSimulationViewInformationSolversWidgetData()),
mGuiStates(QMap<QString, Core::PropertyEditorWidgetGuiState>()),
mDefaultGuiState(Core::PropertyEditorWidgetGuiState())
{
}
//==============================================================================
void SingleCellSimulationViewInformationSolversWidget::retranslateUi()
{
// Update our property names
if (!mOdeSolverData.solversProperty.isEmpty()) {
setNonEditablePropertyItem(mOdeSolverData.solversProperty.name, tr("ODE solver"));
setNonEditablePropertyItem(mOdeSolverData.solversListProperty.name, tr("Name"));
mOdeSolverData.solversListProperty.value->setEmptyListValue(tr("None available"));
}
if (!mDaeSolverData.solversProperty.isEmpty()) {
setNonEditablePropertyItem(mDaeSolverData.solversProperty.name, tr("DAE solver"));
setNonEditablePropertyItem(mDaeSolverData.solversListProperty.name, tr("Name"));
mDaeSolverData.solversListProperty.value->setEmptyListValue(tr("None available"));
}
if (!mNlaSolverData.solversProperty.isEmpty()) {
setNonEditablePropertyItem(mNlaSolverData.solversProperty.name, tr("NLA solver"));
setNonEditablePropertyItem(mNlaSolverData.solversListProperty.name, tr("Name"));
mNlaSolverData.solversListProperty.value->setEmptyListValue(tr("None available"));
}
// Default retranslation
// Note: we must do it last since we set the empty list value of some
// properties above...
PropertyEditorWidget::retranslateUi();
}
//==============================================================================
void SingleCellSimulationViewInformationSolversWidget::addSolverProperties(const SolverInterfaces &pSolverInterfaces,
const Solver::Type &pSolverType,
SingleCellSimulationViewInformationSolversWidgetData &pSolverData)
{
// Make sure that we have at least one solver interface
if (pSolverInterfaces.isEmpty()) {
pSolverData.solversProperty = Core::Property();
pSolverData.solversListProperty = Core::Property();
return;
}
// Add our category property
pSolverData.solversProperty = addCategoryProperty();
// Add our list property for the solvers
pSolverData.solversListProperty = addListProperty(pSolverData.solversProperty);
// Retrieve the name of the solvers which type is the one we are interested
// in
QStringList solvers = QStringList();
foreach (SolverInterface *solverInterface, pSolverInterfaces)
if (solverInterface->type() == pSolverType) {
// Keep track of the solver's name
solvers << solverInterface->name();
// Add the solver's properties
Core::Property property;
Core::Properties properties = Core::Properties();
foreach (const Solver::Property &solverInterfaceProperty,
solverInterface->properties()) {
// Add the solver's property
switch (solverInterfaceProperty.type) {
case Solver::Double:
property = addDoubleProperty(pSolverData.solversProperty);
break;
default:
// Solver::Integer
property = addIntegerProperty(pSolverData.solversProperty);
}
// Set the solver's property's name
setNonEditablePropertyItem(property.name, solverInterfaceProperty.name);
// Set the solver's property's 'unit', if needed
if (solverInterfaceProperty.hasVoiUnit)
setNonEditablePropertyItem(property.unit, "???");
// Note: to assign a non-empty string to our unit item is
// just a way for us to keep track of the fact that
// the property should have a unit (see
// setPropertiesUnit())...
// Keep track of the solver's property
properties << property;
}
// Keep track of the solver's properties
pSolverData.solversProperties.insert(solverInterface->name(), properties);
}
// Add the list of solvers to our list property value item
pSolverData.solversListProperty.value->setList(solvers);
// Keep track of changes to list properties
connect(this, SIGNAL(listPropertyChanged(const QString &)),
this, SLOT(listPropertyChanged(const QString &)));
}
//==============================================================================
void SingleCellSimulationViewInformationSolversWidget::setSolverInterfaces(const SolverInterfaces &pSolverInterfaces)
{
// Remove all our properties
removeAllProperties();
// Add properties for our different solvers
addSolverProperties(pSolverInterfaces, Solver::Ode, mOdeSolverData);
addSolverProperties(pSolverInterfaces, Solver::Dae, mDaeSolverData);
addSolverProperties(pSolverInterfaces, Solver::Nla, mNlaSolverData);
// Show/hide the relevant properties
doListPropertyChanged(mOdeSolverData, mOdeSolverData.solversListProperty.value->text(), true);
doListPropertyChanged(mDaeSolverData, mDaeSolverData.solversListProperty.value->text(), true);
doListPropertyChanged(mNlaSolverData, mNlaSolverData.solversListProperty.value->text(), true);
// Expand all our properties
expandAll();
// Clear any track of previous GUI states and retrieve our default GUI state
// Note: we need to clear any track of GUI states since we removed all the
// properties and added 'new' ones, so any previous GUI state we might
// have had would have been wrong...
mGuiStates.clear();
mDefaultGuiState = guiState();
}
//==============================================================================
void SingleCellSimulationViewInformationSolversWidget::setPropertiesUnit(const SingleCellSimulationViewInformationSolversWidgetData &pSolverData,
const QString &pVoiUnit)
{
// Check whether we need this type of solver and, if not, leave
if (!pSolverData.needSolver)
return;
// Go through the solvers' properties and set the unit of the relevant ones
foreach (const Core::Properties &properties, pSolverData.solversProperties)
foreach (const Core::Property &property, properties)
if (!property.unit->text().isEmpty())
property.unit->setText(pVoiUnit);
}
//==============================================================================
void SingleCellSimulationViewInformationSolversWidget::initialize(const QString &pFileName,
CellMLSupport::CellmlFileRuntime *pCellmlFileRuntime)
{
// Make sure that we have a CellML file runtime
if (!pCellmlFileRuntime)
return;
// Retrieve and initialise our GUI state
setGuiState(mGuiStates.contains(pFileName)?
mGuiStates.value(pFileName):
mDefaultGuiState);
// Make sure that the CellML file runtime is valid
if (pCellmlFileRuntime->isValid()) {
// Show/hide the ODE/DAE solver information
mOdeSolverData.needSolver = pCellmlFileRuntime->modelType() == CellMLSupport::CellmlFileRuntime::Ode;
mDaeSolverData.needSolver = !mOdeSolverData.needSolver;
setPropertyVisible(mOdeSolverData.solversProperty, mOdeSolverData.needSolver);
setPropertyVisible(mDaeSolverData.solversProperty, mDaeSolverData.needSolver);
// Show/hide the NLA solver information
mNlaSolverData.needSolver = pCellmlFileRuntime->needNlaSolver();
setPropertyVisible(mNlaSolverData.solversProperty, mNlaSolverData.needSolver);
// Retranslate ourselves so that the property names get properly set
retranslateUi();
}
// Set the unit of our different properties, if needed
QString voiUnit = pCellmlFileRuntime->variableOfIntegration()->unit();
setPropertiesUnit(mOdeSolverData, voiUnit);
setPropertiesUnit(mDaeSolverData, voiUnit);
setPropertiesUnit(mNlaSolverData, voiUnit);
}
//==============================================================================
void SingleCellSimulationViewInformationSolversWidget::finalize(const QString &pFileName)
{
// Keep track of our GUI state
mGuiStates.insert(pFileName, guiState());
}
//==============================================================================
bool SingleCellSimulationViewInformationSolversWidget::needOdeSolver() const
{
// Return whether we need an ODE solver
return mOdeSolverData.needSolver;
}
//==============================================================================
bool SingleCellSimulationViewInformationSolversWidget::needDaeSolver() const
{
// Return whether we need a DAE solver
return mDaeSolverData.needSolver;
}
//==============================================================================
bool SingleCellSimulationViewInformationSolversWidget::needNlaSolver() const
{
// Return whether we need an NLA solver
return mNlaSolverData.needSolver;
}
//==============================================================================
QStringList SingleCellSimulationViewInformationSolversWidget::odeSolvers() const
{
// Return the available ODE solvers, if any
return mOdeSolverData.solversListProperty.isEmpty()?QStringList():mOdeSolverData.solversListProperty.value->list();
}
//==============================================================================
QStringList SingleCellSimulationViewInformationSolversWidget::daeSolvers() const
{
// Return the available DAE solvers, if any
return mDaeSolverData.solversListProperty.isEmpty()?QStringList():mDaeSolverData.solversListProperty.value->list();
}
//==============================================================================
QStringList SingleCellSimulationViewInformationSolversWidget::nlaSolvers() const
{
// Return the available NLA solvers, if any
return mNlaSolverData.solversListProperty.isEmpty()?QStringList():mNlaSolverData.solversListProperty.value->list();
}
//==============================================================================
bool SingleCellSimulationViewInformationSolversWidget::doListPropertyChanged(const SingleCellSimulationViewInformationSolversWidgetData &pSolverData,
const QString &pSolverName,
const bool &pForceHandling)
{
// By default, we don't handle the change in the list property
bool res = false;
// Check whether the list property that got changed is the one we are after
if ( (pSolverData.solversListProperty == currentProperty())
|| pForceHandling) {
// It is the list property we are after or we want to force the
// handling, so update our result
res = true;
// Go through the different properties for the given type of solver and
// show/hide whatever needs showing/hiding
QMap<QString, Core::Properties>::const_iterator iter = pSolverData.solversProperties.constBegin();
while (iter != pSolverData.solversProperties.constEnd()) {
bool propertyVisible = !iter.key().compare(pSolverName);
foreach (const Core::Property &property, iter.value())
setPropertyVisible(property, propertyVisible);
++iter;
}
}
// Return our result
return res;
}
//==============================================================================
void SingleCellSimulationViewInformationSolversWidget::listPropertyChanged(const QString &pValue)
{
// Try, for the ODE, DAE and NLA solvers list property, to handle the change
// in the list property
if (!doListPropertyChanged(mOdeSolverData, pValue))
if (!doListPropertyChanged(mDaeSolverData, pValue))
doListPropertyChanged(mNlaSolverData, pValue);
}
//==============================================================================
} // namespace SingleCellSimulationView
} // namespace OpenCOR
//==============================================================================
// End of file
//==============================================================================
<commit_msg>Some work on our solvers' properties (#112). We now have a default value.<commit_after>//==============================================================================
// Single cell simulation view information solvers widget
//==============================================================================
#include "cellmlfileruntime.h"
#include "cellmlfilevariable.h"
#include "singlecellsimulationviewinformationsolverswidget.h"
//==============================================================================
namespace OpenCOR {
namespace SingleCellSimulationView {
//==============================================================================
SingleCellSimulationViewInformationSolversWidgetData::SingleCellSimulationViewInformationSolversWidgetData() :
needSolver(true),
solversProperty(Core::Property()),
solversListProperty(Core::Property()),
solversProperties(QMap<QString, Core::Properties>())
{
}
//==============================================================================
SingleCellSimulationViewInformationSolversWidget::SingleCellSimulationViewInformationSolversWidget(QWidget *pParent) :
PropertyEditorWidget(true, pParent),
mOdeSolverData(SingleCellSimulationViewInformationSolversWidgetData()),
mDaeSolverData(SingleCellSimulationViewInformationSolversWidgetData()),
mNlaSolverData(SingleCellSimulationViewInformationSolversWidgetData()),
mGuiStates(QMap<QString, Core::PropertyEditorWidgetGuiState>()),
mDefaultGuiState(Core::PropertyEditorWidgetGuiState())
{
}
//==============================================================================
void SingleCellSimulationViewInformationSolversWidget::retranslateUi()
{
// Update our property names
if (!mOdeSolverData.solversProperty.isEmpty()) {
setNonEditablePropertyItem(mOdeSolverData.solversProperty.name, tr("ODE solver"));
setNonEditablePropertyItem(mOdeSolverData.solversListProperty.name, tr("Name"));
mOdeSolverData.solversListProperty.value->setEmptyListValue(tr("None available"));
}
if (!mDaeSolverData.solversProperty.isEmpty()) {
setNonEditablePropertyItem(mDaeSolverData.solversProperty.name, tr("DAE solver"));
setNonEditablePropertyItem(mDaeSolverData.solversListProperty.name, tr("Name"));
mDaeSolverData.solversListProperty.value->setEmptyListValue(tr("None available"));
}
if (!mNlaSolverData.solversProperty.isEmpty()) {
setNonEditablePropertyItem(mNlaSolverData.solversProperty.name, tr("NLA solver"));
setNonEditablePropertyItem(mNlaSolverData.solversListProperty.name, tr("Name"));
mNlaSolverData.solversListProperty.value->setEmptyListValue(tr("None available"));
}
// Default retranslation
// Note: we must do it last since we set the empty list value of some
// properties above...
PropertyEditorWidget::retranslateUi();
}
//==============================================================================
void SingleCellSimulationViewInformationSolversWidget::addSolverProperties(const SolverInterfaces &pSolverInterfaces,
const Solver::Type &pSolverType,
SingleCellSimulationViewInformationSolversWidgetData &pSolverData)
{
// Make sure that we have at least one solver interface
if (pSolverInterfaces.isEmpty()) {
pSolverData.solversProperty = Core::Property();
pSolverData.solversListProperty = Core::Property();
return;
}
// Add our category property
pSolverData.solversProperty = addCategoryProperty();
// Add our list property for the solvers
pSolverData.solversListProperty = addListProperty(pSolverData.solversProperty);
// Retrieve the name of the solvers which type is the one we are interested
// in
QStringList solvers = QStringList();
foreach (SolverInterface *solverInterface, pSolverInterfaces)
if (solverInterface->type() == pSolverType) {
// Keep track of the solver's name
solvers << solverInterface->name();
// Add the solver's properties
Core::Property property;
Core::Properties properties = Core::Properties();
foreach (const Solver::Property &solverInterfaceProperty,
solverInterface->properties()) {
// Add the solver's property
switch (solverInterfaceProperty.type) {
case Solver::Double:
property = addDoubleProperty(pSolverData.solversProperty);
break;
default:
// Solver::Integer
property = addIntegerProperty(pSolverData.solversProperty);
}
// Set the solver's property's name
setNonEditablePropertyItem(property.name, solverInterfaceProperty.name);
// Set the solver's property's default value
switch (solverInterfaceProperty.type) {
case Solver::Double:
setDoublePropertyItem(property.value, solverInterfaceProperty.defaultValue.toDouble());
break;
default:
// Solver::Integer
setIntegerPropertyItem(property.value, solverInterfaceProperty.defaultValue.toInt());
}
// Set the solver's property's 'unit', if needed
if (solverInterfaceProperty.hasVoiUnit)
setNonEditablePropertyItem(property.unit, "???");
// Note: to assign a non-empty string to our unit item is
// just a way for us to keep track of the fact that
// the property should have a unit (see
// setPropertiesUnit())...
// Keep track of the solver's property
properties << property;
}
// Keep track of the solver's properties
pSolverData.solversProperties.insert(solverInterface->name(), properties);
}
// Add the list of solvers to our list property value item
pSolverData.solversListProperty.value->setList(solvers);
// Keep track of changes to list properties
connect(this, SIGNAL(listPropertyChanged(const QString &)),
this, SLOT(listPropertyChanged(const QString &)));
}
//==============================================================================
void SingleCellSimulationViewInformationSolversWidget::setSolverInterfaces(const SolverInterfaces &pSolverInterfaces)
{
// Remove all our properties
removeAllProperties();
// Add properties for our different solvers
addSolverProperties(pSolverInterfaces, Solver::Ode, mOdeSolverData);
addSolverProperties(pSolverInterfaces, Solver::Dae, mDaeSolverData);
addSolverProperties(pSolverInterfaces, Solver::Nla, mNlaSolverData);
// Show/hide the relevant properties
doListPropertyChanged(mOdeSolverData, mOdeSolverData.solversListProperty.value->text(), true);
doListPropertyChanged(mDaeSolverData, mDaeSolverData.solversListProperty.value->text(), true);
doListPropertyChanged(mNlaSolverData, mNlaSolverData.solversListProperty.value->text(), true);
// Expand all our properties
expandAll();
// Clear any track of previous GUI states and retrieve our default GUI state
// Note: we need to clear any track of GUI states since we removed all the
// properties and added 'new' ones, so any previous GUI state we might
// have had would have been wrong...
mGuiStates.clear();
mDefaultGuiState = guiState();
}
//==============================================================================
void SingleCellSimulationViewInformationSolversWidget::setPropertiesUnit(const SingleCellSimulationViewInformationSolversWidgetData &pSolverData,
const QString &pVoiUnit)
{
// Check whether we need this type of solver and, if not, leave
if (!pSolverData.needSolver)
return;
// Go through the solvers' properties and set the unit of the relevant ones
foreach (const Core::Properties &properties, pSolverData.solversProperties)
foreach (const Core::Property &property, properties)
if (!property.unit->text().isEmpty())
property.unit->setText(pVoiUnit);
}
//==============================================================================
void SingleCellSimulationViewInformationSolversWidget::initialize(const QString &pFileName,
CellMLSupport::CellmlFileRuntime *pCellmlFileRuntime)
{
// Make sure that we have a CellML file runtime
if (!pCellmlFileRuntime)
return;
// Retrieve and initialise our GUI state
setGuiState(mGuiStates.contains(pFileName)?
mGuiStates.value(pFileName):
mDefaultGuiState);
// Make sure that the CellML file runtime is valid
if (pCellmlFileRuntime->isValid()) {
// Show/hide the ODE/DAE solver information
mOdeSolverData.needSolver = pCellmlFileRuntime->modelType() == CellMLSupport::CellmlFileRuntime::Ode;
mDaeSolverData.needSolver = !mOdeSolverData.needSolver;
setPropertyVisible(mOdeSolverData.solversProperty, mOdeSolverData.needSolver);
setPropertyVisible(mDaeSolverData.solversProperty, mDaeSolverData.needSolver);
// Show/hide the NLA solver information
mNlaSolverData.needSolver = pCellmlFileRuntime->needNlaSolver();
setPropertyVisible(mNlaSolverData.solversProperty, mNlaSolverData.needSolver);
// Retranslate ourselves so that the property names get properly set
retranslateUi();
}
// Set the unit of our different properties, if needed
QString voiUnit = pCellmlFileRuntime->variableOfIntegration()->unit();
setPropertiesUnit(mOdeSolverData, voiUnit);
setPropertiesUnit(mDaeSolverData, voiUnit);
setPropertiesUnit(mNlaSolverData, voiUnit);
}
//==============================================================================
void SingleCellSimulationViewInformationSolversWidget::finalize(const QString &pFileName)
{
// Keep track of our GUI state
mGuiStates.insert(pFileName, guiState());
}
//==============================================================================
bool SingleCellSimulationViewInformationSolversWidget::needOdeSolver() const
{
// Return whether we need an ODE solver
return mOdeSolverData.needSolver;
}
//==============================================================================
bool SingleCellSimulationViewInformationSolversWidget::needDaeSolver() const
{
// Return whether we need a DAE solver
return mDaeSolverData.needSolver;
}
//==============================================================================
bool SingleCellSimulationViewInformationSolversWidget::needNlaSolver() const
{
// Return whether we need an NLA solver
return mNlaSolverData.needSolver;
}
//==============================================================================
QStringList SingleCellSimulationViewInformationSolversWidget::odeSolvers() const
{
// Return the available ODE solvers, if any
return mOdeSolverData.solversListProperty.isEmpty()?QStringList():mOdeSolverData.solversListProperty.value->list();
}
//==============================================================================
QStringList SingleCellSimulationViewInformationSolversWidget::daeSolvers() const
{
// Return the available DAE solvers, if any
return mDaeSolverData.solversListProperty.isEmpty()?QStringList():mDaeSolverData.solversListProperty.value->list();
}
//==============================================================================
QStringList SingleCellSimulationViewInformationSolversWidget::nlaSolvers() const
{
// Return the available NLA solvers, if any
return mNlaSolverData.solversListProperty.isEmpty()?QStringList():mNlaSolverData.solversListProperty.value->list();
}
//==============================================================================
bool SingleCellSimulationViewInformationSolversWidget::doListPropertyChanged(const SingleCellSimulationViewInformationSolversWidgetData &pSolverData,
const QString &pSolverName,
const bool &pForceHandling)
{
// By default, we don't handle the change in the list property
bool res = false;
// Check whether the list property that got changed is the one we are after
if ( (pSolverData.solversListProperty == currentProperty())
|| pForceHandling) {
// It is the list property we are after or we want to force the
// handling, so update our result
res = true;
// Go through the different properties for the given type of solver and
// show/hide whatever needs showing/hiding
QMap<QString, Core::Properties>::const_iterator iter = pSolverData.solversProperties.constBegin();
while (iter != pSolverData.solversProperties.constEnd()) {
bool propertyVisible = !iter.key().compare(pSolverName);
foreach (const Core::Property &property, iter.value())
setPropertyVisible(property, propertyVisible);
++iter;
}
}
// Return our result
return res;
}
//==============================================================================
void SingleCellSimulationViewInformationSolversWidget::listPropertyChanged(const QString &pValue)
{
// Try, for the ODE, DAE and NLA solvers list property, to handle the change
// in the list property
if (!doListPropertyChanged(mOdeSolverData, pValue))
if (!doListPropertyChanged(mDaeSolverData, pValue))
doListPropertyChanged(mNlaSolverData, pValue);
}
//==============================================================================
} // namespace SingleCellSimulationView
} // namespace OpenCOR
//==============================================================================
// End of file
//==============================================================================
<|endoftext|>
|
<commit_before>/*
* Copyright(c) Sophist Solutions, Inc. 1990-2021. All rights reserved
*/
#include "../../StroikaPreComp.h"
#if qPlatform_Windows
#include <Windows.h>
#include <winioctl.h>
#endif
#include "../../Characters/Format.h"
#include "../../Characters/String.h"
#include "../../Characters/StringBuilder.h"
#include "../../Characters/ToString.h"
#include "../../Memory/SmallStackBuffer.h"
#include "PathName.h"
#include "Disk.h"
using namespace Stroika::Foundation;
using namespace Stroika::Foundation::Characters;
using namespace Stroika::Foundation::Containers;
using namespace Stroika::Foundation::IO;
using namespace Stroika::Foundation::IO::FileSystem;
/*
* I thought this might be useful. maybe at some point? But so far it doesn't appear super useful
* or needed.
* But we can use this to find out the disk kind for physical devices
* --LGP 2015-09-30
*/
#ifndef qCaptureDiskDeviceInfoWindows_
#define qCaptureDiskDeviceInfoWindows_ 0
#endif
#if qCaptureDiskDeviceInfoWindows_
#include <devguid.h>
#include <regstr.h>
#include <setupapi.h>
#pragma comment(lib, "Setupapi.lib")
DEFINE_GUID (GUID_DEVINTERFACE_DISK, 0x53f56307L, 0xb6bf, 0x11d0, 0x94, 0xf2, 0x00, 0xa0, 0xc9, 0x1e, 0xfb, 0x8b);
#endif
/*
********************************************************************************
************************** IO::FileSystem::DiskInfoType ************************
********************************************************************************
*/
String DiskInfoType::ToString () const
{
StringBuilder sb;
sb += L"{";
sb += L"Device-Name: " + Characters::ToString (fDeviceName) + L", ";
if (fDeviceKind) {
sb += L"Device-Kind: '" + Characters::ToString (*fDeviceKind) + L"', ";
}
if (fSizeInBytes) {
sb += L"Size-In-Bytes: " + Characters::ToString (*fSizeInBytes) + L", ";
}
sb += L"}";
return sb.str ();
}
/*
********************************************************************************
**************************** FileSystem::GetAvailableDisks *********************
********************************************************************************
*/
#if qCaptureDiskDeviceInfoWindows_
namespace {
list<wstring> GetPhysicalDiskDeviceInfo_ ()
{
HDEVINFO hDeviceInfoSet;
ULONG ulMemberIndex;
ULONG ulErrorCode;
BOOL bFound = FALSE;
BOOL bOk;
list<wstring> disks;
// create a HDEVINFO with all present devices
hDeviceInfoSet = ::SetupDiGetClassDevs (&GUID_DEVINTERFACE_DISK, NULL, NULL, DIGCF_PRESENT | DIGCF_DEVICEINTERFACE);
if (hDeviceInfoSet == INVALID_HANDLE_VALUE) {
_ASSERT (FALSE);
return disks;
}
// enumerate through all devices in the set
ulMemberIndex = 0;
while (TRUE) {
// get device info
SP_DEVINFO_DATA deviceInfoData;
deviceInfoData.cbSize = sizeof (SP_DEVINFO_DATA);
if (!::SetupDiEnumDeviceInfo (hDeviceInfoSet, ulMemberIndex, &deviceInfoData)) {
if (::GetLastError () == ERROR_NO_MORE_ITEMS) {
// ok, reached end of the device enumeration
break;
}
else {
// error
_ASSERT (FALSE);
::SetupDiDestroyDeviceInfoList (hDeviceInfoSet);
return disks;
}
}
// get device interfaces
SP_DEVICE_INTERFACE_DATA deviceInterfaceData;
deviceInterfaceData.cbSize = sizeof (SP_DEVICE_INTERFACE_DATA);
if (!::SetupDiEnumDeviceInterfaces (hDeviceInfoSet, NULL, &GUID_DEVINTERFACE_DISK, ulMemberIndex, &deviceInterfaceData)) {
if (::GetLastError () == ERROR_NO_MORE_ITEMS) {
// ok, reached end of the device enumeration
break;
}
else {
// error
_ASSERT (FALSE);
::SetupDiDestroyDeviceInfoList (hDeviceInfoSet);
return disks;
}
}
// process the next device next time
ulMemberIndex++;
// get hardware id of the device
ULONG ulPropertyRegDataType = 0;
ULONG ulRequiredSize = 0;
ULONG ulBufferSize = 0;
BYTE* pbyBuffer = NULL;
if (!::SetupDiGetDeviceRegistryProperty (hDeviceInfoSet, &deviceInfoData, SPDRP_HARDWAREID, &ulPropertyRegDataType, NULL, 0, &ulRequiredSize)) {
if (::GetLastError () == ERROR_INSUFFICIENT_BUFFER) {
pbyBuffer = (BYTE*)::malloc (ulRequiredSize);
ulBufferSize = ulRequiredSize;
if (!::SetupDiGetDeviceRegistryProperty (hDeviceInfoSet, &deviceInfoData, SPDRP_HARDWAREID, &ulPropertyRegDataType, pbyBuffer, ulBufferSize, &ulRequiredSize)) {
// getting the hardware id failed
_ASSERT (FALSE);
::SetupDiDestroyDeviceInfoList (hDeviceInfoSet);
::free (pbyBuffer);
return disks;
}
}
else {
// getting device registry property failed
_ASSERT (FALSE);
::SetupDiDestroyDeviceInfoList (hDeviceInfoSet);
return disks;
}
}
else {
// getting hardware id of the device succeeded unexpectedly
_ASSERT (FALSE);
::SetupDiDestroyDeviceInfoList (hDeviceInfoSet);
return disks;
}
// pbyBuffer is initialized now!
LPCWSTR pszHardwareId = (LPCWSTR)pbyBuffer;
// retrieve detailed information about the device
// (especially the device path which is needed to create the device object)
SP_DEVICE_INTERFACE_DETAIL_DATA* pDeviceInterfaceDetailData = NULL;
ULONG ulDeviceInterfaceDetailDataSize = 0;
ulRequiredSize = 0;
bOk = ::SetupDiGetDeviceInterfaceDetail (hDeviceInfoSet, &deviceInterfaceData, pDeviceInterfaceDetailData, ulDeviceInterfaceDetailDataSize, &ulRequiredSize, NULL);
if (!bOk) {
ulErrorCode = ::GetLastError ();
if (ulErrorCode == ERROR_INSUFFICIENT_BUFFER) {
// insufficient buffer space
// => that's ok, allocate enough space and try again
pDeviceInterfaceDetailData = (SP_DEVICE_INTERFACE_DETAIL_DATA*)::malloc (ulRequiredSize);
pDeviceInterfaceDetailData->cbSize = sizeof (SP_DEVICE_INTERFACE_DETAIL_DATA);
ulDeviceInterfaceDetailDataSize = ulRequiredSize;
deviceInfoData.cbSize = sizeof (SP_DEVINFO_DATA);
bOk = ::SetupDiGetDeviceInterfaceDetail (hDeviceInfoSet, &deviceInterfaceData, pDeviceInterfaceDetailData, ulDeviceInterfaceDetailDataSize, &ulRequiredSize, &deviceInfoData);
ulErrorCode = ::GetLastError ();
}
if (!bOk) {
// retrieving detailed information about the device failed
_ASSERT (FALSE);
::free (pbyBuffer);
::free (pDeviceInterfaceDetailData);
::SetupDiDestroyDeviceInfoList (hDeviceInfoSet);
return disks;
}
}
else {
// retrieving detailed information about the device succeeded unexpectedly
_ASSERT (FALSE);
::free (pbyBuffer);
::SetupDiDestroyDeviceInfoList (hDeviceInfoSet);
return disks;
}
disks.push_back (pDeviceInterfaceDetailData->DevicePath);
// free buffer for device interface details
::free (pDeviceInterfaceDetailData);
// free buffer
::free (pbyBuffer);
}
// destroy device info list
::SetupDiDestroyDeviceInfoList (hDeviceInfoSet);
return disks;
}
}
#endif
namespace {
filesystem::path GetPhysNameForDriveNumber_ (unsigned int i)
{
// This format is NOT super well documented, and was mostly derived from reading the remarks section
// of https://msdn.microsoft.com/en-us/library/windows/desktop/aa363216%28v=vs.85%29.aspx?f=255&MSPPError=-2147217396
// (DeviceIoControl function)
return IO::FileSystem::ToPath (Characters::Format (L"\\\\.\\PhysicalDrive%d", i));
}
}
Collection<DiskInfoType> FileSystem::GetAvailableDisks ()
{
Collection<DiskInfoType> result{};
#if qPlatform_Windows
#if qCaptureDiskDeviceInfoWindows_ && 0
for (const auto& s : GetPhysicalDiskDeviceInfo_ ()) {
DbgTrace (L"s=%s", s.c_str ());
}
#endif
for (int i = 0; i < 64; i++) {
HANDLE hHandle = ::CreateFileW (GetPhysNameForDriveNumber_ (i).c_str (), GENERIC_READ, FILE_SHARE_WRITE | FILE_SHARE_READ, nullptr, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, nullptr);
if (hHandle == INVALID_HANDLE_VALUE) {
break;
}
GET_LENGTH_INFORMATION li{};
{
DWORD dwBytesReturned{};
BOOL bResult = ::DeviceIoControl (hHandle, IOCTL_DISK_GET_LENGTH_INFO, nullptr, 0, &li, sizeof (li), &dwBytesReturned, nullptr);
if (bResult == 0) {
DbgTrace (L"failed - DeviceIoControl - IOCTL_DISK_GET_LENGTH_INFO - ignored");
continue;
}
}
DISK_GEOMETRY driveInfo{};
{
DWORD dwBytesReturned{};
BOOL bResult = ::DeviceIoControl (hHandle, IOCTL_DISK_GET_DRIVE_GEOMETRY, nullptr, 0, &driveInfo, sizeof (driveInfo), &dwBytesReturned, nullptr);
if (bResult == 0) {
DbgTrace (L"failed - DeviceIoControl - IOCTL_DISK_GET_DRIVE_GEOMETRY - ignored");
continue;
}
}
::CloseHandle (hHandle);
/*
* Is the 'disk' a 'remote' device (network), CD-ROM, direct-attached hard disk (e.g. internal) or removable drive,
*/
optional<BlockDeviceKind> deviceKind;
switch (driveInfo.MediaType) {
case FixedMedia:
deviceKind = BlockDeviceKind::eLocalDisk;
break;
case RemovableMedia:
deviceKind = BlockDeviceKind::eRemovableDisk;
break;
}
DiskInfoType di{GetPhysNameForDriveNumber_ (i), deviceKind, static_cast<uint64_t> (li.Length.QuadPart)};
result.Add (di);
}
#endif
return result;
}
<commit_msg>FileSystem::GetAvailableDisks uses FILE_SHARE_READ not FILE_SHARE_WRITE | FILE_SHARE_READ, still seems to work, but still seems to require admin permissions<commit_after>/*
* Copyright(c) Sophist Solutions, Inc. 1990-2021. All rights reserved
*/
#include "../../StroikaPreComp.h"
#if qPlatform_Windows
#include <Windows.h>
#include <winioctl.h>
#endif
#include "../../Characters/Format.h"
#include "../../Characters/String.h"
#include "../../Characters/StringBuilder.h"
#include "../../Characters/ToString.h"
#include "../../Memory/SmallStackBuffer.h"
#include "PathName.h"
#include "Disk.h"
using namespace Stroika::Foundation;
using namespace Stroika::Foundation::Characters;
using namespace Stroika::Foundation::Containers;
using namespace Stroika::Foundation::IO;
using namespace Stroika::Foundation::IO::FileSystem;
/*
* I thought this might be useful. maybe at some point? But so far it doesn't appear super useful
* or needed.
* But we can use this to find out the disk kind for physical devices
* --LGP 2015-09-30
*/
#ifndef qCaptureDiskDeviceInfoWindows_
#define qCaptureDiskDeviceInfoWindows_ 0
#endif
#if qCaptureDiskDeviceInfoWindows_
#include <devguid.h>
#include <regstr.h>
#include <setupapi.h>
#pragma comment(lib, "Setupapi.lib")
DEFINE_GUID (GUID_DEVINTERFACE_DISK, 0x53f56307L, 0xb6bf, 0x11d0, 0x94, 0xf2, 0x00, 0xa0, 0xc9, 0x1e, 0xfb, 0x8b);
#endif
/*
********************************************************************************
************************** IO::FileSystem::DiskInfoType ************************
********************************************************************************
*/
String DiskInfoType::ToString () const
{
StringBuilder sb;
sb += L"{";
sb += L"Device-Name: " + Characters::ToString (fDeviceName) + L", ";
if (fDeviceKind) {
sb += L"Device-Kind: '" + Characters::ToString (*fDeviceKind) + L"', ";
}
if (fSizeInBytes) {
sb += L"Size-In-Bytes: " + Characters::ToString (*fSizeInBytes) + L", ";
}
sb += L"}";
return sb.str ();
}
/*
********************************************************************************
**************************** FileSystem::GetAvailableDisks *********************
********************************************************************************
*/
#if qCaptureDiskDeviceInfoWindows_
namespace {
list<wstring> GetPhysicalDiskDeviceInfo_ ()
{
HDEVINFO hDeviceInfoSet;
ULONG ulMemberIndex;
ULONG ulErrorCode;
BOOL bFound = FALSE;
BOOL bOk;
list<wstring> disks;
// create a HDEVINFO with all present devices
hDeviceInfoSet = ::SetupDiGetClassDevs (&GUID_DEVINTERFACE_DISK, NULL, NULL, DIGCF_PRESENT | DIGCF_DEVICEINTERFACE);
if (hDeviceInfoSet == INVALID_HANDLE_VALUE) {
_ASSERT (FALSE);
return disks;
}
// enumerate through all devices in the set
ulMemberIndex = 0;
while (TRUE) {
// get device info
SP_DEVINFO_DATA deviceInfoData;
deviceInfoData.cbSize = sizeof (SP_DEVINFO_DATA);
if (!::SetupDiEnumDeviceInfo (hDeviceInfoSet, ulMemberIndex, &deviceInfoData)) {
if (::GetLastError () == ERROR_NO_MORE_ITEMS) {
// ok, reached end of the device enumeration
break;
}
else {
// error
_ASSERT (FALSE);
::SetupDiDestroyDeviceInfoList (hDeviceInfoSet);
return disks;
}
}
// get device interfaces
SP_DEVICE_INTERFACE_DATA deviceInterfaceData;
deviceInterfaceData.cbSize = sizeof (SP_DEVICE_INTERFACE_DATA);
if (!::SetupDiEnumDeviceInterfaces (hDeviceInfoSet, NULL, &GUID_DEVINTERFACE_DISK, ulMemberIndex, &deviceInterfaceData)) {
if (::GetLastError () == ERROR_NO_MORE_ITEMS) {
// ok, reached end of the device enumeration
break;
}
else {
// error
_ASSERT (FALSE);
::SetupDiDestroyDeviceInfoList (hDeviceInfoSet);
return disks;
}
}
// process the next device next time
ulMemberIndex++;
// get hardware id of the device
ULONG ulPropertyRegDataType = 0;
ULONG ulRequiredSize = 0;
ULONG ulBufferSize = 0;
BYTE* pbyBuffer = NULL;
if (!::SetupDiGetDeviceRegistryProperty (hDeviceInfoSet, &deviceInfoData, SPDRP_HARDWAREID, &ulPropertyRegDataType, NULL, 0, &ulRequiredSize)) {
if (::GetLastError () == ERROR_INSUFFICIENT_BUFFER) {
pbyBuffer = (BYTE*)::malloc (ulRequiredSize);
ulBufferSize = ulRequiredSize;
if (!::SetupDiGetDeviceRegistryProperty (hDeviceInfoSet, &deviceInfoData, SPDRP_HARDWAREID, &ulPropertyRegDataType, pbyBuffer, ulBufferSize, &ulRequiredSize)) {
// getting the hardware id failed
_ASSERT (FALSE);
::SetupDiDestroyDeviceInfoList (hDeviceInfoSet);
::free (pbyBuffer);
return disks;
}
}
else {
// getting device registry property failed
_ASSERT (FALSE);
::SetupDiDestroyDeviceInfoList (hDeviceInfoSet);
return disks;
}
}
else {
// getting hardware id of the device succeeded unexpectedly
_ASSERT (FALSE);
::SetupDiDestroyDeviceInfoList (hDeviceInfoSet);
return disks;
}
// pbyBuffer is initialized now!
LPCWSTR pszHardwareId = (LPCWSTR)pbyBuffer;
// retrieve detailed information about the device
// (especially the device path which is needed to create the device object)
SP_DEVICE_INTERFACE_DETAIL_DATA* pDeviceInterfaceDetailData = NULL;
ULONG ulDeviceInterfaceDetailDataSize = 0;
ulRequiredSize = 0;
bOk = ::SetupDiGetDeviceInterfaceDetail (hDeviceInfoSet, &deviceInterfaceData, pDeviceInterfaceDetailData, ulDeviceInterfaceDetailDataSize, &ulRequiredSize, NULL);
if (!bOk) {
ulErrorCode = ::GetLastError ();
if (ulErrorCode == ERROR_INSUFFICIENT_BUFFER) {
// insufficient buffer space
// => that's ok, allocate enough space and try again
pDeviceInterfaceDetailData = (SP_DEVICE_INTERFACE_DETAIL_DATA*)::malloc (ulRequiredSize);
pDeviceInterfaceDetailData->cbSize = sizeof (SP_DEVICE_INTERFACE_DETAIL_DATA);
ulDeviceInterfaceDetailDataSize = ulRequiredSize;
deviceInfoData.cbSize = sizeof (SP_DEVINFO_DATA);
bOk = ::SetupDiGetDeviceInterfaceDetail (hDeviceInfoSet, &deviceInterfaceData, pDeviceInterfaceDetailData, ulDeviceInterfaceDetailDataSize, &ulRequiredSize, &deviceInfoData);
ulErrorCode = ::GetLastError ();
}
if (!bOk) {
// retrieving detailed information about the device failed
_ASSERT (FALSE);
::free (pbyBuffer);
::free (pDeviceInterfaceDetailData);
::SetupDiDestroyDeviceInfoList (hDeviceInfoSet);
return disks;
}
}
else {
// retrieving detailed information about the device succeeded unexpectedly
_ASSERT (FALSE);
::free (pbyBuffer);
::SetupDiDestroyDeviceInfoList (hDeviceInfoSet);
return disks;
}
disks.push_back (pDeviceInterfaceDetailData->DevicePath);
// free buffer for device interface details
::free (pDeviceInterfaceDetailData);
// free buffer
::free (pbyBuffer);
}
// destroy device info list
::SetupDiDestroyDeviceInfoList (hDeviceInfoSet);
return disks;
}
}
#endif
namespace {
filesystem::path GetPhysNameForDriveNumber_ (unsigned int i)
{
// This format is NOT super well documented, and was mostly derived from reading the remarks section
// of https://msdn.microsoft.com/en-us/library/windows/desktop/aa363216%28v=vs.85%29.aspx?f=255&MSPPError=-2147217396
// (DeviceIoControl function)
return IO::FileSystem::ToPath (Characters::Format (L"\\\\.\\PhysicalDrive%d", i));
}
}
Collection<DiskInfoType> FileSystem::GetAvailableDisks ()
{
Collection<DiskInfoType> result{};
#if qPlatform_Windows
#if qCaptureDiskDeviceInfoWindows_ && 0
for (const auto& s : GetPhysicalDiskDeviceInfo_ ()) {
DbgTrace (L"s=%s", s.c_str ());
}
#endif
for (int i = 0; i < 64; i++) {
HANDLE hHandle = ::CreateFileW (GetPhysNameForDriveNumber_ (i).c_str (), GENERIC_READ, FILE_SHARE_READ, nullptr, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, nullptr);
if (hHandle == INVALID_HANDLE_VALUE) {
break;
}
GET_LENGTH_INFORMATION li{};
{
DWORD dwBytesReturned{};
BOOL bResult = ::DeviceIoControl (hHandle, IOCTL_DISK_GET_LENGTH_INFO, nullptr, 0, &li, sizeof (li), &dwBytesReturned, nullptr);
if (bResult == 0) {
DbgTrace (L"failed - DeviceIoControl - IOCTL_DISK_GET_LENGTH_INFO - ignored");
continue;
}
}
DISK_GEOMETRY driveInfo{};
{
DWORD dwBytesReturned{};
BOOL bResult = ::DeviceIoControl (hHandle, IOCTL_DISK_GET_DRIVE_GEOMETRY, nullptr, 0, &driveInfo, sizeof (driveInfo), &dwBytesReturned, nullptr);
if (bResult == 0) {
DbgTrace (L"failed - DeviceIoControl - IOCTL_DISK_GET_DRIVE_GEOMETRY - ignored");
continue;
}
}
::CloseHandle (hHandle);
/*
* Is the 'disk' a 'remote' device (network), CD-ROM, direct-attached hard disk (e.g. internal) or removable drive,
*/
optional<BlockDeviceKind> deviceKind;
switch (driveInfo.MediaType) {
case FixedMedia:
deviceKind = BlockDeviceKind::eLocalDisk;
break;
case RemovableMedia:
deviceKind = BlockDeviceKind::eRemovableDisk;
break;
}
DiskInfoType di{GetPhysNameForDriveNumber_ (i), deviceKind, static_cast<uint64_t> (li.Length.QuadPart)};
result.Add (di);
}
#endif
return result;
}
<|endoftext|>
|
<commit_before>#include <cstring>
#if defined _OPENMP
#include <omp.h>
#else
#define omp_get_thread_num() 0
#endif
#ifdef _MSC_VER
#pragma warning(disable:4127)
#endif
#include "common.h"
#include "metrix.h"
#include "OskarBinReader.h"
#define as256p(p) (reinterpret_cast<__m256d*>(p))
#define as256pc(p) (reinterpret_cast<const __m256d*>(p))
template <int grid_size>
void addGrids(
Double4c dst[grid_size][grid_size]
, const Double4c srcs[][grid_size][grid_size]
, int nthreads
)
{
#pragma omp parallel for
for (int i = 0; i < grid_size*grid_size*sizeof(Double4c)/(256/8); i++) {
__m256d sum = as256pc(srcs[0])[i];
for (int g = 1; g < nthreads; g ++)
sum = _mm256_add_pd(sum, as256pc(srcs[g])[i]);
as256p(dst)[i] = sum;
}
}
// We could simply use pointer-to-function template
// but most C++ compilers seem to produce worse code
// in such a case. Thus we wrap it in a class.
template <
int grid_size
, int over
, int w_planes
, bool do_mirror
, typename Inp
> struct cvt {};
template <
int grid_size
, int over
, int w_planes
, bool do_mirror
> struct cvt<grid_size, over, w_planes, do_mirror, Pregridded> {
static void pre(double, Pregridded inp, Pregridded & outpr) {outpr = inp;}
};
template <
int grid_size
, int over
, int w_planes
, bool do_mirror
> struct cvt<grid_size, over, w_planes, do_mirror, Double3> {
static void pre(double scale, Double3 inp, Pregridded & outpr) {
pregridPoint<grid_size, over, w_planes, do_mirror>(scale, inp, outpr);
}
};
template <
int over
, int w_planes
, bool is_half_gcf
, bool use_permutations
, int baselines
, int grid_size
, int ts_ch
, typename Inp
>
// grid must be initialized to 0s.
void gridKernel_scatter(
double scale
, const BlWMap permutations[baselines]
, Double4c grids[][grid_size][grid_size]
// We have a [w_planes][over][over]-shaped array of pointers to
// variable-sized gcf layers, but we precompute (in pregrid)
// exact index into this array, thus we use plain pointer here
, const complexd * gcf
, const Inp uvw[baselines][ts_ch]
, const Double4c vis[baselines][ts_ch]
) {
#pragma omp parallel
{
auto grid = grids[omp_get_thread_num()];
#pragma omp for schedule(dynamic)
for(int bl0 = 0; bl0 < baselines; bl0++) {
int bl;
if (use_permutations) bl = permutations[bl0].bl;
else bl = bl0;
int max_supp_here = get_supp(permutations[bl].wp);
for (int sv = 0; sv < max_supp_here; sv++) { // Moved from 2-levels below according to Romein
for (int i = 0; i < ts_ch; i++) {
Pregridded p;
cvt<grid_size, over, w_planes, is_half_gcf, Inp>::pre(scale, uvw[bl][i], p);
#ifdef __AVX__
// We port Romein CPU code to doubles here (for MS2 we didn't)
// vis0 covers XX and XY, vis1 -- YX and YY
__m256d vis0, vis1;
vis0 = _mm256_load_pd((const double *) &vis[bl][i].XX);
vis1 = _mm256_load_pd((const double *) &vis[bl][i].YX);
#endif
for (int su = 0; su <= max_supp_here; su++) {
// NOTE: Romein writes about moving this to the very outer scope
// (2 levels up) to make things more cache-friendly.
// for (int sv = 0; sv < max_supp_here; sv++) {
// Don't forget our u v are already translated by -max_supp_here/2
int gsu, gsv;
gsu = p.u + su;
gsv = p.v + sv;
complexd supportPixel;
#define __layeroff su * max_supp_here + sv
if (is_half_gcf) {
int index;
index = p.gcf_layer_index;
// Negative index indicates that original w was mirrored
// and we shall negate the index to obtain correct
// offset *and* conjugate the result.
if (index < 0) {
supportPixel = conj((gcf - index)[__layeroff]);
} else {
supportPixel = (gcf + index)[__layeroff];
}
} else {
supportPixel = (gcf + p.gcf_layer_index)[__layeroff];
}
#ifdef __AVX__
__m256d weight_r, weight_i;
weight_r = _mm256_set1_pd(supportPixel.real());
weight_i = _mm256_set1_pd(supportPixel.imag());
/* _mm256_permute_pd(x, 5) swaps adjacent doubles pairs of x:
d0, d1, d2, d3 goes to d1, d0, d3, d2
*/
#define __DO(p,f) \
__m256d * gridptr##p = (__m256d *) &grid[gsu][gsv].f; \
__m256d tr##p = _mm256_mul_pd(weight_r, vis##p); \
__m256d ti##p = _mm256_mul_pd(weight_i, vis##p); \
__m256d tp##p = _mm256_permute_pd(ti##p, 5); \
__m256d t##p = _mm256_addsub_pd(tr##p, tp##p); \
gridptr##p[p] = _mm256_add_pd(gridptr##p[p], t##p)
__DO(0, XX);
__DO(1, YX);
#else
#define __GRID_POL(pol) grid[gsu][gsv].pol += vis[bl][i].pol * supportPixel
__GRID_POL(XX);
__GRID_POL(XY);
__GRID_POL(YX);
__GRID_POL(YY);
#endif
}
}
}
}
}
}
template <
int over
, int w_planes
, bool is_half_gcf
, bool use_permutations
, int baselines
, int grid_size
, int ts_ch
, typename Inp
>
// grid must be initialized to 0s.
void gridKernel_scatter_full(
double scale
, const BlWMap permutations[baselines]
, Double4c grid[grid_size][grid_size]
// We have a [w_planes][over][over]-shaped array of pointers to
// variable-sized gcf layers, but we precompute (in pregrid)
// exact index into this array, thus we use plain pointer here
, const complexd * gcf
, const Inp uvw[baselines][ts_ch]
, const Double4c vis[baselines][ts_ch]
) {
typedef Double4c GT[grid_size][grid_size];
#if defined _OPENMP
int nthreads;
#pragma omp parallel
#pragma omp single
nthreads = omp_get_num_threads();
GT * tmpgrids = new GT[nthreads];
memset(tmpgrids, 0, nthreads * sizeof(GT));
gridKernel_scatter<
over
, w_planes
, is_half_gcf
, use_permutations
, baselines
, grid_size
, ts_ch
, Inp
>(scale, permutations, tmpgrids, gcf, uvw, vis);
addGrids<grid_size>(grid, tmpgrids, nthreads);
delete [] tmpgrids;
#else
gridKernel_scatter<
over
, w_planes
, is_half_gcf
, use_permutations
, baselines
, grid_size
, ts_ch
, Inp
>(scale, permutations, reinterpret_cast<GT*>(&grid), gcf, uvw, vis);
#endif
}
#define gridKernelCPU(hgcfSuff, isHgcf, permSuff, isPerm) \
extern "C" \
void gridKernelCPU##hgcfSuff##permSuff( \
double scale \
, const BlWMap permutations[BASELINES] \
, Double4c grid[GRID_SIZE][GRID_SIZE] \
, const complexd * gcf \
, const Double3 uvw[BASELINES][TIMESTEPS*CHANNELS] \
, const Double4c vis[BASELINES][TIMESTEPS*CHANNELS] \
){ \
gridKernel_scatter_full<OVER, WPLANES, isHgcf, isPerm, BASELINES, GRID_SIZE> \
(scale, permutations, grid, gcf, uvw, vis); \
}
gridKernelCPU(HalfGCF, true, Perm, true)
gridKernelCPU(HalfGCF, true, , false)
gridKernelCPU(FullGCF, false, Perm, true)
gridKernelCPU(FullGCF, false, , false)
/*
extern "C"
void gridKernel_scatter1(
const BlWMap permutations[BASELINES]
, Double4c grid[GRID_SIZE][GRID_SIZE]
, const complexd * gcf
, const Pregridded uvw[BASELINES][TIMESTEPS*CHANNELS]
, const Double4c vis[BASELINES][TIMESTEPS*CHANNELS]
){
// We don't use scale here
gridKernel_scatter_full<OVER, WPLANES, false, false, BASELINES, GRID_SIZE>(0.0, permutations, grid, gcf, uvw, vis);
}
*/
template <int grid_size, int num_pols>
void extractPolarization(
int n
, complexd dst[grid_size][grid_size]
, const complexd src[grid_size][grid_size][num_pols]
)
{
#pragma omp parallel for
for (int i = 0; i < grid_size*grid_size; i++) {
dst[0][i] = src[0][i][n];
}
}
extern "C" void extractPolarization(
int n
, complexd dst[GRID_SIZE][GRID_SIZE]
, const complexd src[GRID_SIZE][GRID_SIZE][NUM_POL]
) {
return extractPolarization<GRID_SIZE, NUM_POL>(n, dst, src);
}<commit_msg>Normalization.<commit_after>#include <cstring>
#if defined _OPENMP
#include <omp.h>
#else
#define omp_get_thread_num() 0
#endif
#ifdef _MSC_VER
#pragma warning(disable:4127)
#endif
#include "common.h"
#include "metrix.h"
#include "OskarBinReader.h"
#define as256p(p) (reinterpret_cast<__m256d*>(p))
#define as256pc(p) (reinterpret_cast<const __m256d*>(p))
template <int grid_size>
void addGrids(
Double4c dst[grid_size][grid_size]
, const Double4c srcs[][grid_size][grid_size]
, int nthreads
)
{
#pragma omp parallel for
for (int i = 0; i < grid_size*grid_size*sizeof(Double4c)/(256/8); i++) {
__m256d sum = as256pc(srcs[0])[i];
for (int g = 1; g < nthreads; g ++)
sum = _mm256_add_pd(sum, as256pc(srcs[g])[i]);
as256p(dst)[i] = sum;
}
}
// We could simply use pointer-to-function template
// but most C++ compilers seem to produce worse code
// in such a case. Thus we wrap it in a class.
template <
int grid_size
, int over
, int w_planes
, bool do_mirror
, typename Inp
> struct cvt {};
template <
int grid_size
, int over
, int w_planes
, bool do_mirror
> struct cvt<grid_size, over, w_planes, do_mirror, Pregridded> {
static void pre(double, Pregridded inp, Pregridded & outpr) {outpr = inp;}
};
template <
int grid_size
, int over
, int w_planes
, bool do_mirror
> struct cvt<grid_size, over, w_planes, do_mirror, Double3> {
static void pre(double scale, Double3 inp, Pregridded & outpr) {
pregridPoint<grid_size, over, w_planes, do_mirror>(scale, inp, outpr);
}
};
template <
int over
, int w_planes
, bool is_half_gcf
, bool use_permutations
, int baselines
, int grid_size
, int ts_ch
, typename Inp
>
// grid must be initialized to 0s.
void gridKernel_scatter(
double scale
, const BlWMap permutations[baselines]
, Double4c grids[][grid_size][grid_size]
// We have a [w_planes][over][over]-shaped array of pointers to
// variable-sized gcf layers, but we precompute (in pregrid)
// exact index into this array, thus we use plain pointer here
, const complexd * gcf
, const Inp uvw[baselines][ts_ch]
, const Double4c vis[baselines][ts_ch]
) {
#pragma omp parallel
{
auto grid = grids[omp_get_thread_num()];
#pragma omp for schedule(dynamic)
for(int bl0 = 0; bl0 < baselines; bl0++) {
int bl;
if (use_permutations) bl = permutations[bl0].bl;
else bl = bl0;
int max_supp_here = get_supp(permutations[bl].wp);
for (int sv = 0; sv < max_supp_here; sv++) { // Moved from 2-levels below according to Romein
for (int i = 0; i < ts_ch; i++) {
Pregridded p;
cvt<grid_size, over, w_planes, is_half_gcf, Inp>::pre(scale, uvw[bl][i], p);
#ifdef __AVX__
// We port Romein CPU code to doubles here (for MS2 we didn't)
// vis0 covers XX and XY, vis1 -- YX and YY
__m256d vis0, vis1;
vis0 = _mm256_load_pd((const double *) &vis[bl][i].XX);
vis1 = _mm256_load_pd((const double *) &vis[bl][i].YX);
#endif
for (int su = 0; su <= max_supp_here; su++) {
// NOTE: Romein writes about moving this to the very outer scope
// (2 levels up) to make things more cache-friendly.
// for (int sv = 0; sv < max_supp_here; sv++) {
// Don't forget our u v are already translated by -max_supp_here/2
int gsu, gsv;
gsu = p.u + su;
gsv = p.v + sv;
complexd supportPixel;
#define __layeroff su * max_supp_here + sv
if (is_half_gcf) {
int index;
index = p.gcf_layer_index;
// Negative index indicates that original w was mirrored
// and we shall negate the index to obtain correct
// offset *and* conjugate the result.
if (index < 0) {
supportPixel = conj((gcf - index)[__layeroff]);
} else {
supportPixel = (gcf + index)[__layeroff];
}
} else {
supportPixel = (gcf + p.gcf_layer_index)[__layeroff];
}
#ifdef __AVX__
__m256d weight_r, weight_i;
weight_r = _mm256_set1_pd(supportPixel.real());
weight_i = _mm256_set1_pd(supportPixel.imag());
/* _mm256_permute_pd(x, 5) swaps adjacent doubles pairs of x:
d0, d1, d2, d3 goes to d1, d0, d3, d2
*/
#define __DO(p,f) \
__m256d * gridptr##p = (__m256d *) &grid[gsu][gsv].f; \
__m256d tr##p = _mm256_mul_pd(weight_r, vis##p); \
__m256d ti##p = _mm256_mul_pd(weight_i, vis##p); \
__m256d tp##p = _mm256_permute_pd(ti##p, 5); \
__m256d t##p = _mm256_addsub_pd(tr##p, tp##p); \
gridptr##p[p] = _mm256_add_pd(gridptr##p[p], t##p)
__DO(0, XX);
__DO(1, YX);
#else
#define __GRID_POL(pol) grid[gsu][gsv].pol += vis[bl][i].pol * supportPixel
__GRID_POL(XX);
__GRID_POL(XY);
__GRID_POL(YX);
__GRID_POL(YY);
#endif
}
}
}
}
}
}
template <
int over
, int w_planes
, bool is_half_gcf
, bool use_permutations
, int baselines
, int grid_size
, int ts_ch
, typename Inp
>
// grid must be initialized to 0s.
void gridKernel_scatter_full(
double scale
, const BlWMap permutations[baselines]
, Double4c grid[grid_size][grid_size]
// We have a [w_planes][over][over]-shaped array of pointers to
// variable-sized gcf layers, but we precompute (in pregrid)
// exact index into this array, thus we use plain pointer here
, const complexd * gcf
, const Inp uvw[baselines][ts_ch]
, const Double4c vis[baselines][ts_ch]
) {
typedef Double4c GT[grid_size][grid_size];
#if defined _OPENMP
int nthreads;
#pragma omp parallel
#pragma omp single
nthreads = omp_get_num_threads();
GT * tmpgrids = new GT[nthreads];
memset(tmpgrids, 0, nthreads * sizeof(GT));
gridKernel_scatter<
over
, w_planes
, is_half_gcf
, use_permutations
, baselines
, grid_size
, ts_ch
, Inp
>(scale, permutations, tmpgrids, gcf, uvw, vis);
addGrids<grid_size>(grid, tmpgrids, nthreads);
delete [] tmpgrids;
#else
gridKernel_scatter<
over
, w_planes
, is_half_gcf
, use_permutations
, baselines
, grid_size
, ts_ch
, Inp
>(scale, permutations, reinterpret_cast<GT*>(&grid), gcf, uvw, vis);
#endif
}
#define gridKernelCPU(hgcfSuff, isHgcf, permSuff, isPerm) \
extern "C" \
void gridKernelCPU##hgcfSuff##permSuff( \
double scale \
, const BlWMap permutations[BASELINES] \
, Double4c grid[GRID_SIZE][GRID_SIZE] \
, const complexd * gcf \
, const Double3 uvw[BASELINES][TIMESTEPS*CHANNELS] \
, const Double4c vis[BASELINES][TIMESTEPS*CHANNELS] \
){ \
gridKernel_scatter_full<OVER, WPLANES, isHgcf, isPerm, BASELINES, GRID_SIZE> \
(scale, permutations, grid, gcf, uvw, vis); \
}
gridKernelCPU(HalfGCF, true, Perm, true)
gridKernelCPU(HalfGCF, true, , false)
gridKernelCPU(FullGCF, false, Perm, true)
gridKernelCPU(FullGCF, false, , false)
/*
extern "C"
void gridKernel_scatter1(
const BlWMap permutations[BASELINES]
, Double4c grid[GRID_SIZE][GRID_SIZE]
, const complexd * gcf
, const Pregridded uvw[BASELINES][TIMESTEPS*CHANNELS]
, const Double4c vis[BASELINES][TIMESTEPS*CHANNELS]
){
// We don't use scale here
gridKernel_scatter_full<OVER, WPLANES, false, false, BASELINES, GRID_SIZE>(0.0, permutations, grid, gcf, uvw, vis);
}
*/
template <int grid_size, int num_pols>
void normalizeAndExtractPolarization(
int n
, complexd dst[grid_size][grid_size]
, const complexd src[grid_size][grid_size][num_pols]
)
{
const double norm = 1.0/double(grid_size * grid_size);
#pragma omp parallel for
for (int i = 0; i < grid_size*grid_size; i++) {
dst[0][i] = src[0][i][n] * norm;
}
}
extern "C" void normalizeAndExtractPolarization(
int n
, complexd dst[GRID_SIZE][GRID_SIZE]
, const complexd src[GRID_SIZE][GRID_SIZE][NUM_POL]
) {
return normalizeAndExtractPolarization<GRID_SIZE, NUM_POL>(n, dst, src);
}<|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 "otbWrapperQtWidgetModel.h"
//Use to create command line from the application parameters
#include "otbWrapperOutputProcessXMLParameter.h"
namespace otb
{
namespace Wrapper
{
QtWidgetModel
::QtWidgetModel(Application* app) :
m_Application(app),
m_LogOutput(),
m_IsRunning(false)
{
// Init only if not already done
if(!m_Application->IsInitialized())
{
m_Application->Init();
}
m_LogOutput = QtLogOutput::New();
// Attach log output to the Application logger
m_Application->GetLogger()->SetTimeStampFormat(itk::LoggerBase::HUMANREADABLE);
m_Application->GetLogger()->AddLogOutput(m_LogOutput);
}
QtWidgetModel::~QtWidgetModel()
{
}
void
QtWidgetModel
::NotifyUpdate()
{
// Update the parameters
m_Application->UpdateParameters();
emit UpdateGui();
// Notify all
if (!m_IsRunning)
{
bool applicationStatus = m_Application->IsApplicationReady();
emit SetApplicationReady(applicationStatus);
}
}
void
QtWidgetModel
::ExecuteAndWriteOutputSlot()
{
// Deactivate the Execute button while processing
emit SetApplicationReady(false);
m_IsRunning = true;
//Buld corresponding command line and display to the Log tab
//Build XML DOM from m_application
OutputProcessXMLParameter::Pointer outXMLParam = OutputProcessXMLParameter::New();
TiXmlElement* XMLAppElement = outXMLParam->ParseApplication(m_Application);
//Create command line from the XML document
TiXmlElement * pName, *pParam;
std::ostringstream cmdLine;
cmdLine << "";
if(XMLAppElement)
{
pName = XMLAppElement->FirstChildElement("name");
cmdLine << "otbcli_" << pName->FirstChild()->ValueStr();
#ifdef _WIN32
cmdLine << ".bat";
#endif
cmdLine << " ";
//Parse application parameters
pParam = XMLAppElement->FirstChildElement("parameter");
while(pParam)
{
//Get pareter key
cmdLine << "-";
cmdLine << pParam->FirstChildElement("key")->FirstChild()->ValueStr();
cmdLine << " ";
//Some parameters can have multiple values. Test it and handle this
//specific case
TiXmlElement * values = pParam->FirstChildElement("values");
if (values)
{
//Loop over value
TiXmlElement * pValue = pParam->FirstChildElement("value");
while(pValue)
{
cmdLine << pValue->FirstChild()->ValueStr();
cmdLine << " ";
pValue = pValue->NextSiblingElement(); // iteration over multiple values
}
}
else
{
//Get parameter value
cmdLine << pParam->FirstChildElement("value")->FirstChild()->ValueStr();
cmdLine << " ";
//In case of OutputImageparameter we need to report output pixel type
TiXmlElement * pPixType = pParam->FirstChildElement("pixtype");
if (pPixType)
{
cmdLine << pPixType->FirstChild()->ValueStr();
cmdLine << " ";
}
}
pParam = pParam->NextSiblingElement(); // iteration over parameters
}
//Insert a new line character at the end of the command line
cmdLine << std::endl;
//Report the command line string to the application logger
m_Application->GetLogger()->Write(itk::LoggerBase::INFO, cmdLine.str());
}
// launch the output image writing
AppliThread * taskAppli = new AppliThread( m_Application );
QObject::connect(
taskAppli,
SIGNAL( ExceptionRaised( QString ) ),
// to:
this,
SIGNAL( ExceptionRaised( QString ) )
);
QObject::connect(
taskAppli,
SIGNAL( ApplicationExecutionDone( int ) ),
// to:
this,
SLOT( OnApplicationExecutionDone( int ) )
);
taskAppli->Execute();
// Tell the Progress Reporter to begin
emit SetProgressReportBegin();
}
void
QtWidgetModel
::OnApplicationExecutionDone( int status )
{
m_IsRunning = false;
// Require GUI update.
NotifyUpdate();
// For the view to activate the button "Execute"
emit SetApplicationReady( true );
// For the progressReport to close the Progress widget
emit SetProgressReportDone( status );
}
void
QtWidgetModel
::SendLogWARNING( const std::string & mes )
{
m_Application->GetLogger()->Write( itk::LoggerBase::WARNING, mes );
}
void
QtWidgetModel
::SendLogINFO( const std::string & mes )
{
m_Application->GetLogger()->Write( itk::LoggerBase::INFO, mes );
}
void
QtWidgetModel
::SendLogDEBUG( const std::string & mes )
{
m_Application->GetLogger()->Write( itk::LoggerBase::DEBUG, mes );
}
}
}
namespace otb
{
namespace Wrapper
{
AppliThread
::~AppliThread()
{
wait();
}
void
AppliThread
::run()
{
int result = -1;
//
// Try to execute OTB-application.
try
{
result = m_Application->ExecuteAndWriteOutput();
}
//
// Catch standard exceptions.
catch( std::exception& err )
{
std::ostringstream message;
message
<< "The following error occurred during OTB-application execution: "
<< err.what()
<< std::endl;
m_Application->GetLogger()->Write( itk::LoggerBase::FATAL, message.str() );
// Signal exception.
emit ExceptionRaised( err.what() );
}
//
// Catch other exceptions.
catch( ... )
{
m_Application->GetLogger()->Write(
itk::LoggerBase::FATAL,
"An unknown exception has been raised during OTB-application execution"
);
// Signal exception.
emit ExceptionRaised( "Exception raised by OTB-application." );
}
//
// Signal OTB-application has ended with result status.
emit ApplicationExecutionDone( result );
}
}
}
<commit_msg>ENH: fix multiple values parameters, avoid ValueStr() function for compat<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 "otbWrapperQtWidgetModel.h"
//Use to create command line from the application parameters
#include "otbWrapperOutputProcessXMLParameter.h"
namespace otb
{
namespace Wrapper
{
QtWidgetModel
::QtWidgetModel(Application* app) :
m_Application(app),
m_LogOutput(),
m_IsRunning(false)
{
// Init only if not already done
if(!m_Application->IsInitialized())
{
m_Application->Init();
}
m_LogOutput = QtLogOutput::New();
// Attach log output to the Application logger
m_Application->GetLogger()->SetTimeStampFormat(itk::LoggerBase::HUMANREADABLE);
m_Application->GetLogger()->AddLogOutput(m_LogOutput);
}
QtWidgetModel::~QtWidgetModel()
{
}
void
QtWidgetModel
::NotifyUpdate()
{
// Update the parameters
m_Application->UpdateParameters();
emit UpdateGui();
// Notify all
if (!m_IsRunning)
{
bool applicationStatus = m_Application->IsApplicationReady();
emit SetApplicationReady(applicationStatus);
}
}
void
QtWidgetModel
::ExecuteAndWriteOutputSlot()
{
// Deactivate the Execute button while processing
emit SetApplicationReady(false);
m_IsRunning = true;
//Buld corresponding command line and display to the Log tab
//Build XML DOM from m_application
OutputProcessXMLParameter::Pointer outXMLParam = OutputProcessXMLParameter::New();
TiXmlElement* XMLAppElement = outXMLParam->ParseApplication(m_Application);
//Create command line from the XML document
TiXmlElement * pName, *pParam;
std::ostringstream cmdLine;
cmdLine << "";
if(XMLAppElement)
{
pName = XMLAppElement->FirstChildElement("name");
cmdLine << "otbcli_" << pName->GetText();
#ifdef _WIN32
cmdLine << ".bat";
#endif
cmdLine << " ";
//Parse application parameters
pParam = XMLAppElement->FirstChildElement("parameter");
while(pParam)
{
//Get pareter key
cmdLine << "-";
cmdLine << pParam->FirstChildElement("key")->GetText();
cmdLine << " ";
//Some parameters can have multiple values. Test it and handle this
//specific case
TiXmlElement * values = pParam->FirstChildElement("values");
if (values)
{
//Loop over value
TiXmlElement * pValue = values->FirstChildElement("value");
while(pValue)
{
cmdLine << pValue->GetText();
cmdLine << " ";
pValue = pValue->NextSiblingElement(); // iteration over multiple values
}
}
else
{
//Get parameter value
cmdLine << pParam->FirstChildElement("value")->GetText();
cmdLine << " ";
//In case of OutputImageparameter we need to report output pixel type
TiXmlElement * pPixType = pParam->FirstChildElement("pixtype");
if (pPixType)
{
cmdLine << pPixType->GetText();
cmdLine << " ";
}
}
pParam = pParam->NextSiblingElement(); // iteration over parameters
}
//Insert a new line character at the end of the command line
cmdLine << std::endl;
//Report the command line string to the application logger
m_Application->GetLogger()->Write(itk::LoggerBase::INFO, cmdLine.str());
}
// launch the output image writing
AppliThread * taskAppli = new AppliThread( m_Application );
QObject::connect(
taskAppli,
SIGNAL( ExceptionRaised( QString ) ),
// to:
this,
SIGNAL( ExceptionRaised( QString ) )
);
QObject::connect(
taskAppli,
SIGNAL( ApplicationExecutionDone( int ) ),
// to:
this,
SLOT( OnApplicationExecutionDone( int ) )
);
taskAppli->Execute();
// Tell the Progress Reporter to begin
emit SetProgressReportBegin();
}
void
QtWidgetModel
::OnApplicationExecutionDone( int status )
{
m_IsRunning = false;
// Require GUI update.
NotifyUpdate();
// For the view to activate the button "Execute"
emit SetApplicationReady( true );
// For the progressReport to close the Progress widget
emit SetProgressReportDone( status );
}
void
QtWidgetModel
::SendLogWARNING( const std::string & mes )
{
m_Application->GetLogger()->Write( itk::LoggerBase::WARNING, mes );
}
void
QtWidgetModel
::SendLogINFO( const std::string & mes )
{
m_Application->GetLogger()->Write( itk::LoggerBase::INFO, mes );
}
void
QtWidgetModel
::SendLogDEBUG( const std::string & mes )
{
m_Application->GetLogger()->Write( itk::LoggerBase::DEBUG, mes );
}
}
}
namespace otb
{
namespace Wrapper
{
AppliThread
::~AppliThread()
{
wait();
}
void
AppliThread
::run()
{
int result = -1;
//
// Try to execute OTB-application.
try
{
result = m_Application->ExecuteAndWriteOutput();
}
//
// Catch standard exceptions.
catch( std::exception& err )
{
std::ostringstream message;
message
<< "The following error occurred during OTB-application execution: "
<< err.what()
<< std::endl;
m_Application->GetLogger()->Write( itk::LoggerBase::FATAL, message.str() );
// Signal exception.
emit ExceptionRaised( err.what() );
}
//
// Catch other exceptions.
catch( ... )
{
m_Application->GetLogger()->Write(
itk::LoggerBase::FATAL,
"An unknown exception has been raised during OTB-application execution"
);
// Signal exception.
emit ExceptionRaised( "Exception raised by OTB-application." );
}
//
// Signal OTB-application has ended with result status.
emit ApplicationExecutionDone( result );
}
}
}
<|endoftext|>
|
<commit_before>/*=========================================================================
*
* Copyright David Doria 2012 daviddoria@gmail.com
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0.txt
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*=========================================================================*/
#ifndef LinearSearchBestLidarTextureGradient_HPP
#define LinearSearchBestLidarTextureGradient_HPP
// Submodules
#include <Utilities/Histogram/HistogramHelpers.hpp>
#include <Utilities/Histogram/HistogramDifferences.hpp>
#include <Utilities/Histogram/HistogramGenerator.hpp>
#include <ITKHelpers/itkNormImageAdaptor.h>
// Custom
#include "ImageProcessing/Derivatives.h"
#include <Utilities/Debug/Debug.h>
// ITK
#include "itkNthElementImageAdaptor.h"
/**
* This class uses comparisons of histograms of the gradient magnitudes to determine the best match
* from a list of patches (normally supplied by a KNN search using an SSD criterion).
*
* This class expects an RGBDxDy image to be passed.
*
* This function template is similar to std::min_element but can be used when the comparison
* involves computing a derived quantity (a.k.a. distance). This algorithm will search for the
* the element in the range [first,last) which has the "smallest" distance (of course, both the
* distance metric and comparison can be overriden to perform something other than the canonical
* Euclidean distance and less-than comparison, which would yield the element with minimum distance).
* \tparam DistanceValueType The value-type for the distance measures.
* \tparam DistanceFunctionType The functor type to compute the distance measure.
* \tparam CompareFunctionType The functor type that can compare two distance measures (strict weak-ordering).
*/
template <typename PropertyMapType, typename TImage, typename TIterator, typename TImageToWrite = TImage>
class LinearSearchBestLidarTextureGradient : public Debug
{
PropertyMapType PropertyMap;
TImage* Image;
Mask* MaskImage;
unsigned int Iteration = 0;
TImageToWrite* ImageToWrite = nullptr;
public:
/** Constructor. This class requires the property map, an image, and a mask. */
LinearSearchBestLidarTextureGradient(PropertyMapType propertyMap, TImage* const image, Mask* const mask, TImageToWrite* imageToWrite = nullptr) :
Debug(), PropertyMap(propertyMap), Image(image), MaskImage(mask), ImageToWrite(imageToWrite)
{}
struct RegionSorter
{
itk::Functor::IndexLexicographicCompare<2> IndexCompareFunctor;
bool operator()(const itk::ImageRegion<2> region1, const itk::ImageRegion<2> region2) const
{
return IndexCompareFunctor(region1.GetIndex(), region2.GetIndex());
}
};
// typedef std::set<itk::ImageRegion<2>, RegionSorter> RegionSetType;
// RegionSetType AlreadyComputedGradient;
typedef float BinValueType; // bins must be float if we are going to normalize
typedef MaskedHistogramGenerator<BinValueType> MaskedHistogramGeneratorType;
typedef HistogramGenerator<BinValueType> HistogramGeneratorType;
typedef HistogramGeneratorType::HistogramType HistogramType;
typedef std::map<itk::ImageRegion<2>, HistogramType, RegionSorter> HistogramMapType;
HistogramMapType PreviouslyComputedRGBHistograms;
HistogramMapType PreviouslyComputedDepthHistograms;
bool WritePatches = false;
/**
* \param first Start of the range in which to search.
* \param last One element past the last element in the range in which to search.
* \param query The element to compare to.
* \return The iterator to the best element in the range (best is defined as the one which would compare favorably to all
* the elements in the range with respect to the distance metric).
*/
typename TIterator::value_type operator()(const TIterator first, const TIterator last, typename TIterator::value_type query)
{
if(WritePatches)
{
if(this->ImageToWrite == nullptr)
{
throw std::runtime_error("LinearSearchBestLidarTextureGradient cannot WriteTopPatches without having an ImageToWrite!");
}
PatchHelpers::WriteTopPatches(this->ImageToWrite, this->PropertyMap, first, last,
"BestPatches", this->Iteration);
}
unsigned int numberOfBins = 30;
// If the input element range is empty, there is nothing to do.
if(first == last)
{
std::cerr << "LinearSearchBestHistogram: Nothing to do..." << std::endl;
return *last;
}
// Get the region to process
itk::ImageRegion<2> queryRegion = get(this->PropertyMap, query).GetRegion();
// typedef itk::Image<float, 2> ImageChannelType;
typedef itk::NthElementImageAdaptor<TImage, float> ImageChannelAdaptorType;
typename ImageChannelAdaptorType::Pointer imageChannelAdaptor = ImageChannelAdaptorType::New();
imageChannelAdaptor->SetImage(this->Image);
typedef itk::Image<itk::CovariantVector<float, 2>, 2> GradientImageType;
// Setup storage for the gradient of each channel
std::vector<GradientImageType::Pointer> imageChannelGradients(this->Image->GetNumberOfComponentsPerPixel());
// Compute the gradient of each channel
for(unsigned int channel = 0; channel < 3; ++channel) // 3 is the number of RGB channels
{
imageChannelAdaptor->SelectNthElement(channel);
if(this->DebugImages)
{
std::stringstream ssImageFile;
ssImageFile << "ImageChannel_" << channel << ".mha";
ITKHelpers::WriteImage(imageChannelAdaptor.GetPointer(), ssImageFile.str());
}
// Compute gradients
GradientImageType::Pointer gradientImage = GradientImageType::New();
gradientImage->SetRegions(this->Image->GetLargestPossibleRegion()); // We allocate the full image because in the next loop we will compute gradients in all of the source patch regions.
gradientImage->Allocate();
Derivatives::MaskedGradientInRegion(imageChannelAdaptor.GetPointer(), this->MaskImage,
queryRegion, gradientImage.GetPointer());
if(this->DebugImages)
{
std::stringstream ssGradientFile;
ssGradientFile << "GradientImage_" << channel << ".mha";
ITKHelpers::WriteImage(gradientImage.GetPointer(), ssGradientFile.str());
}
imageChannelGradients[channel] = gradientImage;
}
HistogramType targetRGBHistogram;
// Store, for each channel (the elements of the vector), the min/max value of the valid region of the target patch
std::vector<GradientImageType::PixelType::RealValueType> minRGBChannelGradientMagnitudes(this->Image->GetNumberOfComponentsPerPixel());
std::vector<GradientImageType::PixelType::RealValueType> maxRGBChannelGradientMagnitudes(this->Image->GetNumberOfComponentsPerPixel());
std::vector<itk::Index<2> > validPixels = ITKHelpers::GetPixelsWithValueInRegion(this->MaskImage, queryRegion, this->MaskImage->GetValidValue());
typedef itk::NormImageAdaptor<GradientImageType, GradientImageType::PixelType::RealValueType> NormImageAdaptorType;
typename NormImageAdaptorType::Pointer normImageAdaptor = NormImageAdaptorType::New();
// Compute the gradient magnitude images for each RGB channel's gradient, and compute the histograms for the target/query region
for(unsigned int channel = 0; channel < 3; ++channel) // 3 is the number of RGB channels
{
imageChannelAdaptor->SelectNthElement(channel);
normImageAdaptor->SetImage(imageChannelGradients[channel].GetPointer());
std::vector<GradientImageType::PixelType::RealValueType> gradientMagnitudes =
ITKHelpers::GetPixelValues(normImageAdaptor.GetPointer(), validPixels);
minRGBChannelGradientMagnitudes[channel] = Helpers::Min(gradientMagnitudes);
maxRGBChannelGradientMagnitudes[channel] = Helpers::Max(gradientMagnitudes);
// Compute histograms of the gradient magnitudes (to measure texture)
bool allowOutside = false;
HistogramType targetRGBChannelHistogram =
MaskedHistogramGeneratorType::ComputeMaskedScalarImageHistogram(
normImageAdaptor.GetPointer(), queryRegion, this->MaskImage, queryRegion, numberOfBins,
minRGBChannelGradientMagnitudes[channel], maxRGBChannelGradientMagnitudes[channel],
allowOutside, this->MaskImage->GetValidValue());
targetRGBChannelHistogram.Normalize();
targetRGBHistogram.Append(targetRGBChannelHistogram);
}
// Compute the gradient magnitude from the depth derivatives, and compute the histogram for the target/query region
// Extract the depth derivative channels
std::vector<unsigned int> depthDerivativeChannels = {3,4};
typedef itk::Image<itk::CovariantVector<float, 2> > DepthDerivativesImageType;
DepthDerivativesImageType::Pointer depthDerivatives = DepthDerivativesImageType::New();
ITKHelpers::ExtractChannels(this->Image, depthDerivativeChannels, depthDerivatives.GetPointer());
// Compute the depth gradient magnitude image
typedef itk::Image<float, 2> DepthGradientMagnitudeImageType;
DepthGradientMagnitudeImageType::Pointer depthGradientMagnitude = DepthGradientMagnitudeImageType::New();
ITKHelpers::MagnitudeImage(depthDerivatives.GetPointer(), depthGradientMagnitude.GetPointer());
// Store the min/max values (histogram range)
std::vector<DepthGradientMagnitudeImageType::PixelType> depthGradientMagnitudes =
ITKHelpers::GetPixelValues(depthGradientMagnitude.GetPointer(), validPixels);
float minDepthChannelGradientMagnitude = Helpers::Min(depthGradientMagnitudes);
float maxDepthChannelGradientMagnitude = Helpers::Max(depthGradientMagnitudes);
// Compute histogram
bool allowOutsideForDepthHistogramCreation = false;
HistogramType targetDepthHistogram =
MaskedHistogramGeneratorType::ComputeMaskedScalarImageHistogram(
depthGradientMagnitude.GetPointer(), queryRegion, this->MaskImage, queryRegion, numberOfBins,
minDepthChannelGradientMagnitude, maxDepthChannelGradientMagnitude,
allowOutsideForDepthHistogramCreation, this->MaskImage->GetValidValue());
targetDepthHistogram.Normalize();
// Initialize
float bestDistance = std::numeric_limits<float>::max();
TIterator bestPatch = last;
unsigned int bestId = 0; // Keep track of which of the top SSD patches is the best by histogram score (just for information sake)
HistogramType bestRGBHistogram;
HistogramType bestDepthHistogram;
// Iterate through all of the input elements
for(TIterator currentPatch = first; currentPatch != last; ++currentPatch)
{
itk::ImageRegion<2> currentRegion = get(this->PropertyMap, *currentPatch).GetRegion();
// Determine if the gradient and histogram have already been computed
typename HistogramMapType::iterator histogramMapIterator;
histogramMapIterator = this->PreviouslyComputedRGBHistograms.find(currentRegion);
bool alreadyComputed;
if(histogramMapIterator == this->PreviouslyComputedRGBHistograms.end())
{
alreadyComputed = false;
}
else
{
alreadyComputed = true;
}
HistogramType testRGBHistogram;
bool allowOutside = true;
// Compute the RGB histograms of the source region using the queryRegion mask
for(unsigned int channel = 0; channel < 3; ++channel) // 3 is the number of RGB channels
{
normImageAdaptor->SetImage(imageChannelGradients[channel].GetPointer());
// typename RegionSetType::iterator setIterator;
// setIterator = this->AlreadyComputedGradient.find(currentRegion);
// if(setIterator == this->AlreadyComputedGradient.end()) // not already computed
// {
// Derivatives::MaskedGradientInRegion(imageChannelAdaptor.GetPointer(), this->MaskImage,
// currentRegion, imageChannelGradients[channel].GetPointer());
// this->AlreadyComputedGradient.insert(currentRegion);
// }
HistogramType testRGBChannelHistogram;
if(!alreadyComputed)
{
// Compute the gradients
Derivatives::MaskedGradientInRegion(imageChannelAdaptor.GetPointer(), this->MaskImage,
currentRegion, imageChannelGradients[channel].GetPointer());
// We don't need a masked histogram since we are using the full source patch
testRGBChannelHistogram = HistogramGeneratorType::ComputeScalarImageHistogram(
normImageAdaptor.GetPointer(), currentRegion,
numberOfBins,
minRGBChannelGradientMagnitudes[channel],
maxRGBChannelGradientMagnitudes[channel], allowOutside);
testRGBChannelHistogram.Normalize();
this->PreviouslyComputedRGBHistograms[currentRegion] = testRGBChannelHistogram;
}
else // already computed
{
testRGBChannelHistogram = this->PreviouslyComputedRGBHistograms[currentRegion];
}
// Compare to the valid region of the source patch
// HistogramType testChannelHistogram =
// MaskedHistogramGeneratorType::ComputeMaskedScalarImageHistogram(
// imageChannelGradientMagnitudes[channel].GetPointer(), currentRegion, this->MaskImage, queryRegion, numberOfBins,
// minChannelGradientMagnitudes[channel], maxChannelGradientMagnitudes[channel], allowOutside, this->MaskImage->GetValidValue());
// Compare to the hole region of the source patch
// HistogramType testChannelHistogram =
// MaskedHistogramGeneratorType::ComputeMaskedScalarImageHistogram(
// imageChannelGradientMagnitudes[channel].GetPointer(), currentRegion, this->MaskImage, queryRegion, numberOfBins,
// minChannelGradientMagnitudes[channel], maxChannelGradientMagnitudes[channel], allowOutside, this->MaskImage->GetHoleValue());
// Compare to the entire source patch (by passing the source region as the mask region, which is entirely valid)
// HistogramType testChannelHistogram =
// MaskedHistogramGeneratorType::ComputeMaskedScalarImageHistogram(
// normImageAdaptor.GetPointer(), currentRegion, this->MaskImage, currentRegion, numberOfBins,
// minChannelGradientMagnitudes[channel], maxChannelGradientMagnitudes[channel], allowOutside, this->MaskImage->GetValidValue());
testRGBHistogram.Append(testRGBChannelHistogram);
}
HistogramType testDepthHistogram;
if(!alreadyComputed)
{
// Compute the depth histogram of the source region using the queryRegion mask
testDepthHistogram = HistogramGeneratorType::ComputeScalarImageHistogram(
depthGradientMagnitude.GetPointer(), currentRegion,
numberOfBins,
minDepthChannelGradientMagnitude,
maxDepthChannelGradientMagnitude, allowOutside);
testDepthHistogram.Normalize();
this->PreviouslyComputedDepthHistograms[currentRegion] = testDepthHistogram;
}
else
{
testDepthHistogram = this->PreviouslyComputedDepthHistograms[currentRegion];
}
// Compute the differences in the histograms
float rgbHistogramDifference = HistogramDifferences::HistogramDifference(targetRGBHistogram, testRGBHistogram);
float depthHistogramDifference = HistogramDifferences::HistogramDifference(targetDepthHistogram, testDepthHistogram);
// Weight the depth histogram 3x so that it is a 1:1 weighting of RGB and depth difference
float histogramDifference = rgbHistogramDifference + 3.0f * depthHistogramDifference;
if(this->DebugOutputs)
{
std::cout << "histogramDifference " << currentPatch - first << " : " << histogramDifference << std::endl;
}
if(histogramDifference < bestDistance)
{
bestDistance = histogramDifference;
bestPatch = currentPatch;
// These are not needed - just for debugging
bestId = currentPatch - first;
bestRGBHistogram = testRGBHistogram;
bestDepthHistogram = testDepthHistogram;
}
}
std::cout << "BestId: " << bestId << std::endl;
std::cout << "Best distance: " << bestDistance << std::endl;
this->Iteration++;
return *bestPatch;
}
}; // end class LinearSearchBestHistogramDifference
#endif
<commit_msg>Compute the gradient in the source region only once.<commit_after>/*=========================================================================
*
* Copyright David Doria 2012 daviddoria@gmail.com
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0.txt
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*=========================================================================*/
#ifndef LinearSearchBestLidarTextureGradient_HPP
#define LinearSearchBestLidarTextureGradient_HPP
// Submodules
#include <Utilities/Histogram/HistogramHelpers.hpp>
#include <Utilities/Histogram/HistogramDifferences.hpp>
#include <Utilities/Histogram/HistogramGenerator.hpp>
#include <ITKHelpers/itkNormImageAdaptor.h>
// Custom
#include "ImageProcessing/Derivatives.h"
#include <Utilities/Debug/Debug.h>
// ITK
#include "itkNthElementImageAdaptor.h"
/**
* This class uses comparisons of histograms of the gradient magnitudes to determine the best match
* from a list of patches (normally supplied by a KNN search using an SSD criterion).
*
* This class expects an RGBDxDy image to be passed.
*
* This function template is similar to std::min_element but can be used when the comparison
* involves computing a derived quantity (a.k.a. distance). This algorithm will search for the
* the element in the range [first,last) which has the "smallest" distance (of course, both the
* distance metric and comparison can be overriden to perform something other than the canonical
* Euclidean distance and less-than comparison, which would yield the element with minimum distance).
* \tparam DistanceValueType The value-type for the distance measures.
* \tparam DistanceFunctionType The functor type to compute the distance measure.
* \tparam CompareFunctionType The functor type that can compare two distance measures (strict weak-ordering).
*/
template <typename PropertyMapType, typename TImage, typename TIterator, typename TImageToWrite = TImage>
class LinearSearchBestLidarTextureGradient : public Debug
{
PropertyMapType PropertyMap;
TImage* Image;
Mask* MaskImage;
unsigned int Iteration = 0;
TImageToWrite* ImageToWrite = nullptr;
typedef itk::Image<itk::CovariantVector<float, 2>, 2> GradientImageType;
std::vector<GradientImageType::Pointer> RGBChannelGradients;
public:
/** Constructor. This class requires the property map, an image, and a mask. */
LinearSearchBestLidarTextureGradient(PropertyMapType propertyMap, TImage* const image, Mask* const mask, TImageToWrite* imageToWrite = nullptr) :
Debug(), PropertyMap(propertyMap), Image(image), MaskImage(mask), ImageToWrite(imageToWrite)
{
// Compute the gradients in all source patches
typedef itk::NthElementImageAdaptor<TImage, float> ImageChannelAdaptorType;
typename ImageChannelAdaptorType::Pointer imageChannelAdaptor = ImageChannelAdaptorType::New();
imageChannelAdaptor->SetImage(this->Image);
RGBChannelGradients.resize(3);
for(unsigned int channel = 0; channel < 3; ++channel) // 3 RGB channels
{
imageChannelAdaptor->SelectNthElement(channel);
GradientImageType::Pointer gradientImage = GradientImageType::New();
gradientImage->SetRegions(this->Image->GetLargestPossibleRegion());
gradientImage->Allocate();
Derivatives::MaskedGradient(imageChannelAdaptor.GetPointer(), this->MaskImage, gradientImage.GetPointer());
RGBChannelGradients[channel] = gradientImage;
}
}
struct RegionSorter
{
itk::Functor::IndexLexicographicCompare<2> IndexCompareFunctor;
bool operator()(const itk::ImageRegion<2> region1, const itk::ImageRegion<2> region2) const
{
return IndexCompareFunctor(region1.GetIndex(), region2.GetIndex());
}
};
typedef float BinValueType; // bins must be float if we are going to normalize
typedef MaskedHistogramGenerator<BinValueType> MaskedHistogramGeneratorType;
typedef HistogramGenerator<BinValueType> HistogramGeneratorType;
typedef HistogramGeneratorType::HistogramType HistogramType;
typedef std::map<itk::ImageRegion<2>, HistogramType, RegionSorter> HistogramMapType;
HistogramMapType PreviouslyComputedRGBHistograms;
HistogramMapType PreviouslyComputedDepthHistograms;
bool WritePatches = false;
/**
* \param first Start of the range in which to search.
* \param last One element past the last element in the range in which to search.
* \param query The element to compare to.
* \return The iterator to the best element in the range (best is defined as the one which would compare favorably to all
* the elements in the range with respect to the distance metric).
*/
typename TIterator::value_type operator()(const TIterator first, const TIterator last, typename TIterator::value_type query)
{
if(WritePatches)
{
if(this->ImageToWrite == nullptr)
{
throw std::runtime_error("LinearSearchBestLidarTextureGradient cannot WriteTopPatches without having an ImageToWrite!");
}
PatchHelpers::WriteTopPatches(this->ImageToWrite, this->PropertyMap, first, last,
"BestPatches", this->Iteration);
}
unsigned int numberOfBins = 30;
// If the input element range is empty, there is nothing to do.
if(first == last)
{
std::cerr << "LinearSearchBestHistogram: Nothing to do..." << std::endl;
return *last;
}
// Get the region to process
itk::ImageRegion<2> queryRegion = get(this->PropertyMap, query).GetRegion();
// typedef itk::Image<float, 2> ImageChannelType;
typedef itk::NthElementImageAdaptor<TImage, float> ImageChannelAdaptorType;
typename ImageChannelAdaptorType::Pointer imageChannelAdaptor = ImageChannelAdaptorType::New();
imageChannelAdaptor->SetImage(this->Image);
// Compute the gradient of each channel
for(unsigned int channel = 0; channel < 3; ++channel) // 3 is the number of RGB channels
{
imageChannelAdaptor->SelectNthElement(channel);
Derivatives::MaskedGradientInRegion(imageChannelAdaptor.GetPointer(), this->MaskImage,
queryRegion, this->RGBChannelGradients[channel].GetPointer());
if(this->DebugImages)
{
std::stringstream ssGradientFile;
ssGradientFile << "GradientImage_" << channel << ".mha";
ITKHelpers::WriteImage(this->RGBChannelGradients[channel].GetPointer(), ssGradientFile.str());
}
}
HistogramType targetRGBHistogram;
// Store, for each channel (the elements of the vector), the min/max value of the valid region of the target patch
std::vector<GradientImageType::PixelType::RealValueType> minRGBChannelGradientMagnitudes(this->Image->GetNumberOfComponentsPerPixel());
std::vector<GradientImageType::PixelType::RealValueType> maxRGBChannelGradientMagnitudes(this->Image->GetNumberOfComponentsPerPixel());
std::vector<itk::Index<2> > validPixels = ITKHelpers::GetPixelsWithValueInRegion(this->MaskImage, queryRegion, this->MaskImage->GetValidValue());
typedef itk::NormImageAdaptor<GradientImageType, GradientImageType::PixelType::RealValueType> NormImageAdaptorType;
typename NormImageAdaptorType::Pointer normImageAdaptor = NormImageAdaptorType::New();
// Compute the gradient magnitude images for each RGB channel's gradient, and compute the histograms for the target/query region
for(unsigned int channel = 0; channel < 3; ++channel) // 3 is the number of RGB channels
{
imageChannelAdaptor->SelectNthElement(channel);
normImageAdaptor->SetImage(this->RGBChannelGradients[channel].GetPointer());
std::vector<GradientImageType::PixelType::RealValueType> gradientMagnitudes =
ITKHelpers::GetPixelValues(normImageAdaptor.GetPointer(), validPixels);
minRGBChannelGradientMagnitudes[channel] = Helpers::Min(gradientMagnitudes);
maxRGBChannelGradientMagnitudes[channel] = Helpers::Max(gradientMagnitudes);
// Compute histograms of the gradient magnitudes (to measure texture)
bool allowOutside = false;
HistogramType targetRGBChannelHistogram =
MaskedHistogramGeneratorType::ComputeMaskedScalarImageHistogram(
normImageAdaptor.GetPointer(), queryRegion, this->MaskImage, queryRegion, numberOfBins,
minRGBChannelGradientMagnitudes[channel], maxRGBChannelGradientMagnitudes[channel],
allowOutside, this->MaskImage->GetValidValue());
targetRGBChannelHistogram.Normalize();
targetRGBHistogram.Append(targetRGBChannelHistogram);
}
// Compute the gradient magnitude from the depth derivatives, and compute the histogram for the target/query region
// Extract the depth derivative channels
std::vector<unsigned int> depthDerivativeChannels = {3,4};
typedef itk::Image<itk::CovariantVector<float, 2> > DepthDerivativesImageType;
DepthDerivativesImageType::Pointer depthDerivatives = DepthDerivativesImageType::New();
ITKHelpers::ExtractChannels(this->Image, depthDerivativeChannels, depthDerivatives.GetPointer());
// Compute the depth gradient magnitude image
typedef itk::Image<float, 2> DepthGradientMagnitudeImageType;
DepthGradientMagnitudeImageType::Pointer depthGradientMagnitude = DepthGradientMagnitudeImageType::New();
ITKHelpers::MagnitudeImage(depthDerivatives.GetPointer(), depthGradientMagnitude.GetPointer());
// Store the min/max values (histogram range)
std::vector<DepthGradientMagnitudeImageType::PixelType> depthGradientMagnitudes =
ITKHelpers::GetPixelValues(depthGradientMagnitude.GetPointer(), validPixels);
float minDepthChannelGradientMagnitude = Helpers::Min(depthGradientMagnitudes);
float maxDepthChannelGradientMagnitude = Helpers::Max(depthGradientMagnitudes);
// Compute histogram
bool allowOutsideForDepthHistogramCreation = false;
HistogramType targetDepthHistogram =
MaskedHistogramGeneratorType::ComputeMaskedScalarImageHistogram(
depthGradientMagnitude.GetPointer(), queryRegion, this->MaskImage, queryRegion, numberOfBins,
minDepthChannelGradientMagnitude, maxDepthChannelGradientMagnitude,
allowOutsideForDepthHistogramCreation, this->MaskImage->GetValidValue());
targetDepthHistogram.Normalize();
// Initialize
float bestDistance = std::numeric_limits<float>::max();
TIterator bestPatch = last;
unsigned int bestId = 0; // Keep track of which of the top SSD patches is the best by histogram score (just for information sake)
HistogramType bestRGBHistogram;
HistogramType bestDepthHistogram;
// Iterate through all of the supplied source patches
for(TIterator currentPatch = first; currentPatch != last; ++currentPatch)
{
itk::ImageRegion<2> currentRegion = get(this->PropertyMap, *currentPatch).GetRegion();
// Determine if the gradient and histogram have already been computed
typename HistogramMapType::iterator histogramMapIterator;
histogramMapIterator = this->PreviouslyComputedRGBHistograms.find(currentRegion);
bool alreadyComputed;
if(histogramMapIterator == this->PreviouslyComputedRGBHistograms.end())
{
alreadyComputed = false;
}
else
{
alreadyComputed = true;
}
HistogramType testRGBHistogram;
bool allowOutside = true;
// Compute the RGB histograms of the source region using the queryRegion mask
for(unsigned int channel = 0; channel < 3; ++channel) // 3 is the number of RGB channels
{
normImageAdaptor->SetImage(this->RGBChannelGradients[channel].GetPointer());
HistogramType testRGBChannelHistogram;
if(!alreadyComputed)
{
// We don't need a masked histogram since we are using the full source patch
testRGBChannelHistogram = HistogramGeneratorType::ComputeScalarImageHistogram(
normImageAdaptor.GetPointer(), currentRegion,
numberOfBins,
minRGBChannelGradientMagnitudes[channel],
maxRGBChannelGradientMagnitudes[channel], allowOutside);
testRGBChannelHistogram.Normalize();
this->PreviouslyComputedRGBHistograms[currentRegion] = testRGBChannelHistogram;
}
else // already computed
{
testRGBChannelHistogram = this->PreviouslyComputedRGBHistograms[currentRegion];
}
// Compare to the valid region of the source patch
// HistogramType testChannelHistogram =
// MaskedHistogramGeneratorType::ComputeMaskedScalarImageHistogram(
// imageChannelGradientMagnitudes[channel].GetPointer(), currentRegion, this->MaskImage, queryRegion, numberOfBins,
// minChannelGradientMagnitudes[channel], maxChannelGradientMagnitudes[channel], allowOutside, this->MaskImage->GetValidValue());
// Compare to the hole region of the source patch
// HistogramType testChannelHistogram =
// MaskedHistogramGeneratorType::ComputeMaskedScalarImageHistogram(
// imageChannelGradientMagnitudes[channel].GetPointer(), currentRegion, this->MaskImage, queryRegion, numberOfBins,
// minChannelGradientMagnitudes[channel], maxChannelGradientMagnitudes[channel], allowOutside, this->MaskImage->GetHoleValue());
// Compare to the entire source patch (by passing the source region as the mask region, which is entirely valid)
// HistogramType testChannelHistogram =
// MaskedHistogramGeneratorType::ComputeMaskedScalarImageHistogram(
// normImageAdaptor.GetPointer(), currentRegion, this->MaskImage, currentRegion, numberOfBins,
// minChannelGradientMagnitudes[channel], maxChannelGradientMagnitudes[channel], allowOutside, this->MaskImage->GetValidValue());
testRGBHistogram.Append(testRGBChannelHistogram);
}
HistogramType testDepthHistogram;
if(!alreadyComputed)
{
// Compute the depth histogram of the source region using the queryRegion mask
testDepthHistogram = HistogramGeneratorType::ComputeScalarImageHistogram(
depthGradientMagnitude.GetPointer(), currentRegion,
numberOfBins,
minDepthChannelGradientMagnitude,
maxDepthChannelGradientMagnitude, allowOutside);
testDepthHistogram.Normalize();
this->PreviouslyComputedDepthHistograms[currentRegion] = testDepthHistogram;
}
else
{
testDepthHistogram = this->PreviouslyComputedDepthHistograms[currentRegion];
}
// Compute the differences in the histograms
float rgbHistogramDifference = HistogramDifferences::HistogramDifference(targetRGBHistogram, testRGBHistogram);
float depthHistogramDifference = HistogramDifferences::HistogramDifference(targetDepthHistogram, testDepthHistogram);
// Weight the depth histogram 3x so that it is a 1:1 weighting of RGB and depth difference
float histogramDifference = rgbHistogramDifference + 3.0f * depthHistogramDifference;
if(this->DebugOutputs)
{
std::cout << "histogramDifference " << currentPatch - first << " : " << histogramDifference << std::endl;
}
if(histogramDifference < bestDistance)
{
bestDistance = histogramDifference;
bestPatch = currentPatch;
// These are not needed - just for debugging
bestId = currentPatch - first;
bestRGBHistogram = testRGBHistogram;
bestDepthHistogram = testDepthHistogram;
}
}
std::cout << "BestId: " << bestId << std::endl;
std::cout << "Best distance: " << bestDistance << std::endl;
this->Iteration++;
return *bestPatch;
}
}; // end class LinearSearchBestHistogramDifference
#endif
<|endoftext|>
|
<commit_before>AliPHOSCorrelations* AddTaskPi0Correlations ( const char* name = "Pi0Corr",
const char* options = "11h",
UInt_t offlineTriggerMask = AliVEvent::kCentral,
AliPHOSCorrelations::TriggerSelection internalTriggerSelection = AliPHOSCorrelations::kNoSelection,
Double_t sigmaWidth = 3.,
Int_t downCentLimit = 0,
Int_t upCentLimit = 90 )
{
//Author: Ponomarenko Daniil
/* $Id$ */
AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager();
if (!mgr)
{
::Error("AddTaskPi0CorrelationsL", "No analysis manager to connect to");
return NULL;
}
if (!mgr->GetInputEventHandler())
{
::Error("AddTaskPi0CorrelationsL", "This task requires an input event handler");
return NULL;
}
stringstream ss;
ss << downCentLimit;
string strDownCentLimit = ss.str();
char text[255];
sprintf(text,"%2i",upCentLimit);
string strUpCentLimit = text;
TString centralityBorder = TString ("CB") + strDownCentLimit.c_str() + TString ("t") + strUpCentLimit.c_str() + TString ("Cnt");
TString sigmaBorder = Form("%2iSigma", int(sigmaWidth*10.));
if (sigmaWidth == 0) sigmaBorder = "00Sigma";
TString sName = TString (name) + sigmaBorder + centralityBorder ;
AliPHOSCorrelations* task = new AliPHOSCorrelations(Form("%sTask", sName.Data()),internalTriggerSelection);
if( TString(options).Contains("10h") ) {
task->SetPeriod( AliPHOSCorrelations::kLHC10h );
task->SetCentralityEstimator("V0M");
}
if( TString(options).Contains("11h") ) {
task->SetPeriod( AliPHOSCorrelations::kLHC11h );
task->SetCentralityEstimator("V0M");
}
if( TString(options).Contains("13") ) {
task->SetPeriod( AliPHOSCorrelations::kLHC13 );
task->SetCentralityEstimator("V0A");
}
// Binning
//Any:
if( AliVEvent::kAny == offlineTriggerMask )
{
const int nbins = 8;
Double_t cbin[nbins+1] = {0., 10., 20., 30., 40., 50., 60., 70., 80.};
TArrayD tbin(nbins+1, cbin);
Int_t nMixed[nbins] = {6, 40, 40, 40, 40, 80, 80, 80};
TArrayI tNMixed(nbins, nMixed);
task->SetCentralityBinning(tbin, tNMixed);
}
//Central:
if( AliVEvent::kCentral == offlineTriggerMask )
{
const int nbins = 4;
Double_t cbin[nbins+1] = {0., 5., 8., 9., 10.};
TArrayD tbin(nbins+1, cbin);
Int_t nMixed[nbins] = {6, 6, 6, 6};
TArrayI tNMixed(nbins, nMixed);
task->SetCentralityBinning(tbin, tNMixed);
}
// SemiCentral:
if( AliVEvent::kSemiCentral == offlineTriggerMask )
{
const int nbins = 8;
Double_t cbin[nbins+1] = {10., 11., 12., 13., 15., 20., 30., 40., 50.};
TArrayD tbin(nbins+1, cbin);
Int_t nMixed[nbins] = {40, 40, 40, 40, 40, 40, 40, 40};
TArrayI tNMixed(nbins, nMixed);
task->SetCentralityBinning(tbin, tNMixed);
}
//INT7:
if( AliVEvent::kINT7 == offlineTriggerMask || AliVEvent::kPHI7 == offlineTriggerMask)
{
const int nbins = 8;
Double_t cbin[nbins+1] = {0., 10., 20., 30., 40., 50., 60., 70., 80.};
TArrayD tbin(nbins+1, cbin);
Int_t nMixed[nbins] = {6, 40, 40, 40, 40, 80, 80, 80};
TArrayI tNMixed(nbins, nMixed);
task->SetCentralityBinning(tbin, tNMixed);
}
// MB or PHOS Trigger:
if( AliVEvent::kMB == offlineTriggerMask || AliVEvent::kPHOSPb == offlineTriggerMask )
{
const int nbins = 8;
Double_t cbin[nbins+1] = {0., 10., 20., 30., 40., 50., 60., 70., 80.};
TArrayD tbin(nbins+1, cbin);
Int_t nMixed[nbins] = {6, 40, 40, 40, 40, 80, 80, 80};
TArrayI tNMixed(nbins, nMixed);
task->SetCentralityBinning(tbin, tNMixed);
}
task->SelectCollisionCandidates(offlineTriggerMask);
task->SetInternalTriggerSelection(internalTriggerSelection);
task->EnableTOFCut(true, 100.e-9);
task->SetCentralityBorders(downCentLimit , upCentLimit) ;
task->SetSigmaWidth(sigmaWidth);
mgr->AddTask(task);
mgr->ConnectInput(task, 0, mgr->GetCommonInputContainer() );
TString cname(Form("%sCoutput1", sName.Data()));
TString pname(Form("%s:%s", AliAnalysisManager::GetCommonFileName(), sName.Data()));
AliAnalysisDataContainer *coutput1 = mgr->CreateContainer(cname.Data(), TList::Class(), AliAnalysisManager::kOutputContainer, pname.Data());
mgr->ConnectOutput(task, 1, coutput1);
return task;
}<commit_msg>Added line at the end<commit_after>AliPHOSCorrelations* AddTaskPi0Correlations ( const char* name = "Pi0Corr",
const char* options = "11h",
UInt_t offlineTriggerMask = AliVEvent::kCentral,
AliPHOSCorrelations::TriggerSelection internalTriggerSelection = AliPHOSCorrelations::kNoSelection,
Double_t sigmaWidth = 3.,
Int_t downCentLimit = 0,
Int_t upCentLimit = 90 )
{
//Author: Ponomarenko Daniil
/* $Id$ */
AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager();
if (!mgr)
{
::Error("AddTaskPi0CorrelationsL", "No analysis manager to connect to");
return NULL;
}
if (!mgr->GetInputEventHandler())
{
::Error("AddTaskPi0CorrelationsL", "This task requires an input event handler");
return NULL;
}
stringstream ss;
ss << downCentLimit;
string strDownCentLimit = ss.str();
char text[255];
sprintf(text,"%2i",upCentLimit);
string strUpCentLimit = text;
TString centralityBorder = TString ("CB") + strDownCentLimit.c_str() + TString ("t") + strUpCentLimit.c_str() + TString ("Cnt");
TString sigmaBorder = Form("%2iSigma", int(sigmaWidth*10.));
if (sigmaWidth == 0) sigmaBorder = "00Sigma";
TString sName = TString (name) + sigmaBorder + centralityBorder ;
AliPHOSCorrelations* task = new AliPHOSCorrelations(Form("%sTask", sName.Data()),internalTriggerSelection);
if( TString(options).Contains("10h") ) {
task->SetPeriod( AliPHOSCorrelations::kLHC10h );
task->SetCentralityEstimator("V0M");
}
if( TString(options).Contains("11h") ) {
task->SetPeriod( AliPHOSCorrelations::kLHC11h );
task->SetCentralityEstimator("V0M");
}
if( TString(options).Contains("13") ) {
task->SetPeriod( AliPHOSCorrelations::kLHC13 );
task->SetCentralityEstimator("V0A");
}
// Binning
//Any:
if( AliVEvent::kAny == offlineTriggerMask )
{
const int nbins = 8;
Double_t cbin[nbins+1] = {0., 10., 20., 30., 40., 50., 60., 70., 80.};
TArrayD tbin(nbins+1, cbin);
Int_t nMixed[nbins] = {6, 40, 40, 40, 40, 80, 80, 80};
TArrayI tNMixed(nbins, nMixed);
task->SetCentralityBinning(tbin, tNMixed);
}
//Central:
if( AliVEvent::kCentral == offlineTriggerMask )
{
const int nbins = 4;
Double_t cbin[nbins+1] = {0., 5., 8., 9., 10.};
TArrayD tbin(nbins+1, cbin);
Int_t nMixed[nbins] = {6, 6, 6, 6};
TArrayI tNMixed(nbins, nMixed);
task->SetCentralityBinning(tbin, tNMixed);
}
// SemiCentral:
if( AliVEvent::kSemiCentral == offlineTriggerMask )
{
const int nbins = 8;
Double_t cbin[nbins+1] = {10., 11., 12., 13., 15., 20., 30., 40., 50.};
TArrayD tbin(nbins+1, cbin);
Int_t nMixed[nbins] = {40, 40, 40, 40, 40, 40, 40, 40};
TArrayI tNMixed(nbins, nMixed);
task->SetCentralityBinning(tbin, tNMixed);
}
//INT7:
if( AliVEvent::kINT7 == offlineTriggerMask || AliVEvent::kPHI7 == offlineTriggerMask)
{
const int nbins = 8;
Double_t cbin[nbins+1] = {0., 10., 20., 30., 40., 50., 60., 70., 80.};
TArrayD tbin(nbins+1, cbin);
Int_t nMixed[nbins] = {6, 40, 40, 40, 40, 80, 80, 80};
TArrayI tNMixed(nbins, nMixed);
task->SetCentralityBinning(tbin, tNMixed);
}
// MB or PHOS Trigger:
if( AliVEvent::kMB == offlineTriggerMask || AliVEvent::kPHOSPb == offlineTriggerMask )
{
const int nbins = 8;
Double_t cbin[nbins+1] = {0., 10., 20., 30., 40., 50., 60., 70., 80.};
TArrayD tbin(nbins+1, cbin);
Int_t nMixed[nbins] = {6, 40, 40, 40, 40, 80, 80, 80};
TArrayI tNMixed(nbins, nMixed);
task->SetCentralityBinning(tbin, tNMixed);
}
task->SelectCollisionCandidates(offlineTriggerMask);
task->SetInternalTriggerSelection(internalTriggerSelection);
task->EnableTOFCut(true, 100.e-9);
task->SetCentralityBorders(downCentLimit , upCentLimit) ;
task->SetSigmaWidth(sigmaWidth);
mgr->AddTask(task);
mgr->ConnectInput(task, 0, mgr->GetCommonInputContainer() );
TString cname(Form("%sCoutput1", sName.Data()));
TString pname(Form("%s:%s", AliAnalysisManager::GetCommonFileName(), sName.Data()));
AliAnalysisDataContainer *coutput1 = mgr->CreateContainer(cname.Data(), TList::Class(), AliAnalysisManager::kOutputContainer, pname.Data());
mgr->ConnectOutput(task, 1, coutput1);
return task;
}
<|endoftext|>
|
<commit_before>/*
* Copyright (C) 2013 Google Inc. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following disclaimer
* in the documentation and/or other materials provided with the
* distribution.
* * Neither the name of Google Inc. nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "InbandTextTrackPrivateImpl.h"
#include "WebInbandTextTrack.h"
#include "core/platform/graphics/InbandTextTrackPrivateClient.h"
#include "public/WebString.h"
#include <wtf/PassOwnPtr.h>
namespace WebKit {
InbandTextTrackPrivateImpl::InbandTextTrackPrivateImpl(WebInbandTextTrack* track)
: m_track(adoptPtr(track))
{
ASSERT(track);
track->setClient(this);
}
InbandTextTrackPrivateImpl::~InbandTextTrackPrivateImpl()
{
}
void InbandTextTrackPrivateImpl::setClient(WebCore::InbandTextTrackPrivateClient* client)
{
InbandTextTrackPrivate::setClient(client);
m_track->setClient(this);
}
void InbandTextTrackPrivateImpl::setMode(Mode mode)
{
m_track->setMode(static_cast<WebInbandTextTrack::Mode>(mode));
}
WebCore::InbandTextTrackPrivate::Mode InbandTextTrackPrivateImpl::mode() const
{
return static_cast<WebCore::InbandTextTrackPrivate::Mode>(m_track->mode());
}
WebCore::InbandTextTrackPrivate::Kind InbandTextTrackPrivateImpl::kind() const
{
return static_cast<WebCore::InbandTextTrackPrivate::Kind>(m_track->kind());
}
bool InbandTextTrackPrivateImpl::isClosedCaptions() const
{
return m_track->isClosedCaptions();
}
AtomicString InbandTextTrackPrivateImpl::label() const
{
return m_track->label();
}
AtomicString InbandTextTrackPrivateImpl::language() const
{
return m_track->language();
}
bool InbandTextTrackPrivateImpl::isDefault() const
{
return m_track->isDefault();
}
int InbandTextTrackPrivateImpl::textTrackIndex() const
{
return m_track->textTrackIndex();
}
void InbandTextTrackPrivateImpl::addWebVTTCue(
double start,
double end,
const WebString& id,
const WebString& content,
const WebString& settings)
{
client()->addWebVTTCue(this, start, end, id, content, settings);
}
} // namespace WebKit
<commit_msg>Remove client association in destructor<commit_after>/*
* Copyright (C) 2013 Google Inc. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following disclaimer
* in the documentation and/or other materials provided with the
* distribution.
* * Neither the name of Google Inc. nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "InbandTextTrackPrivateImpl.h"
#include "WebInbandTextTrack.h"
#include "core/platform/graphics/InbandTextTrackPrivateClient.h"
#include "public/WebString.h"
#include <wtf/PassOwnPtr.h>
namespace WebKit {
InbandTextTrackPrivateImpl::InbandTextTrackPrivateImpl(WebInbandTextTrack* track)
: m_track(adoptPtr(track))
{
ASSERT(track);
track->setClient(this);
}
InbandTextTrackPrivateImpl::~InbandTextTrackPrivateImpl()
{
m_track->setClient(0);
}
void InbandTextTrackPrivateImpl::setClient(WebCore::InbandTextTrackPrivateClient* client)
{
InbandTextTrackPrivate::setClient(client);
}
void InbandTextTrackPrivateImpl::setMode(Mode mode)
{
m_track->setMode(static_cast<WebInbandTextTrack::Mode>(mode));
}
WebCore::InbandTextTrackPrivate::Mode InbandTextTrackPrivateImpl::mode() const
{
return static_cast<WebCore::InbandTextTrackPrivate::Mode>(m_track->mode());
}
WebCore::InbandTextTrackPrivate::Kind InbandTextTrackPrivateImpl::kind() const
{
return static_cast<WebCore::InbandTextTrackPrivate::Kind>(m_track->kind());
}
bool InbandTextTrackPrivateImpl::isClosedCaptions() const
{
return m_track->isClosedCaptions();
}
AtomicString InbandTextTrackPrivateImpl::label() const
{
return m_track->label();
}
AtomicString InbandTextTrackPrivateImpl::language() const
{
return m_track->language();
}
bool InbandTextTrackPrivateImpl::isDefault() const
{
return m_track->isDefault();
}
int InbandTextTrackPrivateImpl::textTrackIndex() const
{
return m_track->textTrackIndex();
}
void InbandTextTrackPrivateImpl::addWebVTTCue(
double start,
double end,
const WebString& id,
const WebString& content,
const WebString& settings)
{
client()->addWebVTTCue(this, start, end, id, content, settings);
}
} // namespace WebKit
<|endoftext|>
|
<commit_before>#include "musicremotewidget.h"
#include "musicremotewidgetforcircle.h"
#include "musicremotewidgetfordiamond.h"
#include "musicremotewidgetforrectangle.h"
#include "musicremotewidgetforsquare.h"
#include "musicremotewidgetforsimplestyle.h"
#include "musicremotewidgetforcomplexstyle.h"
#include "musicremotewidgetforstrip.h"
#include "musicremotewidgetforripples.h"
#include "musicremotewidgetforrayswave.h"
#include "musictinyuiobject.h"
#include "musicclickedslider.h"
#include "musicsettingmanager.h"
MusicRemoteWidget::MusicRemoteWidget(QWidget *parent)
: MusicAbstractMoveWidget(parent)
{
setWindowFlags( windowFlags() | Qt::WindowStaysOnTopHint | Qt::Tool);
setAttribute(Qt::WA_DeleteOnClose);
drawWindowShadow(false);
setMouseTracking(true);
m_showMainWindow = new QPushButton(this);
m_PreSongButton = new QPushButton(this);
m_NextSongButton = new QPushButton(this);
m_PlayButton = new QPushButton(this);
m_SettingButton = new QPushButton(this);
#ifdef Q_OS_UNIX
m_showMainWindow->setFocusPolicy(Qt::NoFocus);
m_PreSongButton->setFocusPolicy(Qt::NoFocus);
m_NextSongButton->setFocusPolicy(Qt::NoFocus);
m_PlayButton->setFocusPolicy(Qt::NoFocus);
m_SettingButton->setFocusPolicy(Qt::NoFocus);
#endif
m_mainWidget = new QWidget(this);
m_mainWidget->setObjectName("mainWidget");
m_showMainWindow->setStyleSheet(MusicUIObject::MPushButtonStyle02);
m_showMainWindow->setIcon(QIcon(":/image/lb_player_logo"));
m_SettingButton->setIcon(QIcon(":/tiny/btn_setting_hover"));
m_showMainWindow->setToolTip(tr("showMainWindow"));
m_PreSongButton->setToolTip(tr("Previous"));
m_NextSongButton->setToolTip(tr("Next"));
m_PlayButton->setToolTip(tr("Play"));
m_SettingButton->setToolTip(tr("showSetting"));
m_PreSongButton->setFixedSize(28, 28);
m_NextSongButton->setFixedSize(28, 28);
m_PlayButton->setFixedSize(28, 28);
m_SettingButton->setFixedSize(20, 20);
m_showMainWindow->setFixedSize(30, 30);
m_PreSongButton->setStyleSheet(MusicUIObject::MKGTinyBtnPrevious);
m_NextSongButton->setStyleSheet(MusicUIObject::MKGTinyBtnNext);
m_PlayButton->setStyleSheet(MusicUIObject::MKGTinyBtnPlay);
m_SettingButton->setStyleSheet(MusicUIObject::MKGTinyBtnSetting);
m_mainWidget->setStyleSheet(QString("#mainWidget{%1}").arg(MusicUIObject::MBackgroundStyle04));
m_showMainWindow->setCursor(QCursor(Qt::PointingHandCursor));
m_PreSongButton->setCursor(QCursor(Qt::PointingHandCursor));
m_NextSongButton->setCursor(QCursor(Qt::PointingHandCursor));
m_PlayButton->setCursor(QCursor(Qt::PointingHandCursor));
m_SettingButton->setCursor(QCursor(Qt::PointingHandCursor));
connect(m_showMainWindow, SIGNAL(clicked()), SIGNAL(musicWindowSignal()));
connect(m_PlayButton, SIGNAL(clicked()), SIGNAL(musicKeySignal()));
connect(m_PreSongButton, SIGNAL(clicked()), SIGNAL(musicPlayPreviousSignal()));
connect(m_NextSongButton, SIGNAL(clicked()), SIGNAL(musicPlayNextSignal()));
connect(m_SettingButton, SIGNAL(clicked()), SIGNAL(musicSettingSignal()));
m_volumeWidget = new QWidget(m_mainWidget);
QHBoxLayout *volumeLayout = new QHBoxLayout(m_volumeWidget);
volumeLayout->setContentsMargins(0, 0, 0, 0);
volumeLayout->setSpacing(1);
m_volumeButton = new QToolButton(m_volumeWidget);
m_volumeButton->setFixedSize(QSize(16, 16));
m_volumeSlider = new MusicClickedSlider(Qt::Horizontal, m_volumeWidget);
m_volumeSlider->setRange(0, 100);
m_volumeSlider->setStyleSheet(MusicUIObject::MSliderStyle01);
m_volumeSlider->setFixedWidth(45);
volumeLayout->addWidget(m_volumeButton);
volumeLayout->addWidget(m_volumeSlider);
m_volumeSlider->setCursor(QCursor(Qt::PointingHandCursor));
connect(m_volumeSlider, SIGNAL(valueChanged(int)), SLOT(musicVolumeChanged(int)));
}
MusicRemoteWidget::~MusicRemoteWidget()
{
delete m_volumeButton;
delete m_volumeSlider;
delete m_volumeWidget;
delete m_showMainWindow;
delete m_PreSongButton;
delete m_NextSongButton;
delete m_PlayButton;
delete m_SettingButton;
delete m_mainWidget;
}
QString MusicRemoteWidget::getClassName()
{
return staticMetaObject.className();
}
void MusicRemoteWidget::showPlayStatus(bool status) const
{
m_PlayButton->setStyleSheet(status ? MusicUIObject::MKGTinyBtnPlay : MusicUIObject::MKGTinyBtnPause);
}
void MusicRemoteWidget::setVolumeValue(int index)
{
blockSignals(true);
m_volumeSlider->setValue(index);
musicVolumeChanged(index);
blockSignals(false);
}
void MusicRemoteWidget::setLabelText(const QString &text)
{
Q_UNUSED(text);
}
int MusicRemoteWidget::mapRemoteTypeIndex()
{
if(MObject_cast(MusicRemoteWidgetForCircle*, this)) return Circle;
else if(MObject_cast(MusicRemoteWidgetForSquare*, this)) return Square;
else if(MObject_cast(MusicRemoteWidgetForRectangle*, this)) return Rectangle;
else if(MObject_cast(MusicRemoteWidgetForSimpleStyle*, this)) return SimpleStyle;
else if(MObject_cast(MusicRemoteWidgetForComplexStyle*, this)) return ComplexStyle;
else if(MObject_cast(MusicRemoteWidgetForDiamond*, this)) return Diamond;
else if(MObject_cast(MusicRemoteWidgetForRipples*, this)) return Ripples;
else if(MObject_cast(MusicRemoteWidgetForRaysWave*, this)) return RaysWave;
else return Null;
}
void MusicRemoteWidget::musicVolumeChanged(int value)
{
emit musicVolumeSignal(value);
QString style = MusicUIObject::MKGTinyBtnSoundWhite;
if(66 < value && value <=100)
{
style += "QToolButton{ margin-left:-48px; }";
}
else if(33 < value && value <=66)
{
style += "QToolButton{ margin-left:-32px; }";
}
else if(0 < value && value <=33)
{
style += "QToolButton{ margin-left:-16px; }";
}
else
{
style += "QToolButton{ margin-left:-64px; }";
}
m_volumeButton->setStyleSheet(style);
}
void MusicRemoteWidget::show()
{
MusicAbstractMoveWidget::show();
M_SETTING_PTR->setValue(MusicSettingManager::RemoteWidgetModeChoiced, mapRemoteTypeIndex());
}
bool MusicRemoteWidget::close()
{
M_SETTING_PTR->setValue(MusicSettingManager::RemoteWidgetModeChoiced, Null);
return MusicAbstractMoveWidget::close();
}
void MusicRemoteWidget::contextMenuEvent(QContextMenuEvent *event)
{
MusicAbstractMoveWidget::contextMenuEvent(event);
QMenu menu(this);
menu.setWindowFlags( menu.windowFlags() | Qt::FramelessWindowHint);
menu.setAttribute(Qt::WA_TranslucentBackground);
menu.setStyleSheet(MusicUIObject::MMenuStyle03);
menu.addAction(QIcon(":/contextMenu/btn_selected"), tr("WindowTop"))->setEnabled(false);
menu.addAction(tr("showMainWindow"), this, SIGNAL(musicWindowSignal()));
menu.addSeparator();
QAction * action = menu.addAction(tr("CircleRemote"));
action->setEnabled(!MObject_cast(MusicRemoteWidgetForCircle*, this));
action->setData(Circle);
action = menu.addAction(tr("SquareRemote"));
action->setEnabled(!MObject_cast(MusicRemoteWidgetForSquare*, this));
action->setData(Square);
action = menu.addAction(tr("RectangleRemote"));
action->setEnabled(!MObject_cast(MusicRemoteWidgetForRectangle*, this));
action->setData(Rectangle);
action = menu.addAction(tr("SimpleStyleRemote"));
action->setEnabled(!MObject_cast(MusicRemoteWidgetForSimpleStyle*, this));
action->setData(SimpleStyle);
action = menu.addAction(tr("ComplexStyleRemote"));
action->setEnabled(!MObject_cast(MusicRemoteWidgetForComplexStyle*, this));
action->setData(ComplexStyle);
action = menu.addAction(tr("DiamondRemote"));
action->setEnabled(!MObject_cast(MusicRemoteWidgetForDiamond*, this));
action->setData(Diamond);
action = menu.addAction(tr("RipplesRemote"));
action->setEnabled(!MObject_cast(MusicRemoteWidgetForRipples*, this));
action->setData(Ripples);
action = menu.addAction(tr("RaysWaveRemote"));
action->setEnabled(!MObject_cast(MusicRemoteWidgetForRaysWave*, this));
action->setData(RaysWave);
menu.addAction(tr("quit"), this, SLOT(close()));
connect(&menu, SIGNAL(triggered(QAction*)), SIGNAL(musicRemoteTypeChanged(QAction*)));
menu.exec(QCursor::pos());
}
void MusicRemoteWidget::adjustPostion(QWidget *w)
{
QSize windowSize = M_SETTING_PTR->value(MusicSettingManager::ScreenSize).toSize();
w->move( windowSize.width() - w->width() - 150, w->height() + 70);
}
<commit_msg>Supported volume button muted[548101]<commit_after>#include "musicremotewidget.h"
#include "musicremotewidgetforcircle.h"
#include "musicremotewidgetfordiamond.h"
#include "musicremotewidgetforrectangle.h"
#include "musicremotewidgetforsquare.h"
#include "musicremotewidgetforsimplestyle.h"
#include "musicremotewidgetforcomplexstyle.h"
#include "musicremotewidgetforstrip.h"
#include "musicremotewidgetforripples.h"
#include "musicremotewidgetforrayswave.h"
#include "musictinyuiobject.h"
#include "musicclickedslider.h"
#include "musicsettingmanager.h"
#include "musicapplication.h"
MusicRemoteWidget::MusicRemoteWidget(QWidget *parent)
: MusicAbstractMoveWidget(parent)
{
setWindowFlags( windowFlags() | Qt::WindowStaysOnTopHint | Qt::Tool);
setAttribute(Qt::WA_DeleteOnClose);
drawWindowShadow(false);
setMouseTracking(true);
m_showMainWindow = new QPushButton(this);
m_PreSongButton = new QPushButton(this);
m_NextSongButton = new QPushButton(this);
m_PlayButton = new QPushButton(this);
m_SettingButton = new QPushButton(this);
#ifdef Q_OS_UNIX
m_showMainWindow->setFocusPolicy(Qt::NoFocus);
m_PreSongButton->setFocusPolicy(Qt::NoFocus);
m_NextSongButton->setFocusPolicy(Qt::NoFocus);
m_PlayButton->setFocusPolicy(Qt::NoFocus);
m_SettingButton->setFocusPolicy(Qt::NoFocus);
#endif
m_mainWidget = new QWidget(this);
m_mainWidget->setObjectName("mainWidget");
m_showMainWindow->setStyleSheet(MusicUIObject::MPushButtonStyle02);
m_showMainWindow->setIcon(QIcon(":/image/lb_player_logo"));
m_SettingButton->setIcon(QIcon(":/tiny/btn_setting_hover"));
m_showMainWindow->setToolTip(tr("showMainWindow"));
m_PreSongButton->setToolTip(tr("Previous"));
m_NextSongButton->setToolTip(tr("Next"));
m_PlayButton->setToolTip(tr("Play"));
m_SettingButton->setToolTip(tr("showSetting"));
m_PreSongButton->setFixedSize(28, 28);
m_NextSongButton->setFixedSize(28, 28);
m_PlayButton->setFixedSize(28, 28);
m_SettingButton->setFixedSize(20, 20);
m_showMainWindow->setFixedSize(30, 30);
m_PreSongButton->setStyleSheet(MusicUIObject::MKGTinyBtnPrevious);
m_NextSongButton->setStyleSheet(MusicUIObject::MKGTinyBtnNext);
m_PlayButton->setStyleSheet(MusicUIObject::MKGTinyBtnPlay);
m_SettingButton->setStyleSheet(MusicUIObject::MKGTinyBtnSetting);
m_mainWidget->setStyleSheet(QString("#mainWidget{%1}").arg(MusicUIObject::MBackgroundStyle04));
m_showMainWindow->setCursor(QCursor(Qt::PointingHandCursor));
m_PreSongButton->setCursor(QCursor(Qt::PointingHandCursor));
m_NextSongButton->setCursor(QCursor(Qt::PointingHandCursor));
m_PlayButton->setCursor(QCursor(Qt::PointingHandCursor));
m_SettingButton->setCursor(QCursor(Qt::PointingHandCursor));
connect(m_showMainWindow, SIGNAL(clicked()), SIGNAL(musicWindowSignal()));
connect(m_PlayButton, SIGNAL(clicked()), SIGNAL(musicKeySignal()));
connect(m_PreSongButton, SIGNAL(clicked()), SIGNAL(musicPlayPreviousSignal()));
connect(m_NextSongButton, SIGNAL(clicked()), SIGNAL(musicPlayNextSignal()));
connect(m_SettingButton, SIGNAL(clicked()), SIGNAL(musicSettingSignal()));
m_volumeWidget = new QWidget(m_mainWidget);
QHBoxLayout *volumeLayout = new QHBoxLayout(m_volumeWidget);
volumeLayout->setContentsMargins(0, 0, 0, 0);
volumeLayout->setSpacing(1);
m_volumeButton = new QToolButton(m_volumeWidget);
m_volumeButton->setFixedSize(QSize(16, 16));
m_volumeSlider = new MusicClickedSlider(Qt::Horizontal, m_volumeWidget);
m_volumeSlider->setRange(0, 100);
m_volumeSlider->setStyleSheet(MusicUIObject::MSliderStyle01);
m_volumeSlider->setFixedWidth(45);
volumeLayout->addWidget(m_volumeButton);
volumeLayout->addWidget(m_volumeSlider);
m_volumeButton->setCursor(QCursor(Qt::PointingHandCursor));
m_volumeSlider->setCursor(QCursor(Qt::PointingHandCursor));
connect(m_volumeButton, SIGNAL(clicked()), MusicApplication::instance(), SLOT(musicVolumeMute()));
connect(m_volumeSlider, SIGNAL(valueChanged(int)), SLOT(musicVolumeChanged(int)));
}
MusicRemoteWidget::~MusicRemoteWidget()
{
delete m_volumeButton;
delete m_volumeSlider;
delete m_volumeWidget;
delete m_showMainWindow;
delete m_PreSongButton;
delete m_NextSongButton;
delete m_PlayButton;
delete m_SettingButton;
delete m_mainWidget;
}
QString MusicRemoteWidget::getClassName()
{
return staticMetaObject.className();
}
void MusicRemoteWidget::showPlayStatus(bool status) const
{
m_PlayButton->setStyleSheet(status ? MusicUIObject::MKGTinyBtnPlay : MusicUIObject::MKGTinyBtnPause);
}
void MusicRemoteWidget::setVolumeValue(int index)
{
blockSignals(true);
m_volumeSlider->setValue(index);
musicVolumeChanged(index);
blockSignals(false);
}
void MusicRemoteWidget::setLabelText(const QString &text)
{
Q_UNUSED(text);
}
int MusicRemoteWidget::mapRemoteTypeIndex()
{
if(MObject_cast(MusicRemoteWidgetForCircle*, this)) return Circle;
else if(MObject_cast(MusicRemoteWidgetForSquare*, this)) return Square;
else if(MObject_cast(MusicRemoteWidgetForRectangle*, this)) return Rectangle;
else if(MObject_cast(MusicRemoteWidgetForSimpleStyle*, this)) return SimpleStyle;
else if(MObject_cast(MusicRemoteWidgetForComplexStyle*, this)) return ComplexStyle;
else if(MObject_cast(MusicRemoteWidgetForDiamond*, this)) return Diamond;
else if(MObject_cast(MusicRemoteWidgetForRipples*, this)) return Ripples;
else if(MObject_cast(MusicRemoteWidgetForRaysWave*, this)) return RaysWave;
else return Null;
}
void MusicRemoteWidget::musicVolumeChanged(int value)
{
emit musicVolumeSignal(value);
QString style = MusicUIObject::MKGTinyBtnSoundWhite;
if(66 < value && value <=100)
{
style += "QToolButton{ margin-left:-48px; }";
}
else if(33 < value && value <=66)
{
style += "QToolButton{ margin-left:-32px; }";
}
else if(0 < value && value <=33)
{
style += "QToolButton{ margin-left:-16px; }";
}
else
{
style += "QToolButton{ margin-left:-64px; }";
}
m_volumeButton->setStyleSheet(style);
}
void MusicRemoteWidget::show()
{
MusicAbstractMoveWidget::show();
M_SETTING_PTR->setValue(MusicSettingManager::RemoteWidgetModeChoiced, mapRemoteTypeIndex());
}
bool MusicRemoteWidget::close()
{
M_SETTING_PTR->setValue(MusicSettingManager::RemoteWidgetModeChoiced, Null);
return MusicAbstractMoveWidget::close();
}
void MusicRemoteWidget::contextMenuEvent(QContextMenuEvent *event)
{
MusicAbstractMoveWidget::contextMenuEvent(event);
QMenu menu(this);
menu.setWindowFlags( menu.windowFlags() | Qt::FramelessWindowHint);
menu.setAttribute(Qt::WA_TranslucentBackground);
menu.setStyleSheet(MusicUIObject::MMenuStyle03);
menu.addAction(QIcon(":/contextMenu/btn_selected"), tr("WindowTop"))->setEnabled(false);
menu.addAction(tr("showMainWindow"), this, SIGNAL(musicWindowSignal()));
menu.addSeparator();
QAction * action = menu.addAction(tr("CircleRemote"));
action->setEnabled(!MObject_cast(MusicRemoteWidgetForCircle*, this));
action->setData(Circle);
action = menu.addAction(tr("SquareRemote"));
action->setEnabled(!MObject_cast(MusicRemoteWidgetForSquare*, this));
action->setData(Square);
action = menu.addAction(tr("RectangleRemote"));
action->setEnabled(!MObject_cast(MusicRemoteWidgetForRectangle*, this));
action->setData(Rectangle);
action = menu.addAction(tr("SimpleStyleRemote"));
action->setEnabled(!MObject_cast(MusicRemoteWidgetForSimpleStyle*, this));
action->setData(SimpleStyle);
action = menu.addAction(tr("ComplexStyleRemote"));
action->setEnabled(!MObject_cast(MusicRemoteWidgetForComplexStyle*, this));
action->setData(ComplexStyle);
action = menu.addAction(tr("DiamondRemote"));
action->setEnabled(!MObject_cast(MusicRemoteWidgetForDiamond*, this));
action->setData(Diamond);
action = menu.addAction(tr("RipplesRemote"));
action->setEnabled(!MObject_cast(MusicRemoteWidgetForRipples*, this));
action->setData(Ripples);
action = menu.addAction(tr("RaysWaveRemote"));
action->setEnabled(!MObject_cast(MusicRemoteWidgetForRaysWave*, this));
action->setData(RaysWave);
menu.addAction(tr("quit"), this, SLOT(close()));
connect(&menu, SIGNAL(triggered(QAction*)), SIGNAL(musicRemoteTypeChanged(QAction*)));
menu.exec(QCursor::pos());
}
void MusicRemoteWidget::adjustPostion(QWidget *w)
{
QSize windowSize = M_SETTING_PTR->value(MusicSettingManager::ScreenSize).toSize();
w->move( windowSize.width() - w->width() - 150, w->height() + 70);
}
<|endoftext|>
|
<commit_before>/*=========================================================================
Program: Insight Segmentation & Registration Toolkit (ITK)
Module:
Language: C++
Date:
Version:
Copyright (c) 2000 National Library of Medicine
All rights reserved.
See COPYRIGHT.txt for copyright details.
=========================================================================*/
#if defined(_MSC_VER)
#pragma warning ( disable : 4786 )
#endif
#include <iostream>
// This file has been generated by BuildHeaderTest.tcl
// Test to include each header file for Insight
#include "itkBlobSpatialObject.txx"
#include "itkEllipseSpatialObject.txx"
#include "itkImageSpatialObject.txx"
#include "itkLineSpatialObject.txx"
#include "itkLineSpatialObjectPoint.txx"
#include "itkNDimensionalSpatialObject.txx"
#include "itkPlaneSpatialObject.txx"
#include "itkScene.txx"
#include "itkSpatialObject.txx"
#include "itkSpatialObjectPoint.txx"
#include "itkSpatialObjectProperty.txx"
#include "itkSurfaceSpatialObject.txx"
#include "itkSurfaceSpatialObjectPoint.txx"
#include "itkTubeSpatialObject.txx"
#include "itkTubeSpatialObjectPoint.txx"
int main ( int , char* )
{
return 0;
}
<commit_msg>ENH: Updated to latest headers<commit_after>/*=========================================================================
Program: Insight Segmentation & Registration Toolkit (ITK)
Module:
Language: C++
Date:
Version:
Copyright (c) 2000 National Library of Medicine
All rights reserved.
See COPYRIGHT.txt for copyright details.
=========================================================================*/
#if defined(_MSC_VER)
#pragma warning ( disable : 4786 )
#endif
#include <iostream>
// This file has been generated by BuildHeaderTest.tcl
// Test to include each header file for Insight
#include "itkBlobSpatialObject.txx"
#include "itkEllipseSpatialObject.txx"
#include "itkGroupSpatialObject.txx"
#include "itkImageSpatialObject.txx"
#include "itkLineSpatialObject.txx"
#include "itkLineSpatialObjectPoint.txx"
#include "itkNDimensionalSpatialObject.txx"
#include "itkPlaneSpatialObject.txx"
#include "itkScene.txx"
#include "itkSpatialObject.txx"
#include "itkSpatialObjectPoint.txx"
#include "itkSpatialObjectProperty.txx"
#include "itkSurfaceSpatialObject.txx"
#include "itkSurfaceSpatialObjectPoint.txx"
#include "itkTubeNetworkSpatialObject.txx"
#include "itkTubeSpatialObject.txx"
#include "itkTubeSpatialObjectPoint.txx"
int main ( int , char* )
{
return 0;
}
<|endoftext|>
|
<commit_before>#include "imu_tortuga.h"
//written by Jeremy Weed
ImuTortugaNode::ImuTortugaNode(std::shared_ptr<ros::NodeHandle> n, int rate, std::string name, std::string device) : RamNode(n){
// JW: There are a lot of debug/error messages here, I'm not sure
// if we want to leave them in or not
ROS_DEBUG("beginning constructor");
this->name = name;
// JW: do I need this here?
ros::Rate loop_rate(rate);
imuPub = n->advertise<sensor_msgs::Imu>("qubo/imu/" + name, 1000);
tempPub = n->advertise<std_msgs::Float64MultiArray>("qubo/imu/"+ name + "/temperature", 1000);
quaternionPub = n->advertise<geometry_msgs::Quaternion>("qubo/imu/" + name + "/quaternion", 1000);
magnetsPub = n->advertise<sensor_msgs::MagneticField>("qubo/imu/" + name + "/magnetometer", 1000);
fd = openIMU(device.c_str());
ROS_DEBUG("fd found: %d", fd);
if(fd <= 0){
ROS_ERROR("(%s) Unable to open IMU board at: %s", name.c_str(), device.c_str());
}
ROS_DEBUG("end of publishers");
temperature.layout.dim.push_back(std_msgs::MultiArrayDimension());
temperature.layout.data_offset = 0;
temperature.layout.dim[0].label = "IMU Temperature";
temperature.layout.dim[0].size = 3;
temperature.layout.dim[0].stride = 3;
ROS_DEBUG("finished constructor");
}
ImuTortugaNode::~ImuTortugaNode(){
close(fd);
}
void ImuTortugaNode::update(){
ROS_DEBUG("updating imu method");
static double roll = 0, pitch = 0, yaw = 0, time_last = 0;
ROS_DEBUG("does read hang?");
checkError(readIMUData(fd, data.get()));
ROS_DEBUG("nope");
double time_current = ros::Time::now().toSec();
msg.header.stamp = ros::Time::now();
msg.header.seq = ++id;
msg.header.frame_id = "0";
msg.orientation_covariance[0] = -1;
msg.linear_acceleration_covariance[0] = -1;
// Our IMU returns values in G's, but we should be publishing in m/s^2
msg.linear_acceleration.x = data->accelX * G_IN_MS2;
msg.linear_acceleration.y = data->accelY * G_IN_MS2;
msg.linear_acceleration.z = data->accelZ * G_IN_MS2;
msg.angular_velocity_covariance[0] = -1;
msg.angular_velocity.x = data->gyroX;
msg.angular_velocity.y = data->gyroY;
msg.angular_velocity.z = data->gyroZ;
ROS_DEBUG("end of imu read");
//temperature data
//its a float 64 array, in x, y, z order
temperature.data[0] = data->tempX;
temperature.data[1] = data->tempY;
temperature.data[2] = data->tempZ;
//magnetometer data
mag.header.stamp = ros::Time::now();
mag.header.seq = id;
mag.header.frame_id = "0";
mag.magnetic_field.x = data->magX;
mag.magnetic_field.y = data->magY;
mag.magnetic_field.z = data->magZ;
double time_delta = time_current - time_last;
/*~~~This is gross and I don't like it~~~*/
//normalize about 2pi radians
roll += fmod(data->gyroX / time_delta, 2 * M_PI);
pitch += fmod(data->gyroY / time_delta, 2 * M_PI);
yaw += fmod(data->gyroZ / time_delta, 2 * M_PI);
//quaternion - probably
quaternion = tf::createQuaternionMsgFromRollPitchYaw(roll, pitch, yaw);
// publish data
imuPub.publish(msg);
tempPub.publish(temperature);
quaternionPub.publish(quaternion);
magnetsPub.publish(mag);
ros::spinOnce();
}
<commit_msg>imu has a runtime error, possible fix<commit_after>#include "imu_tortuga.h"
//written by Jeremy Weed
ImuTortugaNode::ImuTortugaNode(std::shared_ptr<ros::NodeHandle> n, int rate, std::string name, std::string device) : RamNode(n){
ros::Time::init();
// JW: There are a lot of debug/error messages here, I'm not sure
// if we want to leave them in or not
ROS_DEBUG("beginning constructor");
this->name = name;
// JW: do I need this here?
ros::Rate loop_rate(rate);
imuPub = n->advertise<sensor_msgs::Imu>("qubo/imu/" + name, 1000);
tempPub = n->advertise<std_msgs::Float64MultiArray>("qubo/imu/"+ name + "/temperature", 1000);
quaternionPub = n->advertise<geometry_msgs::Quaternion>("qubo/imu/" + name + "/quaternion", 1000);
magnetsPub = n->advertise<sensor_msgs::MagneticField>("qubo/imu/" + name + "/magnetometer", 1000);
fd = openIMU(device.c_str());
ROS_DEBUG("fd found: %d", fd);
if(fd <= 0){
ROS_ERROR("(%s) Unable to open IMU board at: %s", name.c_str(), device.c_str());
}
ROS_DEBUG("end of publishers");
temperature.layout.dim.push_back(std_msgs::MultiArrayDimension());
temperature.layout.data_offset = 0;
temperature.layout.dim[0].label = "IMU Temperature";
temperature.layout.dim[0].size = 3;
temperature.layout.dim[0].stride = 3;
ROS_DEBUG("finished constructor");
}
ImuTortugaNode::~ImuTortugaNode(){
close(fd);
}
void ImuTortugaNode::update(){
ROS_DEBUG("updating imu method");
static double roll = 0, pitch = 0, yaw = 0, time_last = 0;
ROS_DEBUG("does read hang?");
checkError(readIMUData(fd, data.get()));
ROS_DEBUG("nope");
double time_current = ros::Time::now().toSec();
msg.header.stamp = ros::Time::now();
msg.header.seq = ++id;
msg.header.frame_id = "0";
msg.orientation_covariance[0] = -1;
msg.linear_acceleration_covariance[0] = -1;
// Our IMU returns values in G's, but we should be publishing in m/s^2
msg.linear_acceleration.x = data->accelX * G_IN_MS2;
msg.linear_acceleration.y = data->accelY * G_IN_MS2;
msg.linear_acceleration.z = data->accelZ * G_IN_MS2;
msg.angular_velocity_covariance[0] = -1;
msg.angular_velocity.x = data->gyroX;
msg.angular_velocity.y = data->gyroY;
msg.angular_velocity.z = data->gyroZ;
ROS_DEBUG("end of imu read");
//temperature data
//its a float 64 array, in x, y, z order
temperature.data[0] = data->tempX;
temperature.data[1] = data->tempY;
temperature.data[2] = data->tempZ;
//magnetometer data
mag.header.stamp = ros::Time::now();
mag.header.seq = id;
mag.header.frame_id = "0";
mag.magnetic_field.x = data->magX;
mag.magnetic_field.y = data->magY;
mag.magnetic_field.z = data->magZ;
double time_delta = time_current - time_last;
/*~~~This is gross and I don't like it~~~*/
//normalize about 2pi radians
roll += fmod(data->gyroX / time_delta, 2 * M_PI);
pitch += fmod(data->gyroY / time_delta, 2 * M_PI);
yaw += fmod(data->gyroZ / time_delta, 2 * M_PI);
//quaternion - probably
quaternion = tf::createQuaternionMsgFromRollPitchYaw(roll, pitch, yaw);
// publish data
imuPub.publish(msg);
tempPub.publish(temperature);
quaternionPub.publish(quaternion);
magnetsPub.publish(mag);
ros::spinOnce();
}
<|endoftext|>
|
<commit_before>#define __OPENCL__
#include "vglClImage.h"
#include "vglContext.h"
#include "cl2cpp_shaders.h"
#include <opencv2/imgproc/types_c.h>
#include <opencv2/imgproc/imgproc_c.h>
#include <opencv2/highgui/highgui_c.h>
#include <fstream>
#include <string>
/*
argv[1] = input_image_path
argv[2] = number of operations to execute
*/
#define NOT_ENOUGH_ARGS_MSG "\nNot enough arguments provided.\n"
#define WRONG_USAGE "\nWrong usage, you must first add an argument for execution.\n"
#define LACKING_VALUE_FOR_ARG "\n You missed pass the value for %s argument\n"
using namespace std;
string input_path;
string output_path;
string* getValue(int arg_position, int argc, char* argv[])
{
if (arg_position+1 > argc || strcmp(string(argv[arg_position+1]).substr(0,2).c_str(),"--") == 0)
{
printf(LACKING_VALUE_FOR_ARG,argv[arg_position]);
}
else
return new string(argv[arg_position+1]);
}
void process_args(int argc, char* argv[])
{
if (argc > 1)
{
for(int i = 1; i < argc; i++)
{
string arg = string(argv[i]);
if (i == 1 && strcmp(arg.substr(0,2).c_str(),"--") != 0)
{
printf(WRONG_USAGE);
exit(0);
}
else
{
if (strcmp(arg.c_str(),"--input") == 0)
{
string value = * getValue(i,argc,argv);
input_path = value;
}
else if (strcmp(arg.c_str(),"--output") == 0)
{
string value = * getValue(i,argc,argv);
output_path = value;
}
}
}
}
else
{
printf(NOT_ENOUGH_ARGS_MSG);
}
}
int main(int argc, char* argv[])
{
process_args(argc,argv);
return 0;
}
<commit_msg>Added argument interpreter for cloud_template<commit_after>
#define _CRT_SECURE_NO_WARNINGS
#define __OPENCL__
#include "vglClImage.h"
#include "vglContext.h"
#include "cl2cpp_shaders.h"
#include <opencv2/imgproc/types_c.h>
#include <opencv2/imgproc/imgproc_c.h>
#include <opencv2/highgui/highgui_c.h>
#include <fstream>
#include <string>
/*
argv[1] = input_image_path
argv[2] = number of operations to execute
*/
#define NOT_ENOUGH_ARGS_MSG "\nNot enough arguments provided.\n"
#define WRONG_USAGE "\nWrong usage, you must first add an argument for execution.\n"
#define LACKING_VALUE_FOR_ARG "\nYou passed wrong value for %s argument\n"
#define WRONG_TYPE_TO_ARG "\nYou've put a wrong value type in an argument\n"
#define MISSING_SETUP_ARGS_BEFORE "\nYou forgot to set some arguments before calling this argument: %s\n"
using namespace std;
string input_path;
string output_path;
int window_size_x = -1, window_size_y = -1;
float* convolution_window;
string* getValue(int arg_position, int argc, char* argv[])
{
if (arg_position+1 > argc || strcmp(string(argv[arg_position+1]).substr(0,2).c_str(),"--") == 0)
{
printf(LACKING_VALUE_FOR_ARG,argv[arg_position]);
}
else
return new string(argv[arg_position+1]);
}
//troca uma substring por outra substring
string replaceinString(std::string str, std::string tofind, std::string toreplace)
{
size_t position = 0;
for ( position = str.find(tofind); position != std::string::npos; position = str.find(tofind,position) )
{
str.replace(position ,1, toreplace);
}
return(str);
}
//Converte uma string contendo um array, em um array de float
void process_string_to_array(string array,float* convolution_window,int size_x, int size_y)
{
array = array.substr(1,array.length()-2);
array = replaceinString(array," ","");
char* value = strtok((char*)array.c_str(),",");
for (int i = 0; i < size_x*size_y; i++)
{
float f;
if(sscanf(value, "%f", &f) == -1 )
{
printf(WRONG_TYPE_TO_ARG);
printf("argument: window_convolution\n");
printf("erro reading vector position %d\n",i+1);
exit(1);
}
convolution_window[i] = f;
value = strtok(NULL,",");
}
}
void process_args(int argc, char* argv[])
{
if (argc > 1)
{
for(int i = 1; i < argc; i++)
{
string arg = string(argv[i]);
//primeira palavra aps o nome do executvel deve ser um
//argumento e no um valor
if (i == 1 && strcmp(arg.substr(0,2).c_str(),"--") != 0)
{
printf(WRONG_USAGE);
exit(1);
}
else
{
if (strcmp(arg.c_str(),"--input") == 0)
{
string value = * getValue(i,argc,argv);
input_path = value;
}
else if (strcmp(arg.c_str(),"--output") == 0)
{
string value = * getValue(i,argc,argv);
output_path = value;
}
else if(strcmp(arg.c_str(),"--window_size_x") == 0)
{
string value = * getValue(i,argc,argv);
int ivalue;
if(sscanf(value.c_str(), "%d", &ivalue) == -1 )
{
printf(WRONG_TYPE_TO_ARG);
exit(1);
}
window_size_x = ivalue;
}
else if(strcmp(arg.c_str(),"--window_size_y") == 0)
{
string value = * getValue(i,argc,argv);
int ivalue;
if(sscanf(value.c_str(), "%d", &ivalue) == -1 )
{
printf(WRONG_TYPE_TO_ARG);
exit(1);
}
window_size_y = ivalue;
}
else if(strcmp(arg.c_str(),"--window_convolution") == 0)
{
if (window_size_x == -1 || window_size_y == -1)
{
printf(MISSING_SETUP_ARGS_BEFORE,"--window_convolution");
exit(1);
}
string value = *getValue(i,argc,argv);
convolution_window = (float*)malloc(sizeof(float)*window_size_x*window_size_y);
process_string_to_array(value,convolution_window,window_size_x,window_size_y);
}
}
}
}
else
{
printf(NOT_ENOUGH_ARGS_MSG);
}
}
int main(int argc, char* argv[])
{
process_args(argc,argv);
for(int i = 0; i < window_size_x*window_size_y; i++)
{
printf("value number %d: %f\n",i,convolution_window[i]);
}
return 0;
}
<|endoftext|>
|
<commit_before>/*****************************************************************************
* Media Library
*****************************************************************************
* Copyright (C) 2015 Hugo Beauzée-Luyssen, Videolabs
*
* Authors: Hugo Beauzée-Luyssen<hugo@beauzee.fr>
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation; either version 2.1 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
*****************************************************************************/
#if HAVE_CONFIG_H
# include "config.h"
#endif
#include "FsDiscoverer.h"
#include <algorithm>
#include <queue>
#include <utility>
#include "factory/FileSystemFactory.h"
#include "medialibrary/filesystem/IDevice.h"
#include "Media.h"
#include "File.h"
#include "Device.h"
#include "Folder.h"
#include "logging/Logger.h"
#include "MediaLibrary.h"
#include "probe/CrawlerProbe.h"
#include "utils/Filename.h"
namespace
{
class DeviceRemovedException : public std::runtime_error
{
public:
DeviceRemovedException() noexcept
: std::runtime_error( "A device was removed during the discovery" )
{
}
};
}
namespace medialibrary
{
FsDiscoverer::FsDiscoverer( std::shared_ptr<fs::IFileSystemFactory> fsFactory, MediaLibrary* ml, IMediaLibraryCb* cb, std::unique_ptr<prober::IProbe> probe )
: m_ml( ml )
, m_fsFactory( std::move( fsFactory ))
, m_cb( cb )
, m_probe( std::move( probe ) )
{
}
bool FsDiscoverer::discover( const std::string& entryPoint )
{
LOG_INFO( "Running discover on: ", entryPoint );
if ( m_fsFactory->isMrlSupported( entryPoint ) == false )
return false;
std::shared_ptr<fs::IDirectory> fsDir;
try
{
fsDir = m_fsFactory->createDirectory( entryPoint );
}
catch ( std::system_error& ex )
{
LOG_WARN( entryPoint, " discovery aborted because of a filesystem error: ", ex.what() );
return true;
}
auto fsDirMrl = fsDir->mrl(); // Saving MRL now since we might need it after fsDir is moved
auto f = Folder::fromMrl( m_ml, fsDirMrl );
// If the folder exists, we assume it will be handled by reload()
if ( f != nullptr )
return true;
try
{
if ( m_probe->proceedOnDirectory( *fsDir ) == false || m_probe->isHidden( *fsDir ) == true )
return true;
// Fetch files explicitly
fsDir->files();
return addFolder( std::move( fsDir ), m_probe->getFolderParent().get() );
}
catch ( sqlite::errors::ConstraintViolation& ex )
{
LOG_WARN( fsDirMrl, " discovery aborted (assuming blacklisted folder): ", ex.what() );
}
catch ( DeviceRemovedException& )
{
// Simply ignore, the device has already been marked as removed and the DB updated accordingly
LOG_INFO( "Discovery of ", fsDirMrl, " was stopped after the device was removed" );
}
return true;
}
void FsDiscoverer::reloadFolder( std::shared_ptr<Folder> f )
{
auto mrl = f->mrl();
try
{
auto folder = m_fsFactory->createDirectory( mrl );
assert( folder->device() != nullptr );
if ( folder->device() == nullptr )
return;
checkFolder( std::move( folder ), std::move( f ), false );
}
catch ( DeviceRemovedException& )
{
LOG_INFO( "Reloading of ", mrl, " was stopped after the device was removed" );
}
catch ( const std::system_error& ex )
{
LOG_INFO( "Failed to instanciate a directory for ", mrl, ": ", ex.what(),
". Can't reload the folder." );
}
}
bool FsDiscoverer::reload()
{
LOG_INFO( "Reloading all folders" );
auto rootFolders = Folder::fetchRootFolders( m_ml );
for ( const auto& f : rootFolders )
reloadFolder( f );
return true;
}
bool FsDiscoverer::reload( const std::string& entryPoint )
{
if ( m_fsFactory->isMrlSupported( entryPoint ) == false )
return false;
LOG_INFO( "Reloading folder ", entryPoint );
auto folder = Folder::fromMrl( m_ml, entryPoint );
if ( folder == nullptr )
{
LOG_ERROR( "Can't reload ", entryPoint, ": folder wasn't found in database" );
return false;
}
reloadFolder( std::move( folder ) );
return true;
}
void FsDiscoverer::checkFolder( std::shared_ptr<fs::IDirectory> currentFolderFs,
std::shared_ptr<Folder> currentFolder,
bool newFolder ) const
{
try
{
// We already know of this folder, though it may now contain a .nomedia file.
// In this case, simply delete the folder.
if ( m_probe->isHidden( *currentFolderFs ) == true )
{
if ( newFolder == false )
m_ml->deleteFolder( *currentFolder );
return;
}
// Ensuring that the file fetching is done in this scope, to catch errors
currentFolderFs->files();
}
// Only check once for a system_error. They are bound to happen when we list the files/folders
// within, and IProbe::isHidden is the first place when this is done
catch ( std::system_error& ex )
{
LOG_WARN( "Failed to browse ", currentFolderFs->mrl(), ": ", ex.what() );
// Even when we're discovering a new folder, we want to rule out device removal as the cause of
// an IO error. If this is the cause, simply abort the discovery. All the folder we have
// discovered so far will be marked as non-present through sqlite hooks, and we'll resume the
// discovery when the device gets plugged back in
auto device = currentFolderFs->device();
// The device might not be present at all, and therefor we might miss a
// representation for it.
if ( device == nullptr || device->isRemovable() )
{
// If the device is removable/missing, check if it was indeed removed.
LOG_INFO( "The device containing ", currentFolderFs->mrl(), " is ",
device != nullptr ? "removable" : "not found",
". Refreshing device cache..." );
m_ml->refreshDevices( *m_fsFactory );
// If the device was missing, refresh our list of devices in case
// the device was plugged back and/or we missed a notification for it
if ( device == nullptr )
device = currentFolderFs->device();
// The device presence flag will be changed in place, so simply retest it
if ( device == nullptr || device->isPresent() == false )
throw DeviceRemovedException();
LOG_INFO( "Device was not removed" );
}
// However if the device isn't removable, we want to:
// - ignore it when we're discovering a new folder.
// - delete it when it was discovered in the past. This is likely to be due to a permission change
// as we would not check the folder if it wasn't present during the parent folder browsing
// but it might also be that we're checking an entry point.
// The error won't arise earlier, as we only perform IO when reading the folder from this function.
if ( newFolder == false )
{
// If we ever came across this folder, its content is now unaccessible: let's remove it.
m_ml->deleteFolder( *currentFolder );
}
return;
}
if ( m_cb != nullptr )
m_cb->onDiscoveryProgress( currentFolderFs->mrl() );
// Load the folders we already know of:
LOG_INFO( "Checking for modifications in ", currentFolderFs->mrl() );
// Don't try to fetch any potential sub folders if the folder was freshly added
std::vector<std::shared_ptr<Folder>> subFoldersInDB;
if ( newFolder == false )
subFoldersInDB = currentFolder->folders();
for ( const auto& subFolder : currentFolderFs->dirs() )
{
if ( subFolder->device() == nullptr )
continue;
if ( m_probe->stopFileDiscovery() == true )
break;
if ( m_probe->proceedOnDirectory( *subFolder ) == false )
continue;
auto it = std::find_if( begin( subFoldersInDB ), end( subFoldersInDB ), [&subFolder](const std::shared_ptr<Folder>& f) {
return f->mrl() == subFolder->mrl();
});
// We don't know this folder, it's a new one
if ( it == end( subFoldersInDB ) )
{
if ( m_probe->isHidden( *subFolder ) )
continue;
LOG_INFO( "New folder detected: ", subFolder->mrl() );
try
{
addFolder( subFolder, currentFolder.get() );
continue;
}
catch ( sqlite::errors::ConstraintViolation& ex )
{
// Best attempt to detect a foreign key violation, indicating the parent folders have been
// deleted due to blacklisting
if ( strstr( ex.what(), "foreign key" ) != nullptr )
{
LOG_WARN( "Creation of a folder failed because the parent is non existing: ", ex.what(),
". Assuming it was deleted due to blacklisting" );
return;
}
LOG_WARN( "Creation of a duplicated folder failed: ", ex.what(), ". Assuming it was blacklisted" );
continue;
}
}
auto folderInDb = *it;
// In any case, check for modifications, as a change related to a mountpoint might
// not update the folder modification date.
// Also, relying on the modification date probably isn't portable
checkFolder( subFolder, folderInDb, false );
subFoldersInDB.erase( it );
}
if ( m_probe->deleteUnseenFolders() == true )
{
// Now all folders we had in DB but haven't seen from the FS must have been deleted.
for ( const auto& f : subFoldersInDB )
{
LOG_INFO( "Folder ", f->mrl(), " not found in FS, deleting it" );
m_ml->deleteFolder( *f );
}
}
checkFiles( currentFolderFs, currentFolder );
LOG_INFO( "Done checking subfolders in ", currentFolderFs->mrl() );
}
void FsDiscoverer::checkFiles( std::shared_ptr<fs::IDirectory> parentFolderFs,
std::shared_ptr<Folder> parentFolder ) const
{
LOG_INFO( "Checking file in ", parentFolderFs->mrl() );
static const std::string req = "SELECT * FROM " + policy::FileTable::Name
+ " WHERE folder_id = ?";
auto files = File::fetchAll<File>( m_ml, req, parentFolder->id() );
std::vector<std::shared_ptr<fs::IFile>> filesToAdd;
std::vector<std::shared_ptr<File>> filesToRemove;
for ( const auto& fileFs: parentFolderFs->files() )
{
if ( m_probe->stopFileDiscovery() == true )
break;
if ( m_probe->proceedOnFile( *fileFs ) == false )
continue;
auto it = std::find_if( begin( files ), end( files ), [fileFs](const std::shared_ptr<File>& f) {
return f->mrl() == fileFs->mrl();
});
if ( it == end( files ) || m_probe->forceFileRefresh() == true )
{
if ( MediaLibrary::isExtensionSupported( fileFs->extension().c_str() ) == true )
filesToAdd.push_back( fileFs );
continue;
}
if ( fileFs->lastModificationDate() == (*it)->lastModificationDate() )
{
// Unchanged file
files.erase( it );
continue;
}
auto& file = (*it);
LOG_INFO( "Forcing file refresh ", fileFs->mrl() );
// Pre-cache the file's media, since we need it to remove. However, better doing it
// out of a write context, since that way, other threads can also read the database.
file->media();
filesToRemove.push_back( std::move( file ) );
filesToAdd.push_back( fileFs );
files.erase( it );
}
if ( m_probe->deleteUnseenFiles() == false )
files.clear();
using FilesT = decltype( files );
using FilesToRemoveT = decltype( filesToRemove );
using FilesToAddT = decltype( filesToAdd );
sqlite::Tools::withRetries( 3, [this, &parentFolder, &parentFolderFs]
( FilesT files, FilesToAddT filesToAdd, FilesToRemoveT filesToRemove ) {
auto t = m_ml->getConn()->newTransaction();
for ( const auto& file : files )
{
LOG_INFO( "File ", file->mrl(), " not found on filesystem, deleting it" );
auto media = file->media();
if ( media != nullptr && media->isDeleted() == false )
media->removeFile( *file );
else if ( file->isDeleted() == false )
{
// This is unexpected, as the file should have been deleted when the media was
// removed.
LOG_WARN( "Deleting a file without an associated media." );
file->destroy();
}
}
for ( auto& f : filesToRemove )
{
if ( f->type() == IFile::Type::Playlist )
{
f->destroy(); // Trigger cascade: delete Playlist, and playlist/media relations
continue;
}
auto media = f->media();
if ( media != nullptr )
media->removeFile( *f );
else
{
// If there is no media associated with this file, the file had to be removed through
// a trigger
assert( f->isDeleted() );
}
}
// Insert all files at once to avoid SQL write contention
for ( auto& p : filesToAdd )
m_ml->addDiscoveredFile( p, parentFolder, parentFolderFs, m_probe->getPlaylistParent() );
t->commit();
LOG_INFO( "Done checking files in ", parentFolderFs->mrl() );
}, std::move( files ), std::move( filesToAdd ), std::move( filesToRemove ) );
}
bool FsDiscoverer::addFolder( std::shared_ptr<fs::IDirectory> folder,
Folder* parentFolder ) const
{
auto deviceFs = folder->device();
// We are creating a folder, there has to be a device containing it.
assert( deviceFs != nullptr );
// But gracefully handle failure in release mode
if( deviceFs == nullptr )
return false;
auto device = Device::fromUuid( m_ml, deviceFs->uuid() );
if ( device == nullptr )
{
LOG_INFO( "Creating new device in DB ", deviceFs->uuid() );
device = Device::create( m_ml, deviceFs->uuid(),
utils::file::scheme( folder->mrl() ),
deviceFs->isRemovable() );
if ( device == nullptr )
return false;
}
auto f = Folder::create( m_ml, folder->mrl(),
parentFolder != nullptr ? parentFolder->id() : 0,
*device, *deviceFs );
if ( f == nullptr )
return false;
checkFolder( std::move( folder ), std::move( f ), true );
return true;
}
}
<commit_msg>FsDiscoverer: reload: Clarify assumptions<commit_after>/*****************************************************************************
* Media Library
*****************************************************************************
* Copyright (C) 2015 Hugo Beauzée-Luyssen, Videolabs
*
* Authors: Hugo Beauzée-Luyssen<hugo@beauzee.fr>
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation; either version 2.1 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
*****************************************************************************/
#if HAVE_CONFIG_H
# include "config.h"
#endif
#include "FsDiscoverer.h"
#include <algorithm>
#include <queue>
#include <utility>
#include "factory/FileSystemFactory.h"
#include "medialibrary/filesystem/IDevice.h"
#include "Media.h"
#include "File.h"
#include "Device.h"
#include "Folder.h"
#include "logging/Logger.h"
#include "MediaLibrary.h"
#include "probe/CrawlerProbe.h"
#include "utils/Filename.h"
namespace
{
class DeviceRemovedException : public std::runtime_error
{
public:
DeviceRemovedException() noexcept
: std::runtime_error( "A device was removed during the discovery" )
{
}
};
}
namespace medialibrary
{
FsDiscoverer::FsDiscoverer( std::shared_ptr<fs::IFileSystemFactory> fsFactory, MediaLibrary* ml, IMediaLibraryCb* cb, std::unique_ptr<prober::IProbe> probe )
: m_ml( ml )
, m_fsFactory( std::move( fsFactory ))
, m_cb( cb )
, m_probe( std::move( probe ) )
{
}
bool FsDiscoverer::discover( const std::string& entryPoint )
{
LOG_INFO( "Running discover on: ", entryPoint );
if ( m_fsFactory->isMrlSupported( entryPoint ) == false )
return false;
std::shared_ptr<fs::IDirectory> fsDir;
try
{
fsDir = m_fsFactory->createDirectory( entryPoint );
}
catch ( std::system_error& ex )
{
LOG_WARN( entryPoint, " discovery aborted because of a filesystem error: ", ex.what() );
return true;
}
auto fsDirMrl = fsDir->mrl(); // Saving MRL now since we might need it after fsDir is moved
auto f = Folder::fromMrl( m_ml, fsDirMrl );
// If the folder exists, we assume it will be handled by reload()
if ( f != nullptr )
return true;
try
{
if ( m_probe->proceedOnDirectory( *fsDir ) == false || m_probe->isHidden( *fsDir ) == true )
return true;
// Fetch files explicitly
fsDir->files();
return addFolder( std::move( fsDir ), m_probe->getFolderParent().get() );
}
catch ( sqlite::errors::ConstraintViolation& ex )
{
LOG_WARN( fsDirMrl, " discovery aborted (assuming blacklisted folder): ", ex.what() );
}
catch ( DeviceRemovedException& )
{
// Simply ignore, the device has already been marked as removed and the DB updated accordingly
LOG_INFO( "Discovery of ", fsDirMrl, " was stopped after the device was removed" );
}
return true;
}
void FsDiscoverer::reloadFolder( std::shared_ptr<Folder> f )
{
assert( f->isPresent() );
auto mrl = f->mrl();
try
{
auto folder = m_fsFactory->createDirectory( mrl );
assert( folder->device() != nullptr );
if ( folder->device() == nullptr )
return;
checkFolder( std::move( folder ), std::move( f ), false );
}
catch ( DeviceRemovedException& )
{
LOG_INFO( "Reloading of ", mrl, " was stopped after the device was removed" );
}
catch ( const std::system_error& ex )
{
LOG_INFO( "Failed to instanciate a directory for ", mrl, ": ", ex.what(),
". Can't reload the folder." );
}
}
bool FsDiscoverer::reload()
{
LOG_INFO( "Reloading all folders" );
auto rootFolders = Folder::fetchRootFolders( m_ml );
for ( const auto& f : rootFolders )
{
// fetchRootFolders only returns present folders
assert( f->isPresent() == true );
reloadFolder( f );
}
return true;
}
bool FsDiscoverer::reload( const std::string& entryPoint )
{
if ( m_fsFactory->isMrlSupported( entryPoint ) == false )
return false;
LOG_INFO( "Reloading folder ", entryPoint );
auto folder = Folder::fromMrl( m_ml, entryPoint );
if ( folder == nullptr )
{
LOG_ERROR( "Can't reload ", entryPoint, ": folder wasn't found in database" );
return false;
}
reloadFolder( std::move( folder ) );
return true;
}
void FsDiscoverer::checkFolder( std::shared_ptr<fs::IDirectory> currentFolderFs,
std::shared_ptr<Folder> currentFolder,
bool newFolder ) const
{
try
{
// We already know of this folder, though it may now contain a .nomedia file.
// In this case, simply delete the folder.
if ( m_probe->isHidden( *currentFolderFs ) == true )
{
if ( newFolder == false )
m_ml->deleteFolder( *currentFolder );
return;
}
// Ensuring that the file fetching is done in this scope, to catch errors
currentFolderFs->files();
}
// Only check once for a system_error. They are bound to happen when we list the files/folders
// within, and IProbe::isHidden is the first place when this is done
catch ( std::system_error& ex )
{
LOG_WARN( "Failed to browse ", currentFolderFs->mrl(), ": ", ex.what() );
// Even when we're discovering a new folder, we want to rule out device removal as the cause of
// an IO error. If this is the cause, simply abort the discovery. All the folder we have
// discovered so far will be marked as non-present through sqlite hooks, and we'll resume the
// discovery when the device gets plugged back in
auto device = currentFolderFs->device();
// The device might not be present at all, and therefor we might miss a
// representation for it.
if ( device == nullptr || device->isRemovable() )
{
// If the device is removable/missing, check if it was indeed removed.
LOG_INFO( "The device containing ", currentFolderFs->mrl(), " is ",
device != nullptr ? "removable" : "not found",
". Refreshing device cache..." );
m_ml->refreshDevices( *m_fsFactory );
// If the device was missing, refresh our list of devices in case
// the device was plugged back and/or we missed a notification for it
if ( device == nullptr )
device = currentFolderFs->device();
// The device presence flag will be changed in place, so simply retest it
if ( device == nullptr || device->isPresent() == false )
throw DeviceRemovedException();
LOG_INFO( "Device was not removed" );
}
// However if the device isn't removable, we want to:
// - ignore it when we're discovering a new folder.
// - delete it when it was discovered in the past. This is likely to be due to a permission change
// as we would not check the folder if it wasn't present during the parent folder browsing
// but it might also be that we're checking an entry point.
// The error won't arise earlier, as we only perform IO when reading the folder from this function.
if ( newFolder == false )
{
// If we ever came across this folder, its content is now unaccessible: let's remove it.
m_ml->deleteFolder( *currentFolder );
}
return;
}
if ( m_cb != nullptr )
m_cb->onDiscoveryProgress( currentFolderFs->mrl() );
// Load the folders we already know of:
LOG_INFO( "Checking for modifications in ", currentFolderFs->mrl() );
// Don't try to fetch any potential sub folders if the folder was freshly added
std::vector<std::shared_ptr<Folder>> subFoldersInDB;
if ( newFolder == false )
subFoldersInDB = currentFolder->folders();
for ( const auto& subFolder : currentFolderFs->dirs() )
{
if ( subFolder->device() == nullptr )
continue;
if ( m_probe->stopFileDiscovery() == true )
break;
if ( m_probe->proceedOnDirectory( *subFolder ) == false )
continue;
auto it = std::find_if( begin( subFoldersInDB ), end( subFoldersInDB ), [&subFolder](const std::shared_ptr<Folder>& f) {
return f->mrl() == subFolder->mrl();
});
// We don't know this folder, it's a new one
if ( it == end( subFoldersInDB ) )
{
if ( m_probe->isHidden( *subFolder ) )
continue;
LOG_INFO( "New folder detected: ", subFolder->mrl() );
try
{
addFolder( subFolder, currentFolder.get() );
continue;
}
catch ( sqlite::errors::ConstraintViolation& ex )
{
// Best attempt to detect a foreign key violation, indicating the parent folders have been
// deleted due to blacklisting
if ( strstr( ex.what(), "foreign key" ) != nullptr )
{
LOG_WARN( "Creation of a folder failed because the parent is non existing: ", ex.what(),
". Assuming it was deleted due to blacklisting" );
return;
}
LOG_WARN( "Creation of a duplicated folder failed: ", ex.what(), ". Assuming it was blacklisted" );
continue;
}
}
auto folderInDb = *it;
// In any case, check for modifications, as a change related to a mountpoint might
// not update the folder modification date.
// Also, relying on the modification date probably isn't portable
checkFolder( subFolder, folderInDb, false );
subFoldersInDB.erase( it );
}
if ( m_probe->deleteUnseenFolders() == true )
{
// Now all folders we had in DB but haven't seen from the FS must have been deleted.
for ( const auto& f : subFoldersInDB )
{
LOG_INFO( "Folder ", f->mrl(), " not found in FS, deleting it" );
m_ml->deleteFolder( *f );
}
}
checkFiles( currentFolderFs, currentFolder );
LOG_INFO( "Done checking subfolders in ", currentFolderFs->mrl() );
}
void FsDiscoverer::checkFiles( std::shared_ptr<fs::IDirectory> parentFolderFs,
std::shared_ptr<Folder> parentFolder ) const
{
LOG_INFO( "Checking file in ", parentFolderFs->mrl() );
static const std::string req = "SELECT * FROM " + policy::FileTable::Name
+ " WHERE folder_id = ?";
auto files = File::fetchAll<File>( m_ml, req, parentFolder->id() );
std::vector<std::shared_ptr<fs::IFile>> filesToAdd;
std::vector<std::shared_ptr<File>> filesToRemove;
for ( const auto& fileFs: parentFolderFs->files() )
{
if ( m_probe->stopFileDiscovery() == true )
break;
if ( m_probe->proceedOnFile( *fileFs ) == false )
continue;
auto it = std::find_if( begin( files ), end( files ), [fileFs](const std::shared_ptr<File>& f) {
return f->mrl() == fileFs->mrl();
});
if ( it == end( files ) || m_probe->forceFileRefresh() == true )
{
if ( MediaLibrary::isExtensionSupported( fileFs->extension().c_str() ) == true )
filesToAdd.push_back( fileFs );
continue;
}
if ( fileFs->lastModificationDate() == (*it)->lastModificationDate() )
{
// Unchanged file
files.erase( it );
continue;
}
auto& file = (*it);
LOG_INFO( "Forcing file refresh ", fileFs->mrl() );
// Pre-cache the file's media, since we need it to remove. However, better doing it
// out of a write context, since that way, other threads can also read the database.
file->media();
filesToRemove.push_back( std::move( file ) );
filesToAdd.push_back( fileFs );
files.erase( it );
}
if ( m_probe->deleteUnseenFiles() == false )
files.clear();
using FilesT = decltype( files );
using FilesToRemoveT = decltype( filesToRemove );
using FilesToAddT = decltype( filesToAdd );
sqlite::Tools::withRetries( 3, [this, &parentFolder, &parentFolderFs]
( FilesT files, FilesToAddT filesToAdd, FilesToRemoveT filesToRemove ) {
auto t = m_ml->getConn()->newTransaction();
for ( const auto& file : files )
{
LOG_INFO( "File ", file->mrl(), " not found on filesystem, deleting it" );
auto media = file->media();
if ( media != nullptr && media->isDeleted() == false )
media->removeFile( *file );
else if ( file->isDeleted() == false )
{
// This is unexpected, as the file should have been deleted when the media was
// removed.
LOG_WARN( "Deleting a file without an associated media." );
file->destroy();
}
}
for ( auto& f : filesToRemove )
{
if ( f->type() == IFile::Type::Playlist )
{
f->destroy(); // Trigger cascade: delete Playlist, and playlist/media relations
continue;
}
auto media = f->media();
if ( media != nullptr )
media->removeFile( *f );
else
{
// If there is no media associated with this file, the file had to be removed through
// a trigger
assert( f->isDeleted() );
}
}
// Insert all files at once to avoid SQL write contention
for ( auto& p : filesToAdd )
m_ml->addDiscoveredFile( p, parentFolder, parentFolderFs, m_probe->getPlaylistParent() );
t->commit();
LOG_INFO( "Done checking files in ", parentFolderFs->mrl() );
}, std::move( files ), std::move( filesToAdd ), std::move( filesToRemove ) );
}
bool FsDiscoverer::addFolder( std::shared_ptr<fs::IDirectory> folder,
Folder* parentFolder ) const
{
auto deviceFs = folder->device();
// We are creating a folder, there has to be a device containing it.
assert( deviceFs != nullptr );
// But gracefully handle failure in release mode
if( deviceFs == nullptr )
return false;
auto device = Device::fromUuid( m_ml, deviceFs->uuid() );
if ( device == nullptr )
{
LOG_INFO( "Creating new device in DB ", deviceFs->uuid() );
device = Device::create( m_ml, deviceFs->uuid(),
utils::file::scheme( folder->mrl() ),
deviceFs->isRemovable() );
if ( device == nullptr )
return false;
}
auto f = Folder::create( m_ml, folder->mrl(),
parentFolder != nullptr ? parentFolder->id() : 0,
*device, *deviceFs );
if ( f == nullptr )
return false;
checkFolder( std::move( folder ), std::move( f ), true );
return true;
}
}
<|endoftext|>
|
<commit_before>#include "engine/api/json_factory.hpp"
#include "engine/guidance/route_step.hpp"
#include "engine/guidance/step_maneuver.hpp"
#include "engine/guidance/route_leg.hpp"
#include "engine/guidance/route.hpp"
#include "engine/guidance/leg_geometry.hpp"
#include "engine/polyline_compressor.hpp"
#include "engine/hint.hpp"
#include <boost/assert.hpp>
#include <boost/range/irange.hpp>
#include <string>
#include <utility>
#include <algorithm>
#include <vector>
namespace osrm
{
namespace engine
{
namespace api
{
namespace json
{
namespace detail
{
std::string instructionToString(extractor::TurnInstruction instruction)
{
std::string token;
// FIXME this could be an array.
switch (instruction)
{
case extractor::TurnInstruction::GoStraight:
token = "continue";
break;
case extractor::TurnInstruction::TurnSlightRight:
token = "bear right";
break;
case extractor::TurnInstruction::TurnRight:
token = "right";
break;
case extractor::TurnInstruction::TurnSharpRight:
token = "sharp right";
break;
case extractor::TurnInstruction::UTurn:
token = "uturn";
break;
case extractor::TurnInstruction::TurnSharpLeft:
token = "sharp left";
break;
case extractor::TurnInstruction::TurnLeft:
token = "left";
break;
case extractor::TurnInstruction::TurnSlightLeft:
token = "bear left";
break;
case extractor::TurnInstruction::HeadOn:
token = "head on";
break;
case extractor::TurnInstruction::EnterRoundAbout:
token = "enter roundabout";
break;
case extractor::TurnInstruction::LeaveRoundAbout:
token = "leave roundabout";
break;
case extractor::TurnInstruction::StayOnRoundAbout:
token = "stay on roundabout";
break;
case extractor::TurnInstruction::StartAtEndOfStreet:
token = "depart";
break;
case extractor::TurnInstruction::ReachedYourDestination:
token = "arrive";
break;
case extractor::TurnInstruction::NameChanges:
token = "name changed";
break;
case extractor::TurnInstruction::NoTurn:
case extractor::TurnInstruction::ReachViaLocation:
case extractor::TurnInstruction::EnterAgainstAllowedDirection:
case extractor::TurnInstruction::LeaveAgainstAllowedDirection:
case extractor::TurnInstruction::InverseAccessRestrictionFlag:
case extractor::TurnInstruction::AccessRestrictionFlag:
case extractor::TurnInstruction::AccessRestrictionPenalty:
BOOST_ASSERT_MSG(false, "Invalid turn type used");
break;
}
return token;
}
util::json::Array coordinateToLonLat(const util::Coordinate &coordinate)
{
util::json::Array array;
array.values.push_back(static_cast<double>(toFloating(coordinate.lon)));
array.values.push_back(static_cast<double>(toFloating(coordinate.lat)));
return array;
}
// FIXME this actually needs to be configurable from the profiles
std::string modeToString(const extractor::TravelMode mode)
{
std::string token;
switch (mode)
{
case TRAVEL_MODE_INACCESSIBLE:
token = "inaccessible";
break;
case TRAVEL_MODE_DRIVING:
token = "driving";
break;
case TRAVEL_MODE_CYCLING:
token = "cycling";
break;
case TRAVEL_MODE_WALKING:
token = "walking";
break;
case TRAVEL_MODE_FERRY:
token = "ferry";
break;
case TRAVEL_MODE_TRAIN:
token = "train";
break;
case TRAVEL_MODE_PUSHING_BIKE:
token = "pushing bike";
break;
case TRAVEL_MODE_MOVABLE_BRIDGE:
token = "movable bridge";
break;
case TRAVEL_MODE_STEPS_UP:
token = "steps up";
break;
case TRAVEL_MODE_STEPS_DOWN:
token = "steps down";
break;
case TRAVEL_MODE_RIVER_UP:
token = "river upstream";
break;
case TRAVEL_MODE_RIVER_DOWN:
token = "river downstream";
break;
case TRAVEL_MODE_ROUTE:
token = "rout";
break;
default:
token = "other";
break;
}
return token;
}
} // namespace detail
util::json::Object makeStepManeuver(const guidance::StepManeuver &maneuver)
{
util::json::Object step_maneuver;
step_maneuver.values["type"] = detail::instructionToString(maneuver.instruction);
step_maneuver.values["location"] = detail::coordinateToLonLat(maneuver.location);
step_maneuver.values["bearing_before"] = maneuver.bearing_before;
step_maneuver.values["bearing_after"] = maneuver.bearing_after;
return step_maneuver;
}
util::json::Object makeRouteStep(guidance::RouteStep &&step, util::json::Value geometry)
{
util::json::Object route_step;
route_step.values["distance"] = step.distance;
route_step.values["duration"] = step.duration;
route_step.values["name"] = std::move(step.name);
route_step.values["mode"] = detail::modeToString(step.mode);
route_step.values["maneuver"] = makeStepManeuver(step.maneuver);
route_step.values["geometry"] = std::move(geometry);
return route_step;
}
util::json::Object makeRoute(const guidance::Route &route,
util::json::Array &&legs,
boost::optional<util::json::Value> geometry)
{
util::json::Object json_route;
json_route.values["distance"] = route.distance;
json_route.values["duration"] = route.duration;
json_route.values["legs"] = std::move(legs);
if (geometry)
{
json_route.values["geometry"] = std::move(*geometry);
}
return json_route;
}
util::json::Object
makeWaypoint(const util::Coordinate location, std::string &&name, const Hint &hint)
{
util::json::Object waypoint;
waypoint.values["location"] = detail::coordinateToLonLat(location);
waypoint.values["name"] = std::move(name);
waypoint.values["hint"] = hint.ToBase64();
return waypoint;
}
util::json::Object makeRouteLeg(guidance::RouteLeg &&leg, util::json::Array &&steps)
{
util::json::Object route_leg;
route_leg.values["distance"] = leg.distance;
route_leg.values["duration"] = leg.duration;
route_leg.values["summary"] = std::move(leg.summary);
route_leg.values["steps"] = std::move(steps);
return route_leg;
}
util::json::Array makeRouteLegs(std::vector<guidance::RouteLeg> &&legs,
std::vector<util::json::Value> step_geometries)
{
util::json::Array json_legs;
auto step_geometry_iter = step_geometries.begin();
for (const auto idx : boost::irange(0UL, legs.size()))
{
auto &&leg = std::move(legs[idx]);
util::json::Array json_steps;
json_steps.values.reserve(leg.steps.size());
std::transform(
std::make_move_iterator(leg.steps.begin()), std::make_move_iterator(leg.steps.end()),
std::back_inserter(json_steps.values), [&step_geometry_iter](guidance::RouteStep &&step)
{
return makeRouteStep(std::move(step), std::move(*step_geometry_iter++));
});
json_legs.values.push_back(makeRouteLeg(std::move(leg), std::move(json_steps)));
}
return json_legs;
}
}
}
} // namespace engine
} // namespace osrm
<commit_msg>Fixes header includes in the JSON factory<commit_after>#include "engine/api/json_factory.hpp"
#include "engine/guidance/route_step.hpp"
#include "engine/guidance/step_maneuver.hpp"
#include "engine/guidance/route_leg.hpp"
#include "engine/guidance/route.hpp"
#include "engine/guidance/leg_geometry.hpp"
#include "engine/polyline_compressor.hpp"
#include "engine/hint.hpp"
#include <boost/assert.hpp>
#include <boost/range/irange.hpp>
#include <boost/optional.hpp>
#include <string>
#include <utility>
#include <algorithm>
#include <iterator>
#include <vector>
namespace osrm
{
namespace engine
{
namespace api
{
namespace json
{
namespace detail
{
std::string instructionToString(extractor::TurnInstruction instruction)
{
std::string token;
// FIXME this could be an array.
switch (instruction)
{
case extractor::TurnInstruction::GoStraight:
token = "continue";
break;
case extractor::TurnInstruction::TurnSlightRight:
token = "bear right";
break;
case extractor::TurnInstruction::TurnRight:
token = "right";
break;
case extractor::TurnInstruction::TurnSharpRight:
token = "sharp right";
break;
case extractor::TurnInstruction::UTurn:
token = "uturn";
break;
case extractor::TurnInstruction::TurnSharpLeft:
token = "sharp left";
break;
case extractor::TurnInstruction::TurnLeft:
token = "left";
break;
case extractor::TurnInstruction::TurnSlightLeft:
token = "bear left";
break;
case extractor::TurnInstruction::HeadOn:
token = "head on";
break;
case extractor::TurnInstruction::EnterRoundAbout:
token = "enter roundabout";
break;
case extractor::TurnInstruction::LeaveRoundAbout:
token = "leave roundabout";
break;
case extractor::TurnInstruction::StayOnRoundAbout:
token = "stay on roundabout";
break;
case extractor::TurnInstruction::StartAtEndOfStreet:
token = "depart";
break;
case extractor::TurnInstruction::ReachedYourDestination:
token = "arrive";
break;
case extractor::TurnInstruction::NameChanges:
token = "name changed";
break;
case extractor::TurnInstruction::NoTurn:
case extractor::TurnInstruction::ReachViaLocation:
case extractor::TurnInstruction::EnterAgainstAllowedDirection:
case extractor::TurnInstruction::LeaveAgainstAllowedDirection:
case extractor::TurnInstruction::InverseAccessRestrictionFlag:
case extractor::TurnInstruction::AccessRestrictionFlag:
case extractor::TurnInstruction::AccessRestrictionPenalty:
BOOST_ASSERT_MSG(false, "Invalid turn type used");
break;
}
return token;
}
util::json::Array coordinateToLonLat(const util::Coordinate &coordinate)
{
util::json::Array array;
array.values.push_back(static_cast<double>(toFloating(coordinate.lon)));
array.values.push_back(static_cast<double>(toFloating(coordinate.lat)));
return array;
}
// FIXME this actually needs to be configurable from the profiles
std::string modeToString(const extractor::TravelMode mode)
{
std::string token;
switch (mode)
{
case TRAVEL_MODE_INACCESSIBLE:
token = "inaccessible";
break;
case TRAVEL_MODE_DRIVING:
token = "driving";
break;
case TRAVEL_MODE_CYCLING:
token = "cycling";
break;
case TRAVEL_MODE_WALKING:
token = "walking";
break;
case TRAVEL_MODE_FERRY:
token = "ferry";
break;
case TRAVEL_MODE_TRAIN:
token = "train";
break;
case TRAVEL_MODE_PUSHING_BIKE:
token = "pushing bike";
break;
case TRAVEL_MODE_MOVABLE_BRIDGE:
token = "movable bridge";
break;
case TRAVEL_MODE_STEPS_UP:
token = "steps up";
break;
case TRAVEL_MODE_STEPS_DOWN:
token = "steps down";
break;
case TRAVEL_MODE_RIVER_UP:
token = "river upstream";
break;
case TRAVEL_MODE_RIVER_DOWN:
token = "river downstream";
break;
case TRAVEL_MODE_ROUTE:
token = "rout";
break;
default:
token = "other";
break;
}
return token;
}
} // namespace detail
util::json::Object makeStepManeuver(const guidance::StepManeuver &maneuver)
{
util::json::Object step_maneuver;
step_maneuver.values["type"] = detail::instructionToString(maneuver.instruction);
step_maneuver.values["location"] = detail::coordinateToLonLat(maneuver.location);
step_maneuver.values["bearing_before"] = maneuver.bearing_before;
step_maneuver.values["bearing_after"] = maneuver.bearing_after;
return step_maneuver;
}
util::json::Object makeRouteStep(guidance::RouteStep &&step, util::json::Value geometry)
{
util::json::Object route_step;
route_step.values["distance"] = step.distance;
route_step.values["duration"] = step.duration;
route_step.values["name"] = std::move(step.name);
route_step.values["mode"] = detail::modeToString(step.mode);
route_step.values["maneuver"] = makeStepManeuver(step.maneuver);
route_step.values["geometry"] = std::move(geometry);
return route_step;
}
util::json::Object makeRoute(const guidance::Route &route,
util::json::Array &&legs,
boost::optional<util::json::Value> geometry)
{
util::json::Object json_route;
json_route.values["distance"] = route.distance;
json_route.values["duration"] = route.duration;
json_route.values["legs"] = std::move(legs);
if (geometry)
{
json_route.values["geometry"] = std::move(*geometry);
}
return json_route;
}
util::json::Object
makeWaypoint(const util::Coordinate location, std::string &&name, const Hint &hint)
{
util::json::Object waypoint;
waypoint.values["location"] = detail::coordinateToLonLat(location);
waypoint.values["name"] = std::move(name);
waypoint.values["hint"] = hint.ToBase64();
return waypoint;
}
util::json::Object makeRouteLeg(guidance::RouteLeg &&leg, util::json::Array &&steps)
{
util::json::Object route_leg;
route_leg.values["distance"] = leg.distance;
route_leg.values["duration"] = leg.duration;
route_leg.values["summary"] = std::move(leg.summary);
route_leg.values["steps"] = std::move(steps);
return route_leg;
}
util::json::Array makeRouteLegs(std::vector<guidance::RouteLeg> &&legs,
std::vector<util::json::Value> step_geometries)
{
util::json::Array json_legs;
auto step_geometry_iter = step_geometries.begin();
for (const auto idx : boost::irange(0UL, legs.size()))
{
auto &&leg = std::move(legs[idx]);
util::json::Array json_steps;
json_steps.values.reserve(leg.steps.size());
std::transform(
std::make_move_iterator(leg.steps.begin()), std::make_move_iterator(leg.steps.end()),
std::back_inserter(json_steps.values), [&step_geometry_iter](guidance::RouteStep &&step)
{
return makeRouteStep(std::move(step), std::move(*step_geometry_iter++));
});
json_legs.values.push_back(makeRouteLeg(std::move(leg), std::move(json_steps)));
}
return json_legs;
}
}
}
} // namespace engine
} // namespace osrm
<|endoftext|>
|
<commit_before>/*
===========================================================================
Daemon BSD Source Code
Copyright (c) 2015, Daemon Developers
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 Daemon developers 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 DAEMON DEVELOPERS 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 "common/Common.h"
#include "Crypto.h"
#include <nettle/aes.h>
#include <nettle/base64.h>
#include <nettle/md5.h>
#include <nettle/sha2.h>
// Compatibility with old nettle versions
#if !defined(AES256_KEY_SIZE)
#define AES256_KEY_SIZE 32
typedef aes_ctx compat_aes256_ctx;
static void nettle_compat_aes256_set_encrypt_key(compat_aes256_ctx *ctx, const uint8_t *key)
{
nettle_aes_set_encrypt_key(ctx, AES256_KEY_SIZE, key);
}
static void nettle_compat_aes256_set_decrypt_key(compat_aes256_ctx *ctx, const uint8_t *key)
{
nettle_aes_set_decrypt_key(ctx, AES256_KEY_SIZE, key);
}
static void nettle_compat_aes256_encrypt(const compat_aes256_ctx *ctx,
size_t length, uint8_t *dst,
const uint8_t *src)
{
nettle_aes_encrypt(ctx, length, dst, src);
}
static void nettle_compat_aes256_decrypt(const compat_aes256_ctx *ctx,
size_t length, uint8_t *dst,
const uint8_t *src)
{
nettle_aes_decrypt(ctx, length, dst, src);
}
static int nettle_compat_base64_decode_update(base64_decode_ctx *ctx,
size_t *dst_length,
uint8_t *dst,
size_t src_length,
const uint8_t *src)
{
unsigned dst_length_uns = *dst_length;
return nettle_base64_decode_update(ctx, &dst_length_uns, dst, src_length, src);
}
#undef aes256_set_encrypt_key
#define nettle_aes256_set_encrypt_key nettle_compat_aes256_set_encrypt_key
#define nettle_aes256_set_decrypt_key nettle_compat_aes256_set_decrypt_key
#define nettle_aes256_invert_key nettle_compat_aes256_invert_key
#define nettle_aes256_encrypt nettle_compat_aes256_encrypt
#define nettle_aes256_decrypt nettle_compat_aes256_decrypt
#define aes256_ctx compat_aes256_ctx
#define nettle_base64_decode_update nettle_compat_base64_decode_update
#endif // NETTLE_VERSION_MAJOR < 3
namespace Crypto {
Data RandomData( std::size_t bytes )
{
Data data( bytes );
Sys::GenRandomBytes(data.data(), data.size());
return data;
}
namespace Encoding {
/*
* Translates binary data into a hexadecimal string
*/
Data HexEncode( const Data& input )
{
Data output;
output.reserve(input.size()*2);
for ( auto byte : input )
{
output.push_back(Str::HexDigit((byte & 0xF0) >> 4));
output.push_back(Str::HexDigit(byte & 0xF));
}
return output;
}
/*
* Translates a hexadecimal string into binary data
* PRE: input is a valid hexadecimal string
* POST: output contains the decoded string
* Returns true on success
* Note: If the decoding fails, output is unchanged
*/
bool HexDecode( const Data& input, Data& output )
{
if ( input.size() % 2 )
{
return false;
}
Data mid( input.size() / 2 );
for ( std::size_t i = 0; i < input.size(); i += 2 )
{
if ( !Str::cisxdigit( input[i] ) || !Str::cisxdigit( input[i+1] ) )
{
return false;
}
mid[ i / 2 ] = ( Str::GetHex( input[i] ) << 4 ) | Str::GetHex( input[i+1] );
}
output = mid;
return true;
}
/*
* Translates binary data into a base64 encoded string
*/
Data Base64Encode( const Data& input )
{
base64_encode_ctx ctx;
nettle_base64_encode_init( &ctx );
Data output( BASE64_ENCODE_LENGTH( input.size() ) + BASE64_ENCODE_FINAL_LENGTH );
int encoded_bytes = nettle_base64_encode_update(
&ctx, output.data(), input.size(), input.data()
);
encoded_bytes += nettle_base64_encode_final( &ctx, output.data() + encoded_bytes );
output.erase( output.begin() + encoded_bytes, output.end() );
return output;
}
/*
* Translates a base64 encoded string into binary data
* PRE: input is a valid Base64 string
* POST: output contains the decoded string
* Returns true on success
* Note: If the decoding fails, output is unchanged
*/
bool Base64Decode( const Data& input, Data& output )
{
base64_decode_ctx ctx;
nettle_base64_decode_init( &ctx );
Data temp( BASE64_DECODE_LENGTH( input.size() ) );
std::size_t decoded_bytes = 0;
if ( !nettle_base64_decode_update( &ctx, &decoded_bytes, temp.data(),
input.size(), input.data() ) )
{
return false;
}
if ( !nettle_base64_decode_final( &ctx ) )
{
return false;
}
temp.erase( temp.begin() + decoded_bytes, temp.end() );
output = temp;
return true;
}
} // namespace Encoding
namespace Hash {
Data Sha256( const Data& input )
{
sha256_ctx ctx;
nettle_sha256_init( &ctx );
nettle_sha256_update( &ctx, input.size(), input.data() );
Data output( SHA256_DIGEST_SIZE );
nettle_sha256_digest( &ctx, SHA256_DIGEST_SIZE, output.data() );
return output;
}
Data Md5( const Data& input )
{
md5_ctx ctx;
nettle_md5_init( &ctx );
nettle_md5_update( &ctx, input.size(), input.data() );
Data output( MD5_DIGEST_SIZE );
nettle_md5_digest( &ctx, MD5_DIGEST_SIZE, output.data() );
return output;
}
} // namespace Hash
/*
* Adds PKCS#7 padding to the data
*/
void AddPadding( Data& target, std::size_t block_size )
{
auto pad = block_size - target.size() % block_size;
target.resize( target.size() + pad, pad );
}
/*
* Encrypts using the AES256 algorthim
* PRE: Key is 256-bit (32 octects) long
* POST: output contains the encrypted data
* Notes: plain_text will be padded using the PKCS#7 algorthm,
* if the decoding fails, output is unchanged
* Returns true on success
*/
bool Aes256Encrypt( Data plain_text, const Data& key, Data& output )
{
if ( key.size() != AES256_KEY_SIZE )
{
return false;
}
aes256_ctx ctx;
nettle_aes256_set_encrypt_key( &ctx, key.data() );
AddPadding( plain_text, AES_BLOCK_SIZE );
output.resize( plain_text.size(), 0 );
nettle_aes256_encrypt( &ctx, plain_text.size(),
output.data(), plain_text.data() );
nettle_aes256_decrypt( &ctx, plain_text.size(),
plain_text.data(), output.data() );
return true;
}
/*
* Encrypts using the AES256 algorthim
* PRE: Key is 256-bit (32 octects) long,
* cypher_text.size() is an integer multiple of the AES block size
* POST: output contains the decrypted data
* Note: If the decoding fails, output is unchanged
* Returns true on success
*/
bool Aes256Decrypt( Data cypher_text, const Data& key, Data& output )
{
if ( key.size() != AES256_KEY_SIZE || cypher_text.size() % AES_BLOCK_SIZE )
{
return false;
}
aes256_ctx ctx;
nettle_aes256_set_decrypt_key( &ctx, key.data() );
output.resize( cypher_text.size(), 0 );
nettle_aes256_decrypt( &ctx, cypher_text.size(),
output.data(), cypher_text.data() );
// Strip the PKCS#7 padding
if ( !output.empty() )
{
output.erase(output.end() - output.back(), output.end());
}
return true;
}
} // namespace Crypto
<commit_msg>crypto: Support libnettle 3.4+ without warnings<commit_after>/*
===========================================================================
Daemon BSD Source Code
Copyright (c) 2015, Daemon Developers
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 Daemon developers 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 DAEMON DEVELOPERS 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 "common/Common.h"
#include "Crypto.h"
#include <nettle/aes.h>
#include <nettle/base64.h>
#include <nettle/md5.h>
#include <nettle/sha2.h>
// HACK: include this because this pulls in nettle/version.h, which does not
// exist in older versions of nettle.
#include <nettle/bignum.h>
// Compatibility with old nettle versions
#if !defined(AES256_KEY_SIZE)
#define AES256_KEY_SIZE 32
typedef aes_ctx compat_aes256_ctx;
static void nettle_compat_aes256_set_encrypt_key(compat_aes256_ctx *ctx, const uint8_t *key)
{
nettle_aes_set_encrypt_key(ctx, AES256_KEY_SIZE, key);
}
static void nettle_compat_aes256_set_decrypt_key(compat_aes256_ctx *ctx, const uint8_t *key)
{
nettle_aes_set_decrypt_key(ctx, AES256_KEY_SIZE, key);
}
static void nettle_compat_aes256_encrypt(const compat_aes256_ctx *ctx,
size_t length, uint8_t *dst,
const uint8_t *src)
{
nettle_aes_encrypt(ctx, length, dst, src);
}
static void nettle_compat_aes256_decrypt(const compat_aes256_ctx *ctx,
size_t length, uint8_t *dst,
const uint8_t *src)
{
nettle_aes_decrypt(ctx, length, dst, src);
}
static int nettle_compat_base64_decode_update(base64_decode_ctx *ctx,
size_t *dst_length,
uint8_t *dst,
size_t src_length,
const uint8_t *src)
{
unsigned dst_length_uns = *dst_length;
return nettle_base64_decode_update(ctx, &dst_length_uns, reinterpret_cast<char*>(dst), src_length, reinterpret_cast<const char*>(src));
}
#undef aes256_set_encrypt_key
#define nettle_aes256_set_encrypt_key nettle_compat_aes256_set_encrypt_key
#define nettle_aes256_set_decrypt_key nettle_compat_aes256_set_decrypt_key
#define nettle_aes256_invert_key nettle_compat_aes256_invert_key
#define nettle_aes256_encrypt nettle_compat_aes256_encrypt
#define nettle_aes256_decrypt nettle_compat_aes256_decrypt
#define aes256_ctx compat_aes256_ctx
#define nettle_base64_decode_update nettle_compat_base64_decode_update
#endif // NETTLE_VERSION_MAJOR < 3
// Nettle 3.4 changed the base64 API to accept char* arguments instead of uint8_t* args. Account
// for this here.
#if NETTLE_VERSION_MAJOR >= 3 && NETTLE_VERSION_MINOR >= 4
static size_t nettle_compat_base64_encode_update(struct base64_encode_ctx *ctx,
uint8_t *dst,
size_t length,
const uint8_t *src)
{
return nettle_base64_encode_update(ctx,
reinterpret_cast<char*>(dst),
length,
src);
}
static size_t nettle_compat_base64_encode_final(struct base64_encode_ctx *ctx,
uint8_t *dst)
{
return nettle_base64_encode_final(ctx, reinterpret_cast<char*>(dst));
}
static int nettle_compat_base64_decode_update(base64_decode_ctx *ctx,
size_t *dst_length,
uint8_t *dst,
size_t src_length,
const uint8_t *src)
{
return nettle_base64_decode_update(ctx,
dst_length,
dst,
src_length,
reinterpret_cast<const char*>(src));
}
#define nettle_base64_encode_update nettle_compat_base64_encode_update
#define nettle_base64_encode_final nettle_compat_base64_encode_final
#define nettle_base64_decode_update nettle_compat_base64_decode_update
#endif // NETTLE_VERSION_MAJOR >= 3 || NETTLE_VERSION_MINOR >= 4
namespace Crypto {
Data RandomData( std::size_t bytes )
{
Data data( bytes );
Sys::GenRandomBytes(data.data(), data.size());
return data;
}
namespace Encoding {
/*
* Translates binary data into a hexadecimal string
*/
Data HexEncode( const Data& input )
{
Data output;
output.reserve(input.size()*2);
for ( auto byte : input )
{
output.push_back(Str::HexDigit((byte & 0xF0) >> 4));
output.push_back(Str::HexDigit(byte & 0xF));
}
return output;
}
/*
* Translates a hexadecimal string into binary data
* PRE: input is a valid hexadecimal string
* POST: output contains the decoded string
* Returns true on success
* Note: If the decoding fails, output is unchanged
*/
bool HexDecode( const Data& input, Data& output )
{
if ( input.size() % 2 )
{
return false;
}
Data mid( input.size() / 2 );
for ( std::size_t i = 0; i < input.size(); i += 2 )
{
if ( !Str::cisxdigit( input[i] ) || !Str::cisxdigit( input[i+1] ) )
{
return false;
}
mid[ i / 2 ] = ( Str::GetHex( input[i] ) << 4 ) | Str::GetHex( input[i+1] );
}
output = mid;
return true;
}
/*
* Translates binary data into a base64 encoded string
*/
Data Base64Encode( const Data& input )
{
base64_encode_ctx ctx;
nettle_base64_encode_init( &ctx );
Data output( BASE64_ENCODE_LENGTH( input.size() ) + BASE64_ENCODE_FINAL_LENGTH );
int encoded_bytes = nettle_base64_encode_update(
&ctx, output.data(), input.size(), input.data()
);
encoded_bytes += nettle_base64_encode_final( &ctx, output.data() + encoded_bytes );
output.erase( output.begin() + encoded_bytes, output.end() );
return output;
}
/*
* Translates a base64 encoded string into binary data
* PRE: input is a valid Base64 string
* POST: output contains the decoded string
* Returns true on success
* Note: If the decoding fails, output is unchanged
*/
bool Base64Decode( const Data& input, Data& output )
{
base64_decode_ctx ctx;
nettle_base64_decode_init( &ctx );
Data temp( BASE64_DECODE_LENGTH( input.size() ) );
std::size_t decoded_bytes = 0;
if ( !nettle_base64_decode_update( &ctx, &decoded_bytes, temp.data(),
input.size(), input.data() ) )
{
return false;
}
if ( !nettle_base64_decode_final( &ctx ) )
{
return false;
}
temp.erase( temp.begin() + decoded_bytes, temp.end() );
output = temp;
return true;
}
} // namespace Encoding
namespace Hash {
Data Sha256( const Data& input )
{
sha256_ctx ctx;
nettle_sha256_init( &ctx );
nettle_sha256_update( &ctx, input.size(), input.data() );
Data output( SHA256_DIGEST_SIZE );
nettle_sha256_digest( &ctx, SHA256_DIGEST_SIZE, output.data() );
return output;
}
Data Md5( const Data& input )
{
md5_ctx ctx;
nettle_md5_init( &ctx );
nettle_md5_update( &ctx, input.size(), input.data() );
Data output( MD5_DIGEST_SIZE );
nettle_md5_digest( &ctx, MD5_DIGEST_SIZE, output.data() );
return output;
}
} // namespace Hash
/*
* Adds PKCS#7 padding to the data
*/
void AddPadding( Data& target, std::size_t block_size )
{
auto pad = block_size - target.size() % block_size;
target.resize( target.size() + pad, pad );
}
/*
* Encrypts using the AES256 algorthim
* PRE: Key is 256-bit (32 octects) long
* POST: output contains the encrypted data
* Notes: plain_text will be padded using the PKCS#7 algorthm,
* if the decoding fails, output is unchanged
* Returns true on success
*/
bool Aes256Encrypt( Data plain_text, const Data& key, Data& output )
{
if ( key.size() != AES256_KEY_SIZE )
{
return false;
}
aes256_ctx ctx;
nettle_aes256_set_encrypt_key( &ctx, key.data() );
AddPadding( plain_text, AES_BLOCK_SIZE );
output.resize( plain_text.size(), 0 );
nettle_aes256_encrypt( &ctx, plain_text.size(),
output.data(), plain_text.data() );
nettle_aes256_decrypt( &ctx, plain_text.size(),
plain_text.data(), output.data() );
return true;
}
/*
* Encrypts using the AES256 algorthim
* PRE: Key is 256-bit (32 octects) long,
* cypher_text.size() is an integer multiple of the AES block size
* POST: output contains the decrypted data
* Note: If the decoding fails, output is unchanged
* Returns true on success
*/
bool Aes256Decrypt( Data cypher_text, const Data& key, Data& output )
{
if ( key.size() != AES256_KEY_SIZE || cypher_text.size() % AES_BLOCK_SIZE )
{
return false;
}
aes256_ctx ctx;
nettle_aes256_set_decrypt_key( &ctx, key.data() );
output.resize( cypher_text.size(), 0 );
nettle_aes256_decrypt( &ctx, cypher_text.size(),
output.data(), cypher_text.data() );
// Strip the PKCS#7 padding
if ( !output.empty() )
{
output.erase(output.end() - output.back(), output.end());
}
return true;
}
} // namespace Crypto
<|endoftext|>
|
<commit_before>/*************************************************************************
*
* $RCSfile: sane.hxx,v $
*
* $Revision: 1.4 $
*
* last change: $Author: hr $ $Date: 2001-11-02 10:50:21 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the "License"); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#ifndef _SANE_HXX
#define _SANE_HXX
#include <osl/thread.h>
#include <tools/string.hxx>
#include <vcl/bitmap.hxx>
#include <sane/sane.h>
#include <scanner.hxx>
// ---------------------
// - BitmapTransporter -
// ---------------------
class BitmapTransporter : public OWeakObject, AWT::XBitmap
{
SvMemoryStream m_aStream;
vos::OMutex m_aProtector;
public:
BitmapTransporter();
virtual ~BitmapTransporter();
// XInterface
virtual ANY SAL_CALL queryInterface( const Type & rType ) throw( RuntimeException );
virtual void SAL_CALL acquire() throw() { OWeakObject::acquire(); }
virtual void SAL_CALL release() throw() { OWeakObject::release(); }
virtual AWT::Size SAL_CALL getSize() throw();
virtual SEQ( sal_Int8 ) SAL_CALL getDIB() throw();
virtual SEQ( sal_Int8 ) SAL_CALL getMaskDIB() throw() { return SEQ( sal_Int8 )(); }
// Misc
void lock() { m_aProtector.acquire(); }
void unlock() { m_aProtector.release(); }
SvMemoryStream& getStream() { return m_aStream; }
};
// --------
// - Sane -
// --------
class Sane
{
private:
static int nRefCount;
static void* pSaneLib;
static SANE_Status (*p_init)( SANE_Int*,
SANE_Auth_Callback );
static void (*p_exit)();
static SANE_Status (*p_get_devices)( const SANE_Device***,
SANE_Bool );
static SANE_Status (*p_open)( SANE_String_Const, SANE_Handle );
static void (*p_close)( SANE_Handle );
static const SANE_Option_Descriptor* (*p_get_option_descriptor)(
SANE_Handle, SANE_Int );
static SANE_Status (*p_control_option)( SANE_Handle, SANE_Int,
SANE_Action, void*,
SANE_Int* );
static SANE_Status (*p_get_parameters)( SANE_Handle,
SANE_Parameters* );
static SANE_Status (*p_start)( SANE_Handle );
static SANE_Status (*p_read)( SANE_Handle, SANE_Byte*, SANE_Int,
SANE_Int* );
static void (*p_cancel)( SANE_Handle );
static SANE_Status (*p_set_io_mode)( SANE_Handle, SANE_Bool );
static SANE_Status (*p_get_select_fd)( SANE_Handle, SANE_Int* );
static const SANE_String_Const (*p_strstatus)( SANE_Status );
static SANE_Int nVersion;
static SANE_Device** ppDevices;
static int nDevices;
const SANE_Option_Descriptor** mppOptions;
int mnOptions;
int mnDevice;
SANE_Handle maHandle;
Link maReloadOptionsLink;
inline void* LoadSymbol( char* );
void Init();
void DeInit();
void Stop();
SANE_Status ControlOption( int, SANE_Action, void* );
BOOL CheckConsistency( const char*, BOOL bInit = FALSE );
public:
Sane();
~Sane();
static BOOL IsSane()
{ return pSaneLib ? TRUE : FALSE; }
BOOL IsOpen()
{ return maHandle ? TRUE : FALSE; }
static int CountDevices()
{ return nDevices; }
static String GetName( int n )
{ return String( ppDevices[n]->name ? ppDevices[n]->name : "", osl_getThreadTextEncoding() ); }
static String GetVendor( int n )
{ return String( ppDevices[n]->vendor ? ppDevices[n]->vendor : "", osl_getThreadTextEncoding() ); }
static String GetModel( int n )
{ return String( ppDevices[n]->model ? ppDevices[n]->model : "", osl_getThreadTextEncoding() ); }
static String GetType( int n )
{ return String( ppDevices[n]->type ? ppDevices[n]->type : "", osl_getThreadTextEncoding() ); }
String GetOptionName( int n )
{ return String( mppOptions[n]->name ? (char*)mppOptions[n]->name : "", osl_getThreadTextEncoding() ); }
String GetOptionTitle( int n )
{ return String( mppOptions[n]->title ? (char*)mppOptions[n]->title : "", osl_getThreadTextEncoding() ); }
SANE_Value_Type GetOptionType( int n )
{ return mppOptions[n]->type; }
SANE_Unit GetOptionUnit( int n )
{ return mppOptions[n]->unit; }
String GetOptionUnitName( int n );
SANE_Int GetOptionCap( int n )
{ return mppOptions[n]->cap; }
SANE_Constraint_Type GetOptionConstraintType( int n )
{ return mppOptions[n]->constraint_type; }
const char** GetStringConstraint( int n )
{ return (const char**)mppOptions[n]->constraint.string_list; }
int GetRange( int, double*& );
inline int GetOptionElements( int n );
int GetOptionByName( const char* );
BOOL GetOptionValue( int, BOOL& );
BOOL GetOptionValue( int, ByteString& );
BOOL GetOptionValue( int, double&, int nElement = 0 );
BOOL GetOptionValue( int, double* );
BOOL SetOptionValue( int, BOOL );
BOOL SetOptionValue( int, const String& );
BOOL SetOptionValue( int, double, int nElement = 0 );
BOOL SetOptionValue( int, double* );
BOOL ActivateButtonOption( int );
int CountOptions() { return mnOptions; }
int GetDeviceNumber() { return mnDevice; }
BOOL Open( const char* );
BOOL Open( int );
void Close();
void ReloadDevices();
void ReloadOptions();
BOOL Start( BitmapTransporter& );
inline Link SetReloadOptionsHdl( const Link& rLink );
};
inline int Sane::GetOptionElements( int n )
{
if( mppOptions[n]->type == SANE_TYPE_FIXED ||
mppOptions[n]->type == SANE_TYPE_INT )
{
return mppOptions[n]->size/sizeof( SANE_Word );
}
return 1;
}
inline Link Sane::SetReloadOptionsHdl( const Link& rLink )
{
Link aRet = maReloadOptionsLink;
maReloadOptionsLink = rLink;
return aRet;
}
#endif
<commit_msg>INTEGRATION: CWS ooo19126 (1.4.580); FILE MERGED 2005/09/05 13:00:58 rt 1.4.580.1: #i54170# Change license header: remove SISSL<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: sane.hxx,v $
*
* $Revision: 1.5 $
*
* last change: $Author: rt $ $Date: 2005-09-08 20:37:12 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#ifndef _SANE_HXX
#define _SANE_HXX
#include <osl/thread.h>
#include <tools/string.hxx>
#include <vcl/bitmap.hxx>
#include <sane/sane.h>
#include <scanner.hxx>
// ---------------------
// - BitmapTransporter -
// ---------------------
class BitmapTransporter : public OWeakObject, AWT::XBitmap
{
SvMemoryStream m_aStream;
vos::OMutex m_aProtector;
public:
BitmapTransporter();
virtual ~BitmapTransporter();
// XInterface
virtual ANY SAL_CALL queryInterface( const Type & rType ) throw( RuntimeException );
virtual void SAL_CALL acquire() throw() { OWeakObject::acquire(); }
virtual void SAL_CALL release() throw() { OWeakObject::release(); }
virtual AWT::Size SAL_CALL getSize() throw();
virtual SEQ( sal_Int8 ) SAL_CALL getDIB() throw();
virtual SEQ( sal_Int8 ) SAL_CALL getMaskDIB() throw() { return SEQ( sal_Int8 )(); }
// Misc
void lock() { m_aProtector.acquire(); }
void unlock() { m_aProtector.release(); }
SvMemoryStream& getStream() { return m_aStream; }
};
// --------
// - Sane -
// --------
class Sane
{
private:
static int nRefCount;
static void* pSaneLib;
static SANE_Status (*p_init)( SANE_Int*,
SANE_Auth_Callback );
static void (*p_exit)();
static SANE_Status (*p_get_devices)( const SANE_Device***,
SANE_Bool );
static SANE_Status (*p_open)( SANE_String_Const, SANE_Handle );
static void (*p_close)( SANE_Handle );
static const SANE_Option_Descriptor* (*p_get_option_descriptor)(
SANE_Handle, SANE_Int );
static SANE_Status (*p_control_option)( SANE_Handle, SANE_Int,
SANE_Action, void*,
SANE_Int* );
static SANE_Status (*p_get_parameters)( SANE_Handle,
SANE_Parameters* );
static SANE_Status (*p_start)( SANE_Handle );
static SANE_Status (*p_read)( SANE_Handle, SANE_Byte*, SANE_Int,
SANE_Int* );
static void (*p_cancel)( SANE_Handle );
static SANE_Status (*p_set_io_mode)( SANE_Handle, SANE_Bool );
static SANE_Status (*p_get_select_fd)( SANE_Handle, SANE_Int* );
static const SANE_String_Const (*p_strstatus)( SANE_Status );
static SANE_Int nVersion;
static SANE_Device** ppDevices;
static int nDevices;
const SANE_Option_Descriptor** mppOptions;
int mnOptions;
int mnDevice;
SANE_Handle maHandle;
Link maReloadOptionsLink;
inline void* LoadSymbol( char* );
void Init();
void DeInit();
void Stop();
SANE_Status ControlOption( int, SANE_Action, void* );
BOOL CheckConsistency( const char*, BOOL bInit = FALSE );
public:
Sane();
~Sane();
static BOOL IsSane()
{ return pSaneLib ? TRUE : FALSE; }
BOOL IsOpen()
{ return maHandle ? TRUE : FALSE; }
static int CountDevices()
{ return nDevices; }
static String GetName( int n )
{ return String( ppDevices[n]->name ? ppDevices[n]->name : "", osl_getThreadTextEncoding() ); }
static String GetVendor( int n )
{ return String( ppDevices[n]->vendor ? ppDevices[n]->vendor : "", osl_getThreadTextEncoding() ); }
static String GetModel( int n )
{ return String( ppDevices[n]->model ? ppDevices[n]->model : "", osl_getThreadTextEncoding() ); }
static String GetType( int n )
{ return String( ppDevices[n]->type ? ppDevices[n]->type : "", osl_getThreadTextEncoding() ); }
String GetOptionName( int n )
{ return String( mppOptions[n]->name ? (char*)mppOptions[n]->name : "", osl_getThreadTextEncoding() ); }
String GetOptionTitle( int n )
{ return String( mppOptions[n]->title ? (char*)mppOptions[n]->title : "", osl_getThreadTextEncoding() ); }
SANE_Value_Type GetOptionType( int n )
{ return mppOptions[n]->type; }
SANE_Unit GetOptionUnit( int n )
{ return mppOptions[n]->unit; }
String GetOptionUnitName( int n );
SANE_Int GetOptionCap( int n )
{ return mppOptions[n]->cap; }
SANE_Constraint_Type GetOptionConstraintType( int n )
{ return mppOptions[n]->constraint_type; }
const char** GetStringConstraint( int n )
{ return (const char**)mppOptions[n]->constraint.string_list; }
int GetRange( int, double*& );
inline int GetOptionElements( int n );
int GetOptionByName( const char* );
BOOL GetOptionValue( int, BOOL& );
BOOL GetOptionValue( int, ByteString& );
BOOL GetOptionValue( int, double&, int nElement = 0 );
BOOL GetOptionValue( int, double* );
BOOL SetOptionValue( int, BOOL );
BOOL SetOptionValue( int, const String& );
BOOL SetOptionValue( int, double, int nElement = 0 );
BOOL SetOptionValue( int, double* );
BOOL ActivateButtonOption( int );
int CountOptions() { return mnOptions; }
int GetDeviceNumber() { return mnDevice; }
BOOL Open( const char* );
BOOL Open( int );
void Close();
void ReloadDevices();
void ReloadOptions();
BOOL Start( BitmapTransporter& );
inline Link SetReloadOptionsHdl( const Link& rLink );
};
inline int Sane::GetOptionElements( int n )
{
if( mppOptions[n]->type == SANE_TYPE_FIXED ||
mppOptions[n]->type == SANE_TYPE_INT )
{
return mppOptions[n]->size/sizeof( SANE_Word );
}
return 1;
}
inline Link Sane::SetReloadOptionsHdl( const Link& rLink )
{
Link aRet = maReloadOptionsLink;
maReloadOptionsLink = rLink;
return aRet;
}
#endif
<|endoftext|>
|
<commit_before>#ifndef ORG_EEROS_CONTROL_PATHPLANNERCONSTACC_HPP_
#define ORG_EEROS_CONTROL_PATHPLANNERCONSTACC_HPP_
#include <eeros/control/Output.hpp>
#include <eeros/control/TrajectoryGenerator.hpp>
#include <eeros/core/System.hpp>
#include <cmath>
#include <mutex>
namespace eeros {
namespace control {
/**
* This path planner with constant acceleration generates a trajectory as follows.
* The trajectory leads from the start position to its end position. The acceleration is
* set to a positive constant value. The velocity starts from 0 and goes up to its maximum value
* which can be chosen. After this maximum velocity is reached the acceleration is set to 0 and
* the trajectory continues with constant velocity. Towards the end a constant deceleration
* makes sure that the final position is reached with the velocity reaching 0.
*
* @tparam T - output type (must be a composite type),
* a trajectory in 3-dimensional space needs T = Matrix<3,1,double>,
* a trajectory in linear space needs T = Matrix<1,1,double>
*
* @since v1.0
*/
template<typename T>
class PathPlannerConstAcc : public TrajectoryGenerator<T, 3> {
using E = typename T::value_type;
public:
/**
* Constructs a path planner with a trajectory where the acceleration is always constant.
* The trajectory will start with an constant acceleration (will not be higher than accMax).
* As soon as velMax is reached, the acceleration will be 0 and the velocity will stay constant
* (will not be higher than velMax). For the third part the trajectory will stop with a
* constant deceleration (will not be higher decMax).
* The sampling time must be set to the time with which the timedomain containing this block will run.
*
* @param velMax - maximum velocity
* @param acc - maximum acceleration
* @param dec - maximum deceleration
* @param dt - sampling time
*/
PathPlannerConstAcc(T velMax, T acc, T dec, double dt)
: finished(true), velMax(velMax), acc(acc), dec(dec), dt(dt) {
posOut.getSignal().clear();
velOut.getSignal().clear();
accOut.getSignal().clear();
}
/**
* Disabling use of copy constructor because the block should never be copied unintentionally.
*/
PathPlannerConstAcc(const PathPlannerConstAcc& s) = delete;
/**
* Query if a requested trajectory has already reached its end position.
*
* @return - end of trajectory is reached
*/
virtual bool endReached() {
std::lock_guard<std::mutex> lck(mtx);
return finished;
}
/**
* Runs the path planner block. With the precalculated values for the
* acceleration for all sampling points on the trajectory, the resulting velocities
* and positions are calculated and written to the appropriate outputs.
*/
virtual void run() {
std::lock_guard<std::mutex> lck(mtx);
std::array<T, 3> y = this->last;
t += dt;
if (!finished) {
for (unsigned int i = 0; i < a1p.size(); i++) {
switch (range) {
case 1:
if (t <= dT1) {
y[0][i] = a1p[i] * pow(t, 2) + c1p[i];
y[1][i] = b1v[i] * t;
y[2][i] = c1a[i];
}
if (fabs(t - dT1) < 1e-12 && i == a1p.size() - 1) {
range = 2;
t = 0;
}
break;
case 2:
if (t <= dT2) {
y[0][i] = b2p[i] * t + c2p[i];
y[1][i] = c2v[i];
y[2][i] = c2a[i];
}
if (fabs(t - dT2) < 1e-12 && i == a1p.size() - 1) {
range = 3;
t = 0;
}
break;
case 3:
if (t <= dT3) {
y[0][i] = a3p[i] * pow(t, 2) + b3p[i] * t + c3p[i];
y[1][i] = b3v[i] * t + c3v[i];
y[2][i] = c3a[i];
}
if (fabs(t - dT3) < 1e-12 && i == a1p.size() - 1) {
range = 4;
t = 0;
}
break;
case 4:
finished = true;
y[0][i] = endPos[i];
y[1][i] = 0.0;
y[2][i] = 0.0;
break;
}
// keep last position value
this->last[0][i] = y[0][i];
this->last[1][i] = y[1][i];
this->last[2][i] = y[2][i];
}
}
posOut.getSignal().setValue(y[0]);
velOut.getSignal().setValue(y[1]);
accOut.getSignal().setValue(y[2]);
timestamp_t time = System::getTimeNs();
posOut.getSignal().setTimestamp(time);
velOut.getSignal().setTimestamp(time);
accOut.getSignal().setTimestamp(time);
}
using TrajectoryGenerator<T, 3>::move;
/**
* Dispatches a new trajectory from start to end.
* With both parameters only the first index in the array, that is the position
* will be considered. The higher derivatives won't be taken into account.
* The function will terminate immediately and return false if the last trajectory
* is not finished.
*
* @param start - array containing start position and its higher derivatives
* @param end - array containing end position and its higher derivatives
* @return - a trajectory could be sucessfully generated for this parameters
*
* @see setStart()
* @see run()
*/
virtual bool move(std::array<T, 3> start, std::array<T, 3> end) {
if (!finished) return false;
T calcVelNorm, calcAccNorm, calcDecNorm;
E velNorm, accNorm, decNorm;
T distance = end[0] - start[0];
endPos = end[0];
T zero; zero = 0;
if (distance == zero) return false;
// normalize
for (unsigned int i = 0; i < calcVelNorm.size(); i++) {
calcVelNorm[i] = fabs(velMax[i] / distance[i]);
calcAccNorm[i] = fabs(acc[i] / distance[i]);
calcDecNorm[i] = fabs(dec[i] / distance[i]);
}
// find minimum
velNorm = calcVelNorm[0]; accNorm = calcAccNorm[0]; decNorm = calcDecNorm[0];
for (unsigned int i = 0; i < calcVelNorm.size(); i++) {
if (calcVelNorm[i] < velNorm) velNorm = calcVelNorm[i];
if (calcAccNorm[i] < accNorm) accNorm = calcAccNorm[i];
if (calcDecNorm[i] < decNorm) decNorm = calcDecNorm[i];
}
// determine if maximum velocity can be reached, else limit it
E velNormMax = sqrt(2 * (accNorm * decNorm) / (accNorm + decNorm));
if (velNorm > velNormMax) velNorm = velNormMax;
// calculate time intervals
dT1 = velNorm / accNorm;
dT3 = velNorm / decNorm;
dT2 = 1 / velNorm - (dT1 + dT3) * 0.5;
if (dT2 < 0) dT2 = 0;
// make time intervals multiple of sampling time
dT1 = ceil(dT1 / dt) * dt;
dT2 = ceil(dT2 / dt) * dt;
dT3 = ceil(dT3 / dt) * dt;
// log.info() << "dT1 = " << dT1 << ", dT2 = " << dT2 << ", dT3 = " << dT3;
// recalculate velocity with definitive time interval values
velNorm = 1 / ((dT2 + (dT1 + dT3) / 2));
// log.info() << "vel norm = " << velNorm;
T vel = velNorm * distance;
c1a = vel / dT1;
b1v = c1a;
a1p = 0.5 * c1a;
c1p = start[0];
c2a = 0;
c2v = vel;
b2p = c2v;
c2p = a1p * pow(dT1,2) + c1p;
c3a = -vel / dT3;
b3v = c3a;
c3v = vel;
a3p = 0.5 * c3a;
b3p = c3v;
c3p = b2p * dT2 + c2p;
std::lock_guard<std::mutex> lck(mtx);
finished = false;
range = 1;
t = 0;
return true;
}
using TrajectoryGenerator<T, 3>::setStart;
/**
* Sets the start position and state of the higher derivatives (velocity, acceleration ...)
*
* @param start - array containing start position and its higher derivatives
*/
virtual void setStart(std::array<T, 3> start) {
std::lock_guard<std::mutex> lck(mtx);
this->last = start;
this->finished = true;
}
/**
* Sets the maximum value for the velocity. The maximum velocity during the steady phase of the trajectory.
*
* @param vel - maximum velocity
*/
virtual void setMaxSpeed(T vel) {velMax = vel;}
/**
* Sets the value for the acceleration. The acceleration is used for the start of the trajectory.
*
* @param acc - acceleration
*/
virtual void setMaxAcc(T acc) {this->acc = acc;}
/**
* Sets the value for the deceleration. The deceleration is used for the end of the trajectory.
*
* @param dec - deceleration
*/
virtual void setMaxDec(T dec) {this->dec = dec;}
/**
* Getter function for the position output.
*
* @return The position output
*/
virtual Output<T>& getPosOut() {return posOut;}
/**
* Getter function for the velocity output.
*
* @return The velocity output
*/
virtual Output<T>& getVelOut() {return velOut;}
/**
* Getter function for the acceleration output.
*
* @return The acceleration output
*/
virtual Output<T>& getAccOut() {return accOut;}
private:
Output<T> posOut, velOut, accOut;
bool finished;
int range;
T velMax, acc, dec;
double t, dt, dT1, dT2, dT3;
// naming of coefficients: a|b|c & 1|2|3 & a|v|p
// a|b|c : a for t*t factor, b for linear factor, c for constant
// 1|2|3 : one of the three parts on the time axis
// a|v|p : result will be a for acc, v for vel, p for position
// e.g. a1p -> coeffizient for time intervall 1, used to multiply with t^2 resulting in the position
T a1p, c1p, b1v, c1a, b2p, c2p, c2v, c2a, a3p, b3p, c3p, b3v, c3v, c3a;
T endPos;
std::mutex mtx;
};
/**
* Operator overload (<<) to enable an easy way to print the state of a
* PathPlannerConstAcc instance to an output stream.\n
* Does not print a newline control character.
*/
template<typename T>
std::ostream &operator<<(std::ostream &os, PathPlannerConstAcc<T> &pp) {
os << "Block path planner constant acceleration: '" << pp.getName() << "'";
return os;
}
};
};
#endif /* ORG_EEROS_CONTROL_PATHPLANNERCONSTACC_HPP_ */
<commit_msg>Correct path planning<commit_after>#ifndef ORG_EEROS_CONTROL_PATHPLANNERCONSTACC_HPP_
#define ORG_EEROS_CONTROL_PATHPLANNERCONSTACC_HPP_
#include <eeros/control/Output.hpp>
#include <eeros/control/TrajectoryGenerator.hpp>
#include <eeros/core/System.hpp>
#include <cmath>
#include <mutex>
namespace eeros {
namespace control {
/**
* This path planner with constant acceleration generates a trajectory as follows.
* The trajectory leads from the start position to its end position. The acceleration is
* set to a positive constant value. The velocity starts from 0 and goes up to its maximum value
* which can be chosen. After this maximum velocity is reached the acceleration is set to 0 and
* the trajectory continues with constant velocity. Towards the end a constant deceleration
* makes sure that the final position is reached with the velocity reaching 0.
*
* @tparam T - output type (must be a composite type),
* a trajectory in 3-dimensional space needs T = Matrix<3,1,double>,
* a trajectory in linear space needs T = Matrix<1,1,double>
*
* @since v1.0
*/
template<typename T>
class PathPlannerConstAcc : public TrajectoryGenerator<T, 3> {
using E = typename T::value_type;
public:
/**
* Constructs a path planner with a trajectory where the acceleration is always constant.
* The trajectory will start with an constant acceleration (will not be higher than accMax).
* As soon as velMax is reached, the acceleration will be 0 and the velocity will stay constant
* (will not be higher than velMax). For the third part the trajectory will stop with a
* constant deceleration (will not be higher decMax).
* The sampling time must be set to the time with which the timedomain containing this block will run.
*
* @param velMax - maximum velocity
* @param acc - maximum acceleration
* @param dec - maximum deceleration
* @param dt - sampling time
*/
PathPlannerConstAcc(T velMax, T acc, T dec, double dt)
: finished(true), velMax(velMax), acc(acc), dec(dec), dt(dt) {
posOut.getSignal().clear();
velOut.getSignal().clear();
accOut.getSignal().clear();
}
/**
* Disabling use of copy constructor because the block should never be copied unintentionally.
*/
PathPlannerConstAcc(const PathPlannerConstAcc& s) = delete;
/**
* Query if a requested trajectory has already reached its end position.
*
* @return - end of trajectory is reached
*/
virtual bool endReached() {
std::lock_guard<std::mutex> lck(mtx);
return finished;
}
/**
* Runs the path planner block. With the precalculated values for the
* acceleration for all sampling points on the trajectory, the resulting velocities
* and positions are calculated and written to the appropriate outputs.
*/
virtual void run() {
std::lock_guard<std::mutex> lck(mtx);
std::array<T, 3> y = this->last;
t += dt;
if (!finished) {
for (unsigned int i = 0; i < a1p.size(); i++) {
switch (range) {
case 1:
if (t <= dT1) {
y[0][i] = a1p[i] * pow(t, 2) + c1p[i];
y[1][i] = b1v[i] * t;
y[2][i] = c1a[i];
}
if (fabs(t - dT1) < 1e-12 && i == a1p.size() - 1) {
range = 2;
t = 0;
}
break;
case 2:
if (t <= dT2) {
y[0][i] = b2p[i] * t + c2p[i];
y[1][i] = c2v[i];
y[2][i] = c2a[i];
}
if (dT2 < 1e-12 || (fabs(t - dT2) < 1e-12 && i == a1p.size() - 1)) {
range = 3;
t = 0;
}
break;
case 3:
if (t <= dT3) {
y[0][i] = a3p[i] * pow(t, 2) + b3p[i] * t + c3p[i];
y[1][i] = b3v[i] * t + c3v[i];
y[2][i] = c3a[i];
}
if (fabs(t - dT3) < 1e-12 && i == a1p.size() - 1) {
range = 4;
t = 0;
}
break;
case 4:
finished = true;
y[0][i] = endPos[i];
y[1][i] = 0.0;
y[2][i] = 0.0;
break;
}
// keep last position value
this->last[0][i] = y[0][i];
this->last[1][i] = y[1][i];
this->last[2][i] = y[2][i];
}
}
posOut.getSignal().setValue(y[0]);
velOut.getSignal().setValue(y[1]);
accOut.getSignal().setValue(y[2]);
timestamp_t time = System::getTimeNs();
posOut.getSignal().setTimestamp(time);
velOut.getSignal().setTimestamp(time);
accOut.getSignal().setTimestamp(time);
}
using TrajectoryGenerator<T, 3>::move;
/**
* Dispatches a new trajectory from start to end.
* With both parameters only the first index in the array, that is the position
* will be considered. The higher derivatives won't be taken into account.
* The function will terminate immediately and return false if the last trajectory
* is not finished.
*
* @param start - array containing start position and its higher derivatives
* @param end - array containing end position and its higher derivatives
* @return - a trajectory could be sucessfully generated for this parameters
*
* @see setStart()
* @see run()
*/
virtual bool move(std::array<T, 3> start, std::array<T, 3> end) {
if (!finished) return false;
T calcVelNorm, calcAccNorm, calcDecNorm;
E velNorm, accNorm, decNorm;
T distance = end[0] - start[0];
endPos = end[0];
T zero; zero = 0;
if (distance == zero) return false;
// normalize
for (unsigned int i = 0; i < calcVelNorm.size(); i++) {
calcVelNorm[i] = fabs(velMax[i] / distance[i]);
calcAccNorm[i] = fabs(acc[i] / distance[i]);
calcDecNorm[i] = fabs(dec[i] / distance[i]);
}
// find minimum
velNorm = calcVelNorm[0]; accNorm = calcAccNorm[0]; decNorm = calcDecNorm[0];
for (unsigned int i = 0; i < calcVelNorm.size(); i++) {
if (calcVelNorm[i] < velNorm) velNorm = calcVelNorm[i];
if (calcAccNorm[i] < accNorm) accNorm = calcAccNorm[i];
if (calcDecNorm[i] < decNorm) decNorm = calcDecNorm[i];
}
// determine if maximum velocity can be reached, else limit it
E velNormMax = sqrt(2 * (accNorm * decNorm) / (accNorm + decNorm));
if (velNorm > velNormMax) velNorm = velNormMax;
// calculate time intervals
dT1 = velNorm / accNorm;
dT3 = velNorm / decNorm;
dT2 = 1 / velNorm - (dT1 + dT3) * 0.5;
if (dT2 < 0) dT2 = 0;
// make time intervals multiple of sampling time
dT1 = ceil(dT1 / dt) * dt;
dT2 = ceil(dT2 / dt) * dt;
dT3 = ceil(dT3 / dt) * dt;
// log.info() << "dT1 = " << dT1 << ", dT2 = " << dT2 << ", dT3 = " << dT3;
// recalculate velocity with definitive time interval values
velNorm = 1 / ((dT2 + (dT1 + dT3) / 2));
// log.info() << "vel norm = " << velNorm;
T vel = velNorm * distance;
c1a = vel / dT1;
b1v = c1a;
a1p = 0.5 * c1a;
c1p = start[0];
c2a = 0;
c2v = vel;
b2p = c2v;
c2p = a1p * pow(dT1,2) + c1p;
c3a = -vel / dT3;
b3v = c3a;
c3v = vel;
a3p = 0.5 * c3a;
b3p = c3v;
c3p = b2p * dT2 + c2p;
std::lock_guard<std::mutex> lck(mtx);
finished = false;
range = 1;
t = 0;
return true;
}
using TrajectoryGenerator<T, 3>::setStart;
/**
* Sets the start position and state of the higher derivatives (velocity, acceleration ...)
*
* @param start - array containing start position and its higher derivatives
*/
virtual void setStart(std::array<T, 3> start) {
std::lock_guard<std::mutex> lck(mtx);
this->last = start;
this->finished = true;
}
/**
* Sets the maximum value for the velocity. The maximum velocity during the steady phase of the trajectory.
*
* @param vel - maximum velocity
*/
virtual void setMaxSpeed(T vel) {velMax = vel;}
/**
* Sets the value for the acceleration. The acceleration is used for the start of the trajectory.
*
* @param acc - acceleration
*/
virtual void setMaxAcc(T acc) {this->acc = acc;}
/**
* Sets the value for the deceleration. The deceleration is used for the end of the trajectory.
*
* @param dec - deceleration
*/
virtual void setMaxDec(T dec) {this->dec = dec;}
/**
* Getter function for the position output.
*
* @return The position output
*/
virtual Output<T>& getPosOut() {return posOut;}
/**
* Getter function for the velocity output.
*
* @return The velocity output
*/
virtual Output<T>& getVelOut() {return velOut;}
/**
* Getter function for the acceleration output.
*
* @return The acceleration output
*/
virtual Output<T>& getAccOut() {return accOut;}
private:
Output<T> posOut, velOut, accOut;
bool finished;
int range;
T velMax, acc, dec;
double t, dt, dT1, dT2, dT3;
// naming of coefficients: a|b|c & 1|2|3 & a|v|p
// a|b|c : a for t*t factor, b for linear factor, c for constant
// 1|2|3 : one of the three parts on the time axis
// a|v|p : result will be a for acc, v for vel, p for position
// e.g. a1p -> coeffizient for time intervall 1, used to multiply with t^2 resulting in the position
T a1p, c1p, b1v, c1a, b2p, c2p, c2v, c2a, a3p, b3p, c3p, b3v, c3v, c3a;
T endPos;
std::mutex mtx;
};
/**
* Operator overload (<<) to enable an easy way to print the state of a
* PathPlannerConstAcc instance to an output stream.\n
* Does not print a newline control character.
*/
template<typename T>
std::ostream &operator<<(std::ostream &os, PathPlannerConstAcc<T> &pp) {
os << "Block path planner constant acceleration: '" << pp.getName() << "'";
return os;
}
};
};
#endif /* ORG_EEROS_CONTROL_PATHPLANNERCONSTACC_HPP_ */
<|endoftext|>
|
<commit_before>/*=========================================================================
Program: Visualization Toolkit
Module: TestVtkLineChartView.cxx
Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
All rights reserved.
See Copyright.txt or http://www.kitware.com/Copyright.htm for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notice for more information.
=========================================================================*/
/*-------------------------------------------------------------------------
Copyright 2008 Sandia Corporation.
Under the terms of Contract DE-AC04-94AL85000 with Sandia Corporation,
the U.S. Government retains certain rights in this software.
-------------------------------------------------------------------------*/
#include "vtkQtLineChartView.h"
#include "vtkQtChartTableRepresentation.h"
#include "vtkQtTableView.h"
#include "vtkSphereSource.h"
#include "vtkDataObjectToTable.h"
#include "vtkTable.h"
#include "vtkSmartPointer.h"
#include "QTestApp.h"
#include <QWidget>
#define VTK_CREATE(type, name) \
vtkSmartPointer<type> name = vtkSmartPointer<type>::New()
int TestVtkLineChartView(int argc, char* argv[])
{
QTestApp app(argc, argv);
// Create a sphere and create a vtkTable from its point data (normal vectors)
VTK_CREATE(vtkSphereSource, sphereSource);
VTK_CREATE(vtkDataObjectToTable, tableConverter);
tableConverter->SetInput(sphereSource->GetOutput());
tableConverter->SetFieldType(vtkDataObjectToTable::POINT_DATA);
tableConverter->Update();
vtkTable* pointTable = tableConverter->GetOutput();
// Create a line chart view
vtkSmartPointer<vtkQtLineChartView> chartView =
vtkSmartPointer<vtkQtLineChartView>::New();
chartView->SetupDefaultInteractor();
// Set the chart title
chartView->SetTitle("Sphere Normals");
// Add the table to the view
vtkDataRepresentation* dataRep = chartView->AddRepresentationFromInput(pointTable);
// You can downcast to get the chart representation:
vtkQtChartTableRepresentation* chartRep =
vtkQtChartTableRepresentation::SafeDownCast(dataRep);
if (!chartRep)
{
cerr << "Failed to get chart table representation." << endl;
return 1;
}
// TODO-
// The user shouldn't be required to call Update().
// The view should handle updates automatically.
chartView->Update();
// Show the view's qt widget
chartView->Show();
// Show the table in a vtkQtTableView
VTK_CREATE(vtkQtTableView, tableView);
tableView->AddRepresentationFromInput(pointTable);
tableView->SetSplitMultiComponentColumns(true);
tableView->Update();
tableView->GetWidget()->show();
// Start the Qt event loop to run the application
int status = app.exec();
return status;
}
<commit_msg>ENH: Change call order in TestVtkLineChartView.cxx to prevent warnings from being printed.<commit_after>/*=========================================================================
Program: Visualization Toolkit
Module: TestVtkLineChartView.cxx
Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
All rights reserved.
See Copyright.txt or http://www.kitware.com/Copyright.htm for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notice for more information.
=========================================================================*/
/*-------------------------------------------------------------------------
Copyright 2008 Sandia Corporation.
Under the terms of Contract DE-AC04-94AL85000 with Sandia Corporation,
the U.S. Government retains certain rights in this software.
-------------------------------------------------------------------------*/
#include "vtkQtLineChartView.h"
#include "vtkQtChartTableRepresentation.h"
#include "vtkQtTableView.h"
#include "vtkSphereSource.h"
#include "vtkDataObjectToTable.h"
#include "vtkTable.h"
#include "vtkSmartPointer.h"
#include "QTestApp.h"
#include <QWidget>
#define VTK_CREATE(type, name) \
vtkSmartPointer<type> name = vtkSmartPointer<type>::New()
int TestVtkLineChartView(int argc, char* argv[])
{
QTestApp app(argc, argv);
// Create a sphere and create a vtkTable from its point data (normal vectors)
VTK_CREATE(vtkSphereSource, sphereSource);
VTK_CREATE(vtkDataObjectToTable, tableConverter);
tableConverter->SetInput(sphereSource->GetOutput());
tableConverter->SetFieldType(vtkDataObjectToTable::POINT_DATA);
tableConverter->Update();
vtkTable* pointTable = tableConverter->GetOutput();
// Create a line chart view
vtkSmartPointer<vtkQtLineChartView> chartView =
vtkSmartPointer<vtkQtLineChartView>::New();
chartView->SetupDefaultInteractor();
// Set the chart title
chartView->SetTitle("Sphere Normals");
// Add the table to the view
vtkDataRepresentation* dataRep = chartView->AddRepresentationFromInput(pointTable);
// You can downcast to get the chart representation:
vtkQtChartTableRepresentation* chartRep =
vtkQtChartTableRepresentation::SafeDownCast(dataRep);
if (!chartRep)
{
cerr << "Failed to get chart table representation." << endl;
return 1;
}
// TODO-
// The user shouldn't be required to call Update().
// The view should handle updates automatically.
chartView->Update();
// Show the view's qt widget
chartView->Show();
// Show the table in a vtkQtTableView
VTK_CREATE(vtkQtTableView, tableView);
tableView->SetSplitMultiComponentColumns(true);
tableView->AddRepresentationFromInput(pointTable);
tableView->Update();
tableView->GetWidget()->show();
// Start the Qt event loop to run the application
int status = app.exec();
return status;
}
<|endoftext|>
|
<commit_before>/**
* Copyright (c) 2016 zScale Technology GmbH <legal@zscale.io>
* Authors:
* - Paul Asmuth <paul@zscale.io>
* - Laura Schlimmer <laura@zscale.io>
*
* This program is free software: you can redistribute it and/or modify it under
* the terms of the GNU Affero General Public License ("the license") as
* published by the Free Software Foundation, either version 3 of the License,
* or any later version.
*
* In accordance with Section 7(e) of the license, the licensing of the Program
* under the license does not imply a trademark license. Therefore any rights,
* title and interest in our trademarks remain entirely with us.
*
* 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 license for more details.
*
* You can be released from the requirements of the license by purchasing a
* commercial license. Buying such a license is mandatory as soon as you develop
* commercial activities involving this program without disclosing the source
* code of your own applications
*/
#include <eventql/eventql.h>
#include <eventql/util/stdtypes.h>
#include <eventql/util/application.h>
#include <eventql/util/cli/flagparser.h>
#include <eventql/util/csv/BinaryCSVOutputStream.h>
#include <eventql/util/http/httpclient.h>
#include <eventql/util/json/jsonoutputstream.h>
#include "eventql/util/thread/FixedSizeThreadPool.h"
#include "eventql/util/util/SimpleRateLimit.h"
#include <eventql/util/mysql/MySQL.h>
#include <eventql/util/mysql/MySQLConnection.h>
using namespace eventql;
struct UploadShard {
Buffer data;
size_t nrows;
};
static const size_t kMaxRetries = 5;
bool run(const cli::FlagParser& flags) {
auto source_table = flags.getString("source_table");
auto destination_table = flags.getString("destination_table");
auto shard_size = flags.getInt("shard_size");
auto num_upload_threads = flags.getInt("upload_threads");
auto mysql_addr = flags.getString("mysql");
auto host = flags.getString("host");
auto port = flags.getInt("port");
auto db = flags.getString("database");
logInfo("mysql2evql", "Connecting to MySQL Server...");
util::mysql::mysqlInit();
auto mysql_conn = util::mysql::MySQLConnection::openConnection(URI(mysql_addr));
logInfo(
"mysql2evql",
"Analyzing the input table. This might take a few minutes...");
auto schema = mysql_conn->getTableSchema(source_table);
logDebug("mysql2evql", "Table Schema:\n$0", schema->toString());
Vector<String> column_names;
for (const auto& field : schema->fields()) {
column_names.emplace_back(field.name);
}
/* status line */
std::atomic<size_t> num_rows_uploaded(0);
util::SimpleRateLimitedFn status_line(kMicrosPerSecond, [&] () {
logInfo(
"mysql2evql",
"Uploading... $0 rows",
num_rows_uploaded.load());
});
/* start upload threads */
http::HTTPMessage::HeaderList auth_headers;
if (flags.isSet("auth_token")) {
auth_headers.emplace_back(
"Authorization",
StringUtil::format("Token $0", flags.getString("auth_token")));
//} else if (!cfg_.getPassword().isEmpty()) {
// auth_headers.emplace_back(
// "Authorization",
// StringUtil::format("Basic $0",
// util::Base64::encode(
// cfg_.getUser() + ":" + cfg_.getPassword().get())));
}
auto insert_uri = StringUtil::format(
"http://$0:$1/api/v1/tables/insert",
host,
port);
bool upload_done = false;
bool upload_error = false;
thread::Queue<UploadShard> upload_queue(1);
Vector<std::thread> upload_threads(num_upload_threads);
for (size_t i = 0; i < num_upload_threads; ++i) {
upload_threads[i] = std::thread([&] {
while (!upload_done) {
auto shard = upload_queue.interruptiblePop();
if (shard.isEmpty()) {
continue;
}
auto retry = 0;
size_t status_code;
for (; ;) {
iputs("uploading with retries, retry $0", retry);
logDebug(
"mysql2evql",
"Uploading batch; target=$0:$1 size=$2MB",
host,
port,
shard.get().data.size() / 1000000.0);
try {
http::HTTPClient http_client;
auto upload_res = http_client.executeRequest(
http::HTTPRequest::mkPost(
insert_uri,
"[" + shard.get().data.toString() + "]",
auth_headers));
if (upload_res.statusCode() != 201) {
status_code = upload_res.statusCode();
logError(
"mysql2evql", "[FATAL ERROR]: HTTP Status Code $0 $1",
upload_res.statusCode(),
upload_res.body().toString());
RAISE(kRuntimeError, upload_res.body().toString());
}
num_rows_uploaded += shard.get().nrows;
status_line.runMaybe();
break;
} catch (const std::exception& e) {
logError("mysql2evql", e, "error while uploading table data");
/* retry upload kMaxRetries times unless an authentication failure occurs */
if (++retry < kMaxRetries && status_code != 403) {
auto base_wait = 2;
auto increased_wait = base_wait * (pow(base_wait, retry));
sleep(increased_wait);
continue;
} else {
upload_error = true;
break;
}
}
}
}
});
}
/* fetch rows from mysql */
UploadShard shard;
shard.nrows = 0;
json::JSONOutputStream json(BufferOutputStream::fromBuffer(&shard.data));
String where_expr;
if (flags.isSet("filter")) {
where_expr = "WHERE " + flags.getString("filter");
}
auto get_rows_qry = StringUtil::format(
"SELECT * FROM `$0` $1;",
source_table,
where_expr);
mysql_conn->executeQuery(
get_rows_qry,
[&] (const Vector<String>& column_values) -> bool {
++shard.nrows;
if (shard.nrows > 1) {
json.addComma();
}
json.beginObject();
json.addObjectEntry("database");
json.addString(db);
json.addComma();
json.addObjectEntry("table");
json.addString(destination_table);
json.addComma();
json.addObjectEntry("data");
json.beginObject();
for (size_t i = 0; i < column_names.size() && i < column_values.size(); ++i) {
if (i > 0 ){
json.addComma();
}
json.addObjectEntry(column_names[i]);
json.addString(column_values[i]);
}
json.endObject();
json.endObject();
if (shard.nrows == shard_size) {
upload_queue.insert(shard, true);
shard.data.clear();
shard.nrows = 0;
}
status_line.runMaybe();
return true;
});
if (shard.nrows > 0) {
upload_queue.insert(shard, true);
}
upload_queue.waitUntilEmpty();
upload_done = true;
upload_queue.wakeup();
for (auto& t : upload_threads) {
t.join();
}
status_line.runForce();
if (upload_error) {
logInfo("mysql2evql", "Upload finished with errors");
return false;
} else {
logInfo("mysql2evql", "Upload finished successfully :)");
return true;
}
}
int main(int argc, const char** argv) {
Application::init();
Application::logToStderr("mysql2evql");
cli::FlagParser flags;
flags.defineFlag(
"loglevel",
cli::FlagParser::T_STRING,
false,
NULL,
"INFO",
"loglevel",
"<level>");
flags.defineFlag(
"source_table",
cli::FlagParser::T_STRING,
true,
"t",
NULL,
"table name",
"<name>");
flags.defineFlag(
"destination_table",
cli::FlagParser::T_STRING,
true,
"t",
NULL,
"table name",
"<name>");
flags.defineFlag(
"host",
cli::FlagParser::T_STRING,
true,
"h",
NULL,
"eventql server hostname",
"<host>");
flags.defineFlag(
"port",
cli::FlagParser::T_INTEGER,
true,
"p",
NULL,
"eventql server port",
"<port>");
flags.defineFlag(
"database",
cli::FlagParser::T_STRING,
true,
"db",
"",
"eventql database",
"<database>");
flags.defineFlag(
"auth_token",
cli::FlagParser::T_STRING,
false,
NULL,
NULL,
"auth token",
"<token>");
flags.defineFlag(
"mysql",
cli::FlagParser::T_STRING,
true,
"x",
"mysql://localhost:3306/mydb?user=root",
"MySQL connection string",
"<url>");
flags.defineFlag(
"filter",
cli::FlagParser::T_STRING,
false,
NULL,
NULL,
"boolean sql expression",
"<sql_expr>");
flags.defineFlag(
"shard_size",
cli::FlagParser::T_INTEGER,
false,
NULL,
"128",
"shard size",
"<num>");
flags.defineFlag(
"upload_threads",
cli::FlagParser::T_INTEGER,
false,
NULL,
"8",
"concurrent uploads",
"<num>");
try {
flags.parseArgv(argc, argv);
} catch (const StandardException& e) {
logError("mysql2evql", "$0", e.what());
auto stdout_os = OutputStream::getStdout();
flags.printUsage(stdout_os.get());
return 0;
}
Logger::get()->setMinimumLogLevel(
strToLogLevel(flags.getString("loglevel")));
try {
if (run(flags)) {
return 0;
} else {
return 1;
}
} catch (const StandardException& e) {
logFatal("mysql2evql", "$0", e.what());
return 1;
}
}
<commit_msg>mysql2evql: configurable num of max retries<commit_after>/**
* Copyright (c) 2016 zScale Technology GmbH <legal@zscale.io>
* Authors:
* - Paul Asmuth <paul@zscale.io>
* - Laura Schlimmer <laura@zscale.io>
*
* This program is free software: you can redistribute it and/or modify it under
* the terms of the GNU Affero General Public License ("the license") as
* published by the Free Software Foundation, either version 3 of the License,
* or any later version.
*
* In accordance with Section 7(e) of the license, the licensing of the Program
* under the license does not imply a trademark license. Therefore any rights,
* title and interest in our trademarks remain entirely with us.
*
* 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 license for more details.
*
* You can be released from the requirements of the license by purchasing a
* commercial license. Buying such a license is mandatory as soon as you develop
* commercial activities involving this program without disclosing the source
* code of your own applications
*/
#include <eventql/eventql.h>
#include <eventql/util/stdtypes.h>
#include <eventql/util/application.h>
#include <eventql/util/cli/flagparser.h>
#include <eventql/util/csv/BinaryCSVOutputStream.h>
#include <eventql/util/http/httpclient.h>
#include <eventql/util/json/jsonoutputstream.h>
#include "eventql/util/thread/FixedSizeThreadPool.h"
#include "eventql/util/util/SimpleRateLimit.h"
#include <eventql/util/mysql/MySQL.h>
#include <eventql/util/mysql/MySQLConnection.h>
using namespace eventql;
struct UploadShard {
Buffer data;
size_t nrows;
};
bool run(const cli::FlagParser& flags) {
auto source_table = flags.getString("source_table");
auto destination_table = flags.getString("destination_table");
auto shard_size = flags.getInt("shard_size");
auto num_upload_threads = flags.getInt("upload_threads");
auto mysql_addr = flags.getString("mysql");
auto host = flags.getString("host");
auto port = flags.getInt("port");
auto db = flags.getString("database");
auto max_retries = flags.getInt("max_retries");
logInfo("mysql2evql", "Connecting to MySQL Server...");
util::mysql::mysqlInit();
auto mysql_conn = util::mysql::MySQLConnection::openConnection(URI(mysql_addr));
logInfo(
"mysql2evql",
"Analyzing the input table. This might take a few minutes...");
auto schema = mysql_conn->getTableSchema(source_table);
logDebug("mysql2evql", "Table Schema:\n$0", schema->toString());
Vector<String> column_names;
for (const auto& field : schema->fields()) {
column_names.emplace_back(field.name);
}
/* status line */
std::atomic<size_t> num_rows_uploaded(0);
util::SimpleRateLimitedFn status_line(kMicrosPerSecond, [&] () {
logInfo(
"mysql2evql",
"Uploading... $0 rows",
num_rows_uploaded.load());
});
/* start upload threads */
http::HTTPMessage::HeaderList auth_headers;
if (flags.isSet("auth_token")) {
auth_headers.emplace_back(
"Authorization",
StringUtil::format("Token $0", flags.getString("auth_token")));
//} else if (!cfg_.getPassword().isEmpty()) {
// auth_headers.emplace_back(
// "Authorization",
// StringUtil::format("Basic $0",
// util::Base64::encode(
// cfg_.getUser() + ":" + cfg_.getPassword().get())));
}
auto insert_uri = StringUtil::format(
"http://$0:$1/api/v1/tables/insert",
host,
port);
bool upload_done = false;
bool upload_error = false;
thread::Queue<UploadShard> upload_queue(1);
Vector<std::thread> upload_threads(num_upload_threads);
for (size_t i = 0; i < num_upload_threads; ++i) {
upload_threads[i] = std::thread([&] {
while (!upload_done) {
auto shard = upload_queue.interruptiblePop();
if (shard.isEmpty()) {
continue;
}
auto retry = 0;
size_t status_code;
for (; ;) {
iputs("uploading with retries, retry $0", retry);
logDebug(
"mysql2evql",
"Uploading batch; target=$0:$1 size=$2MB",
host,
port,
shard.get().data.size() / 1000000.0);
try {
http::HTTPClient http_client;
auto upload_res = http_client.executeRequest(
http::HTTPRequest::mkPost(
insert_uri,
"[" + shard.get().data.toString() + "]",
auth_headers));
if (upload_res.statusCode() != 201) {
status_code = upload_res.statusCode();
logError(
"mysql2evql", "[FATAL ERROR]: HTTP Status Code $0 $1",
upload_res.statusCode(),
upload_res.body().toString());
RAISE(kRuntimeError, upload_res.body().toString());
}
num_rows_uploaded += shard.get().nrows;
status_line.runMaybe();
break;
} catch (const std::exception& e) {
logError("mysql2evql", e, "error while uploading table data");
/* retry upload kMaxRetries times unless an authentication failure occurs */
if (++retry < max_retries && status_code != 403) {
auto base_wait = 2;
auto increased_wait = base_wait * (pow(base_wait, retry));
sleep(increased_wait);
continue;
} else {
upload_error = true;
break;
}
}
}
}
});
}
/* fetch rows from mysql */
UploadShard shard;
shard.nrows = 0;
json::JSONOutputStream json(BufferOutputStream::fromBuffer(&shard.data));
String where_expr;
if (flags.isSet("filter")) {
where_expr = "WHERE " + flags.getString("filter");
}
auto get_rows_qry = StringUtil::format(
"SELECT * FROM `$0` $1;",
source_table,
where_expr);
mysql_conn->executeQuery(
get_rows_qry,
[&] (const Vector<String>& column_values) -> bool {
++shard.nrows;
if (shard.nrows > 1) {
json.addComma();
}
json.beginObject();
json.addObjectEntry("database");
json.addString(db);
json.addComma();
json.addObjectEntry("table");
json.addString(destination_table);
json.addComma();
json.addObjectEntry("data");
json.beginObject();
for (size_t i = 0; i < column_names.size() && i < column_values.size(); ++i) {
if (i > 0 ){
json.addComma();
}
json.addObjectEntry(column_names[i]);
json.addString(column_values[i]);
}
json.endObject();
json.endObject();
if (shard.nrows == shard_size) {
upload_queue.insert(shard, true);
shard.data.clear();
shard.nrows = 0;
}
status_line.runMaybe();
return true;
});
if (shard.nrows > 0) {
upload_queue.insert(shard, true);
}
upload_queue.waitUntilEmpty();
upload_done = true;
upload_queue.wakeup();
for (auto& t : upload_threads) {
t.join();
}
status_line.runForce();
if (upload_error) {
logInfo("mysql2evql", "Upload finished with errors");
return false;
} else {
logInfo("mysql2evql", "Upload finished successfully :)");
return true;
}
}
int main(int argc, const char** argv) {
Application::init();
Application::logToStderr("mysql2evql");
cli::FlagParser flags;
flags.defineFlag(
"loglevel",
cli::FlagParser::T_STRING,
false,
NULL,
"INFO",
"loglevel",
"<level>");
flags.defineFlag(
"source_table",
cli::FlagParser::T_STRING,
true,
"t",
NULL,
"table name",
"<name>");
flags.defineFlag(
"destination_table",
cli::FlagParser::T_STRING,
true,
"t",
NULL,
"table name",
"<name>");
flags.defineFlag(
"host",
cli::FlagParser::T_STRING,
true,
"h",
NULL,
"eventql server hostname",
"<host>");
flags.defineFlag(
"port",
cli::FlagParser::T_INTEGER,
true,
"p",
NULL,
"eventql server port",
"<port>");
flags.defineFlag(
"database",
cli::FlagParser::T_STRING,
true,
"db",
"",
"eventql database",
"<database>");
flags.defineFlag(
"auth_token",
cli::FlagParser::T_STRING,
false,
NULL,
NULL,
"auth token",
"<token>");
flags.defineFlag(
"mysql",
cli::FlagParser::T_STRING,
true,
"x",
"mysql://localhost:3306/mydb?user=root",
"MySQL connection string",
"<url>");
flags.defineFlag(
"filter",
cli::FlagParser::T_STRING,
false,
NULL,
NULL,
"boolean sql expression",
"<sql_expr>");
flags.defineFlag(
"shard_size",
cli::FlagParser::T_INTEGER,
false,
NULL,
"128",
"shard size",
"<num>");
flags.defineFlag(
"upload_threads",
cli::FlagParser::T_INTEGER,
false,
NULL,
"8",
"concurrent uploads",
"<num>");
flags.defineFlag(
"max_retries",
cli::FlagParser::T_INTEGER,
false,
NULL,
"20",
"max number of upload retries",
"<num>");
try {
flags.parseArgv(argc, argv);
} catch (const StandardException& e) {
logError("mysql2evql", "$0", e.what());
auto stdout_os = OutputStream::getStdout();
flags.printUsage(stdout_os.get());
return 0;
}
Logger::get()->setMinimumLogLevel(
strToLogLevel(flags.getString("loglevel")));
try {
if (run(flags)) {
return 0;
} else {
return 1;
}
} catch (const StandardException& e) {
logFatal("mysql2evql", "$0", e.what());
return 1;
}
}
<|endoftext|>
|
<commit_before>#include "k/scheduler.h"
#include "etl/armv7m/exception_table.h"
#include "etl/armv7m/instructions.h"
#include "k/context.h"
#include "k/list.h"
namespace k {
Context * current;
List<Context> runnable;
static bool switch_pending;
void pend_switch() {
switch_pending = true;
}
void do_deferred_switch() {
if (!switch_pending) return;
switch_pending = false;
while (runnable.is_empty()) {
etl::armv7m::wait_for_interrupt();
}
current = runnable.peek().ref()->owner;
}
} // namespace k
<commit_msg>k/scheduler: don't idle in kernel mode.<commit_after>#include "k/scheduler.h"
#include "etl/armv7m/exception_table.h"
#include "etl/armv7m/instructions.h"
#include "k/context.h"
#include "k/list.h"
namespace k {
Context * current;
List<Context> runnable;
static bool switch_pending;
void pend_switch() {
switch_pending = true;
}
void do_deferred_switch() {
if (!switch_pending) return;
switch_pending = false;
// TODO: we ought to turn on strict Maybe checking in the kernel.
auto head = runnable.peek();
ETL_ASSERT(head);
current = head.ref()->owner;
}
} // namespace k
<|endoftext|>
|
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: io.cxx,v $
*
* $Revision: 1.8 $
*
* last change: $Author: obo $ $Date: 2006-09-17 10:02:36 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_basic.hxx"
#ifndef _STREAM_HXX //autogen
#include <tools/stream.hxx>
#endif
#include "sbcomp.hxx"
#include "iosys.hxx"
// Test, ob ein I/O-Channel angegeben wurde
BOOL SbiParser::Channel( BOOL bAlways )
{
BOOL bRes = FALSE;
Peek();
if( IsHash() )
{
SbiExpression aExpr( this );
while( Peek() == COMMA || Peek() == SEMICOLON )
Next();
aExpr.Gen();
aGen.Gen( _CHANNEL );
bRes = TRUE;
}
else if( bAlways )
Error( SbERR_EXPECTED, "#" );
return bRes;
}
// Fuer PRINT und WRITE wird bei Objektvariablen versucht,
// die Default-Property anzusprechen.
// PRINT
void SbiParser::Print()
{
BOOL bChan = Channel();
// Die Ausdruecke zum Drucken:
while( !bAbort )
{
if( !IsEoln( Peek() ) )
{
SbiExpression* pExpr = new SbiExpression( this );
pExpr->Gen();
delete pExpr;
Peek();
aGen.Gen( eCurTok == COMMA ? _PRINTF : _BPRINT );
}
if( eCurTok == COMMA || eCurTok == SEMICOLON )
{
Next();
if( IsEoln( Peek() ) ) break;
}
else
{
aGen.Gen( _PRCHAR, '\n' );
break;
}
}
if( bChan )
aGen.Gen( _CHAN0 );
}
// WRITE #chan, expr, ...
void SbiParser::Write()
{
BOOL bChan = Channel();
// Die Ausdruecke zum Drucken:
while( !bAbort )
{
SbiExpression* pExpr = new SbiExpression( this );
pExpr->Gen();
delete pExpr;
aGen.Gen( _BWRITE );
if( Peek() == COMMA )
{
aGen.Gen( _PRCHAR, ',' );
Next();
if( IsEoln( Peek() ) ) break;
}
else
{
aGen.Gen( _PRCHAR, '\n' );
break;
}
}
if( bChan )
aGen.Gen( _CHAN0 );
}
// LINE INPUT [prompt], var$
void SbiParser::LineInput()
{
Channel( TRUE );
// BOOL bChan = Channel( TRUE );
SbiExpression* pExpr = new SbiExpression( this, SbOPERAND );
/* AB 15.1.96: Keinen allgemeinen Ausdruck mehr zulassen
SbiExpression* pExpr = new SbiExpression( this );
if( !pExpr->IsVariable() )
{
SbiToken eTok = Peek();
if( eTok == COMMA || eTok == SEMICOLON ) Next();
else Error( SbERR_EXPECTED, COMMA );
// mit Prompt
if( !bChan )
{
pExpr->Gen();
aGen.Gen( _PROMPT );
}
else
Error( SbERR_VAR_EXPECTED );
delete pExpr;
pExpr = new SbiExpression( this, SbOPERAND );
}
*/
if( !pExpr->IsVariable() )
Error( SbERR_VAR_EXPECTED );
if( pExpr->GetType() != SbxVARIANT && pExpr->GetType() != SbxSTRING )
Error( SbERR_CONVERSION );
pExpr->Gen();
aGen.Gen( _LINPUT );
delete pExpr;
aGen.Gen( _CHAN0 ); // ResetChannel() nicht mehr in StepLINPUT()
}
// INPUT
void SbiParser::Input()
{
aGen.Gen( _RESTART );
Channel( TRUE );
// BOOL bChan = Channel( TRUE );
SbiExpression* pExpr = new SbiExpression( this, SbOPERAND );
/* ALT: Jetzt keinen allgemeinen Ausdruck mehr zulassen
SbiExpression* pExpr = new SbiExpression( this );
...
siehe LineInput
*/
while( !bAbort )
{
if( !pExpr->IsVariable() )
Error( SbERR_VAR_EXPECTED );
pExpr->Gen();
aGen.Gen( _INPUT );
if( Peek() == COMMA )
{
Next();
delete pExpr;
pExpr = new SbiExpression( this, SbOPERAND );
}
else break;
}
delete pExpr;
aGen.Gen( _CHAN0 ); // ResetChannel() nicht mehr in StepINPUT()
}
// OPEN stringexpr FOR mode ACCCESS access mode AS Channel [Len=n]
void SbiParser::Open()
{
SbiExpression aFileName( this );
SbiToken eTok;
TestToken( FOR );
short nMode = 0;
short nFlags = 0;
switch( Next() )
{
case INPUT:
nMode = STREAM_READ; nFlags |= SBSTRM_INPUT; break;
case OUTPUT:
nMode = STREAM_WRITE | STREAM_TRUNC; nFlags |= SBSTRM_OUTPUT; break;
case APPEND:
nMode = STREAM_WRITE; nFlags |= SBSTRM_APPEND; break;
case RANDOM:
nMode = STREAM_READ | STREAM_WRITE; nFlags |= SBSTRM_RANDOM; break;
case BINARY:
nMode = STREAM_READ | STREAM_WRITE; nFlags |= SBSTRM_BINARY; break;
default:
Error( SbERR_SYNTAX );
}
if( Peek() == ACCESS )
{
Next();
eTok = Next();
// #27964# Nur STREAM_READ,STREAM_WRITE-Flags in nMode beeinflussen
nMode &= ~(STREAM_READ | STREAM_WRITE); // loeschen
if( eTok == READ )
{
if( Peek() == WRITE )
{
Next();
nMode |= (STREAM_READ | STREAM_WRITE);
}
else
nMode |= STREAM_READ;
}
else if( eTok == WRITE )
nMode |= STREAM_WRITE;
else
Error( SbERR_SYNTAX );
}
switch( Peek() )
{
#ifdef SHARED
#undef SHARED
#define tmpSHARED
#endif
case SHARED:
Next(); nMode |= STREAM_SHARE_DENYNONE; break;
#ifdef tmpSHARED
#define SHARED
#undef tmpSHARED
#endif
case LOCK:
Next();
eTok = Next();
if( eTok == READ )
{
if( Peek() == WRITE ) Next(), nMode |= STREAM_SHARE_DENYALL;
else nMode |= STREAM_SHARE_DENYREAD;
}
else if( eTok == WRITE )
nMode |= STREAM_SHARE_DENYWRITE;
else
Error( SbERR_SYNTAX );
break;
default: break;
}
TestToken( AS );
// Die Kanalnummer
SbiExpression* pChan = new SbiExpression( this );
if( !pChan )
Error( SbERR_SYNTAX );
SbiExpression* pLen = NULL;
if( Peek() == SYMBOL )
{
Next();
String aLen( aSym );
if( aLen.EqualsIgnoreCaseAscii( "LEN" ) )
{
TestToken( EQ );
pLen = new SbiExpression( this );
}
}
if( !pLen ) pLen = new SbiExpression( this, 128, SbxINTEGER );
// Der Stack fuer den OPEN-Befehl sieht wie folgt aus:
// Blocklaenge
// Kanalnummer
// Dateiname
pLen->Gen();
if( pChan )
pChan->Gen();
aFileName.Gen();
aGen.Gen( _OPEN, nMode, nFlags );
delete pLen;
delete pChan;
}
// NAME file AS file
void SbiParser::Name()
{
SbiExpression aExpr1( this );
TestToken( AS );
SbiExpression aExpr2( this );
aExpr1.Gen();
aExpr2.Gen();
aGen.Gen( _RENAME );
}
// CLOSE [n,...]
void SbiParser::Close()
{
Peek();
if( IsEoln( eCurTok ) )
aGen.Gen( _CLOSE, 0 );
else
for( ;; )
{
if( Channel( TRUE ) )
aGen.Gen( _CLOSE, 1 );
else
break;
if( IsEoln( Peek() ) )
break;
}
}
<commit_msg>INTEGRATION: CWS ab30 (1.7.30); FILE MERGED 2006/10/18 16:21:01 ab 1.7.30.4: #i60132# Fix in SbiParser::Close() 2006/10/18 12:49:40 ab 1.7.30.3: #i60132# Fixed problem found by Linux compiler 2006/10/17 14:52:22 ab 1.7.30.2: RESYNC: (1.7-1.8); FILE MERGED 2006/09/15 12:51:17 ab 1.7.30.1: #i60132# Allow channel without # in close command<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: io.cxx,v $
*
* $Revision: 1.9 $
*
* last change: $Author: vg $ $Date: 2006-11-02 11:02:36 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_basic.hxx"
#ifndef _STREAM_HXX //autogen
#include <tools/stream.hxx>
#endif
#include "sbcomp.hxx"
#include "iosys.hxx"
// Test, ob ein I/O-Channel angegeben wurde
BOOL SbiParser::Channel( BOOL bAlways )
{
BOOL bRes = FALSE;
Peek();
if( IsHash() )
{
SbiExpression aExpr( this );
while( Peek() == COMMA || Peek() == SEMICOLON )
Next();
aExpr.Gen();
aGen.Gen( _CHANNEL );
bRes = TRUE;
}
else if( bAlways )
Error( SbERR_EXPECTED, "#" );
return bRes;
}
// Fuer PRINT und WRITE wird bei Objektvariablen versucht,
// die Default-Property anzusprechen.
// PRINT
void SbiParser::Print()
{
BOOL bChan = Channel();
// Die Ausdruecke zum Drucken:
while( !bAbort )
{
if( !IsEoln( Peek() ) )
{
SbiExpression* pExpr = new SbiExpression( this );
pExpr->Gen();
delete pExpr;
Peek();
aGen.Gen( eCurTok == COMMA ? _PRINTF : _BPRINT );
}
if( eCurTok == COMMA || eCurTok == SEMICOLON )
{
Next();
if( IsEoln( Peek() ) ) break;
}
else
{
aGen.Gen( _PRCHAR, '\n' );
break;
}
}
if( bChan )
aGen.Gen( _CHAN0 );
}
// WRITE #chan, expr, ...
void SbiParser::Write()
{
BOOL bChan = Channel();
// Die Ausdruecke zum Drucken:
while( !bAbort )
{
SbiExpression* pExpr = new SbiExpression( this );
pExpr->Gen();
delete pExpr;
aGen.Gen( _BWRITE );
if( Peek() == COMMA )
{
aGen.Gen( _PRCHAR, ',' );
Next();
if( IsEoln( Peek() ) ) break;
}
else
{
aGen.Gen( _PRCHAR, '\n' );
break;
}
}
if( bChan )
aGen.Gen( _CHAN0 );
}
// LINE INPUT [prompt], var$
void SbiParser::LineInput()
{
Channel( TRUE );
// BOOL bChan = Channel( TRUE );
SbiExpression* pExpr = new SbiExpression( this, SbOPERAND );
/* AB 15.1.96: Keinen allgemeinen Ausdruck mehr zulassen
SbiExpression* pExpr = new SbiExpression( this );
if( !pExpr->IsVariable() )
{
SbiToken eTok = Peek();
if( eTok == COMMA || eTok == SEMICOLON ) Next();
else Error( SbERR_EXPECTED, COMMA );
// mit Prompt
if( !bChan )
{
pExpr->Gen();
aGen.Gen( _PROMPT );
}
else
Error( SbERR_VAR_EXPECTED );
delete pExpr;
pExpr = new SbiExpression( this, SbOPERAND );
}
*/
if( !pExpr->IsVariable() )
Error( SbERR_VAR_EXPECTED );
if( pExpr->GetType() != SbxVARIANT && pExpr->GetType() != SbxSTRING )
Error( SbERR_CONVERSION );
pExpr->Gen();
aGen.Gen( _LINPUT );
delete pExpr;
aGen.Gen( _CHAN0 ); // ResetChannel() nicht mehr in StepLINPUT()
}
// INPUT
void SbiParser::Input()
{
aGen.Gen( _RESTART );
Channel( TRUE );
// BOOL bChan = Channel( TRUE );
SbiExpression* pExpr = new SbiExpression( this, SbOPERAND );
/* ALT: Jetzt keinen allgemeinen Ausdruck mehr zulassen
SbiExpression* pExpr = new SbiExpression( this );
...
siehe LineInput
*/
while( !bAbort )
{
if( !pExpr->IsVariable() )
Error( SbERR_VAR_EXPECTED );
pExpr->Gen();
aGen.Gen( _INPUT );
if( Peek() == COMMA )
{
Next();
delete pExpr;
pExpr = new SbiExpression( this, SbOPERAND );
}
else break;
}
delete pExpr;
aGen.Gen( _CHAN0 ); // ResetChannel() nicht mehr in StepINPUT()
}
// OPEN stringexpr FOR mode ACCCESS access mode AS Channel [Len=n]
void SbiParser::Open()
{
SbiExpression aFileName( this );
SbiToken eTok;
TestToken( FOR );
short nMode = 0;
short nFlags = 0;
switch( Next() )
{
case INPUT:
nMode = STREAM_READ; nFlags |= SBSTRM_INPUT; break;
case OUTPUT:
nMode = STREAM_WRITE | STREAM_TRUNC; nFlags |= SBSTRM_OUTPUT; break;
case APPEND:
nMode = STREAM_WRITE; nFlags |= SBSTRM_APPEND; break;
case RANDOM:
nMode = STREAM_READ | STREAM_WRITE; nFlags |= SBSTRM_RANDOM; break;
case BINARY:
nMode = STREAM_READ | STREAM_WRITE; nFlags |= SBSTRM_BINARY; break;
default:
Error( SbERR_SYNTAX );
}
if( Peek() == ACCESS )
{
Next();
eTok = Next();
// #27964# Nur STREAM_READ,STREAM_WRITE-Flags in nMode beeinflussen
nMode &= ~(STREAM_READ | STREAM_WRITE); // loeschen
if( eTok == READ )
{
if( Peek() == WRITE )
{
Next();
nMode |= (STREAM_READ | STREAM_WRITE);
}
else
nMode |= STREAM_READ;
}
else if( eTok == WRITE )
nMode |= STREAM_WRITE;
else
Error( SbERR_SYNTAX );
}
switch( Peek() )
{
#ifdef SHARED
#undef SHARED
#define tmpSHARED
#endif
case SHARED:
Next(); nMode |= STREAM_SHARE_DENYNONE; break;
#ifdef tmpSHARED
#define SHARED
#undef tmpSHARED
#endif
case LOCK:
Next();
eTok = Next();
if( eTok == READ )
{
if( Peek() == WRITE ) Next(), nMode |= STREAM_SHARE_DENYALL;
else nMode |= STREAM_SHARE_DENYREAD;
}
else if( eTok == WRITE )
nMode |= STREAM_SHARE_DENYWRITE;
else
Error( SbERR_SYNTAX );
break;
default: break;
}
TestToken( AS );
// Die Kanalnummer
SbiExpression* pChan = new SbiExpression( this );
if( !pChan )
Error( SbERR_SYNTAX );
SbiExpression* pLen = NULL;
if( Peek() == SYMBOL )
{
Next();
String aLen( aSym );
if( aLen.EqualsIgnoreCaseAscii( "LEN" ) )
{
TestToken( EQ );
pLen = new SbiExpression( this );
}
}
if( !pLen ) pLen = new SbiExpression( this, 128, SbxINTEGER );
// Der Stack fuer den OPEN-Befehl sieht wie folgt aus:
// Blocklaenge
// Kanalnummer
// Dateiname
pLen->Gen();
if( pChan )
pChan->Gen();
aFileName.Gen();
aGen.Gen( _OPEN, nMode, nFlags );
delete pLen;
delete pChan;
}
// NAME file AS file
void SbiParser::Name()
{
SbiExpression aExpr1( this );
TestToken( AS );
SbiExpression aExpr2( this );
aExpr1.Gen();
aExpr2.Gen();
aGen.Gen( _RENAME );
}
// CLOSE [n,...]
void SbiParser::Close()
{
Peek();
if( IsEoln( eCurTok ) )
aGen.Gen( _CLOSE, 0 );
else
for( ;; )
{
SbiExpression aExpr( this );
while( Peek() == COMMA || Peek() == SEMICOLON )
Next();
aExpr.Gen();
aGen.Gen( _CHANNEL );
aGen.Gen( _CLOSE, 1 );
if( IsEoln( Peek() ) )
break;
}
}
<|endoftext|>
|
<commit_before>/* **************************************************************************
Copyright (c): 2008 - 2013 Hericus Software, LLC
License: The MIT License (MIT)
Authors: Steven M. Cherry
************************************************************************** */
#include <algorithm>
#include <AnException.h>
#include <EnEx.h>
#include <Log.h>
#include <XmlHelpers.h>
#include <Timer.h>
using namespace SLib;
#include "HelixConfig.h"
#include "HelixFS.h"
#include "HelixCompileTask.h"
using namespace Helix::Build;
HelixCompileTask::HelixCompileTask(HelixFSFolder folder, HelixFSFile file)
: m_folder( folder ), m_file( file )
{
EnEx ee(FL, "HelixCompileTask::HelixCompileTask()");
}
HelixCompileTask::HelixCompileTask(const HelixCompileTask& c) :
m_folder( c.m_folder ), m_file( c.m_file )
{
EnEx ee(FL, "HelixCompileTask::HelixCompileTask(const HelixCompileTask& c)");
}
HelixCompileTask& HelixCompileTask::operator=(const HelixCompileTask& c)
{
EnEx ee(FL, "HelixCompileTask::operator=(const HelixCompileTask& c)");
return *this;
}
HelixCompileTask::HelixCompileTask(const HelixCompileTask&& c) :
m_folder( c.m_folder ), m_file( c.m_file )
{
EnEx ee(FL, "HelixCompileTask::HelixCompileTask(const HelixCompileTask&& c)");
}
HelixCompileTask& HelixCompileTask::operator=(const HelixCompileTask&& c)
{
EnEx ee(FL, "HelixCompileTask::operator=(const HelixCompileTask&& c)");
return *this;
}
HelixCompileTask::~HelixCompileTask()
{
EnEx ee(FL, "HelixCompileTask::~HelixCompileTask()");
}
HelixFSFile HelixCompileTask::File()
{
return m_file;
}
HelixFSFolder HelixCompileTask::Folder()
{
return m_folder;
}
twine HelixCompileTask::GetCommandLine()
{
EnEx ee(FL, "HelixCompileTask::GetCommandLine()");
twine tpl6( "../../../../../../3rdParty" );
twine tpl5( "../../../../../3rdParty" );
twine tpl4( "../../../../3rdParty" );
twine cmd;
cmd = "cd " + FixPhysical(m_folder->PhysicalFolderName()) + " && ";
if(m_file->FolderName() == "logic/util"){
cmd.append(CC(tpl5) + "-I sqldo -I ../../glob -I ../../client -I ../admin -I ../admin/sqldo "
);
cmd.append( m_file->FileName() );
} else if(m_file->FolderName() == "logic/admin"){
cmd.append(CC(tpl5) + "-I sqldo -I ../../glob -I ../../client -I ../util -I ../util/sqldo ");
cmd.append( m_file->FileName() );
} else if(m_file->FolderName() == "glob"){
if(m_file->FileName() == "Jvm.cpp") return ""; // Skip this one
cmd.append(CC(tpl4) +
"-I../logic/util -I../logic/util/sqldo -I ../logic/admin -I ../logic/admin/sqldo "
);
cmd.append( m_file->FileName() );
} else if(m_file->FolderName() == "server"){
#ifdef _WIN32
if(m_file->FileName() == "HelixDaemon.cpp") return ""; // Skip this one
#else
if(m_file->FileName() == "HelixSvc.cpp") return ""; // Skip this one
#endif
cmd.append(CC(tpl4) + "-I ../glob -I ../logic/admin -I../logic/util ");
cmd.append( m_file->FileName() );
} else if(m_file->FolderName() == "client"){
cmd.append(CC(tpl4) +
"-I../glob -I../logic/admin -I../logic/admin/sqldo -I../logic/util -I../logic/util/sqldo "
);
cmd.append( m_file->FileName() );
} else if(m_file->FolderName().find("logic/") != TWINE_NOT_FOUND && !m_file->FolderName().endsWith("/sqldo")){
auto splits = twine(m_file->FolderName()).split("/");
auto& logicName = splits[ splits.size() - 1 ];
cmd.append(CC(tpl5) + "-I sqldo " + LogicIncludes(logicName));
// Pick up any dependent folders from our config file
for(auto& depName : HelixConfig::getInstance().LogicDepends( logicName ) ){
cmd.append( DependentInclude( logicName, depName, false ) );
}
cmd.append( m_file->FileName() );
} else if(m_file->FolderName().find("logic/") != TWINE_NOT_FOUND && m_file->FolderName().endsWith("/sqldo")){
auto splits = twine(m_file->FolderName()).split("/");
auto& logicName = splits[ splits.size() - 2 ];
//printf("Logic name is %s\n", logicName() );
cmd.append(CC(tpl6) + LogicIncludes(logicName, true));
// Pick up any dependent folders from our config file
auto deps = HelixConfig::getInstance().LogicDepends( logicName );
for(auto depName : deps){
cmd.append( DependentInclude( logicName, depName, true ) );
}
//printf("Finished adding dependencies\n");
cmd.append( m_file->FileName() );
}
return cmd;
}
twine HelixCompileTask::FixPhysical(const twine& path)
{
twine ret(path);
#ifdef _WIN32
ret.replace( '/', '\\' );
#endif
return ret;
}
twine HelixCompileTask::CC(const twine& tpl)
{
#ifdef _WIN32
# ifdef _X86_
// ///////////////////////////////////////////////////////////////////////////////////
// 32-bit windows
// ///////////////////////////////////////////////////////////////////////////////////
throw AnException(0, FL, "Compiling on 32-bit Windows not yet supported");
# else
// ///////////////////////////////////////////////////////////////////////////////////
// 64-bit windows
// ///////////////////////////////////////////////////////////////////////////////////
return "cl.exe /std:c++14 -c -wd4251 -Zp8 -EHsc -O2 -D_WIN64 -DWIN64 -D_AMD64=1 -D__64BIT__ -DWIN32 -D_MT -D_DLL -DLINT_ARGS -MP8 -MD -W3 -D \"_CRT_SECURE_NO_DEPRECATE\" -D \"_CRT_NON_COMFORMING_SWPRINTFS\" -D CS_NO_LARGE_IDENTIFIERS -I " + tpl + "/include -I " + tpl + "/include/libxml2 -I . ";
# endif
#elif __APPLE__
// ///////////////////////////////////////////////////////////////////////////////////
// 64-bit mac
// ///////////////////////////////////////////////////////////////////////////////////
return "g++ -std=c++14 -c -g -Wall -D_REENTRANT -fPIC -O2 -I/usr/local/opt/openssl/include -I/usr/include -I/usr/include/libxml2 -I" + tpl + "/include -I. ";
#elif __linux__
// ///////////////////////////////////////////////////////////////////////////////////
// 64-bit linux
// ///////////////////////////////////////////////////////////////////////////////////
return "g++ -std=c++14 -c -g -Wall -D_REENTRANT -fPIC -O2 -rdynamic -I/usr/include -I/usr/include/libxml2 -I" + tpl + "/include -I. ";
#else
throw AnException(0, FL, "Unknown compile environment.");
#endif
}
twine HelixCompileTask::LogicIncludes(const twine& logicName, bool fromSqldo)
{
HelixConfig& conf = HelixConfig::getInstance();
twine prefix;
if(conf.UseCore()){
twine coreFolder = conf.CoreFolder();
if(fromSqldo){
prefix = "-I../../../" + coreFolder + "/server/c";
} else {
prefix = "-I../../" + coreFolder + "/server/c";
}
} else {
auto logicRepo = conf.LogicRepo( logicName );
if(logicRepo.empty()){ // Just a normal local logic folder
if(fromSqldo){
prefix = "-I../../..";
} else {
prefix = "-I../..";
}
} else { // This is a remote logic folder, the paths get more complex
auto ourRepo = HelixFS::OurRepo();
if(fromSqldo){
// The compile is targeting a folder that looks like this:
// repo-name/server/c/logic/logic_name/sqldo
//
// We need to back out of all of that and reference our repo for glob, client, etc
prefix = "-I../../../../../../" + ourRepo + "/server/c";
} else {
// The compile is targeting a folder that looks like this:
// repo-name/server/c/logic/logic_name
//
// We need to back out of all of that and reference our repo for glob, client, etc
prefix = "-I../../../../../" + ourRepo + "/server/c";
}
}
}
return prefix + "/glob " +
prefix + "/client " +
prefix + "/logic/util " + prefix + "/logic/util/sqldo " +
prefix + "/logic/admin " + prefix + "/logic/admin/sqldo ";
}
twine HelixCompileTask::DependentInclude(const twine& ourLogic, const twine& depLogic, bool fromSqldo)
{
HelixConfig& conf = HelixConfig::getInstance();
twine prefix;
auto depRepo = conf.LogicRepo( depLogic ); // What repo are they in?
if(depRepo.empty()){
// they are in the same repo as we are - easy path to configure
if(fromSqldo){
prefix = "-I../../" + depLogic;
} else {
prefix = "-I../" + depLogic;
}
} else {
// they are in a different repository - path gets more complex
if(fromSqldo){
prefix = "-I../../../../../../" + depRepo + "/server/c/logic/" + depLogic;
} else {
prefix = "-I../../../../../" + depRepo + "/server/c/logic/" + depLogic;
}
}
// Include the dependent logic folder and the dependent logic sqldo folder
return prefix + " " + prefix + "/sqldo ";
}
<commit_msg>adding /nologo to the windows compile comannd line.<commit_after>/* **************************************************************************
Copyright (c): 2008 - 2013 Hericus Software, LLC
License: The MIT License (MIT)
Authors: Steven M. Cherry
************************************************************************** */
#include <algorithm>
#include <AnException.h>
#include <EnEx.h>
#include <Log.h>
#include <XmlHelpers.h>
#include <Timer.h>
using namespace SLib;
#include "HelixConfig.h"
#include "HelixFS.h"
#include "HelixCompileTask.h"
using namespace Helix::Build;
HelixCompileTask::HelixCompileTask(HelixFSFolder folder, HelixFSFile file)
: m_folder( folder ), m_file( file )
{
EnEx ee(FL, "HelixCompileTask::HelixCompileTask()");
}
HelixCompileTask::HelixCompileTask(const HelixCompileTask& c) :
m_folder( c.m_folder ), m_file( c.m_file )
{
EnEx ee(FL, "HelixCompileTask::HelixCompileTask(const HelixCompileTask& c)");
}
HelixCompileTask& HelixCompileTask::operator=(const HelixCompileTask& c)
{
EnEx ee(FL, "HelixCompileTask::operator=(const HelixCompileTask& c)");
return *this;
}
HelixCompileTask::HelixCompileTask(const HelixCompileTask&& c) :
m_folder( c.m_folder ), m_file( c.m_file )
{
EnEx ee(FL, "HelixCompileTask::HelixCompileTask(const HelixCompileTask&& c)");
}
HelixCompileTask& HelixCompileTask::operator=(const HelixCompileTask&& c)
{
EnEx ee(FL, "HelixCompileTask::operator=(const HelixCompileTask&& c)");
return *this;
}
HelixCompileTask::~HelixCompileTask()
{
EnEx ee(FL, "HelixCompileTask::~HelixCompileTask()");
}
HelixFSFile HelixCompileTask::File()
{
return m_file;
}
HelixFSFolder HelixCompileTask::Folder()
{
return m_folder;
}
twine HelixCompileTask::GetCommandLine()
{
EnEx ee(FL, "HelixCompileTask::GetCommandLine()");
twine tpl6( "../../../../../../3rdParty" );
twine tpl5( "../../../../../3rdParty" );
twine tpl4( "../../../../3rdParty" );
twine cmd;
cmd = "cd " + FixPhysical(m_folder->PhysicalFolderName()) + " && ";
if(m_file->FolderName() == "logic/util"){
cmd.append(CC(tpl5) + "-I sqldo -I ../../glob -I ../../client -I ../admin -I ../admin/sqldo "
);
cmd.append( m_file->FileName() );
} else if(m_file->FolderName() == "logic/admin"){
cmd.append(CC(tpl5) + "-I sqldo -I ../../glob -I ../../client -I ../util -I ../util/sqldo ");
cmd.append( m_file->FileName() );
} else if(m_file->FolderName() == "glob"){
if(m_file->FileName() == "Jvm.cpp") return ""; // Skip this one
cmd.append(CC(tpl4) +
"-I../logic/util -I../logic/util/sqldo -I ../logic/admin -I ../logic/admin/sqldo "
);
cmd.append( m_file->FileName() );
} else if(m_file->FolderName() == "server"){
#ifdef _WIN32
if(m_file->FileName() == "HelixDaemon.cpp") return ""; // Skip this one
#else
if(m_file->FileName() == "HelixSvc.cpp") return ""; // Skip this one
#endif
cmd.append(CC(tpl4) + "-I ../glob -I ../logic/admin -I../logic/util ");
cmd.append( m_file->FileName() );
} else if(m_file->FolderName() == "client"){
cmd.append(CC(tpl4) +
"-I../glob -I../logic/admin -I../logic/admin/sqldo -I../logic/util -I../logic/util/sqldo "
);
cmd.append( m_file->FileName() );
} else if(m_file->FolderName().find("logic/") != TWINE_NOT_FOUND && !m_file->FolderName().endsWith("/sqldo")){
auto splits = twine(m_file->FolderName()).split("/");
auto& logicName = splits[ splits.size() - 1 ];
cmd.append(CC(tpl5) + "-I sqldo " + LogicIncludes(logicName));
// Pick up any dependent folders from our config file
for(auto& depName : HelixConfig::getInstance().LogicDepends( logicName ) ){
cmd.append( DependentInclude( logicName, depName, false ) );
}
cmd.append( m_file->FileName() );
} else if(m_file->FolderName().find("logic/") != TWINE_NOT_FOUND && m_file->FolderName().endsWith("/sqldo")){
auto splits = twine(m_file->FolderName()).split("/");
auto& logicName = splits[ splits.size() - 2 ];
//printf("Logic name is %s\n", logicName() );
cmd.append(CC(tpl6) + LogicIncludes(logicName, true));
// Pick up any dependent folders from our config file
auto deps = HelixConfig::getInstance().LogicDepends( logicName );
for(auto depName : deps){
cmd.append( DependentInclude( logicName, depName, true ) );
}
//printf("Finished adding dependencies\n");
cmd.append( m_file->FileName() );
}
return cmd;
}
twine HelixCompileTask::FixPhysical(const twine& path)
{
twine ret(path);
#ifdef _WIN32
ret.replace( '/', '\\' );
#endif
return ret;
}
twine HelixCompileTask::CC(const twine& tpl)
{
#ifdef _WIN32
# ifdef _X86_
// ///////////////////////////////////////////////////////////////////////////////////
// 32-bit windows
// ///////////////////////////////////////////////////////////////////////////////////
throw AnException(0, FL, "Compiling on 32-bit Windows not yet supported");
# else
// ///////////////////////////////////////////////////////////////////////////////////
// 64-bit windows
// ///////////////////////////////////////////////////////////////////////////////////
return "cl.exe /nologo /std:c++14 -c -wd4251 -Zp8 -EHsc -O2 -D_WIN64 -DWIN64 -D_AMD64=1 -D__64BIT__ -DWIN32 -D_MT -D_DLL -DLINT_ARGS -MP8 -MD -W3 -D \"_CRT_SECURE_NO_DEPRECATE\" -D \"_CRT_NON_COMFORMING_SWPRINTFS\" -D CS_NO_LARGE_IDENTIFIERS -I " + tpl + "/include -I " + tpl + "/include/libxml2 -I . ";
# endif
#elif __APPLE__
// ///////////////////////////////////////////////////////////////////////////////////
// 64-bit mac
// ///////////////////////////////////////////////////////////////////////////////////
return "g++ -std=c++14 -c -g -Wall -D_REENTRANT -fPIC -O2 -I/usr/local/opt/openssl/include -I/usr/include -I/usr/include/libxml2 -I" + tpl + "/include -I. ";
#elif __linux__
// ///////////////////////////////////////////////////////////////////////////////////
// 64-bit linux
// ///////////////////////////////////////////////////////////////////////////////////
return "g++ -std=c++14 -c -g -Wall -D_REENTRANT -fPIC -O2 -rdynamic -I/usr/include -I/usr/include/libxml2 -I" + tpl + "/include -I. ";
#else
throw AnException(0, FL, "Unknown compile environment.");
#endif
}
twine HelixCompileTask::LogicIncludes(const twine& logicName, bool fromSqldo)
{
HelixConfig& conf = HelixConfig::getInstance();
twine prefix;
if(conf.UseCore()){
twine coreFolder = conf.CoreFolder();
if(fromSqldo){
prefix = "-I../../../" + coreFolder + "/server/c";
} else {
prefix = "-I../../" + coreFolder + "/server/c";
}
} else {
auto logicRepo = conf.LogicRepo( logicName );
if(logicRepo.empty()){ // Just a normal local logic folder
if(fromSqldo){
prefix = "-I../../..";
} else {
prefix = "-I../..";
}
} else { // This is a remote logic folder, the paths get more complex
auto ourRepo = HelixFS::OurRepo();
if(fromSqldo){
// The compile is targeting a folder that looks like this:
// repo-name/server/c/logic/logic_name/sqldo
//
// We need to back out of all of that and reference our repo for glob, client, etc
prefix = "-I../../../../../../" + ourRepo + "/server/c";
} else {
// The compile is targeting a folder that looks like this:
// repo-name/server/c/logic/logic_name
//
// We need to back out of all of that and reference our repo for glob, client, etc
prefix = "-I../../../../../" + ourRepo + "/server/c";
}
}
}
return prefix + "/glob " +
prefix + "/client " +
prefix + "/logic/util " + prefix + "/logic/util/sqldo " +
prefix + "/logic/admin " + prefix + "/logic/admin/sqldo ";
}
twine HelixCompileTask::DependentInclude(const twine& ourLogic, const twine& depLogic, bool fromSqldo)
{
HelixConfig& conf = HelixConfig::getInstance();
twine prefix;
auto depRepo = conf.LogicRepo( depLogic ); // What repo are they in?
if(depRepo.empty()){
// they are in the same repo as we are - easy path to configure
if(fromSqldo){
prefix = "-I../../" + depLogic;
} else {
prefix = "-I../" + depLogic;
}
} else {
// they are in a different repository - path gets more complex
if(fromSqldo){
prefix = "-I../../../../../../" + depRepo + "/server/c/logic/" + depLogic;
} else {
prefix = "-I../../../../../" + depRepo + "/server/c/logic/" + depLogic;
}
}
// Include the dependent logic folder and the dependent logic sqldo folder
return prefix + " " + prefix + "/sqldo ";
}
<|endoftext|>
|
<commit_before>// Copyright (c) 2018 Iqiyi, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Authors: Daojin Cai (caidaojin@qiyi.com)
#include <algorithm>
#include "butil/fast_rand.h"
#include "brpc/socket.h"
#include "brpc/policy/weighted_round_robin_load_balancer.h"
#include "butil/strings/string_number_conversions.h"
namespace {
const std::vector<uint64_t> prime_stride = {
2,3,5,11,17,29,47,71,107,137,163,251,307,379,569,683,857,1289,1543,1949,2617,
2927,3407,4391,6599,9901,14867,22303,33457,50207,75323,112997,169501,254257,
381389,572087,849083,1273637,1910471,2865727,4298629,6447943,9671923,14507903,
21761863,32642861,48964297,73446469,110169743,165254623,247881989,371822987,
557734537,836601847,1254902827,1882354259,2823531397,4235297173,6352945771,
9529418671};
bool IsCoprime(uint64_t num1, uint64_t num2) {
uint64_t temp;
if (num1 < num2) {
temp = num1;
num1 = num2;
num2 = temp;
}
while (true) {
temp = num1 % num2;
if (temp == 0) {
break;
} else {
num1 = num2;
num2 = temp;
}
}
return num2 == 1;
}
// Get a reasonable stride according to weights configured of servers.
uint64_t GetStride(const uint64_t weight_sum, const size_t num) {
if (weight_sum == 1) {
return 1;
}
uint32_t average_weight = weight_sum / num;
auto iter = std::lower_bound(prime_stride.begin(), prime_stride.end(),
average_weight);
while (iter != prime_stride.end()
&& !IsCoprime(weight_sum, *iter)) {
++iter;
}
CHECK(iter != prime_stride.end()) << "Failed to get stride";
return *iter > weight_sum ? *iter % weight_sum : *iter;
}
} // namespace
namespace brpc {
namespace policy {
bool WeightedRoundRobinLoadBalancer::Add(Servers& bg, const ServerId& id) {
if (bg.server_list.capacity() < 128) {
bg.server_list.reserve(128);
}
uint32_t weight = 0;
if (butil::StringToUint(id.tag, &weight) &&
weight > 0) {
bool insert_server =
bg.server_map.emplace(id.id, bg.server_list.size()).second;
if (insert_server) {
bg.server_list.emplace_back(id.id, weight);
bg.weight_sum += weight;
return true;
}
} else {
LOG(ERROR) << "Invalid weight is set: " << id.tag;
}
return false;
}
bool WeightedRoundRobinLoadBalancer::Remove(Servers& bg, const ServerId& id) {
auto iter = bg.server_map.find(id.id);
if (iter != bg.server_map.end()) {
const size_t index = iter->second;
bg.weight_sum -= bg.server_list[index].weight;
bg.server_list[index] = bg.server_list.back();
bg.server_map[bg.server_list[index].id] = index;
bg.server_list.pop_back();
bg.server_map.erase(iter);
return true;
}
return false;
}
size_t WeightedRoundRobinLoadBalancer::BatchAdd(
Servers& bg, const std::vector<ServerId>& servers) {
size_t count = 0;
for (size_t i = 0; i < servers.size(); ++i) {
count += !!Add(bg, servers[i]);
}
return count;
}
size_t WeightedRoundRobinLoadBalancer::BatchRemove(
Servers& bg, const std::vector<ServerId>& servers) {
size_t count = 0;
for (size_t i = 0; i < servers.size(); ++i) {
count += !!Remove(bg, servers[i]);
}
return count;
}
bool WeightedRoundRobinLoadBalancer::AddServer(const ServerId& id) {
return _db_servers.Modify(Add, id);
}
bool WeightedRoundRobinLoadBalancer::RemoveServer(const ServerId& id) {
return _db_servers.Modify(Remove, id);
}
size_t WeightedRoundRobinLoadBalancer::AddServersInBatch(
const std::vector<ServerId>& servers) {
const size_t n = _db_servers.Modify(BatchAdd, servers);
LOG_IF(ERROR, n != servers.size())
<< "Fail to AddServersInBatch, expected " << servers.size()
<< " actually " << n;
return n;
}
size_t WeightedRoundRobinLoadBalancer::RemoveServersInBatch(
const std::vector<ServerId>& servers) {
const size_t n = _db_servers.Modify(BatchRemove, servers);
LOG_IF(ERROR, n != servers.size())
<< "Fail to RemoveServersInBatch, expected " << servers.size()
<< " actually " << n;
return n;
}
int WeightedRoundRobinLoadBalancer::SelectServer(const SelectIn& in, SelectOut* out) {
butil::DoublyBufferedData<Servers, TLS>::ScopedPtr s;
if (_db_servers.Read(&s) != 0) {
return ENOMEM;
}
if (s->server_list.empty()) {
return ENODATA;
}
TLS& tls = s.tls();
if (tls.IsNeededCaculateNewStride(s->weight_sum, s->server_list.size())) {
if (tls.stride == 0) {
tls.position = butil::fast_rand_less_than(s->server_list.size());
}
tls.stride = GetStride(s->weight_sum, s->server_list.size());
}
// If server list changed, the position may be out of range.
tls.position %= s->server_list.size();
// Check whether remain server was removed from server list.
if (tls.remain_server.weight > 0 &&
tls.remain_server.id != s->server_list[tls.position].id) {
tls.remain_server.weight = 0;
}
// The servers that can not be choosed.
std::unordered_set<SocketId> filter;
TLS tls_temp = tls;
uint64_t remain_weight = s->weight_sum;
size_t remain_servers = s->server_list.size();
while (remain_servers > 0) {
SocketId server_id = GetServerInNextStride(s->server_list, filter, tls_temp);
if (!ExcludedServers::IsExcluded(in.excluded, server_id)
&& Socket::Address(server_id, out->ptr) == 0
&& !(*out->ptr)->IsLogOff()) {
// update tls.
tls.remain_server = tls_temp.remain_server;
tls.position = tls_temp.position;
return 0;
} else {
// Skip this invalid server. We need calculate a new stride for server selection.
filter.emplace(server_id);
remain_weight -= (s->server_list[s->server_map.at(server_id)]).weight;
if (--remain_servers == 0) {
break;
}
// Select from begining status.
tls_temp.stride = GetStride(remain_weight, remain_servers);
tls_temp.position = tls.position;
tls_temp.remain_server = tls.remain_server;
}
}
return EHOSTDOWN;
}
SocketId WeightedRoundRobinLoadBalancer::GetServerInNextStride(
const std::vector<Server>& server_list,
const std::unordered_set<SocketId>& filter,
TLS& tls) {
SocketId final_server = INVALID_STREAM_ID;
uint64_t stride = tls.stride;
Server& remain = tls.remain_server;
if (remain.weight > 0) {
if (filter.count(remain.id) == 0) {
final_server = remain.id;
if (remain.weight > stride) {
remain.weight -= stride;
return final_server;
} else {
stride -= remain.weight;
}
}
remain.weight = 0;
++tls.position;
tls.position %= server_list.size();
}
while (stride > 0) {
final_server = server_list[tls.position].id;
if (filter.count(final_server) == 0) {
uint32_t configured_weight = server_list[tls.position].weight;
if (configured_weight > stride) {
remain.id = final_server;
remain.weight = configured_weight - stride;
return final_server;
}
stride -= configured_weight;
}
++tls.position;
tls.position %= server_list.size();
}
return final_server;
}
LoadBalancer* WeightedRoundRobinLoadBalancer::New() const {
return new (std::nothrow) WeightedRoundRobinLoadBalancer;
}
void WeightedRoundRobinLoadBalancer::Destroy() {
delete this;
}
void WeightedRoundRobinLoadBalancer::Describe(
std::ostream &os, const DescribeOptions& options) {
if (!options.verbose) {
os << "wrr";
return;
}
os << "WeightedRoundRobin{";
butil::DoublyBufferedData<Servers, TLS>::ScopedPtr s;
if (_db_servers.Read(&s) != 0) {
os << "fail to read _db_servers";
} else {
os << "n=" << s->server_list.size() << ':';
for (const auto& server : s->server_list) {
os << ' ' << server.id << '(' << server.weight << ')';
}
}
os << '}';
}
} // namespace policy
} // namespace brpc
<commit_msg>little change<commit_after>// Copyright (c) 2018 Iqiyi, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Authors: Daojin Cai (caidaojin@qiyi.com)
#include <algorithm>
#include "butil/fast_rand.h"
#include "brpc/socket.h"
#include "brpc/policy/weighted_round_robin_load_balancer.h"
#include "butil/strings/string_number_conversions.h"
namespace {
const std::vector<uint64_t> prime_stride = {
2,3,5,11,17,29,47,71,107,137,163,251,307,379,569,683,857,1289,1543,1949,2617,
2927,3407,4391,6599,9901,14867,22303,33457,50207,75323,112997,169501,254257,
381389,572087,849083,1273637,1910471,2865727,4298629,6447943,9671923,14507903,
21761863,32642861,48964297,73446469,110169743,165254623,247881989,371822987,
557734537,836601847,1254902827,1882354259,2823531397,4235297173,6352945771,
9529418671};
bool IsCoprime(uint64_t num1, uint64_t num2) {
uint64_t temp;
if (num1 < num2) {
temp = num1;
num1 = num2;
num2 = temp;
}
while (true) {
temp = num1 % num2;
if (temp == 0) {
break;
} else {
num1 = num2;
num2 = temp;
}
}
return num2 == 1;
}
// Get a reasonable stride according to weights configured of servers.
uint64_t GetStride(const uint64_t weight_sum, const size_t num) {
if (weight_sum == 1) {
return 1;
}
uint32_t average_weight = weight_sum / num;
auto iter = std::lower_bound(prime_stride.begin(), prime_stride.end(),
average_weight);
while (iter != prime_stride.end()
&& !IsCoprime(weight_sum, *iter)) {
++iter;
}
CHECK(iter != prime_stride.end()) << "Failed to get stride";
return *iter > weight_sum ? *iter % weight_sum : *iter;
}
} // namespace
namespace brpc {
namespace policy {
bool WeightedRoundRobinLoadBalancer::Add(Servers& bg, const ServerId& id) {
if (bg.server_list.capacity() < 128) {
bg.server_list.reserve(128);
}
uint32_t weight = 0;
if (butil::StringToUint(id.tag, &weight) &&
weight > 0) {
bool insert_server =
bg.server_map.emplace(id.id, bg.server_list.size()).second;
if (insert_server) {
bg.server_list.emplace_back(id.id, weight);
bg.weight_sum += weight;
return true;
}
} else {
LOG(ERROR) << "Invalid weight is set: " << id.tag;
}
return false;
}
bool WeightedRoundRobinLoadBalancer::Remove(Servers& bg, const ServerId& id) {
auto iter = bg.server_map.find(id.id);
if (iter != bg.server_map.end()) {
const size_t index = iter->second;
bg.weight_sum -= bg.server_list[index].weight;
bg.server_list[index] = bg.server_list.back();
bg.server_map[bg.server_list[index].id] = index;
bg.server_list.pop_back();
bg.server_map.erase(iter);
return true;
}
return false;
}
size_t WeightedRoundRobinLoadBalancer::BatchAdd(
Servers& bg, const std::vector<ServerId>& servers) {
size_t count = 0;
for (size_t i = 0; i < servers.size(); ++i) {
count += !!Add(bg, servers[i]);
}
return count;
}
size_t WeightedRoundRobinLoadBalancer::BatchRemove(
Servers& bg, const std::vector<ServerId>& servers) {
size_t count = 0;
for (size_t i = 0; i < servers.size(); ++i) {
count += !!Remove(bg, servers[i]);
}
return count;
}
bool WeightedRoundRobinLoadBalancer::AddServer(const ServerId& id) {
return _db_servers.Modify(Add, id);
}
bool WeightedRoundRobinLoadBalancer::RemoveServer(const ServerId& id) {
return _db_servers.Modify(Remove, id);
}
size_t WeightedRoundRobinLoadBalancer::AddServersInBatch(
const std::vector<ServerId>& servers) {
const size_t n = _db_servers.Modify(BatchAdd, servers);
LOG_IF(ERROR, n != servers.size())
<< "Fail to AddServersInBatch, expected " << servers.size()
<< " actually " << n;
return n;
}
size_t WeightedRoundRobinLoadBalancer::RemoveServersInBatch(
const std::vector<ServerId>& servers) {
const size_t n = _db_servers.Modify(BatchRemove, servers);
LOG_IF(ERROR, n != servers.size())
<< "Fail to RemoveServersInBatch, expected " << servers.size()
<< " actually " << n;
return n;
}
int WeightedRoundRobinLoadBalancer::SelectServer(const SelectIn& in, SelectOut* out) {
butil::DoublyBufferedData<Servers, TLS>::ScopedPtr s;
if (_db_servers.Read(&s) != 0) {
return ENOMEM;
}
if (s->server_list.empty()) {
return ENODATA;
}
TLS& tls = s.tls();
if (tls.IsNeededCaculateNewStride(s->weight_sum, s->server_list.size())) {
if (tls.stride == 0) {
tls.position = butil::fast_rand_less_than(s->server_list.size());
}
tls.stride = GetStride(s->weight_sum, s->server_list.size());
}
// If server list changed, the position may be out of range.
tls.position %= s->server_list.size();
// Check whether remain server was removed from server list.
if (tls.remain_server.weight > 0 &&
tls.remain_server.id != s->server_list[tls.position].id) {
tls.remain_server.weight = 0;
}
// The servers that can not be choosed.
std::unordered_set<SocketId> filter;
TLS tls_temp = tls;
uint64_t remain_weight = s->weight_sum;
size_t remain_servers = s->server_list.size();
while (remain_servers > 0) {
SocketId server_id = GetServerInNextStride(s->server_list, filter, tls_temp);
if (!ExcludedServers::IsExcluded(in.excluded, server_id)
&& Socket::Address(server_id, out->ptr) == 0
&& !(*out->ptr)->IsLogOff()) {
// update tls.
tls.remain_server = tls_temp.remain_server;
tls.position = tls_temp.position;
return 0;
} else {
// Skip this invalid server. We need calculate a new stride for server selection.
if (--remain_servers == 0) {
break;
}
filter.emplace(server_id);
remain_weight -= (s->server_list[s->server_map.at(server_id)]).weight;
// Select from begining status.
tls_temp.stride = GetStride(remain_weight, remain_servers);
tls_temp.position = tls.position;
tls_temp.remain_server = tls.remain_server;
}
}
return EHOSTDOWN;
}
SocketId WeightedRoundRobinLoadBalancer::GetServerInNextStride(
const std::vector<Server>& server_list,
const std::unordered_set<SocketId>& filter,
TLS& tls) {
SocketId final_server = INVALID_STREAM_ID;
uint64_t stride = tls.stride;
Server& remain = tls.remain_server;
if (remain.weight > 0) {
if (filter.count(remain.id) == 0) {
final_server = remain.id;
if (remain.weight > stride) {
remain.weight -= stride;
return final_server;
} else {
stride -= remain.weight;
}
}
remain.weight = 0;
++tls.position;
tls.position %= server_list.size();
}
while (stride > 0) {
final_server = server_list[tls.position].id;
if (filter.count(final_server) == 0) {
uint32_t configured_weight = server_list[tls.position].weight;
if (configured_weight > stride) {
remain.id = final_server;
remain.weight = configured_weight - stride;
return final_server;
}
stride -= configured_weight;
}
++tls.position;
tls.position %= server_list.size();
}
return final_server;
}
LoadBalancer* WeightedRoundRobinLoadBalancer::New() const {
return new (std::nothrow) WeightedRoundRobinLoadBalancer;
}
void WeightedRoundRobinLoadBalancer::Destroy() {
delete this;
}
void WeightedRoundRobinLoadBalancer::Describe(
std::ostream &os, const DescribeOptions& options) {
if (!options.verbose) {
os << "wrr";
return;
}
os << "WeightedRoundRobin{";
butil::DoublyBufferedData<Servers, TLS>::ScopedPtr s;
if (_db_servers.Read(&s) != 0) {
os << "fail to read _db_servers";
} else {
os << "n=" << s->server_list.size() << ':';
for (const auto& server : s->server_list) {
os << ' ' << server.id << '(' << server.weight << ')';
}
}
os << '}';
}
} // namespace policy
} // namespace brpc
<|endoftext|>
|
<commit_before>/*
* Copyright (c) 2013 Juniper Networks, Inc. All rights reserved.
*/
#include "ifmap/ifmap_graph_walker.h"
#include <boost/bind.hpp>
#include "base/logging.h"
#include "db/db_graph.h"
#include "db/db_table.h"
#include "ifmap/ifmap_client.h"
#include "ifmap/ifmap_exporter.h"
#include "ifmap/ifmap_link.h"
#include "ifmap/ifmap_log.h"
#include "ifmap/ifmap_table.h"
#include "ifmap/ifmap_server.h"
#include "ifmap/ifmap_log_types.h"
#include "ifmap/ifmap_update.h"
#include "ifmap/ifmap_util.h"
#include "ifmap/ifmap_whitelist.h"
#include "schema/vnc_cfg_types.h"
class GraphPropagateFilter : public DBGraph::VisitorFilter {
public:
GraphPropagateFilter(IFMapExporter *exporter,
const IFMapTypenameWhiteList *type_filter,
const BitSet &bitset)
: exporter_(exporter),
type_filter_(type_filter),
bset_(bitset) {
}
bool VertexFilter(const DBGraphVertex *vertex) const {
return type_filter_->VertexFilter(vertex);
}
bool EdgeFilter(const DBGraphVertex *source, const DBGraphVertex *target,
const DBGraphEdge *edge) const {
bool accept = type_filter_->EdgeFilter(source, target, edge);
if (!accept) {
return false;
}
const IFMapNode *tgt = static_cast<const IFMapNode *>(target);
const IFMapNodeState *state = NodeStateLookup(tgt);
if (state != NULL && state->interest().Contains(bset_)) {
return false;
}
return true;
}
const IFMapNodeState *NodeStateLookup(const IFMapNode *node) const {
const DBTable *table = node->table();
const DBState *state =
node->GetState(table, exporter_->TableListenerId(table));
return static_cast<const IFMapNodeState *>(state);
}
private:
IFMapExporter *exporter_;
const IFMapTypenameWhiteList *type_filter_;
const BitSet &bset_;
};
IFMapGraphWalker::IFMapGraphWalker(DBGraph *graph, IFMapExporter *exporter)
: graph_(graph),
exporter_(exporter),
work_queue_(TaskScheduler::GetInstance()->GetTaskId("db::DBTable"), 0,
boost::bind(&IFMapGraphWalker::Worker, this, _1)) {
work_queue_.SetExitCallback(
boost::bind(&IFMapGraphWalker::WorkBatchEnd, this, _1));
traversal_white_list_.reset(new IFMapTypenameWhiteList());
AddNodesToWhitelist();
AddLinksToWhitelist();
}
IFMapGraphWalker::~IFMapGraphWalker() {
}
void IFMapGraphWalker::JoinVertex(DBGraphVertex *vertex, const BitSet &bset) {
IFMAP_DEBUG(JoinVertex, vertex->ToString());
IFMapNode *node = static_cast<IFMapNode *>(vertex);
IFMapNodeState *state = exporter_->NodeStateLocate(node);
state->InterestOr(bset);
node->table()->Change(node);
// Mark all dependent links as potentially modified.
for (IFMapNodeState::iterator iter = state->begin(); iter != state->end();
++iter) {
DBTable *table = exporter_->link_table();
table->Change(iter.operator->());
}
}
void IFMapGraphWalker::ProcessLinkAdd(IFMapNode *lnode, IFMapNode *rnode,
const BitSet &bset) {
GraphPropagateFilter filter(exporter_, traversal_white_list_.get(), bset);
graph_->Visit(rnode,
boost::bind(&IFMapGraphWalker::JoinVertex, this, _1, bset),
0,
filter);
}
void IFMapGraphWalker::LinkAdd(IFMapNode *lnode, const BitSet &lhs,
IFMapNode *rnode, const BitSet &rhs) {
IFMAP_DEBUG(LinkOper, "LinkAdd", lnode->ToString(), rnode->ToString(),
lhs.ToString(), rhs.ToString());
if (!lhs.empty() && !rhs.Contains(lhs) &&
traversal_white_list_->VertexFilter(rnode) &&
traversal_white_list_->EdgeFilter(lnode, rnode, NULL)) {
ProcessLinkAdd(lnode, rnode, lhs);
}
if (!rhs.empty() && !lhs.Contains(rhs) &&
traversal_white_list_->VertexFilter(lnode) &&
traversal_white_list_->EdgeFilter(rnode, lnode, NULL)) {
ProcessLinkAdd(rnode, lnode, rhs);
}
}
void IFMapGraphWalker::LinkRemove(const BitSet &bset) {
QueueEntry entry;
entry.set = bset;
work_queue_.Enqueue(entry);
}
// Check if the neighbor or link to neighbor should be filtered. Returns true
// if rnode or link to rnode should be filtered.
bool IFMapGraphWalker::FilterNeighbor(IFMapNode *lnode, IFMapNode *rnode) {
if (!traversal_white_list_->VertexFilter(rnode) ||
!traversal_white_list_->EdgeFilter(lnode, rnode, NULL)) {
return true;
}
return false;
}
void IFMapGraphWalker::RecomputeInterest(DBGraphVertex *vertex, int bit) {
IFMapNode *node = static_cast<IFMapNode *>(vertex);
IFMapNodeState *state = exporter_->NodeStateLocate(node);
state->nmask_set(bit);
}
bool IFMapGraphWalker::Worker(QueueEntry work_entry) {
const BitSet &bset = work_entry.set;
IFMapServer *server = exporter_->server();
for (size_t i = bset.find_first(); i != BitSet::npos;
i = bset.find_next(i)) {
IFMapClient *client = server->GetClient(i);
if (client == NULL) {
continue;
}
// TODO: In order to handle interest based on the vswitch registration
// there need to be links in the graph that correspond to these.
IFMapTable *table = IFMapTable::FindTable(server->database(),
"virtual-router");
IFMapNode *node = table->FindNode(client->identifier());
if ((node != NULL) && node->IsVertexValid()) {
graph_->Visit(node,
boost::bind(&IFMapGraphWalker::RecomputeInterest, this, _1, i),
0, *traversal_white_list_.get());
}
}
rm_mask_ |= work_entry.set;
return true;
}
void IFMapGraphWalker::CleanupInterest(DBGraphVertex *vertex) {
// interest = interest - rm_mask_ + nmask
IFMapNode *node = static_cast<IFMapNode *>(vertex);
IFMapNodeState *state = exporter_->NodeStateLookup(node);
if (state == NULL) {
return;
}
if (!state->interest().empty() && !state->nmask().empty()) {
IFMAP_DEBUG(CleanupInterest, node->ToString(),
state->interest().ToString(), rm_mask_.ToString(),
state->nmask().ToString());
}
BitSet ninterest;
ninterest.BuildComplement(state->interest(), rm_mask_);
ninterest |= state->nmask();
state->nmask_clear();
if (state->interest() == ninterest) {
return;
}
state->SetInterest(ninterest);
node->table()->Change(node);
// Mark all dependent links as potentially modified.
for (IFMapNodeState::iterator iter = state->begin();
iter != state->end(); ++iter) {
DBTable *table = exporter_->link_table();
table->Change(iter.operator->());
}
}
// Cleanup all graph nodes that a bit set in the remove mask (rm_mask_) but
// where not visited by the walker.
void IFMapGraphWalker::WorkBatchEnd(bool done) {
for (DBGraph::vertex_iterator iter = graph_->vertex_list_begin();
iter != graph_->vertex_list_end(); ++iter) {
DBGraphVertex *vertex = iter.operator->();
CleanupInterest(vertex);
}
rm_mask_.clear();
}
// The nodes listed below and the nodes in
// IFMapGraphTraversalFilterCalculator::CreateNodeBlackList() are mutually
// exclusive
void IFMapGraphWalker::AddNodesToWhitelist() {
traversal_white_list_->include_vertex.insert("virtual-router");
traversal_white_list_->include_vertex.insert("virtual-machine");
traversal_white_list_->include_vertex.insert("bgp-router");
traversal_white_list_->include_vertex.insert("global-system-config");
traversal_white_list_->include_vertex.insert("provider-attachment");
traversal_white_list_->include_vertex.insert("service-instance");
traversal_white_list_->include_vertex.insert("global-vrouter-config");
traversal_white_list_->include_vertex.insert(
"virtual-machine-interface");
traversal_white_list_->include_vertex.insert("security-group");
traversal_white_list_->include_vertex.insert("physical-router");
traversal_white_list_->include_vertex.insert("service-template");
traversal_white_list_->include_vertex.insert("instance-ip");
traversal_white_list_->include_vertex.insert("virtual-network");
traversal_white_list_->include_vertex.insert("floating-ip");
traversal_white_list_->include_vertex.insert("customer-attachment");
traversal_white_list_->include_vertex.insert(
"virtual-machine-interface-routing-instance");
traversal_white_list_->include_vertex.insert("physical-interface");
traversal_white_list_->include_vertex.insert("domain");
traversal_white_list_->include_vertex.insert("floating-ip-pool");
traversal_white_list_->include_vertex.insert("logical-interface");
traversal_white_list_->include_vertex.insert(
"virtual-network-network-ipam");
traversal_white_list_->include_vertex.insert("access-control-list");
traversal_white_list_->include_vertex.insert("routing-instance");
traversal_white_list_->include_vertex.insert("namespace");
traversal_white_list_->include_vertex.insert("virtual-DNS");
traversal_white_list_->include_vertex.insert("network-ipam");
traversal_white_list_->include_vertex.insert("virtual-DNS-record");
traversal_white_list_->include_vertex.insert("interface-route-table");
traversal_white_list_->include_vertex.insert("virtual-ip");
traversal_white_list_->include_vertex.insert("loadbalancer-pool");
traversal_white_list_->include_vertex.insert("loadbalancer-member");
traversal_white_list_->include_vertex.insert("loadbalancer-healthmonitor");
traversal_white_list_->include_vertex.insert("subnet");
}
void IFMapGraphWalker::AddLinksToWhitelist() {
traversal_white_list_->include_edge.insert(
"source=virtual-router,target=virtual-machine");
traversal_white_list_->include_edge.insert(
"source=virtual-router,target=bgp-router");
traversal_white_list_->include_edge.insert(
"source=virtual-router,target=global-system-config");
traversal_white_list_->include_edge.insert(
"source=virtual-router,target=provider-attachment");
traversal_white_list_->include_edge.insert(
"source=virtual-router,target=physical-router");
traversal_white_list_->include_edge.insert(
"source=virtual-machine,target=service-instance");
traversal_white_list_->include_edge.insert(
"source=virtual-machine,target=virtual-machine-interface");
traversal_white_list_->include_edge.insert(
"source=virtual-machine-interface,target=virtual-machine");
traversal_white_list_->include_edge.insert(
"source=bgp-router,target=physical-router");
traversal_white_list_->include_edge.insert(
"source=service-instance,target=service-template");
traversal_white_list_->include_edge.insert(
"source=global-system-config,target=global-vrouter-config");
traversal_white_list_->include_edge.insert(
"source=virtual-machine-interface,target=instance-ip");
traversal_white_list_->include_edge.insert(
"source=virtual-machine-interface,target=virtual-network");
traversal_white_list_->include_edge.insert(
"source=virtual-machine-interface,target=security-group");
traversal_white_list_->include_edge.insert(
"source=virtual-machine-interface,target=floating-ip");
traversal_white_list_->include_edge.insert(
"source=virtual-machine-interface,target=customer-attachment");
traversal_white_list_->include_edge.insert(
"source=virtual-machine-interface,target=virtual-machine-interface-routing-instance");
traversal_white_list_->include_edge.insert(
"source=virtual-machine-interface,target=interface-route-table");
traversal_white_list_->include_edge.insert(
"source=logical-interface,target=virtual-machine-interface");
traversal_white_list_->include_edge.insert(
"source=physical-router,target=physical-interface");
traversal_white_list_->include_edge.insert(
"source=physical-router,target=logical-interface");
traversal_white_list_->include_edge.insert(
"source=physical-router,target=virtual-network");
traversal_white_list_->include_edge.insert(
"source=physical-interface,target=logical-interface");
traversal_white_list_->include_edge.insert(
"source=service-template,target=domain");
traversal_white_list_->include_edge.insert(
"source=virtual-network,target=floating-ip-pool");
traversal_white_list_->include_edge.insert(
"source=virtual-network,target=virtual-network-network-ipam");
traversal_white_list_->include_edge.insert(
"source=virtual-network,target=access-control-list");
traversal_white_list_->include_edge.insert(
"source=virtual-network,target=routing-instance");
traversal_white_list_->include_edge.insert(
"source=domain,target=namespace");
traversal_white_list_->include_edge.insert(
"source=domain,target=virtual-DNS");
traversal_white_list_->include_edge.insert(
"source=virtual-network-network-ipam,target=network-ipam");
traversal_white_list_->include_edge.insert(
"source=virtual-DNS,target=virtual-DNS-record");
traversal_white_list_->include_edge.insert(
"source=security-group,target=access-control-list");
traversal_white_list_->include_edge.insert(
"source=service-instance,target=loadbalancer-pool");
traversal_white_list_->include_edge.insert(
"source=loadbalancer-pool,target=loadbalancer-healthmonitor");
traversal_white_list_->include_edge.insert(
"source=loadbalancer-pool,target=virtual-ip");
traversal_white_list_->include_edge.insert(
"source=loadbalancer-pool,target=loadbalancer-member");
traversal_white_list_->include_edge.insert(
"source=virtual-machine-interface,target=subnet");
// Manually add required links not picked by the
// IFMapGraphTraversalFilterCalculator
traversal_white_list_->include_edge.insert(
"source=floating-ip,target=floating-ip-pool");
traversal_white_list_->include_edge.insert(
"source=virtual-machine-interface-routing-instance,target=routing-instance");
// VDNS needs dns/dhcp info from IPAM and FQN from Domain.
traversal_white_list_->include_edge.insert(
"source=network-ipam,target=virtual-DNS");
// Need this to get from floating-ip-pool to the virtual-network we are
// getting the pool from. EG: public-network (might not have any VMs)
traversal_white_list_->include_edge.insert(
"source=floating-ip-pool,target=virtual-network");
}
<commit_msg>IFMap walker changes to support VMI sub-interface<commit_after>/*
* Copyright (c) 2013 Juniper Networks, Inc. All rights reserved.
*/
#include "ifmap/ifmap_graph_walker.h"
#include <boost/bind.hpp>
#include "base/logging.h"
#include "db/db_graph.h"
#include "db/db_table.h"
#include "ifmap/ifmap_client.h"
#include "ifmap/ifmap_exporter.h"
#include "ifmap/ifmap_link.h"
#include "ifmap/ifmap_log.h"
#include "ifmap/ifmap_table.h"
#include "ifmap/ifmap_server.h"
#include "ifmap/ifmap_log_types.h"
#include "ifmap/ifmap_update.h"
#include "ifmap/ifmap_util.h"
#include "ifmap/ifmap_whitelist.h"
#include "schema/vnc_cfg_types.h"
class GraphPropagateFilter : public DBGraph::VisitorFilter {
public:
GraphPropagateFilter(IFMapExporter *exporter,
const IFMapTypenameWhiteList *type_filter,
const BitSet &bitset)
: exporter_(exporter),
type_filter_(type_filter),
bset_(bitset) {
}
bool VertexFilter(const DBGraphVertex *vertex) const {
return type_filter_->VertexFilter(vertex);
}
bool EdgeFilter(const DBGraphVertex *source, const DBGraphVertex *target,
const DBGraphEdge *edge) const {
bool accept = type_filter_->EdgeFilter(source, target, edge);
if (!accept) {
return false;
}
const IFMapNode *tgt = static_cast<const IFMapNode *>(target);
const IFMapNodeState *state = NodeStateLookup(tgt);
if (state != NULL && state->interest().Contains(bset_)) {
return false;
}
return true;
}
const IFMapNodeState *NodeStateLookup(const IFMapNode *node) const {
const DBTable *table = node->table();
const DBState *state =
node->GetState(table, exporter_->TableListenerId(table));
return static_cast<const IFMapNodeState *>(state);
}
private:
IFMapExporter *exporter_;
const IFMapTypenameWhiteList *type_filter_;
const BitSet &bset_;
};
IFMapGraphWalker::IFMapGraphWalker(DBGraph *graph, IFMapExporter *exporter)
: graph_(graph),
exporter_(exporter),
work_queue_(TaskScheduler::GetInstance()->GetTaskId("db::DBTable"), 0,
boost::bind(&IFMapGraphWalker::Worker, this, _1)) {
work_queue_.SetExitCallback(
boost::bind(&IFMapGraphWalker::WorkBatchEnd, this, _1));
traversal_white_list_.reset(new IFMapTypenameWhiteList());
AddNodesToWhitelist();
AddLinksToWhitelist();
}
IFMapGraphWalker::~IFMapGraphWalker() {
}
void IFMapGraphWalker::JoinVertex(DBGraphVertex *vertex, const BitSet &bset) {
IFMAP_DEBUG(JoinVertex, vertex->ToString());
IFMapNode *node = static_cast<IFMapNode *>(vertex);
IFMapNodeState *state = exporter_->NodeStateLocate(node);
state->InterestOr(bset);
node->table()->Change(node);
// Mark all dependent links as potentially modified.
for (IFMapNodeState::iterator iter = state->begin(); iter != state->end();
++iter) {
DBTable *table = exporter_->link_table();
table->Change(iter.operator->());
}
}
void IFMapGraphWalker::ProcessLinkAdd(IFMapNode *lnode, IFMapNode *rnode,
const BitSet &bset) {
GraphPropagateFilter filter(exporter_, traversal_white_list_.get(), bset);
graph_->Visit(rnode,
boost::bind(&IFMapGraphWalker::JoinVertex, this, _1, bset),
0,
filter);
}
void IFMapGraphWalker::LinkAdd(IFMapNode *lnode, const BitSet &lhs,
IFMapNode *rnode, const BitSet &rhs) {
IFMAP_DEBUG(LinkOper, "LinkAdd", lnode->ToString(), rnode->ToString(),
lhs.ToString(), rhs.ToString());
if (!lhs.empty() && !rhs.Contains(lhs) &&
traversal_white_list_->VertexFilter(rnode) &&
traversal_white_list_->EdgeFilter(lnode, rnode, NULL)) {
ProcessLinkAdd(lnode, rnode, lhs);
}
if (!rhs.empty() && !lhs.Contains(rhs) &&
traversal_white_list_->VertexFilter(lnode) &&
traversal_white_list_->EdgeFilter(rnode, lnode, NULL)) {
ProcessLinkAdd(rnode, lnode, rhs);
}
}
void IFMapGraphWalker::LinkRemove(const BitSet &bset) {
QueueEntry entry;
entry.set = bset;
work_queue_.Enqueue(entry);
}
// Check if the neighbor or link to neighbor should be filtered. Returns true
// if rnode or link to rnode should be filtered.
bool IFMapGraphWalker::FilterNeighbor(IFMapNode *lnode, IFMapNode *rnode) {
if (!traversal_white_list_->VertexFilter(rnode) ||
!traversal_white_list_->EdgeFilter(lnode, rnode, NULL)) {
return true;
}
return false;
}
void IFMapGraphWalker::RecomputeInterest(DBGraphVertex *vertex, int bit) {
IFMapNode *node = static_cast<IFMapNode *>(vertex);
IFMapNodeState *state = exporter_->NodeStateLocate(node);
state->nmask_set(bit);
}
bool IFMapGraphWalker::Worker(QueueEntry work_entry) {
const BitSet &bset = work_entry.set;
IFMapServer *server = exporter_->server();
for (size_t i = bset.find_first(); i != BitSet::npos;
i = bset.find_next(i)) {
IFMapClient *client = server->GetClient(i);
if (client == NULL) {
continue;
}
// TODO: In order to handle interest based on the vswitch registration
// there need to be links in the graph that correspond to these.
IFMapTable *table = IFMapTable::FindTable(server->database(),
"virtual-router");
IFMapNode *node = table->FindNode(client->identifier());
if ((node != NULL) && node->IsVertexValid()) {
graph_->Visit(node,
boost::bind(&IFMapGraphWalker::RecomputeInterest, this, _1, i),
0, *traversal_white_list_.get());
}
}
rm_mask_ |= work_entry.set;
return true;
}
void IFMapGraphWalker::CleanupInterest(DBGraphVertex *vertex) {
// interest = interest - rm_mask_ + nmask
IFMapNode *node = static_cast<IFMapNode *>(vertex);
IFMapNodeState *state = exporter_->NodeStateLookup(node);
if (state == NULL) {
return;
}
if (!state->interest().empty() && !state->nmask().empty()) {
IFMAP_DEBUG(CleanupInterest, node->ToString(),
state->interest().ToString(), rm_mask_.ToString(),
state->nmask().ToString());
}
BitSet ninterest;
ninterest.BuildComplement(state->interest(), rm_mask_);
ninterest |= state->nmask();
state->nmask_clear();
if (state->interest() == ninterest) {
return;
}
state->SetInterest(ninterest);
node->table()->Change(node);
// Mark all dependent links as potentially modified.
for (IFMapNodeState::iterator iter = state->begin();
iter != state->end(); ++iter) {
DBTable *table = exporter_->link_table();
table->Change(iter.operator->());
}
}
// Cleanup all graph nodes that a bit set in the remove mask (rm_mask_) but
// where not visited by the walker.
void IFMapGraphWalker::WorkBatchEnd(bool done) {
for (DBGraph::vertex_iterator iter = graph_->vertex_list_begin();
iter != graph_->vertex_list_end(); ++iter) {
DBGraphVertex *vertex = iter.operator->();
CleanupInterest(vertex);
}
rm_mask_.clear();
}
// The nodes listed below and the nodes in
// IFMapGraphTraversalFilterCalculator::CreateNodeBlackList() are mutually
// exclusive
void IFMapGraphWalker::AddNodesToWhitelist() {
traversal_white_list_->include_vertex.insert("virtual-router");
traversal_white_list_->include_vertex.insert("virtual-machine");
traversal_white_list_->include_vertex.insert("bgp-router");
traversal_white_list_->include_vertex.insert("global-system-config");
traversal_white_list_->include_vertex.insert("provider-attachment");
traversal_white_list_->include_vertex.insert("service-instance");
traversal_white_list_->include_vertex.insert("global-vrouter-config");
traversal_white_list_->include_vertex.insert(
"virtual-machine-interface");
traversal_white_list_->include_vertex.insert("security-group");
traversal_white_list_->include_vertex.insert("physical-router");
traversal_white_list_->include_vertex.insert("service-template");
traversal_white_list_->include_vertex.insert("instance-ip");
traversal_white_list_->include_vertex.insert("virtual-network");
traversal_white_list_->include_vertex.insert("floating-ip");
traversal_white_list_->include_vertex.insert("customer-attachment");
traversal_white_list_->include_vertex.insert(
"virtual-machine-interface-routing-instance");
traversal_white_list_->include_vertex.insert("physical-interface");
traversal_white_list_->include_vertex.insert("domain");
traversal_white_list_->include_vertex.insert("floating-ip-pool");
traversal_white_list_->include_vertex.insert("logical-interface");
traversal_white_list_->include_vertex.insert(
"virtual-network-network-ipam");
traversal_white_list_->include_vertex.insert("access-control-list");
traversal_white_list_->include_vertex.insert("routing-instance");
traversal_white_list_->include_vertex.insert("namespace");
traversal_white_list_->include_vertex.insert("virtual-DNS");
traversal_white_list_->include_vertex.insert("network-ipam");
traversal_white_list_->include_vertex.insert("virtual-DNS-record");
traversal_white_list_->include_vertex.insert("interface-route-table");
traversal_white_list_->include_vertex.insert("virtual-ip");
traversal_white_list_->include_vertex.insert("loadbalancer-pool");
traversal_white_list_->include_vertex.insert("loadbalancer-member");
traversal_white_list_->include_vertex.insert("loadbalancer-healthmonitor");
traversal_white_list_->include_vertex.insert("subnet");
}
void IFMapGraphWalker::AddLinksToWhitelist() {
traversal_white_list_->include_edge.insert(
"source=virtual-router,target=virtual-machine");
traversal_white_list_->include_edge.insert(
"source=virtual-router,target=bgp-router");
traversal_white_list_->include_edge.insert(
"source=virtual-router,target=global-system-config");
traversal_white_list_->include_edge.insert(
"source=virtual-router,target=provider-attachment");
traversal_white_list_->include_edge.insert(
"source=virtual-router,target=physical-router");
traversal_white_list_->include_edge.insert(
"source=virtual-machine,target=service-instance");
traversal_white_list_->include_edge.insert(
"source=virtual-machine,target=virtual-machine-interface");
traversal_white_list_->include_edge.insert(
"source=virtual-machine-interface,target=virtual-machine");
traversal_white_list_->include_edge.insert(
"source=bgp-router,target=physical-router");
traversal_white_list_->include_edge.insert(
"source=service-instance,target=service-template");
traversal_white_list_->include_edge.insert(
"source=global-system-config,target=global-vrouter-config");
traversal_white_list_->include_edge.insert(
"source=virtual-machine-interface,target=virtual-machine-interface");
traversal_white_list_->include_edge.insert(
"source=virtual-machine-interface,target=instance-ip");
traversal_white_list_->include_edge.insert(
"source=virtual-machine-interface,target=virtual-network");
traversal_white_list_->include_edge.insert(
"source=virtual-machine-interface,target=security-group");
traversal_white_list_->include_edge.insert(
"source=virtual-machine-interface,target=floating-ip");
traversal_white_list_->include_edge.insert(
"source=virtual-machine-interface,target=customer-attachment");
traversal_white_list_->include_edge.insert(
"source=virtual-machine-interface,target=virtual-machine-interface-routing-instance");
traversal_white_list_->include_edge.insert(
"source=virtual-machine-interface,target=interface-route-table");
traversal_white_list_->include_edge.insert(
"source=logical-interface,target=virtual-machine-interface");
traversal_white_list_->include_edge.insert(
"source=physical-router,target=physical-interface");
traversal_white_list_->include_edge.insert(
"source=physical-router,target=logical-interface");
traversal_white_list_->include_edge.insert(
"source=physical-router,target=virtual-network");
traversal_white_list_->include_edge.insert(
"source=physical-interface,target=logical-interface");
traversal_white_list_->include_edge.insert(
"source=service-template,target=domain");
traversal_white_list_->include_edge.insert(
"source=virtual-network,target=floating-ip-pool");
traversal_white_list_->include_edge.insert(
"source=virtual-network,target=virtual-network-network-ipam");
traversal_white_list_->include_edge.insert(
"source=virtual-network,target=access-control-list");
traversal_white_list_->include_edge.insert(
"source=virtual-network,target=routing-instance");
traversal_white_list_->include_edge.insert(
"source=domain,target=namespace");
traversal_white_list_->include_edge.insert(
"source=domain,target=virtual-DNS");
traversal_white_list_->include_edge.insert(
"source=virtual-network-network-ipam,target=network-ipam");
traversal_white_list_->include_edge.insert(
"source=virtual-DNS,target=virtual-DNS-record");
traversal_white_list_->include_edge.insert(
"source=security-group,target=access-control-list");
traversal_white_list_->include_edge.insert(
"source=service-instance,target=loadbalancer-pool");
traversal_white_list_->include_edge.insert(
"source=loadbalancer-pool,target=loadbalancer-healthmonitor");
traversal_white_list_->include_edge.insert(
"source=loadbalancer-pool,target=virtual-ip");
traversal_white_list_->include_edge.insert(
"source=loadbalancer-pool,target=loadbalancer-member");
traversal_white_list_->include_edge.insert(
"source=virtual-machine-interface,target=subnet");
// Manually add required links not picked by the
// IFMapGraphTraversalFilterCalculator
traversal_white_list_->include_edge.insert(
"source=floating-ip,target=floating-ip-pool");
traversal_white_list_->include_edge.insert(
"source=virtual-machine-interface-routing-instance,target=routing-instance");
// VDNS needs dns/dhcp info from IPAM and FQN from Domain.
traversal_white_list_->include_edge.insert(
"source=network-ipam,target=virtual-DNS");
// Need this to get from floating-ip-pool to the virtual-network we are
// getting the pool from. EG: public-network (might not have any VMs)
traversal_white_list_->include_edge.insert(
"source=floating-ip-pool,target=virtual-network");
}
<|endoftext|>
|
<commit_before>// Copyright 2010-2014 RethinkDB, all rights reserved.
#include "clustering/administration/servers/config_client.hpp"
server_config_client_t::server_config_client_t(
mailbox_manager_t *_mailbox_manager,
watchable_map_t<peer_id_t, cluster_directory_metadata_t> *_directory_view,
watchable_map_t<std::pair<peer_id_t, server_id_t>, empty_value_t>
*_peer_connections_map) :
mailbox_manager(_mailbox_manager),
directory_view(_directory_view),
peer_connections_map(_peer_connections_map),
directory_subs(
directory_view,
std::bind(&server_config_client_t::on_directory_change, this, ph::_1, ph::_2),
initial_call_t::YES),
peer_connections_map_subs(
peer_connections_map,
std::bind(&server_config_client_t::on_peer_connections_map_change,
this, ph::_1, ph::_2),
initial_call_t::YES)
{ }
bool server_config_client_t::set_config(
const server_id_t &server_id,
const name_string_t &old_server_name,
const server_config_t &new_config,
signal_t *interruptor,
admin_err_t *error_out) {
bool name_collision = false, is_noop = false;
server_config_map.read_all(
[&](const server_id_t &sid, const server_config_versioned_t *conf) {
if (sid != server_id && conf->config.name == new_config.name) {
name_collision = true;
} else if (sid == server_id && conf->config == new_config) {
is_noop = true;
}
});
if (name_collision) {
*error_out = admin_err_t{
strprintf("Cannot rename server `%s` to `%s` because server `%s` "
"already exists.",
old_server_name.c_str(), new_config.name.c_str(),
new_config.name.c_str()),
query_state_t::FAILED};
return false;
}
if (is_noop) {
return true;
}
std::string disconnect_msg = strprintf("Lost contact with server `%s` while trying "
"to change the server configuration. The configuration may or may not have been "
"changed.", old_server_name.c_str());
boost::optional<peer_id_t> peer = server_to_peer_map.get_key(server_id);
if (!static_cast<bool>(peer)) {
*error_out = admin_err_t{disconnect_msg, query_state_t::FAILED};
return false;
}
server_config_business_card_t bcard;
directory_view->read_key(*peer, [&](const cluster_directory_metadata_t *md) {
guarantee(md != nullptr);
bcard = md->server_config_business_card.get();
});
server_config_version_t version;
{
promise_t<std::pair<server_config_version_t, std::string> > reply;
mailbox_t<void(server_config_version_t, std::string)> ack_mailbox(
mailbox_manager,
[&](signal_t *, server_config_version_t v, const std::string &m) {
reply.pulse(std::make_pair(v, m));
});
disconnect_watcher_t disconnect_watcher(mailbox_manager, *peer);
send(mailbox_manager, bcard.set_config_addr,
new_config, ack_mailbox.get_address());
wait_any_t waiter(reply.get_ready_signal(), &disconnect_watcher);
wait_interruptible(&waiter, interruptor);
if (!reply.is_pulsed()) {
*error_out = admin_err_t{disconnect_msg, query_state_t::FAILED};
return false;
}
if (!reply.assert_get_value().second.empty()) {
guarantee(reply.assert_get_value().first == 0);
*error_out = admin_err_t{
strprintf("Error when trying to change the configuration of "
"server `%s`: %s The configuration was not changed.",
old_server_name.c_str(),
reply.assert_get_value().second.c_str()),
query_state_t::FAILED};
return false;
}
version = reply.assert_get_value().first;
}
/* Wait up to 10 seconds for the change to appear in the directory. */
try {
signal_timer_t timeout;
timeout.start(10000);
wait_any_t waiter(interruptor, &timeout);
server_config_map.run_key_until_satisfied(
server_id,
[&](const server_config_versioned_t *conf) {
return conf == nullptr || conf->version >= version;
},
&waiter);
} catch (const interrupted_exc_t &) {
if (interruptor->is_pulsed()) {
throw;
}
}
return true;
}
void server_config_client_t::install_server_metadata(
const peer_id_t &peer_id,
const cluster_directory_metadata_t &metadata) {
const server_id_t &server_id = metadata.server_id;
server_to_peer_map.set_key(server_id, peer_id);
peer_connections_map->read_all(
[&](const std::pair<peer_id_t, server_id_t> &pair, const empty_value_t *) {
if (pair.first == peer_id) {
connections_map.set_key(
std::make_pair(server_id, pair.second), empty_value_t());
}
});
server_config_map.set_key(server_id, metadata.server_config);
}
void server_config_client_t::on_directory_change(
const peer_id_t &peer_id,
const cluster_directory_metadata_t *metadata) {
if (metadata != nullptr) {
if (metadata->peer_type != SERVER_PEER) {
return;
}
const server_id_t &server_id = metadata->server_id;
if (!static_cast<bool>(peer_to_server_map.get_key(peer_id))) {
all_server_to_peer_map.insert(std::make_pair(server_id, peer_id));
peer_to_server_map.set_key(peer_id, server_id);
install_server_metadata(peer_id, *metadata);
} else {
server_config_map.set_key(server_id, metadata->server_config);
}
} else {
boost::optional<server_id_t> server_id = peer_to_server_map.get_key(peer_id);
if (!static_cast<bool>(server_id)) {
return;
}
for (auto it = all_server_to_peer_map.lower_bound(*server_id); ; ++it) {
guarantee(it != all_server_to_peer_map.end());
if (it->second == peer_id) {
all_server_to_peer_map.erase(it);
break;
}
}
peer_to_server_map.delete_key(peer_id);
server_to_peer_map.delete_key(*server_id);
peer_connections_map->read_all(
[&](const std::pair<peer_id_t, server_id_t> &pair, const empty_value_t *) {
if (pair.first == peer_id) {
connections_map.delete_key(std::make_pair(*server_id, pair.second));
}
});
server_config_map.delete_key(*server_id);
/* If there is another connected peer with the same server ID, reinstall its
values. */
auto jt = all_server_to_peer_map.find(*server_id);
if (jt != all_server_to_peer_map.end()) {
directory_view->read_key(jt->second,
[&](const cluster_directory_metadata_t *other_metadata) {
guarantee(other_metadata != nullptr);
guarantee(other_metadata->server_id == *server_id);
install_server_metadata(jt->second, *other_metadata);
});
}
}
}
void server_config_client_t::on_peer_connections_map_change(
const std::pair<peer_id_t, server_id_t> &key,
const empty_value_t *value) {
directory_view->read_key(key.first,
[&](const cluster_directory_metadata_t *metadata) {
if (metadata != nullptr) {
if (value != nullptr) {
connections_map.set_key(
std::make_pair(metadata->server_id, key.second), empty_value_t());
} else {
connections_map.delete_key(
std::make_pair(metadata->server_id, key.second));
}
}
});
}
<commit_msg>Fixed error message.<commit_after>// Copyright 2010-2014 RethinkDB, all rights reserved.
#include "clustering/administration/servers/config_client.hpp"
server_config_client_t::server_config_client_t(
mailbox_manager_t *_mailbox_manager,
watchable_map_t<peer_id_t, cluster_directory_metadata_t> *_directory_view,
watchable_map_t<std::pair<peer_id_t, server_id_t>, empty_value_t>
*_peer_connections_map) :
mailbox_manager(_mailbox_manager),
directory_view(_directory_view),
peer_connections_map(_peer_connections_map),
directory_subs(
directory_view,
std::bind(&server_config_client_t::on_directory_change, this, ph::_1, ph::_2),
initial_call_t::YES),
peer_connections_map_subs(
peer_connections_map,
std::bind(&server_config_client_t::on_peer_connections_map_change,
this, ph::_1, ph::_2),
initial_call_t::YES)
{ }
bool server_config_client_t::set_config(
const server_id_t &server_id,
const name_string_t &old_server_name,
const server_config_t &new_config,
signal_t *interruptor,
admin_err_t *error_out) {
bool name_collision = false, is_noop = false;
server_config_map.read_all(
[&](const server_id_t &sid, const server_config_versioned_t *conf) {
if (sid != server_id && conf->config.name == new_config.name) {
name_collision = true;
} else if (sid == server_id && conf->config == new_config) {
is_noop = true;
}
});
if (name_collision) {
*error_out = admin_err_t{
strprintf("Cannot rename server `%s` to `%s` because server `%s` "
"already exists.",
old_server_name.c_str(), new_config.name.c_str(),
new_config.name.c_str()),
query_state_t::FAILED};
return false;
}
if (is_noop) {
return true;
}
std::string disconnect_msg = strprintf("Lost contact with server `%s` while trying "
"to change the server configuration. The configuration may or may not have been "
"changed.", old_server_name.c_str());
boost::optional<peer_id_t> peer = server_to_peer_map.get_key(server_id);
if (!static_cast<bool>(peer)) {
std::string s = strprintf(
"Could not contact server `%s` while trying to change the server "
"configuration. The configuration was not changed.",
old_server_name.c_str());
*error_out = admin_err_t{s, query_state_t::FAILED};
return false;
}
server_config_business_card_t bcard;
directory_view->read_key(*peer, [&](const cluster_directory_metadata_t *md) {
guarantee(md != nullptr);
bcard = md->server_config_business_card.get();
});
server_config_version_t version;
{
promise_t<std::pair<server_config_version_t, std::string> > reply;
mailbox_t<void(server_config_version_t, std::string)> ack_mailbox(
mailbox_manager,
[&](signal_t *, server_config_version_t v, const std::string &m) {
reply.pulse(std::make_pair(v, m));
});
disconnect_watcher_t disconnect_watcher(mailbox_manager, *peer);
send(mailbox_manager, bcard.set_config_addr,
new_config, ack_mailbox.get_address());
wait_any_t waiter(reply.get_ready_signal(), &disconnect_watcher);
wait_interruptible(&waiter, interruptor);
if (!reply.is_pulsed()) {
*error_out = admin_err_t{disconnect_msg, query_state_t::INDETERMINATE};
return false;
}
if (!reply.assert_get_value().second.empty()) {
guarantee(reply.assert_get_value().first == 0);
*error_out = admin_err_t{
strprintf("Error when trying to change the configuration of "
"server `%s`: %s The configuration was not changed.",
old_server_name.c_str(),
reply.assert_get_value().second.c_str()),
query_state_t::FAILED};
return false;
}
version = reply.assert_get_value().first;
}
/* Wait up to 10 seconds for the change to appear in the directory. */
try {
signal_timer_t timeout;
timeout.start(10000);
wait_any_t waiter(interruptor, &timeout);
server_config_map.run_key_until_satisfied(
server_id,
[&](const server_config_versioned_t *conf) {
return conf == nullptr || conf->version >= version;
},
&waiter);
} catch (const interrupted_exc_t &) {
if (interruptor->is_pulsed()) {
throw;
}
}
return true;
}
void server_config_client_t::install_server_metadata(
const peer_id_t &peer_id,
const cluster_directory_metadata_t &metadata) {
const server_id_t &server_id = metadata.server_id;
server_to_peer_map.set_key(server_id, peer_id);
peer_connections_map->read_all(
[&](const std::pair<peer_id_t, server_id_t> &pair, const empty_value_t *) {
if (pair.first == peer_id) {
connections_map.set_key(
std::make_pair(server_id, pair.second), empty_value_t());
}
});
server_config_map.set_key(server_id, metadata.server_config);
}
void server_config_client_t::on_directory_change(
const peer_id_t &peer_id,
const cluster_directory_metadata_t *metadata) {
if (metadata != nullptr) {
if (metadata->peer_type != SERVER_PEER) {
return;
}
const server_id_t &server_id = metadata->server_id;
if (!static_cast<bool>(peer_to_server_map.get_key(peer_id))) {
all_server_to_peer_map.insert(std::make_pair(server_id, peer_id));
peer_to_server_map.set_key(peer_id, server_id);
install_server_metadata(peer_id, *metadata);
} else {
server_config_map.set_key(server_id, metadata->server_config);
}
} else {
boost::optional<server_id_t> server_id = peer_to_server_map.get_key(peer_id);
if (!static_cast<bool>(server_id)) {
return;
}
for (auto it = all_server_to_peer_map.lower_bound(*server_id); ; ++it) {
guarantee(it != all_server_to_peer_map.end());
if (it->second == peer_id) {
all_server_to_peer_map.erase(it);
break;
}
}
peer_to_server_map.delete_key(peer_id);
server_to_peer_map.delete_key(*server_id);
peer_connections_map->read_all(
[&](const std::pair<peer_id_t, server_id_t> &pair, const empty_value_t *) {
if (pair.first == peer_id) {
connections_map.delete_key(std::make_pair(*server_id, pair.second));
}
});
server_config_map.delete_key(*server_id);
/* If there is another connected peer with the same server ID, reinstall its
values. */
auto jt = all_server_to_peer_map.find(*server_id);
if (jt != all_server_to_peer_map.end()) {
directory_view->read_key(jt->second,
[&](const cluster_directory_metadata_t *other_metadata) {
guarantee(other_metadata != nullptr);
guarantee(other_metadata->server_id == *server_id);
install_server_metadata(jt->second, *other_metadata);
});
}
}
}
void server_config_client_t::on_peer_connections_map_change(
const std::pair<peer_id_t, server_id_t> &key,
const empty_value_t *value) {
directory_view->read_key(key.first,
[&](const cluster_directory_metadata_t *metadata) {
if (metadata != nullptr) {
if (value != nullptr) {
connections_map.set_key(
std::make_pair(metadata->server_id, key.second), empty_value_t());
} else {
connections_map.delete_key(
std::make_pair(metadata->server_id, key.second));
}
}
});
}
<|endoftext|>
|
<commit_before>/*===================================================================
The Medical Imaging Interaction Toolkit (MITK)
Copyright (c) German Cancer Research Center,
Division of Medical and Biological Informatics.
All rights reserved.
This software is distributed WITHOUT ANY WARRANTY; without
even the implied warranty of MERCHANTABILITY or FITNESS FOR
A PARTICULAR PURPOSE.
See LICENSE.txt or http://www.mitk.org for details.
===================================================================*/
#include "mitkContourModelReader.h"
#include <iostream>
#include <fstream>
#include <locale>
mitk::ContourModelReader::ContourModelReader()
{
m_Success = false;
}
mitk::ContourModelReader::~ContourModelReader()
{}
void mitk::ContourModelReader::GenerateData()
{
std::locale::global(std::locale("C"));
m_Success = false;
if ( m_FileName == "" )
{
itkWarningMacro( << "Sorry, filename has not been set!" );
return ;
}
if ( ! this->CanReadFile( m_FileName.c_str() ) )
{
itkWarningMacro( << "Sorry, can't read file " << m_FileName << "!" );
return ;
}
try{
TiXmlDocument doc(m_FileName.c_str());
bool loadOkay = doc.LoadFile();
if (loadOkay)
{
TiXmlHandle docHandle( &doc );
//handle geometry information
TiXmlElement* currentContourModelElement = docHandle.FirstChildElement("contourModel").FirstChildElement("head").FirstChildElement("geometryInformation").ToElement();
/*++++ handle n contourModels within data tags ++++*/
unsigned int contourCounter(0);
for( TiXmlElement* currentContourModelElement = docHandle.FirstChildElement("contourModel").FirstChildElement("data").ToElement();
currentContourModelElement != NULL; currentContourModelElement = currentContourModelElement->NextSiblingElement())
{
mitk::ContourModel::Pointer newContourModel = mitk::ContourModel::New();
if(currentContourModelElement->FirstChildElement("timestep") != NULL)
{
/*++++ handle n timesteps within timestep tags ++++*/
for( TiXmlElement* currentTimeSeries = currentContourModelElement->FirstChildElement("timestep")->ToElement();
currentTimeSeries != NULL; currentTimeSeries = currentTimeSeries->NextSiblingElement())
{
unsigned int currentTimeStep(0);
currentTimeStep = atoi(currentTimeSeries->Attribute("n"));
newContourModel = this->ReadPoint(newContourModel, currentTimeSeries, currentTimeStep);
}
/*++++ END handle n timesteps within timestep tags ++++*/
}
else
{
//this should not happen
MITK_WARN << "wrong file format!";
//newContourModel = this->ReadPoint(newContourModel, currentContourModelElement, 0);
}
this->SetNthOutput( contourCounter, newContourModel );
contourCounter++;
}
/*++++ END handle n contourModels within data tags ++++*/
}
else
{
MITK_WARN << "XML parser error!";
}
}catch(...)
{
MITK_ERROR << "Cannot read contourModel.";
m_Success = false;
}
m_Success = true;
}
void mitk::ContourModelReader::ReadPoint(mitk::ContourModel::Pointer newContourModel,
TiXmlElement* currentTimeSeries, unsigned int currentTimeStep)
{
//check if the timesteps in contourModel have to be expanded
if(currentTimeStep != newContourModel->GetTimeSteps())
{
newContourModel->Expand(currentTimeStep+1);
}
//read all points within controlPoints tag
if(currentTimeSeries->FirstChildElement("controlPoints")->FirstChildElement("point") != NULL)
{
for( TiXmlElement* currentPoint = currentTimeSeries->FirstChildElement("controlPoints")->FirstChildElement("point")->ToElement();
currentPoint != NULL; currentPoint = currentPoint->NextSiblingElement())
{
mitk::PointSpecificationType spec((mitk::PointSpecificationType) 0);
double x(0.0);
double y(0.0);
double z(0.0);
x = atof(currentPoint->FirstChildElement("x")->GetText());
y = atof(currentPoint->FirstChildElement("y")->GetText());
z = atof(currentPoint->FirstChildElement("z")->GetText());
mitk::Point3D point;
mitk::FillVector3D(point, x, y, z);
newContourModel->AddVertex(point);
}
}
else
{
//nothing to read
}
}
void mitk::ContourModelReader::GenerateOutputInformation()
{
}
int mitk::ContourModelReader::CanReadFile ( const char *name )
{
std::ifstream in( name );
bool isGood = in.good();
in.close();
return isGood;
}
bool mitk::ContourModelReader::CanReadFile(const std::string filename, const std::string filePrefix, const std::string filePattern)
{
// First check the extension
if( filename == "" )
{
//MITK_INFO<<"No filename specified."<<std::endl;
return false;
}
// check if image is serie
if( filePattern != "" && filePrefix != "" )
return false;
bool extensionFound = false;
std::string::size_type MPSPos = filename.rfind(".cnt");
if ((MPSPos != std::string::npos)
&& (MPSPos == filename.length() - 4))
{
extensionFound = true;
}
MPSPos = filename.rfind(".CNT");
if ((MPSPos != std::string::npos)
&& (MPSPos == filename.length() - 4))
{
extensionFound = true;
}
if( !extensionFound )
{
//MITK_INFO<<"The filename extension is not recognized."<<std::endl;
return false;
}
return true;
}
void mitk::ContourModelReader::ResizeOutputs( const unsigned int& num )
{
unsigned int prevNum = this->GetNumberOfOutputs();
this->SetNumberOfOutputs( num );
for ( unsigned int i = prevNum; i < num; ++i )
{
this->SetNthOutput( i, this->MakeOutput( i ).GetPointer() );
}
}
bool mitk::ContourModelReader::GetSuccess() const
{
return m_Success;
}
<commit_msg>change method to void so no assingment is needed<commit_after>/*===================================================================
The Medical Imaging Interaction Toolkit (MITK)
Copyright (c) German Cancer Research Center,
Division of Medical and Biological Informatics.
All rights reserved.
This software is distributed WITHOUT ANY WARRANTY; without
even the implied warranty of MERCHANTABILITY or FITNESS FOR
A PARTICULAR PURPOSE.
See LICENSE.txt or http://www.mitk.org for details.
===================================================================*/
#include "mitkContourModelReader.h"
#include <iostream>
#include <fstream>
#include <locale>
mitk::ContourModelReader::ContourModelReader()
{
m_Success = false;
}
mitk::ContourModelReader::~ContourModelReader()
{}
void mitk::ContourModelReader::GenerateData()
{
std::locale::global(std::locale("C"));
m_Success = false;
if ( m_FileName == "" )
{
itkWarningMacro( << "Sorry, filename has not been set!" );
return ;
}
if ( ! this->CanReadFile( m_FileName.c_str() ) )
{
itkWarningMacro( << "Sorry, can't read file " << m_FileName << "!" );
return ;
}
try{
TiXmlDocument doc(m_FileName.c_str());
bool loadOkay = doc.LoadFile();
if (loadOkay)
{
TiXmlHandle docHandle( &doc );
//handle geometry information
TiXmlElement* currentContourModelElement = docHandle.FirstChildElement("contourModel").FirstChildElement("head").FirstChildElement("geometryInformation").ToElement();
/*++++ handle n contourModels within data tags ++++*/
unsigned int contourCounter(0);
for( TiXmlElement* currentContourModelElement = docHandle.FirstChildElement("contourModel").FirstChildElement("data").ToElement();
currentContourModelElement != NULL; currentContourModelElement = currentContourModelElement->NextSiblingElement())
{
mitk::ContourModel::Pointer newContourModel = mitk::ContourModel::New();
if(currentContourModelElement->FirstChildElement("timestep") != NULL)
{
/*++++ handle n timesteps within timestep tags ++++*/
for( TiXmlElement* currentTimeSeries = currentContourModelElement->FirstChildElement("timestep")->ToElement();
currentTimeSeries != NULL; currentTimeSeries = currentTimeSeries->NextSiblingElement())
{
unsigned int currentTimeStep(0);
currentTimeStep = atoi(currentTimeSeries->Attribute("n"));
this->ReadPoint(newContourModel, currentTimeSeries, currentTimeStep);
}
/*++++ END handle n timesteps within timestep tags ++++*/
}
else
{
//this should not happen
MITK_WARN << "wrong file format!";
//newContourModel = this->ReadPoint(newContourModel, currentContourModelElement, 0);
}
this->SetNthOutput( contourCounter, newContourModel );
contourCounter++;
}
/*++++ END handle n contourModels within data tags ++++*/
}
else
{
MITK_WARN << "XML parser error!";
}
}catch(...)
{
MITK_ERROR << "Cannot read contourModel.";
m_Success = false;
}
m_Success = true;
}
void mitk::ContourModelReader::ReadPoint(mitk::ContourModel::Pointer newContourModel,
TiXmlElement* currentTimeSeries, unsigned int currentTimeStep)
{
//check if the timesteps in contourModel have to be expanded
if(currentTimeStep != newContourModel->GetTimeSteps())
{
newContourModel->Expand(currentTimeStep+1);
}
//read all points within controlPoints tag
if(currentTimeSeries->FirstChildElement("controlPoints")->FirstChildElement("point") != NULL)
{
for( TiXmlElement* currentPoint = currentTimeSeries->FirstChildElement("controlPoints")->FirstChildElement("point")->ToElement();
currentPoint != NULL; currentPoint = currentPoint->NextSiblingElement())
{
mitk::PointSpecificationType spec((mitk::PointSpecificationType) 0);
double x(0.0);
double y(0.0);
double z(0.0);
x = atof(currentPoint->FirstChildElement("x")->GetText());
y = atof(currentPoint->FirstChildElement("y")->GetText());
z = atof(currentPoint->FirstChildElement("z")->GetText());
mitk::Point3D point;
mitk::FillVector3D(point, x, y, z);
newContourModel->AddVertex(point);
}
}
else
{
//nothing to read
}
}
void mitk::ContourModelReader::GenerateOutputInformation()
{
}
int mitk::ContourModelReader::CanReadFile ( const char *name )
{
std::ifstream in( name );
bool isGood = in.good();
in.close();
return isGood;
}
bool mitk::ContourModelReader::CanReadFile(const std::string filename, const std::string filePrefix, const std::string filePattern)
{
// First check the extension
if( filename == "" )
{
//MITK_INFO<<"No filename specified."<<std::endl;
return false;
}
// check if image is serie
if( filePattern != "" && filePrefix != "" )
return false;
bool extensionFound = false;
std::string::size_type MPSPos = filename.rfind(".cnt");
if ((MPSPos != std::string::npos)
&& (MPSPos == filename.length() - 4))
{
extensionFound = true;
}
MPSPos = filename.rfind(".CNT");
if ((MPSPos != std::string::npos)
&& (MPSPos == filename.length() - 4))
{
extensionFound = true;
}
if( !extensionFound )
{
//MITK_INFO<<"The filename extension is not recognized."<<std::endl;
return false;
}
return true;
}
void mitk::ContourModelReader::ResizeOutputs( const unsigned int& num )
{
unsigned int prevNum = this->GetNumberOfOutputs();
this->SetNumberOfOutputs( num );
for ( unsigned int i = prevNum; i < num; ++i )
{
this->SetNthOutput( i, this->MakeOutput( i ).GetPointer() );
}
}
bool mitk::ContourModelReader::GetSuccess() const
{
return m_Success;
}
<|endoftext|>
|
<commit_before>/*
* This istream filter adds HTTP chunking.
*
* author: Max Kellermann <mk@cm4all.com>
*/
#include "istream_chunked.hxx"
#include "istream_internal.hxx"
#include "pool.hxx"
#include "format.h"
#include "util/Cast.hxx"
#include <assert.h>
#include <string.h>
struct ChunkedIstream {
struct istream output;
struct istream *input;
/**
* This flag is true while writing the buffer inside
* istream_chunked_read(). chunked_input_data() will check it,
* and refuse to accept more data from the input. This avoids
* writing the buffer recursively.
*/
bool writing_buffer = false;
char buffer[7];
size_t buffer_sent = sizeof(buffer);
size_t missing_from_current_chunk = 0;
ChunkedIstream(struct pool &p, struct istream &_input);
};
static inline int
chunked_buffer_empty(const ChunkedIstream *chunked)
{
assert(chunked->buffer_sent <= sizeof(chunked->buffer));
return chunked->buffer_sent == sizeof(chunked->buffer);
}
/** set the buffer length and return a pointer to the first byte */
static inline char *
chunked_buffer_set(ChunkedIstream *chunked, size_t length)
{
assert(chunked_buffer_empty(chunked));
assert(length <= sizeof(chunked->buffer));
chunked->buffer_sent = sizeof(chunked->buffer) - length;
return chunked->buffer + chunked->buffer_sent;
}
/** append data to the buffer */
static void
chunked_buffer_append(ChunkedIstream *chunked,
const void *data, size_t length)
{
assert(data != nullptr);
assert(length > 0);
assert(length <= chunked->buffer_sent);
const void *old = chunked->buffer + chunked->buffer_sent;
size_t old_length = sizeof(chunked->buffer) - chunked->buffer_sent;
#ifndef NDEBUG
/* simulate a buffer reset; if we don't do this, an assertion in
chunked_buffer_set() fails (which is invalid for this special
case) */
chunked->buffer_sent = sizeof(chunked->buffer);
#endif
auto dest = chunked_buffer_set(chunked, old_length + length);
memmove(dest, old, old_length);
dest += old_length;
memcpy(dest, data, length);
}
static void
chunked_start_chunk(ChunkedIstream *chunked, size_t length)
{
assert(length > 0);
assert(chunked_buffer_empty(chunked));
assert(chunked->missing_from_current_chunk == 0);
if (length > 0x8000)
/* maximum chunk size is 32kB for now */
length = 0x8000;
chunked->missing_from_current_chunk = length;
auto buffer = chunked_buffer_set(chunked, 6);
format_uint16_hex_fixed(buffer, (uint16_t)length);
buffer[4] = '\r';
buffer[5] = '\n';
}
/**
* Returns true if the buffer is consumed.
*/
static bool
chunked_write_buffer(ChunkedIstream *chunked)
{
size_t length = sizeof(chunked->buffer) - chunked->buffer_sent;
if (length == 0)
return true;
size_t nbytes = istream_invoke_data(&chunked->output,
chunked->buffer + chunked->buffer_sent,
length);
if (nbytes > 0)
chunked->buffer_sent += nbytes;
return nbytes == length;
}
/**
* Wrapper for chunked_write_buffer() that sets and clears the
* writing_buffer flag. This requires acquiring a pool reference to
* do that safely.
*
* @return true if the buffer is consumed.
*/
static bool
chunked_write_buffer2(ChunkedIstream *chunked)
{
const ScopePoolRef ref(*chunked->output.pool TRACE_ARGS);
assert(!chunked->writing_buffer);
chunked->writing_buffer = true;
const bool result = chunked_write_buffer(chunked);
chunked->writing_buffer = false;
return result;
}
static size_t
chunked_feed(ChunkedIstream *chunked, const char *data, size_t length)
{
size_t total = 0, rest, nbytes;
assert(chunked->input != nullptr);
do {
assert(!chunked->writing_buffer);
if (chunked_buffer_empty(chunked) &&
chunked->missing_from_current_chunk == 0)
chunked_start_chunk(chunked, length - total);
if (!chunked_write_buffer(chunked))
return chunked->input == nullptr ? 0 : total;
assert(chunked_buffer_empty(chunked));
if (chunked->missing_from_current_chunk == 0) {
/* we have just written the previous chunk trailer;
re-start this loop to start a new chunk */
nbytes = rest = 0;
continue;
}
rest = length - total;
if (rest > chunked->missing_from_current_chunk)
rest = chunked->missing_from_current_chunk;
nbytes = istream_invoke_data(&chunked->output, data + total, rest);
if (nbytes == 0)
return chunked->input == nullptr ? 0 : total;
total += nbytes;
chunked->missing_from_current_chunk -= nbytes;
if (chunked->missing_from_current_chunk == 0) {
/* a chunk ends with "\r\n" */
char *buffer = chunked_buffer_set(chunked, 2);
buffer[0] = '\r';
buffer[1] = '\n';
}
} while ((!chunked_buffer_empty(chunked) || total < length) &&
nbytes == rest);
return total;
}
/*
* istream handler
*
*/
static size_t
chunked_input_data(const void *data, size_t length, void *ctx)
{
auto *chunked = (ChunkedIstream *)ctx;
if (chunked->writing_buffer)
/* this is a recursive call from istream_chunked_read(): bail
out */
return 0;
const ScopePoolRef ref(*chunked->output.pool TRACE_ARGS);
return chunked_feed(chunked, (const char*)data, length);
}
static void
chunked_input_eof(void *ctx)
{
auto *chunked = (ChunkedIstream *)ctx;
assert(chunked->input != nullptr);
assert(chunked->missing_from_current_chunk == 0);
chunked->input = nullptr;
/* write EOF chunk (length 0) */
chunked_buffer_append(chunked, "0\r\n\r\n", 5);
/* flush the buffer */
if (chunked_write_buffer(chunked))
istream_deinit_eof(&chunked->output);
}
static void
chunked_input_abort(GError *error, void *ctx)
{
auto *chunked = (ChunkedIstream *)ctx;
assert(chunked->input != nullptr);
chunked->input = nullptr;
istream_deinit_abort(&chunked->output, error);
}
static constexpr struct istream_handler chunked_input_handler = {
.data = chunked_input_data,
.eof = chunked_input_eof,
.abort = chunked_input_abort,
};
/*
* istream implementation
*
*/
static inline ChunkedIstream *
istream_to_chunked(struct istream *istream)
{
return &ContainerCast2(*istream, &ChunkedIstream::output);
}
static void
istream_chunked_read(struct istream *istream)
{
ChunkedIstream *chunked = istream_to_chunked(istream);
if (!chunked_write_buffer2(chunked))
return;
if (chunked->input == nullptr) {
istream_deinit_eof(&chunked->output);
return;
}
assert(chunked->input != nullptr);
if (chunked_buffer_empty(chunked) &&
chunked->missing_from_current_chunk == 0) {
off_t available = istream_available(chunked->input, true);
if (available > 0) {
chunked_start_chunk(chunked, available);
if (!chunked_write_buffer2(chunked))
return;
}
}
istream_read(chunked->input);
}
static void
istream_chunked_close(struct istream *istream)
{
ChunkedIstream *chunked = istream_to_chunked(istream);
if (chunked->input != nullptr)
istream_free_handler(&chunked->input);
istream_deinit(&chunked->output);
}
static constexpr struct istream_class istream_chunked = {
.read = istream_chunked_read,
.close = istream_chunked_close,
};
/*
* constructor
*
*/
inline ChunkedIstream::ChunkedIstream(struct pool &p, struct istream &_input)
{
istream_init(&output, &istream_chunked, &p);
istream_assign_handler(&input, &_input,
&chunked_input_handler, this,
0);
}
struct istream *
istream_chunked_new(struct pool *pool, struct istream *input)
{
assert(input != nullptr);
assert(!istream_has_handler(input));
auto *chunked = NewFromPool<ChunkedIstream>(*pool, *pool, *input);
return &chunked->output;
}
<commit_msg>istream/chunked: move functions into the struct<commit_after>/*
* This istream filter adds HTTP chunking.
*
* author: Max Kellermann <mk@cm4all.com>
*/
#include "istream_chunked.hxx"
#include "istream_internal.hxx"
#include "pool.hxx"
#include "format.h"
#include "util/Cast.hxx"
#include <assert.h>
#include <string.h>
struct ChunkedIstream {
struct istream output;
struct istream *input;
/**
* This flag is true while writing the buffer inside
* istream_chunked_read(). chunked_input_data() will check it,
* and refuse to accept more data from the input. This avoids
* writing the buffer recursively.
*/
bool writing_buffer = false;
char buffer[7];
size_t buffer_sent = sizeof(buffer);
size_t missing_from_current_chunk = 0;
ChunkedIstream(struct pool &p, struct istream &_input);
bool IsBufferEmpty() const {
assert(buffer_sent <= sizeof(buffer));
return buffer_sent == sizeof(buffer);
}
/** set the buffer length and return a pointer to the first byte */
char *SetBuffer(size_t length) {
assert(IsBufferEmpty());
assert(length <= sizeof(buffer));
buffer_sent = sizeof(buffer) - length;
return buffer + buffer_sent;
}
/** append data to the buffer */
void AppendToBuffer(const void *data, size_t length);
void StartChunk(size_t length);
/**
* Returns true if the buffer is consumed.
*/
bool SendBuffer();
/**
* Wrapper for SendBuffer() that sets and clears the
* writing_buffer flag. This requires acquiring a pool reference
* to do that safely.
*
* @return true if the buffer is consumed.
*/
bool SendBuffer2();
size_t Feed(const char *data, size_t length);
};
void
ChunkedIstream::AppendToBuffer(const void *data, size_t length)
{
assert(data != nullptr);
assert(length > 0);
assert(length <= buffer_sent);
const void *old = buffer + buffer_sent;
size_t old_length = sizeof(buffer) - buffer_sent;
#ifndef NDEBUG
/* simulate a buffer reset; if we don't do this, an assertion in
chunked_buffer_set() fails (which is invalid for this special
case) */
buffer_sent = sizeof(buffer);
#endif
auto dest = SetBuffer(old_length + length);
memmove(dest, old, old_length);
dest += old_length;
memcpy(dest, data, length);
}
void
ChunkedIstream::StartChunk(size_t length)
{
assert(length > 0);
assert(IsBufferEmpty());
assert(missing_from_current_chunk == 0);
if (length > 0x8000)
/* maximum chunk size is 32kB for now */
length = 0x8000;
missing_from_current_chunk = length;
auto p = SetBuffer(6);
format_uint16_hex_fixed(p, (uint16_t)length);
p[4] = '\r';
p[5] = '\n';
}
bool
ChunkedIstream::SendBuffer()
{
size_t length = sizeof(buffer) - buffer_sent;
if (length == 0)
return true;
size_t nbytes = istream_invoke_data(&output, buffer + buffer_sent, length);
if (nbytes > 0)
buffer_sent += nbytes;
return nbytes == length;
}
bool
ChunkedIstream::SendBuffer2()
{
const ScopePoolRef ref(*output.pool TRACE_ARGS);
assert(!writing_buffer);
writing_buffer = true;
const bool result = SendBuffer();
writing_buffer = false;
return result;
}
inline size_t
ChunkedIstream::Feed(const char *data, size_t length)
{
size_t total = 0, rest, nbytes;
assert(input != nullptr);
do {
assert(!writing_buffer);
if (IsBufferEmpty() && missing_from_current_chunk == 0)
StartChunk(length - total);
if (!SendBuffer())
return input == nullptr ? 0 : total;
assert(IsBufferEmpty());
if (missing_from_current_chunk == 0) {
/* we have just written the previous chunk trailer;
re-start this loop to start a new chunk */
nbytes = rest = 0;
continue;
}
rest = length - total;
if (rest > missing_from_current_chunk)
rest = missing_from_current_chunk;
nbytes = istream_invoke_data(&output, data + total, rest);
if (nbytes == 0)
return input == nullptr ? 0 : total;
total += nbytes;
missing_from_current_chunk -= nbytes;
if (missing_from_current_chunk == 0) {
/* a chunk ends with "\r\n" */
char *p = SetBuffer(2);
p[0] = '\r';
p[1] = '\n';
}
} while ((!IsBufferEmpty() || total < length) && nbytes == rest);
return total;
}
/*
* istream handler
*
*/
static size_t
chunked_input_data(const void *data, size_t length, void *ctx)
{
auto *chunked = (ChunkedIstream *)ctx;
if (chunked->writing_buffer)
/* this is a recursive call from istream_chunked_read(): bail
out */
return 0;
const ScopePoolRef ref(*chunked->output.pool TRACE_ARGS);
return chunked->Feed((const char*)data, length);
}
static void
chunked_input_eof(void *ctx)
{
auto *chunked = (ChunkedIstream *)ctx;
assert(chunked->input != nullptr);
assert(chunked->missing_from_current_chunk == 0);
chunked->input = nullptr;
/* write EOF chunk (length 0) */
chunked->AppendToBuffer("0\r\n\r\n", 5);
/* flush the buffer */
if (chunked->SendBuffer())
istream_deinit_eof(&chunked->output);
}
static void
chunked_input_abort(GError *error, void *ctx)
{
auto *chunked = (ChunkedIstream *)ctx;
assert(chunked->input != nullptr);
chunked->input = nullptr;
istream_deinit_abort(&chunked->output, error);
}
static constexpr struct istream_handler chunked_input_handler = {
.data = chunked_input_data,
.eof = chunked_input_eof,
.abort = chunked_input_abort,
};
/*
* istream implementation
*
*/
static inline ChunkedIstream *
istream_to_chunked(struct istream *istream)
{
return &ContainerCast2(*istream, &ChunkedIstream::output);
}
static void
istream_chunked_read(struct istream *istream)
{
ChunkedIstream *chunked = istream_to_chunked(istream);
if (!chunked->SendBuffer2())
return;
if (chunked->input == nullptr) {
istream_deinit_eof(&chunked->output);
return;
}
assert(chunked->input != nullptr);
if (chunked->IsBufferEmpty() &&
chunked->missing_from_current_chunk == 0) {
off_t available = istream_available(chunked->input, true);
if (available > 0) {
chunked->StartChunk(available);
if (!chunked->SendBuffer2())
return;
}
}
istream_read(chunked->input);
}
static void
istream_chunked_close(struct istream *istream)
{
ChunkedIstream *chunked = istream_to_chunked(istream);
if (chunked->input != nullptr)
istream_free_handler(&chunked->input);
istream_deinit(&chunked->output);
}
static constexpr struct istream_class istream_chunked = {
.read = istream_chunked_read,
.close = istream_chunked_close,
};
/*
* constructor
*
*/
inline ChunkedIstream::ChunkedIstream(struct pool &p, struct istream &_input)
{
istream_init(&output, &istream_chunked, &p);
istream_assign_handler(&input, &_input,
&chunked_input_handler, this,
0);
}
struct istream *
istream_chunked_new(struct pool *pool, struct istream *input)
{
assert(input != nullptr);
assert(!istream_has_handler(input));
auto *chunked = NewFromPool<ChunkedIstream>(*pool, *pool, *input);
return &chunked->output;
}
<|endoftext|>
|
<commit_before>/*
* Copyright 2007-2017 Content Management AG
* All rights reserved.
*
* author: Max Kellermann <mk@cm4all.com>
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* - Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* - Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the
* distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* FOUNDATION 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 "istream_deflate.hxx"
#include "UnusedPtr.hxx"
#include "New.hxx"
#include "FacadeIstream.hxx"
#include "pool/pool.hxx"
#include "fb_pool.hxx"
#include "SliceFifoBuffer.hxx"
#include "event/DeferEvent.hxx"
#include "util/Cast.hxx"
#include "util/ConstBuffer.hxx"
#include "util/WritableBuffer.hxx"
#include <zlib.h>
#include <stdexcept>
#include <assert.h>
class ZlibError : public std::runtime_error {
int code;
public:
explicit ZlibError(int _code, const char *_msg)
:std::runtime_error(_msg), code(_code) {}
int GetCode() const noexcept {
return code;
}
};
class DeflateIstream final : public FacadeIstream {
const bool gzip;
bool z_initialized = false, z_stream_end = false;
z_stream z;
bool had_input, had_output;
bool reading;
SliceFifoBuffer buffer;
/**
* This callback is used to request more data from the input if an
* OnData() call did not produce any output. This tries to
* prevent stalling the stream.
*/
DeferEvent defer;
public:
DeflateIstream(struct pool &_pool, UnusedIstreamPtr _input,
EventLoop &event_loop, bool _gzip)
:FacadeIstream(_pool, std::move(_input)),
gzip(_gzip),
reading(false),
defer(event_loop, BIND_THIS_METHOD(OnDeferred))
{
}
~DeflateIstream() {
defer.Cancel();
}
bool InitZlib() noexcept;
void DeinitZlib() noexcept {
if (z_initialized) {
z_initialized = false;
deflateEnd(&z);
}
}
void Abort(std::exception_ptr ep) noexcept {
DeinitZlib();
if (HasInput())
ClearAndCloseInput();
DestroyError(ep);
}
void Abort(int code, const char *msg) noexcept {
Abort(std::make_exception_ptr(ZlibError(code, msg)));
}
/**
* Submit data from the buffer to our istream handler.
*
* @return the number of bytes which were handled, or 0 if the
* stream was closed
*/
size_t TryWrite() noexcept;
/**
* Starts to write to the buffer.
*
* @return a pointer to the writable buffer, or nullptr if there is no
* room (our istream handler blocks) or if the stream was closed
*/
WritableBuffer<void> BufferWrite() noexcept {
buffer.AllocateIfNull(fb_pool_get());
auto w = buffer.Write();
if (w.empty() && TryWrite() > 0)
w = buffer.Write();
return w.ToVoid();
}
void TryFlush() noexcept;
/**
* Read from our input until we have submitted some bytes to our
* istream handler.
*/
void ForceRead() noexcept;
void TryFinish() noexcept;
/* virtual methods from class Istream */
void _Read() noexcept override {
if (!buffer.empty())
TryWrite();
else if (HasInput())
ForceRead();
else
TryFinish();
}
void _Close() noexcept override {
DeinitZlib();
if (HasInput())
input.Close();
Destroy();
}
/* virtual methods from class IstreamHandler */
size_t OnData(const void *data, size_t length) noexcept override;
void OnEof() noexcept override;
void OnError(std::exception_ptr ep) noexcept override;
private:
int GetWindowBits() const noexcept {
return MAX_WBITS + gzip * 16;
}
void OnDeferred() noexcept {
assert(HasInput());
ForceRead();
}
};
static voidpf
z_alloc(voidpf opaque, uInt items, uInt size) noexcept
{
struct pool *pool = (struct pool *)opaque;
return p_malloc(pool, items * size);
}
static void
z_free(voidpf opaque, voidpf address) noexcept
{
(void)opaque;
(void)address;
}
bool
DeflateIstream::InitZlib() noexcept
{
if (z_initialized)
return true;
z.zalloc = z_alloc;
z.zfree = z_free;
z.opaque = &GetPool();
int err = deflateInit2(&z, Z_DEFAULT_COMPRESSION,
Z_DEFLATED, GetWindowBits(), 8,
Z_DEFAULT_STRATEGY);
if (err != Z_OK) {
Abort(err, "deflateInit(Z_FINISH) failed");
return false;
}
z_initialized = true;
return true;
}
size_t
DeflateIstream::TryWrite() noexcept
{
auto r = buffer.Read();
assert(!r.empty());
size_t nbytes = InvokeData(r.data, r.size);
if (nbytes == 0)
return 0;
buffer.Consume(nbytes);
buffer.FreeIfEmpty();
if (nbytes == r.size && !HasInput() && z_stream_end) {
DeinitZlib();
DestroyEof();
return 0;
}
return nbytes;
}
inline void
DeflateIstream::TryFlush() noexcept
{
assert(!z_stream_end);
auto w = BufferWrite();
if (w.empty())
return;
z.next_out = (Bytef *)w.data;
z.avail_out = (uInt)w.size;
z.next_in = nullptr;
z.avail_in = 0;
int err = deflate(&z, Z_SYNC_FLUSH);
if (err != Z_OK) {
Abort(err, "deflate(Z_SYNC_FLUSH) failed");
return;
}
buffer.Append(w.size - (size_t)z.avail_out);
if (!buffer.empty())
TryWrite();
}
inline void
DeflateIstream::ForceRead() noexcept
{
assert(!reading);
const ScopePoolRef ref(GetPool() TRACE_ARGS);
bool had_input2 = false;
had_output = false;
while (1) {
had_input = false;
reading = true;
input.Read();
reading = false;
if (!HasInput() || had_output)
return;
if (!had_input)
break;
had_input2 = true;
}
if (had_input2)
TryFlush();
}
void
DeflateIstream::TryFinish() noexcept
{
assert(!z_stream_end);
auto w = BufferWrite();
if (w.empty())
return;
z.next_out = (Bytef *)w.data;
z.avail_out = (uInt)w.size;
z.next_in = nullptr;
z.avail_in = 0;
int err = deflate(&z, Z_FINISH);
if (err == Z_STREAM_END)
z_stream_end = true;
else if (err != Z_OK) {
Abort(err, "deflate(Z_FINISH) failed");
return;
}
buffer.Append(w.size - (size_t)z.avail_out);
if (z_stream_end && buffer.empty()) {
DeinitZlib();
DestroyEof();
} else
TryWrite();
}
/*
* istream handler
*
*/
size_t
DeflateIstream::OnData(const void *data, size_t length) noexcept
{
assert(HasInput());
auto w = BufferWrite();
if (w.size < 64) /* reserve space for end-of-stream marker */
return 0;
if (!InitZlib())
return 0;
had_input = true;
if (!reading)
had_output = false;
z.next_out = (Bytef *)w.data;
z.avail_out = (uInt)w.size;
z.next_in = (Bytef *)const_cast<void *>(data);
z.avail_in = (uInt)length;
do {
auto err = deflate(&z, Z_NO_FLUSH);
if (err != Z_OK) {
Abort(err, "deflate() failed");
return 0;
}
size_t nbytes = w.size - (size_t)z.avail_out;
if (nbytes > 0) {
had_output = true;
buffer.Append(nbytes);
const ScopePoolRef ref(GetPool() TRACE_ARGS);
TryWrite();
if (!z_initialized)
return 0;
} else
break;
w = BufferWrite();
if (w.size < 64) /* reserve space for end-of-stream marker */
break;
z.next_out = (Bytef *)w.data;
z.avail_out = (uInt)w.size;
} while (z.avail_in > 0);
if (!reading && !had_output)
/* we received data from our input, but we did not produce any
output (and we're not looping inside ForceRead()) - to
avoid stalling the stream, trigger the DeferEvent */
defer.Schedule();
return length - (size_t)z.avail_in;
}
void
DeflateIstream::OnEof() noexcept
{
ClearInput();
defer.Cancel();
if (!InitZlib())
return;
TryFinish();
}
void
DeflateIstream::OnError(std::exception_ptr ep) noexcept
{
ClearInput();
DeinitZlib();
DestroyError(ep);
}
/*
* constructor
*
*/
UnusedIstreamPtr
istream_deflate_new(struct pool &pool, UnusedIstreamPtr input,
EventLoop &event_loop, bool gzip) noexcept
{
return NewIstreamPtr<DeflateIstream>(pool, std::move(input),
event_loop, gzip);
}
<commit_msg>istream/deflate: use DestructObserver instead of pool reference<commit_after>/*
* Copyright 2007-2019 Content Management AG
* All rights reserved.
*
* author: Max Kellermann <mk@cm4all.com>
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* - Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* - Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the
* distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* FOUNDATION 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 "istream_deflate.hxx"
#include "UnusedPtr.hxx"
#include "New.hxx"
#include "FacadeIstream.hxx"
#include "pool/pool.hxx"
#include "fb_pool.hxx"
#include "SliceFifoBuffer.hxx"
#include "event/DeferEvent.hxx"
#include "util/Cast.hxx"
#include "util/ConstBuffer.hxx"
#include "util/DestructObserver.hxx"
#include "util/WritableBuffer.hxx"
#include <zlib.h>
#include <stdexcept>
#include <assert.h>
class ZlibError : public std::runtime_error {
int code;
public:
explicit ZlibError(int _code, const char *_msg)
:std::runtime_error(_msg), code(_code) {}
int GetCode() const noexcept {
return code;
}
};
class DeflateIstream final : public FacadeIstream, DestructAnchor {
const bool gzip;
bool z_initialized = false, z_stream_end = false;
z_stream z;
bool had_input, had_output;
bool reading;
SliceFifoBuffer buffer;
/**
* This callback is used to request more data from the input if an
* OnData() call did not produce any output. This tries to
* prevent stalling the stream.
*/
DeferEvent defer;
public:
DeflateIstream(struct pool &_pool, UnusedIstreamPtr _input,
EventLoop &event_loop, bool _gzip)
:FacadeIstream(_pool, std::move(_input)),
gzip(_gzip),
reading(false),
defer(event_loop, BIND_THIS_METHOD(OnDeferred))
{
}
~DeflateIstream() {
defer.Cancel();
}
bool InitZlib() noexcept;
void DeinitZlib() noexcept {
if (z_initialized)
deflateEnd(&z);
}
void Abort(std::exception_ptr ep) noexcept {
DeinitZlib();
if (HasInput())
ClearAndCloseInput();
DestroyError(ep);
}
void Abort(int code, const char *msg) noexcept {
Abort(std::make_exception_ptr(ZlibError(code, msg)));
}
/**
* Submit data from the buffer to our istream handler.
*
* @return the number of bytes which were handled, or 0 if the
* stream was closed
*/
size_t TryWrite() noexcept;
/**
* Starts to write to the buffer.
*
* @return a pointer to the writable buffer, or nullptr if there is no
* room (our istream handler blocks) or if the stream was closed
*/
WritableBuffer<void> BufferWrite() noexcept {
buffer.AllocateIfNull(fb_pool_get());
auto w = buffer.Write();
if (w.empty() && TryWrite() > 0)
w = buffer.Write();
return w.ToVoid();
}
void TryFlush() noexcept;
/**
* Read from our input until we have submitted some bytes to our
* istream handler.
*/
void ForceRead() noexcept;
void TryFinish() noexcept;
/* virtual methods from class Istream */
void _Read() noexcept override {
if (!buffer.empty())
TryWrite();
else if (HasInput())
ForceRead();
else
TryFinish();
}
void _Close() noexcept override {
DeinitZlib();
if (HasInput())
input.Close();
Destroy();
}
/* virtual methods from class IstreamHandler */
size_t OnData(const void *data, size_t length) noexcept override;
void OnEof() noexcept override;
void OnError(std::exception_ptr ep) noexcept override;
private:
int GetWindowBits() const noexcept {
return MAX_WBITS + gzip * 16;
}
void OnDeferred() noexcept {
assert(HasInput());
ForceRead();
}
};
static voidpf
z_alloc(voidpf opaque, uInt items, uInt size) noexcept
{
struct pool *pool = (struct pool *)opaque;
return p_malloc(pool, items * size);
}
static void
z_free(voidpf opaque, voidpf address) noexcept
{
(void)opaque;
(void)address;
}
bool
DeflateIstream::InitZlib() noexcept
{
if (z_initialized)
return true;
z.zalloc = z_alloc;
z.zfree = z_free;
z.opaque = &GetPool();
int err = deflateInit2(&z, Z_DEFAULT_COMPRESSION,
Z_DEFLATED, GetWindowBits(), 8,
Z_DEFAULT_STRATEGY);
if (err != Z_OK) {
Abort(err, "deflateInit(Z_FINISH) failed");
return false;
}
z_initialized = true;
return true;
}
size_t
DeflateIstream::TryWrite() noexcept
{
auto r = buffer.Read();
assert(!r.empty());
size_t nbytes = InvokeData(r.data, r.size);
if (nbytes == 0)
return 0;
buffer.Consume(nbytes);
buffer.FreeIfEmpty();
if (nbytes == r.size && !HasInput() && z_stream_end) {
DeinitZlib();
DestroyEof();
return 0;
}
return nbytes;
}
inline void
DeflateIstream::TryFlush() noexcept
{
assert(!z_stream_end);
auto w = BufferWrite();
if (w.empty())
return;
z.next_out = (Bytef *)w.data;
z.avail_out = (uInt)w.size;
z.next_in = nullptr;
z.avail_in = 0;
int err = deflate(&z, Z_SYNC_FLUSH);
if (err != Z_OK) {
Abort(err, "deflate(Z_SYNC_FLUSH) failed");
return;
}
buffer.Append(w.size - (size_t)z.avail_out);
if (!buffer.empty())
TryWrite();
}
inline void
DeflateIstream::ForceRead() noexcept
{
assert(!reading);
const DestructObserver destructed(*this);
bool had_input2 = false;
had_output = false;
while (1) {
had_input = false;
reading = true;
input.Read();
if (destructed)
return;
reading = false;
if (!HasInput() || had_output)
return;
if (!had_input)
break;
had_input2 = true;
}
if (had_input2)
TryFlush();
}
void
DeflateIstream::TryFinish() noexcept
{
assert(!z_stream_end);
auto w = BufferWrite();
if (w.empty())
return;
z.next_out = (Bytef *)w.data;
z.avail_out = (uInt)w.size;
z.next_in = nullptr;
z.avail_in = 0;
int err = deflate(&z, Z_FINISH);
if (err == Z_STREAM_END)
z_stream_end = true;
else if (err != Z_OK) {
Abort(err, "deflate(Z_FINISH) failed");
return;
}
buffer.Append(w.size - (size_t)z.avail_out);
if (z_stream_end && buffer.empty()) {
DeinitZlib();
DestroyEof();
} else
TryWrite();
}
/*
* istream handler
*
*/
size_t
DeflateIstream::OnData(const void *data, size_t length) noexcept
{
assert(HasInput());
auto w = BufferWrite();
if (w.size < 64) /* reserve space for end-of-stream marker */
return 0;
if (!InitZlib())
return 0;
had_input = true;
if (!reading)
had_output = false;
z.next_out = (Bytef *)w.data;
z.avail_out = (uInt)w.size;
z.next_in = (Bytef *)const_cast<void *>(data);
z.avail_in = (uInt)length;
do {
auto err = deflate(&z, Z_NO_FLUSH);
if (err != Z_OK) {
Abort(err, "deflate() failed");
return 0;
}
size_t nbytes = w.size - (size_t)z.avail_out;
if (nbytes > 0) {
had_output = true;
buffer.Append(nbytes);
const DestructObserver destructed(*this);
TryWrite();
if (destructed)
return 0;
} else
break;
w = BufferWrite();
if (w.size < 64) /* reserve space for end-of-stream marker */
break;
z.next_out = (Bytef *)w.data;
z.avail_out = (uInt)w.size;
} while (z.avail_in > 0);
if (!reading && !had_output)
/* we received data from our input, but we did not produce any
output (and we're not looping inside ForceRead()) - to
avoid stalling the stream, trigger the DeferEvent */
defer.Schedule();
return length - (size_t)z.avail_in;
}
void
DeflateIstream::OnEof() noexcept
{
ClearInput();
defer.Cancel();
if (!InitZlib())
return;
TryFinish();
}
void
DeflateIstream::OnError(std::exception_ptr ep) noexcept
{
ClearInput();
DeinitZlib();
DestroyError(ep);
}
/*
* constructor
*
*/
UnusedIstreamPtr
istream_deflate_new(struct pool &pool, UnusedIstreamPtr input,
EventLoop &event_loop, bool gzip) noexcept
{
return NewIstreamPtr<DeflateIstream>(pool, std::move(input),
event_loop, gzip);
}
<|endoftext|>
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.