text stringlengths 54 60.6k |
|---|
<commit_before>/*
* zk_agg_selector.cpp
*
*
*
* Created on: Jun 23, 2010
* Author: Dmitriy V. Ryaboy
*/
#include "zk_agg_selector.h"
#include "zk_client.h"
#include "zk_status.h"
using namespace std;
// TODO(wanli): share this with zk_status.cpp
const string QUEUE_SIZE_KEY = "queue size";
const string MSGS_RECEIVED_KEY = "bytes received rate";
RandomAggSelector::RandomAggSelector(zhandle_t *zh)
: zh_(zh) {
}
RandomAggSelector::~RandomAggSelector() {
}
bool RandomAggSelector::selectScribeAggregator(string& parentZnode,
string& remoteHost,
unsigned long& remotePort) {
struct String_vector children;
bool ret;
if (ZOK != zoo_get_children(zh_, parentZnode.c_str(), 0, &children)) {
ret = false;
} else if (0 == children.count) {
ret = false;
} else {
string remoteScribeZnode = children.data[rand() % children.count];
size_t index = remoteScribeZnode.find(":");
// TODO(wanli): refactor the following into a function
remoteHost = remoteScribeZnode.substr(0, index);
string port = remoteScribeZnode.substr(index+1, string::npos);
remotePort = static_cast<unsigned long>(atol(port.c_str()));
ret = true;
}
return ret;
}
MsgCounterAggSelector::MsgCounterAggSelector(boost::shared_ptr<ZKStatusReader> zkStatusReader, zhandle_t *zh)
: zkStatusReader_(zkStatusReader),
zh_(zh) {
}
MsgCounterAggSelector::~MsgCounterAggSelector() {
}
bool MsgCounterAggSelector::selectScribeAggregator(string& parentZnode,
string& remoteHost,
unsigned long& remotePort) {
host_counters_map_t host_counters_map;
zkStatusReader_->getCountersForAllHosts(parentZnode, host_counters_map);
int max = 0, sum = 0;
for (host_counters_map_t::iterator iter = host_counters_map.begin(); iter != host_counters_map.end(); iter++ ) {
int measure = (iter->second.count(QUEUE_SIZE_KEY) != 0) ? (int) iter->second[QUEUE_SIZE_KEY] : 0;
measure += (iter->second.count(MSGS_RECEIVED_KEY) != 0) ? (int) iter->second[MSGS_RECEIVED_KEY] : 0;
if (measure > max) { max = measure; }
LOG_DEBUG("ZK AGGREGATOR %s -->", iter->first.c_str());
for (counter_map_t::iterator counterIter = iter->second.begin(); counterIter != iter->second.end(); counterIter++) {
LOG_DEBUG(" %s --> %lld", counterIter->first.c_str(), counterIter->second);
}
}
map<std::string, int> weight_map;
//TODO (dvryaboy) make sum resilient to overflow
for (host_counters_map_t::iterator iter = host_counters_map.begin(); iter != host_counters_map.end(); iter++ ) {
int measure = (iter->second.count(QUEUE_SIZE_KEY) != 0) ? (int) iter->second[QUEUE_SIZE_KEY] : 0;
measure += (iter->second.count(MSGS_RECEIVED_KEY) != 0) ? (int) iter->second[MSGS_RECEIVED_KEY] : 0;
weight_map[iter->first] = (int) max - measure + 1;
sum += weight_map[iter->first];
}
int r = rand() % sum;
for (map<std::string, int>::iterator iter = weight_map.begin(); iter != weight_map.end(); iter++ ) {
if ( (r -= iter->second) < 0 ) {
size_t index = iter->first.find(":");
remoteHost = iter->first.substr(parentZnode.length() + 1, index - parentZnode.length() - 1);
string port = iter->first.substr(index+1, string::npos);
remotePort = static_cast<unsigned long>(atol(port.c_str()));
LOG_OPER("Selected %s, %ld", remoteHost.c_str(), remotePort);
return true;
}
}
LOG_OPER("Couldn't find any aggregator");
return false;
}
AggSelector* AggSelectorFactory::createAggSelector(
boost::shared_ptr<ZKStatusReader> zkStatusReader, zhandle_t *zh, string& aggName) {
if (aggName.compare("RandomAggSelector") == 0) {
return new RandomAggSelector(zh);
} else if (aggName.compare("MsgCounterAggSelector") == 0) {
return new MsgCounterAggSelector(zkStatusReader, zh);
} else {
LOG_OPER("Fall back to random aggregator selector");
return new RandomAggSelector(zh);
}
}
<commit_msg>add TODOs<commit_after>/*
* zk_agg_selector.cpp
*
*
*
* Created on: Jun 23, 2010
* Author: Dmitriy V. Ryaboy
*/
#include "zk_agg_selector.h"
#include "zk_client.h"
#include "zk_status.h"
using namespace std;
// TODO(wanli): share this with zk_status.cpp
const string QUEUE_SIZE_KEY = "queue size";
const string MSGS_RECEIVED_KEY = "bytes received rate";
RandomAggSelector::RandomAggSelector(zhandle_t *zh)
: zh_(zh) {
}
RandomAggSelector::~RandomAggSelector() {
// TODO(wanli): add LOG_OPER here
}
bool RandomAggSelector::selectScribeAggregator(string& parentZnode,
string& remoteHost,
unsigned long& remotePort) {
struct String_vector children;
bool ret;
if (ZOK != zoo_get_children(zh_, parentZnode.c_str(), 0, &children)) {
ret = false;
} else if (0 == children.count) {
ret = false;
} else {
string remoteScribeZnode = children.data[rand() % children.count];
size_t index = remoteScribeZnode.find(":");
// TODO(wanli): refactor the following into a function
remoteHost = remoteScribeZnode.substr(0, index);
string port = remoteScribeZnode.substr(index+1, string::npos);
remotePort = static_cast<unsigned long>(atol(port.c_str()));
ret = true;
}
return ret;
}
MsgCounterAggSelector::MsgCounterAggSelector(boost::shared_ptr<ZKStatusReader> zkStatusReader, zhandle_t *zh)
: zkStatusReader_(zkStatusReader),
zh_(zh) {
// TODO(wanli): add LOG_OPER here
}
MsgCounterAggSelector::~MsgCounterAggSelector() {
}
bool MsgCounterAggSelector::selectScribeAggregator(string& parentZnode,
string& remoteHost,
unsigned long& remotePort) {
host_counters_map_t host_counters_map;
zkStatusReader_->getCountersForAllHosts(parentZnode, host_counters_map);
int max = 0, sum = 0;
for (host_counters_map_t::iterator iter = host_counters_map.begin(); iter != host_counters_map.end(); iter++ ) {
int measure = (iter->second.count(QUEUE_SIZE_KEY) != 0) ? (int) iter->second[QUEUE_SIZE_KEY] : 0;
measure += (iter->second.count(MSGS_RECEIVED_KEY) != 0) ? (int) iter->second[MSGS_RECEIVED_KEY] : 0;
if (measure > max) { max = measure; }
LOG_DEBUG("ZK AGGREGATOR %s -->", iter->first.c_str());
for (counter_map_t::iterator counterIter = iter->second.begin(); counterIter != iter->second.end(); counterIter++) {
LOG_DEBUG(" %s --> %lld", counterIter->first.c_str(), counterIter->second);
}
}
map<std::string, int> weight_map;
//TODO (dvryaboy) make sum resilient to overflow
for (host_counters_map_t::iterator iter = host_counters_map.begin(); iter != host_counters_map.end(); iter++ ) {
int measure = (iter->second.count(QUEUE_SIZE_KEY) != 0) ? (int) iter->second[QUEUE_SIZE_KEY] : 0;
measure += (iter->second.count(MSGS_RECEIVED_KEY) != 0) ? (int) iter->second[MSGS_RECEIVED_KEY] : 0;
weight_map[iter->first] = (int) max - measure + 1;
sum += weight_map[iter->first];
}
int r = rand() % sum;
for (map<std::string, int>::iterator iter = weight_map.begin(); iter != weight_map.end(); iter++ ) {
if ( (r -= iter->second) < 0 ) {
size_t index = iter->first.find(":");
remoteHost = iter->first.substr(parentZnode.length() + 1, index - parentZnode.length() - 1);
string port = iter->first.substr(index+1, string::npos);
remotePort = static_cast<unsigned long>(atol(port.c_str()));
LOG_OPER("Selected %s, %ld", remoteHost.c_str(), remotePort);
return true;
}
}
LOG_OPER("Couldn't find any aggregator");
return false;
}
// make this configurable.
AggSelector* AggSelectorFactory::createAggSelector(
boost::shared_ptr<ZKStatusReader> zkStatusReader, zhandle_t *zh, string& aggName) {
if (aggName.compare("RandomAggSelector") == 0) {
return new RandomAggSelector(zh);
} else if (aggName.compare("MsgCounterAggSelector") == 0) {
return new MsgCounterAggSelector(zkStatusReader, zh);
} else {
LOG_OPER("Fall back to random aggregator selector");
return new RandomAggSelector(zh);
}
}
<|endoftext|> |
<commit_before>#include "ROOT/RTaskArena.hxx"
#include "TError.h"
#include "TROOT.h"
#include "TThread.h"
#include <fstream>
#include <sys/stat.h>
#include <thread>
#include "tbb/task_arena.h"
//////////////////////////////////////////////////////////////////////////
///
/// \class ROOT::Internal::RTaskArenaWrapper
/// \ingroup Parallelism
/// \brief Wrapper over tbb::task_arena
///
/// This class is a wrapper over tbb::task_arena, in order to keep
/// TBB away from ROOT's headers. We keep a single global instance,
/// obtained with `ROOT::Internal::GetGlobalTaskArena()`, to be used by any
/// parallel ROOT class with TBB as a backend. This has several advantages:
///
/// - Provides a unique interface to the TBB scheduler: TThreadExecutor,
/// IMT and any class relying on TBB will get a pointer to the scheduler
/// through `ROOT::Internal::GetGlobalTaskArena()`, which will return a
/// reference to the only pointer to the TBB scheduler that will be
/// active in any ROOT Process
/// - Solves multiple undefined behaviors. Guaranteeing that all classes
/// use the same task arena avoids interferences and undefined behavior
/// by providing a single instance of the tbb::task_arena and automated
/// bookkeeping, instantiation and destruction.
///
/// #### Examples:
/// ~~~{.cpp}
/// root[] auto gTA = ROOT::Internal::GetGlobalTaskArena() //get a shared_ptr to the global arena
/// root[] gTA->InitGlobalTaskArena(nWorkers) // Initialize the global arena and enable Thread Safety in ROOT
/// root[] gTA->TaskArenaSize() // Get the current size of the arena (number of worker threads)
/// root[] gTA->Access() //std::unique_ptr to the internal tbb::task_arena for interacting directly with it (needed to call operations such as execute)
/// root[] root[] gTA->Access().max_concurrency() // call to tbb::task_arena::max_concurrency()
/// ~~~
///
//////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
/// Returns the available number of logical cores.
///
/// - Checks if there is CFS bandwidth control in place (linux, via cgroups,
/// assuming standard paths)
/// - Otherwise, returns the number of logical cores provided by
/// std::thread::hardware_concurrency()
////////////////////////////////////////////////////////////////////////////////
static Int_t LogicalCPUBandwithControl()
{
#ifdef R__LINUX
// Check for CFS bandwith control
std::ifstream f;
std::string quotaFile("/sys/fs/cgroup/cpuacct/cpu.cfs_quota_us");
struct stat buffer;
// Does the file exist?
if(stat(quotaFile.c_str(), &buffer) == 0) {
f.open(quotaFile);
float cfs_quota;
f>>cfs_quota;
f.close();
if(cfs_quota > 0) {
std::string periodFile("/sys/fs/cgroup/cpuacct/cpu.cfs_period_us");
f.open(periodFile);
float cfs_period;
f>>cfs_period;
f.close();
return static_cast<int>(std::ceil(cfs_quota/cfs_period));
}
}
#endif
return std::thread::hardware_concurrency();
}
namespace ROOT{
namespace Internal {
////////////////////////////////////////////////////////////////////////////////
/// Initializes the tbb::task_arena within RTaskArenaWrapper
///
/// * Can't be reinitialized
/// * Checks for CPU bandwidth control and avoids oversubscribing
/// * If no BC in place and maxConcurrency<1, defaults to the default tbb number of threads,
/// which is CPU affinity aware
////////////////////////////////////////////////////////////////////////////////
RTaskArenaWrapper::RTaskArenaWrapper(unsigned maxConcurrency): fTBBArena(new tbb::task_arena{})
{
if (!fTBBArena->is_active()) {
const unsigned tbbDefaultNumberThreads = fTBBArena->max_concurrency(); // not initialized, automatic state
maxConcurrency = maxConcurrency > 0 ? std::min(maxConcurrency, tbbDefaultNumberThreads) : tbbDefaultNumberThreads;
const unsigned bcCpus = LogicalCPUBandwithControl();
if (maxConcurrency>bcCpus) {
Warning("RTaskArenaWrapper", "CPU Bandwith Control Active. Proceeding with %d threads accordingly",
bcCpus);
maxConcurrency = bcCpus;
}
fTBBArena->initialize(maxConcurrency);
fNWorkers = maxConcurrency;
ROOT::EnableThreadSafety();
} else {
const unsigned current = fTBBArena->max_concurrency();
if (maxConcurrency && (current != maxConcurrency)) {
Warning("RTaskArenaWrapper", "There's already an active task arena. Proceeding with the current %d threads",
current);
}
}
}
RTaskArenaWrapper::~RTaskArenaWrapper()
{
fNWorkers = 0u;
}
unsigned RTaskArenaWrapper::fNWorkers = 0u;
unsigned RTaskArenaWrapper::TaskArenaSize()
{
return fNWorkers;
}
////////////////////////////////////////////////////////////////////////////////
/// Provides access to the wrapped tbb::task_arena
////////////////////////////////////////////////////////////////////////////////
tbb::task_arena &RTaskArenaWrapper::Access()
{
return *fTBBArena;
}
std::shared_ptr<ROOT::Internal::RTaskArenaWrapper> GetGlobalTaskArena(unsigned maxConcurrency)
{
static std::weak_ptr<ROOT::Internal::RTaskArenaWrapper> weak_GTAWrapper;
if (weak_GTAWrapper.expired()) {
std::shared_ptr<ROOT::Internal::RTaskArenaWrapper> shared_GTAWrapper(new ROOT::Internal::RTaskArenaWrapper(maxConcurrency));
weak_GTAWrapper = shared_GTAWrapper;
return weak_GTAWrapper.lock();
}
return weak_GTAWrapper.lock();
}
} // namespace Internal
} // namespace ROOT
<commit_msg>replace use of stat by ifstream only<commit_after>#include "ROOT/RTaskArena.hxx"
#include "TError.h"
#include "TROOT.h"
#include "TThread.h"
#include <fstream>
#include <thread>
#include "tbb/task_arena.h"
//////////////////////////////////////////////////////////////////////////
///
/// \class ROOT::Internal::RTaskArenaWrapper
/// \ingroup Parallelism
/// \brief Wrapper over tbb::task_arena
///
/// This class is a wrapper over tbb::task_arena, in order to keep
/// TBB away from ROOT's headers. We keep a single global instance,
/// obtained with `ROOT::Internal::GetGlobalTaskArena()`, to be used by any
/// parallel ROOT class with TBB as a backend. This has several advantages:
///
/// - Provides a unique interface to the TBB scheduler: TThreadExecutor,
/// IMT and any class relying on TBB will get a pointer to the scheduler
/// through `ROOT::Internal::GetGlobalTaskArena()`, which will return a
/// reference to the only pointer to the TBB scheduler that will be
/// active in any ROOT Process
/// - Solves multiple undefined behaviors. Guaranteeing that all classes
/// use the same task arena avoids interferences and undefined behavior
/// by providing a single instance of the tbb::task_arena and automated
/// bookkeeping, instantiation and destruction.
///
/// #### Examples:
/// ~~~{.cpp}
/// root[] auto gTA = ROOT::Internal::GetGlobalTaskArena() //get a shared_ptr to the global arena
/// root[] gTA->InitGlobalTaskArena(nWorkers) // Initialize the global arena and enable Thread Safety in ROOT
/// root[] gTA->TaskArenaSize() // Get the current size of the arena (number of worker threads)
/// root[] gTA->Access() //std::unique_ptr to the internal tbb::task_arena for interacting directly with it (needed to call operations such as execute)
/// root[] root[] gTA->Access().max_concurrency() // call to tbb::task_arena::max_concurrency()
/// ~~~
///
//////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
/// Returns the available number of logical cores.
///
/// - Checks if there is CFS bandwidth control in place (linux, via cgroups,
/// assuming standard paths)
/// - Otherwise, returns the number of logical cores provided by
/// std::thread::hardware_concurrency()
////////////////////////////////////////////////////////////////////////////////
static Int_t LogicalCPUBandwithControl()
{
#ifdef R__LINUX
// Check for CFS bandwith control
std::ifstream f("/sys/fs/cgroup/cpuacct/cpu.cfs_quota_us"); // quota file
if(f) {
float cfs_quota;
f>>cfs_quota;
f.close();
if(cfs_quota > 0) {
f.open("/sys/fs/cgroup/cpuacct/cpu.cfs_period_us"); // period file
float cfs_period;
f>>cfs_period;
f.close();
return static_cast<int>(std::ceil(cfs_quota/cfs_period));
}
}
#endif
return std::thread::hardware_concurrency();
}
namespace ROOT{
namespace Internal {
////////////////////////////////////////////////////////////////////////////////
/// Initializes the tbb::task_arena within RTaskArenaWrapper
///
/// * Can't be reinitialized
/// * Checks for CPU bandwidth control and avoids oversubscribing
/// * If no BC in place and maxConcurrency<1, defaults to the default tbb number of threads,
/// which is CPU affinity aware
////////////////////////////////////////////////////////////////////////////////
RTaskArenaWrapper::RTaskArenaWrapper(unsigned maxConcurrency): fTBBArena(new tbb::task_arena{})
{
if (!fTBBArena->is_active()) {
const unsigned tbbDefaultNumberThreads = fTBBArena->max_concurrency(); // not initialized, automatic state
maxConcurrency = maxConcurrency > 0 ? std::min(maxConcurrency, tbbDefaultNumberThreads) : tbbDefaultNumberThreads;
const unsigned bcCpus = LogicalCPUBandwithControl();
if (maxConcurrency>bcCpus) {
Warning("RTaskArenaWrapper", "CPU Bandwith Control Active. Proceeding with %d threads accordingly",
bcCpus);
maxConcurrency = bcCpus;
}
fTBBArena->initialize(maxConcurrency);
fNWorkers = maxConcurrency;
ROOT::EnableThreadSafety();
} else {
const unsigned current = fTBBArena->max_concurrency();
if (maxConcurrency && (current != maxConcurrency)) {
Warning("RTaskArenaWrapper", "There's already an active task arena. Proceeding with the current %d threads",
current);
}
}
}
RTaskArenaWrapper::~RTaskArenaWrapper()
{
fNWorkers = 0u;
}
unsigned RTaskArenaWrapper::fNWorkers = 0u;
unsigned RTaskArenaWrapper::TaskArenaSize()
{
return fNWorkers;
}
////////////////////////////////////////////////////////////////////////////////
/// Provides access to the wrapped tbb::task_arena
////////////////////////////////////////////////////////////////////////////////
tbb::task_arena &RTaskArenaWrapper::Access()
{
return *fTBBArena;
}
std::shared_ptr<ROOT::Internal::RTaskArenaWrapper> GetGlobalTaskArena(unsigned maxConcurrency)
{
static std::weak_ptr<ROOT::Internal::RTaskArenaWrapper> weak_GTAWrapper;
if (weak_GTAWrapper.expired()) {
std::shared_ptr<ROOT::Internal::RTaskArenaWrapper> shared_GTAWrapper(new ROOT::Internal::RTaskArenaWrapper(maxConcurrency));
weak_GTAWrapper = shared_GTAWrapper;
return weak_GTAWrapper.lock();
}
return weak_GTAWrapper.lock();
}
} // namespace Internal
} // namespace ROOT
<|endoftext|> |
<commit_before>/****************************************************************************
*
* Copyright (c) 2013 PX4 Development Team. All rights reserved.
* Author: @author Thomas Gubler <thomasgubler@gmail.com>
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
* 3. Neither the name PX4 nor the names of its contributors may be
* used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
* OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
* AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
****************************************************************************/
/**
* @file mTecs.cpp
*
* @author Thomas Gubler <thomasgubler@gmail.com>
*/
#include "mTecs.h"
#include <lib/geo/geo.h>
#include <stdio.h>
namespace fwPosctrl {
mTecs::mTecs() :
SuperBlock(NULL, "MT"),
/* Parameters */
_mTecsEnabled(this, "ENABLED"),
_airspeedMin(this, "FW_AIRSPD_MIN", false),
/* Publications */
_status(&getPublications(), ORB_ID(tecs_status)),
/* control blocks */
_controlTotalEnergy(this, "THR"),
_controlEnergyDistribution(this, "PIT", true),
_controlAltitude(this, "FPA", true),
_controlAirSpeed(this, "ACC"),
_flightPathAngleLowpass(this, "FPA_LP"),
_altitudeLowpass(this, "ALT_LP"),
_airspeedLowpass(this, "A_LP"),
_airspeedDerivative(this, "AD"),
_throttleSp(0.0f),
_pitchSp(0.0f),
_BlockOutputLimiterTakeoffThrottle(this, "TKF_THR"),
_BlockOutputLimiterTakeoffPitch(this, "TKF_PIT", true),
_BlockOutputLimiterUnderspeedThrottle(this, "USP_THR"),
_BlockOutputLimiterUnderspeedPitch(this, "USP_PIT", true),
_BlockOutputLimiterLandThrottle(this, "LND_THR"),
_BlockOutputLimiterLandPitch(this, "LND_PIT", true),
timestampLastIteration(hrt_absolute_time()),
_firstIterationAfterReset(true),
_dtCalculated(false),
_counter(0),
_debug(false)
{
warnx("starting");
}
mTecs::~mTecs()
{
}
int mTecs::updateAltitudeSpeed(float flightPathAngle, float altitude, float altitudeSp, float airspeed,
float airspeedSp, tecs_mode mode, LimitOverride limitOverride)
{
/* check if all input arguments are numbers and abort if not so */
if (!isfinite(flightPathAngle) || !isfinite(altitude) ||
!isfinite(altitudeSp) || !isfinite(airspeed) || !isfinite(airspeedSp) || !isfinite(mode)) {
return -1;
}
/* time measurement */
updateTimeMeasurement();
/* Filter altitude */
float altitudeFiltered = _altitudeLowpass.update(altitude);
/* calculate flight path angle setpoint from altitude setpoint */
float flightPathAngleSp = _controlAltitude.update(altitudeSp - altitudeFiltered);
/* Debug output */
if (_counter % 10 == 0) {
debug("***");
debug("updateAltitudeSpeed: altitudeSp %.4f, altitude %.4f, altitude filtered %.4f, flightPathAngleSp %.4f", (double)altitudeSp, (double)altitude, (double)altitudeFiltered, (double)flightPathAngleSp);
}
/* Write part of the status message */
_status.altitudeSp = altitudeSp;
_status.altitude = altitude;
_status.altitudeFiltered = altitudeFiltered;
/* use flightpath angle setpoint for total energy control */
return updateFlightPathAngleSpeed(flightPathAngle, flightPathAngleSp, airspeed,
airspeedSp, mode, limitOverride);
}
int mTecs::updateFlightPathAngleSpeed(float flightPathAngle, float flightPathAngleSp, float airspeed,
float airspeedSp, tecs_mode mode, LimitOverride limitOverride)
{
/* check if all input arguments are numbers and abort if not so */
if (!isfinite(flightPathAngle) || !isfinite(flightPathAngleSp) ||
!isfinite(airspeed) || !isfinite(airspeedSp) || !isfinite(mode)) {
return -1;
}
/* time measurement */
updateTimeMeasurement();
/* Filter airspeed */
float airspeedFiltered = _airspeedLowpass.update(airspeed);
/* calculate longitudinal acceleration setpoint from airspeed setpoint*/
float accelerationLongitudinalSp = _controlAirSpeed.update(airspeedSp - airspeedFiltered);
/* Debug output */
if (_counter % 10 == 0) {
debug("updateFlightPathAngleSpeed airspeedSp %.4f, airspeed %.4f airspeedFiltered %.4f,"
"accelerationLongitudinalSp%.4f",
(double)airspeedSp, (double)airspeed,
(double)airspeedFiltered, (double)accelerationLongitudinalSp);
}
/* Write part of the status message */
_status.airspeedSp = airspeedSp;
_status.airspeed = airspeed;
_status.airspeedFiltered = airspeedFiltered;
/* use longitudinal acceleration setpoint for total energy control */
return updateFlightPathAngleAcceleration(flightPathAngle, flightPathAngleSp, airspeedFiltered,
accelerationLongitudinalSp, mode, limitOverride);
}
int mTecs::updateFlightPathAngleAcceleration(float flightPathAngle, float flightPathAngleSp, float airspeedFiltered,
float accelerationLongitudinalSp, tecs_mode mode, LimitOverride limitOverride)
{
/* check if all input arguments are numbers and abort if not so */
if (!isfinite(flightPathAngle) || !isfinite(flightPathAngleSp) ||
!isfinite(airspeedFiltered) || !isfinite(accelerationLongitudinalSp) || !isfinite(mode)) {
return -1;
}
/* time measurement */
updateTimeMeasurement();
/* update parameters first */
updateParams();
/* Filter flightpathangle */
float flightPathAngleFiltered = _flightPathAngleLowpass.update(flightPathAngle);
/* calculate values (energies) */
float flightPathAngleError = flightPathAngleSp - flightPathAngleFiltered;
float airspeedDerivative = 0.0f;
if(_airspeedDerivative.getDt() > 0.0f) {
airspeedDerivative = _airspeedDerivative.update(airspeedFiltered);
}
float airspeedDerivativeNorm = airspeedDerivative / CONSTANTS_ONE_G;
float airspeedDerivativeSp = accelerationLongitudinalSp;
float airspeedDerivativeNormSp = airspeedDerivativeSp / CONSTANTS_ONE_G;
float airspeedDerivativeNormError = airspeedDerivativeNormSp - airspeedDerivativeNorm;
float totalEnergyRate = flightPathAngleFiltered + airspeedDerivativeNorm;
float totalEnergyRateError = flightPathAngleError + airspeedDerivativeNormError;
float totalEnergyRateSp = flightPathAngleSp + airspeedDerivativeNormSp;
float totalEnergyRateError2 = totalEnergyRateSp - totalEnergyRate;
float energyDistributionRate = flightPathAngleFiltered - airspeedDerivativeNorm;
float energyDistributionRateError = flightPathAngleError - airspeedDerivativeNormError;
float energyDistributionRateSp = flightPathAngleSp - airspeedDerivativeNormSp;
float energyDistributionRateError2 = energyDistributionRateSp - energyDistributionRate;
/* Debug output */
if (_counter % 10 == 0) {
debug("totalEnergyRateSp %.2f, totalEnergyRate %.2f, totalEnergyRateError %.2f totalEnergyRateError2 %.2f airspeedDerivativeNorm %.4f",
(double)totalEnergyRateSp, (double)totalEnergyRate, (double)totalEnergyRateError, (double)totalEnergyRateError2, (double)airspeedDerivativeNorm);
debug("energyDistributionRateSp %.2f, energyDistributionRate %.2f, energyDistributionRateError %.2f energyDistributionRateError2 %.2f",
(double)energyDistributionRateSp, (double)energyDistributionRate, (double)energyDistributionRateError, (double)energyDistributionRateError2);
}
/* Check airspeed: if below safe value switch to underspeed mode (if not in land or takeoff mode) */
if (mode != TECS_MODE_LAND && mode != TECS_MODE_TAKEOFF && airspeedFiltered < _airspeedMin.get()) {
mode = TECS_MODE_UNDERSPEED;
}
/* Set special ouput limiters if we are not in TECS_MODE_NORMAL */
BlockOutputLimiter *outputLimiterThrottle = &_controlTotalEnergy.getOutputLimiter();
BlockOutputLimiter *outputLimiterPitch = &_controlEnergyDistribution.getOutputLimiter();
if (mode == TECS_MODE_TAKEOFF) {
outputLimiterThrottle = &_BlockOutputLimiterTakeoffThrottle;
outputLimiterPitch = &_BlockOutputLimiterTakeoffPitch;
} else if (mode == TECS_MODE_LAND) {
// only limit pitch but do not limit throttle
outputLimiterPitch = &_BlockOutputLimiterLandPitch;
} else if (mode == TECS_MODE_LAND_THROTTLELIM) {
outputLimiterThrottle = &_BlockOutputLimiterLandThrottle;
outputLimiterPitch = &_BlockOutputLimiterLandPitch;
} else if (mode == TECS_MODE_UNDERSPEED) {
outputLimiterThrottle = &_BlockOutputLimiterUnderspeedThrottle;
outputLimiterPitch = &_BlockOutputLimiterUnderspeedPitch;
}
/* Apply overrride given by the limitOverride argument (this is used for limits which are not given by
* parameters such as pitch limits with takeoff waypoints or throttle limits when the launchdetector
* is running) */
limitOverride.applyOverride(*outputLimiterThrottle, *outputLimiterPitch);
/* Write part of the status message */
_status.flightPathAngleSp = flightPathAngleSp;
_status.flightPathAngle = flightPathAngle;
_status.flightPathAngleFiltered = flightPathAngleFiltered;
_status.airspeedDerivativeSp = airspeedDerivativeSp;
_status.airspeedDerivative = airspeedDerivative;
_status.totalEnergyRateSp = totalEnergyRateSp;
_status.totalEnergyRate = totalEnergyRate;
_status.energyDistributionRateSp = energyDistributionRateSp;
_status.energyDistributionRate = energyDistributionRate;
_status.mode = mode;
/** update control blocks **/
/* update total energy rate control block */
_throttleSp = _controlTotalEnergy.update(totalEnergyRateSp, totalEnergyRateError, outputLimiterThrottle);
/* update energy distribution rate control block */
_pitchSp = _controlEnergyDistribution.update(energyDistributionRateSp, energyDistributionRateError, outputLimiterPitch);
if (_counter % 10 == 0) {
debug("_throttleSp %.1f, _pitchSp %.1f, flightPathAngleSp %.1f, flightPathAngle %.1f accelerationLongitudinalSp %.1f, airspeedDerivative %.1f",
(double)_throttleSp, (double)_pitchSp,
(double)flightPathAngleSp, (double)flightPathAngle,
(double)accelerationLongitudinalSp, (double)airspeedDerivative);
}
/* publish status messge */
_status.update();
/* clean up */
_firstIterationAfterReset = false;
_dtCalculated = false;
_counter++;
return 0;
}
void mTecs::resetIntegrators()
{
_controlTotalEnergy.getIntegral().setY(0.0f);
_controlEnergyDistribution.getIntegral().setY(0.0f);
timestampLastIteration = hrt_absolute_time();
_firstIterationAfterReset = true;
}
void mTecs::resetDerivatives(float airspeed)
{
_airspeedDerivative.setU(airspeed);
}
void mTecs::updateTimeMeasurement()
{
if (!_dtCalculated) {
float deltaTSeconds = 0.0f;
if (!_firstIterationAfterReset) {
hrt_abstime timestampNow = hrt_absolute_time();
deltaTSeconds = (float)(timestampNow - timestampLastIteration) * 1e-6f;
timestampLastIteration = timestampNow;
}
setDt(deltaTSeconds);
_dtCalculated = true;
}
}
void mTecs::debug_print(const char *fmt, va_list args)
{
fprintf(stderr, "%s: ", "[mtecs]");
vfprintf(stderr, fmt, args);
fprintf(stderr, "\n");
}
void mTecs::debug(const char *fmt, ...) {
if (!_debug) {
return;
}
va_list args;
va_start(args, fmt);
debug_print(fmt, args);
}
} /* namespace fwPosctrl */
<commit_msg>removed debug statement from mTECS<commit_after>/****************************************************************************
*
* Copyright (c) 2013 PX4 Development Team. All rights reserved.
* Author: @author Thomas Gubler <thomasgubler@gmail.com>
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
* 3. Neither the name PX4 nor the names of its contributors may be
* used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
* OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
* AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
****************************************************************************/
/**
* @file mTecs.cpp
*
* @author Thomas Gubler <thomasgubler@gmail.com>
*/
#include "mTecs.h"
#include <lib/geo/geo.h>
#include <stdio.h>
namespace fwPosctrl {
mTecs::mTecs() :
SuperBlock(NULL, "MT"),
/* Parameters */
_mTecsEnabled(this, "ENABLED"),
_airspeedMin(this, "FW_AIRSPD_MIN", false),
/* Publications */
_status(&getPublications(), ORB_ID(tecs_status)),
/* control blocks */
_controlTotalEnergy(this, "THR"),
_controlEnergyDistribution(this, "PIT", true),
_controlAltitude(this, "FPA", true),
_controlAirSpeed(this, "ACC"),
_flightPathAngleLowpass(this, "FPA_LP"),
_altitudeLowpass(this, "ALT_LP"),
_airspeedLowpass(this, "A_LP"),
_airspeedDerivative(this, "AD"),
_throttleSp(0.0f),
_pitchSp(0.0f),
_BlockOutputLimiterTakeoffThrottle(this, "TKF_THR"),
_BlockOutputLimiterTakeoffPitch(this, "TKF_PIT", true),
_BlockOutputLimiterUnderspeedThrottle(this, "USP_THR"),
_BlockOutputLimiterUnderspeedPitch(this, "USP_PIT", true),
_BlockOutputLimiterLandThrottle(this, "LND_THR"),
_BlockOutputLimiterLandPitch(this, "LND_PIT", true),
timestampLastIteration(hrt_absolute_time()),
_firstIterationAfterReset(true),
_dtCalculated(false),
_counter(0),
_debug(false)
{
}
mTecs::~mTecs()
{
}
int mTecs::updateAltitudeSpeed(float flightPathAngle, float altitude, float altitudeSp, float airspeed,
float airspeedSp, tecs_mode mode, LimitOverride limitOverride)
{
/* check if all input arguments are numbers and abort if not so */
if (!isfinite(flightPathAngle) || !isfinite(altitude) ||
!isfinite(altitudeSp) || !isfinite(airspeed) || !isfinite(airspeedSp) || !isfinite(mode)) {
return -1;
}
/* time measurement */
updateTimeMeasurement();
/* Filter altitude */
float altitudeFiltered = _altitudeLowpass.update(altitude);
/* calculate flight path angle setpoint from altitude setpoint */
float flightPathAngleSp = _controlAltitude.update(altitudeSp - altitudeFiltered);
/* Debug output */
if (_counter % 10 == 0) {
debug("***");
debug("updateAltitudeSpeed: altitudeSp %.4f, altitude %.4f, altitude filtered %.4f, flightPathAngleSp %.4f", (double)altitudeSp, (double)altitude, (double)altitudeFiltered, (double)flightPathAngleSp);
}
/* Write part of the status message */
_status.altitudeSp = altitudeSp;
_status.altitude = altitude;
_status.altitudeFiltered = altitudeFiltered;
/* use flightpath angle setpoint for total energy control */
return updateFlightPathAngleSpeed(flightPathAngle, flightPathAngleSp, airspeed,
airspeedSp, mode, limitOverride);
}
int mTecs::updateFlightPathAngleSpeed(float flightPathAngle, float flightPathAngleSp, float airspeed,
float airspeedSp, tecs_mode mode, LimitOverride limitOverride)
{
/* check if all input arguments are numbers and abort if not so */
if (!isfinite(flightPathAngle) || !isfinite(flightPathAngleSp) ||
!isfinite(airspeed) || !isfinite(airspeedSp) || !isfinite(mode)) {
return -1;
}
/* time measurement */
updateTimeMeasurement();
/* Filter airspeed */
float airspeedFiltered = _airspeedLowpass.update(airspeed);
/* calculate longitudinal acceleration setpoint from airspeed setpoint*/
float accelerationLongitudinalSp = _controlAirSpeed.update(airspeedSp - airspeedFiltered);
/* Debug output */
if (_counter % 10 == 0) {
debug("updateFlightPathAngleSpeed airspeedSp %.4f, airspeed %.4f airspeedFiltered %.4f,"
"accelerationLongitudinalSp%.4f",
(double)airspeedSp, (double)airspeed,
(double)airspeedFiltered, (double)accelerationLongitudinalSp);
}
/* Write part of the status message */
_status.airspeedSp = airspeedSp;
_status.airspeed = airspeed;
_status.airspeedFiltered = airspeedFiltered;
/* use longitudinal acceleration setpoint for total energy control */
return updateFlightPathAngleAcceleration(flightPathAngle, flightPathAngleSp, airspeedFiltered,
accelerationLongitudinalSp, mode, limitOverride);
}
int mTecs::updateFlightPathAngleAcceleration(float flightPathAngle, float flightPathAngleSp, float airspeedFiltered,
float accelerationLongitudinalSp, tecs_mode mode, LimitOverride limitOverride)
{
/* check if all input arguments are numbers and abort if not so */
if (!isfinite(flightPathAngle) || !isfinite(flightPathAngleSp) ||
!isfinite(airspeedFiltered) || !isfinite(accelerationLongitudinalSp) || !isfinite(mode)) {
return -1;
}
/* time measurement */
updateTimeMeasurement();
/* update parameters first */
updateParams();
/* Filter flightpathangle */
float flightPathAngleFiltered = _flightPathAngleLowpass.update(flightPathAngle);
/* calculate values (energies) */
float flightPathAngleError = flightPathAngleSp - flightPathAngleFiltered;
float airspeedDerivative = 0.0f;
if(_airspeedDerivative.getDt() > 0.0f) {
airspeedDerivative = _airspeedDerivative.update(airspeedFiltered);
}
float airspeedDerivativeNorm = airspeedDerivative / CONSTANTS_ONE_G;
float airspeedDerivativeSp = accelerationLongitudinalSp;
float airspeedDerivativeNormSp = airspeedDerivativeSp / CONSTANTS_ONE_G;
float airspeedDerivativeNormError = airspeedDerivativeNormSp - airspeedDerivativeNorm;
float totalEnergyRate = flightPathAngleFiltered + airspeedDerivativeNorm;
float totalEnergyRateError = flightPathAngleError + airspeedDerivativeNormError;
float totalEnergyRateSp = flightPathAngleSp + airspeedDerivativeNormSp;
float totalEnergyRateError2 = totalEnergyRateSp - totalEnergyRate;
float energyDistributionRate = flightPathAngleFiltered - airspeedDerivativeNorm;
float energyDistributionRateError = flightPathAngleError - airspeedDerivativeNormError;
float energyDistributionRateSp = flightPathAngleSp - airspeedDerivativeNormSp;
float energyDistributionRateError2 = energyDistributionRateSp - energyDistributionRate;
/* Debug output */
if (_counter % 10 == 0) {
debug("totalEnergyRateSp %.2f, totalEnergyRate %.2f, totalEnergyRateError %.2f totalEnergyRateError2 %.2f airspeedDerivativeNorm %.4f",
(double)totalEnergyRateSp, (double)totalEnergyRate, (double)totalEnergyRateError, (double)totalEnergyRateError2, (double)airspeedDerivativeNorm);
debug("energyDistributionRateSp %.2f, energyDistributionRate %.2f, energyDistributionRateError %.2f energyDistributionRateError2 %.2f",
(double)energyDistributionRateSp, (double)energyDistributionRate, (double)energyDistributionRateError, (double)energyDistributionRateError2);
}
/* Check airspeed: if below safe value switch to underspeed mode (if not in land or takeoff mode) */
if (mode != TECS_MODE_LAND && mode != TECS_MODE_TAKEOFF && airspeedFiltered < _airspeedMin.get()) {
mode = TECS_MODE_UNDERSPEED;
}
/* Set special ouput limiters if we are not in TECS_MODE_NORMAL */
BlockOutputLimiter *outputLimiterThrottle = &_controlTotalEnergy.getOutputLimiter();
BlockOutputLimiter *outputLimiterPitch = &_controlEnergyDistribution.getOutputLimiter();
if (mode == TECS_MODE_TAKEOFF) {
outputLimiterThrottle = &_BlockOutputLimiterTakeoffThrottle;
outputLimiterPitch = &_BlockOutputLimiterTakeoffPitch;
} else if (mode == TECS_MODE_LAND) {
// only limit pitch but do not limit throttle
outputLimiterPitch = &_BlockOutputLimiterLandPitch;
} else if (mode == TECS_MODE_LAND_THROTTLELIM) {
outputLimiterThrottle = &_BlockOutputLimiterLandThrottle;
outputLimiterPitch = &_BlockOutputLimiterLandPitch;
} else if (mode == TECS_MODE_UNDERSPEED) {
outputLimiterThrottle = &_BlockOutputLimiterUnderspeedThrottle;
outputLimiterPitch = &_BlockOutputLimiterUnderspeedPitch;
}
/* Apply overrride given by the limitOverride argument (this is used for limits which are not given by
* parameters such as pitch limits with takeoff waypoints or throttle limits when the launchdetector
* is running) */
limitOverride.applyOverride(*outputLimiterThrottle, *outputLimiterPitch);
/* Write part of the status message */
_status.flightPathAngleSp = flightPathAngleSp;
_status.flightPathAngle = flightPathAngle;
_status.flightPathAngleFiltered = flightPathAngleFiltered;
_status.airspeedDerivativeSp = airspeedDerivativeSp;
_status.airspeedDerivative = airspeedDerivative;
_status.totalEnergyRateSp = totalEnergyRateSp;
_status.totalEnergyRate = totalEnergyRate;
_status.energyDistributionRateSp = energyDistributionRateSp;
_status.energyDistributionRate = energyDistributionRate;
_status.mode = mode;
/** update control blocks **/
/* update total energy rate control block */
_throttleSp = _controlTotalEnergy.update(totalEnergyRateSp, totalEnergyRateError, outputLimiterThrottle);
/* update energy distribution rate control block */
_pitchSp = _controlEnergyDistribution.update(energyDistributionRateSp, energyDistributionRateError, outputLimiterPitch);
if (_counter % 10 == 0) {
debug("_throttleSp %.1f, _pitchSp %.1f, flightPathAngleSp %.1f, flightPathAngle %.1f accelerationLongitudinalSp %.1f, airspeedDerivative %.1f",
(double)_throttleSp, (double)_pitchSp,
(double)flightPathAngleSp, (double)flightPathAngle,
(double)accelerationLongitudinalSp, (double)airspeedDerivative);
}
/* publish status messge */
_status.update();
/* clean up */
_firstIterationAfterReset = false;
_dtCalculated = false;
_counter++;
return 0;
}
void mTecs::resetIntegrators()
{
_controlTotalEnergy.getIntegral().setY(0.0f);
_controlEnergyDistribution.getIntegral().setY(0.0f);
timestampLastIteration = hrt_absolute_time();
_firstIterationAfterReset = true;
}
void mTecs::resetDerivatives(float airspeed)
{
_airspeedDerivative.setU(airspeed);
}
void mTecs::updateTimeMeasurement()
{
if (!_dtCalculated) {
float deltaTSeconds = 0.0f;
if (!_firstIterationAfterReset) {
hrt_abstime timestampNow = hrt_absolute_time();
deltaTSeconds = (float)(timestampNow - timestampLastIteration) * 1e-6f;
timestampLastIteration = timestampNow;
}
setDt(deltaTSeconds);
_dtCalculated = true;
}
}
void mTecs::debug_print(const char *fmt, va_list args)
{
fprintf(stderr, "%s: ", "[mtecs]");
vfprintf(stderr, fmt, args);
fprintf(stderr, "\n");
}
void mTecs::debug(const char *fmt, ...) {
if (!_debug) {
return;
}
va_list args;
va_start(args, fmt);
debug_print(fmt, args);
}
} /* namespace fwPosctrl */
<|endoftext|> |
<commit_before>#include <vector>
#include <thread>
#include <set>
#include <mutex>
#include <chrono>
#include <condition_variable>
#include <gtest/gtest.h>
#include "cppkafka/consumer.h"
#include "cppkafka/producer.h"
#include "cppkafka/utils/consumer_dispatcher.h"
#include "cppkafka/utils/buffered_producer.h"
#include "test_utils.h"
using std::vector;
using std::move;
using std::string;
using std::thread;
using std::set;
using std::mutex;
using std::tie;
using std::condition_variable;
using std::lock_guard;
using std::unique_lock;
using std::chrono::seconds;
using std::chrono::milliseconds;
using std::chrono::system_clock;
using namespace cppkafka;
class ConsumerTest : public testing::Test {
public:
static const string KAFKA_TOPIC;
Configuration make_producer_config() {
Configuration config;
config.set("metadata.broker.list", KAFKA_TEST_INSTANCE);
return config;
}
Configuration make_consumer_config(const string& group_id = "consumer_test") {
Configuration config;
config.set("metadata.broker.list", KAFKA_TEST_INSTANCE);
config.set("enable.auto.commit", false);
config.set("group.id", group_id);
return config;
}
};
const string ConsumerTest::KAFKA_TOPIC = "cppkafka_test1";
TEST_F(ConsumerTest, AssignmentCallback) {
vector<TopicPartition> assignment;
int partition = 0;
// Create a consumer and subscribe to the topic
Consumer consumer(make_consumer_config());
consumer.set_assignment_callback([&](const vector<TopicPartition>& topic_partitions) {
assignment = topic_partitions;
});
consumer.subscribe({ KAFKA_TOPIC });
ConsumerRunner runner(consumer, 1, 3);
// Produce a message just so we stop the consumer
Producer producer(make_producer_config());
string payload = "Hello world!";
producer.produce(MessageBuilder(KAFKA_TOPIC).partition(partition).payload(payload));
runner.try_join();
// All 3 partitions should be ours
EXPECT_EQ(3, assignment.size());
set<int> partitions = { 0, 1, 2 };
for (const auto& topic_partition : assignment) {
EXPECT_EQ(KAFKA_TOPIC, topic_partition.get_topic());
EXPECT_TRUE(partitions.erase(topic_partition.get_partition()));
}
EXPECT_EQ(1, runner.get_messages().size());
EXPECT_EQ(vector<string>{ KAFKA_TOPIC }, consumer.get_subscription());
assignment = consumer.get_assignment();
EXPECT_EQ(3, assignment.size());
int64_t low;
int64_t high;
tie(low, high) = consumer.get_offsets({ KAFKA_TOPIC, partition });
EXPECT_GT(high, low);
EXPECT_EQ(high, runner.get_messages().back().get_offset() + 1);
}
TEST_F(ConsumerTest, Rebalance) {
vector<TopicPartition> assignment1;
vector<TopicPartition> assignment2;
bool revocation_called = false;
int partition = 0;
// Create a consumer and subscribe to the topic
Consumer consumer1(make_consumer_config());
consumer1.set_assignment_callback([&](const vector<TopicPartition>& topic_partitions) {
assignment1 = topic_partitions;
});
consumer1.set_revocation_callback([&](const vector<TopicPartition>&) {
revocation_called = true;
});
consumer1.subscribe({ KAFKA_TOPIC });
ConsumerRunner runner1(consumer1, 1, 3);
// Create a second consumer and subscribe to the topic
Consumer consumer2(make_consumer_config());
consumer2.set_assignment_callback([&](const vector<TopicPartition>& topic_partitions) {
assignment2 = topic_partitions;
});
consumer2.subscribe({ KAFKA_TOPIC });
ConsumerRunner runner2(consumer2, 1, 1);
EXPECT_TRUE(revocation_called);
// Produce a message just so we stop the consumer
Producer producer(make_producer_config());
string payload = "Hello world!";
producer.produce(MessageBuilder(KAFKA_TOPIC).partition(partition).payload(payload));
runner1.try_join();
runner2.try_join();
// All 3 partitions should be assigned
EXPECT_EQ(3, assignment1.size() + assignment2.size());
set<int> partitions = { 0, 1, 2 };
for (const auto& topic_partition : assignment1) {
EXPECT_EQ(KAFKA_TOPIC, topic_partition.get_topic());
EXPECT_TRUE(partitions.erase(topic_partition.get_partition()));
}
for (const auto& topic_partition : assignment2) {
EXPECT_EQ(KAFKA_TOPIC, topic_partition.get_topic());
EXPECT_TRUE(partitions.erase(topic_partition.get_partition()));
}
EXPECT_EQ(1, runner1.get_messages().size() + runner2.get_messages().size());
}
TEST_F(ConsumerTest, OffsetCommit) {
int partition = 0;
int64_t message_offset = 0;
bool offset_commit_called = false;
// Create a consumer and subscribe to the topic
Configuration config = make_consumer_config("offset_commit");
config.set_offset_commit_callback([&](Consumer&, Error error,
const TopicPartitionList& topic_partitions) {
offset_commit_called = true;
EXPECT_FALSE(error);
ASSERT_EQ(1, topic_partitions.size());
EXPECT_EQ(KAFKA_TOPIC, topic_partitions[0].get_topic());
EXPECT_EQ(0, topic_partitions[0].get_partition());
EXPECT_EQ(message_offset + 1, topic_partitions[0].get_offset());
});
Consumer consumer(config);
consumer.assign({ { KAFKA_TOPIC, 0 } });
ConsumerRunner runner(consumer, 1, 1);
// Produce a message just so we stop the consumer
Producer producer(make_producer_config());
string payload = "Hello world!";
producer.produce(MessageBuilder(KAFKA_TOPIC).partition(partition).payload(payload));
runner.try_join();
ASSERT_EQ(1, runner.get_messages().size());
const Message& msg = runner.get_messages()[0];
message_offset = msg.get_offset();
consumer.commit(msg);
for (size_t i = 0; i < 3 && !offset_commit_called; ++i) {
consumer.poll();
}
EXPECT_TRUE(offset_commit_called);
}
TEST_F(ConsumerTest, Throttle) {
int partition = 0;
// Create a consumer and subscribe to the topic
Configuration config = make_consumer_config("offset_commit");
Consumer consumer(config);
consumer.assign({ { KAFKA_TOPIC, 0 } });
{
ConsumerRunner runner(consumer, 0, 1);
runner.try_join();
}
// Produce a message just so we stop the consumer
BufferedProducer<string> producer(make_producer_config());
string payload = "Hello world!";
producer.produce(MessageBuilder(KAFKA_TOPIC).partition(partition).payload(payload));
producer.flush();
size_t callback_executed_count = 0;
ConsumerDispatcher dispatcher(consumer);
dispatcher.run(
[&](Message msg) {
callback_executed_count++;
if (callback_executed_count == 3) {
return Message();
}
return move(msg);
},
[&](ConsumerDispatcher::Timeout) {
if (callback_executed_count == 3) {
dispatcher.stop();
}
}
);
EXPECT_EQ(3, callback_executed_count);
}
TEST_F(ConsumerTest, ConsumeBatch) {
int partition = 0;
// Create a consumer and subscribe to the topic
Configuration config = make_consumer_config("test");
Consumer consumer(config);
consumer.assign({ { KAFKA_TOPIC, 0 } });
{
ConsumerRunner runner(consumer, 0, 1);
runner.try_join();
}
// Produce a message just so we stop the consumer
BufferedProducer<string> producer(make_producer_config());
string payload = "Hello world!";
// Produce it twice
producer.produce(MessageBuilder(KAFKA_TOPIC).partition(partition).payload(payload));
producer.produce(MessageBuilder(KAFKA_TOPIC).partition(partition).payload(payload));
producer.flush();
vector<Message> messages = consumer.poll_batch(2);
ASSERT_EQ(2, messages.size());
EXPECT_EQ(payload, messages[0].get_payload());
EXPECT_EQ(payload, messages[1].get_payload());
}
<commit_msg>Fix Consumer::poll_batch test<commit_after>#include <vector>
#include <thread>
#include <set>
#include <mutex>
#include <chrono>
#include <iterator>
#include <condition_variable>
#include <gtest/gtest.h>
#include "cppkafka/consumer.h"
#include "cppkafka/producer.h"
#include "cppkafka/utils/consumer_dispatcher.h"
#include "cppkafka/utils/buffered_producer.h"
#include "test_utils.h"
using std::vector;
using std::move;
using std::string;
using std::thread;
using std::set;
using std::mutex;
using std::tie;
using std::condition_variable;
using std::lock_guard;
using std::unique_lock;
using std::make_move_iterator;
using std::chrono::seconds;
using std::chrono::milliseconds;
using std::chrono::system_clock;
using namespace cppkafka;
class ConsumerTest : public testing::Test {
public:
static const string KAFKA_TOPIC;
Configuration make_producer_config() {
Configuration config;
config.set("metadata.broker.list", KAFKA_TEST_INSTANCE);
return config;
}
Configuration make_consumer_config(const string& group_id = "consumer_test") {
Configuration config;
config.set("metadata.broker.list", KAFKA_TEST_INSTANCE);
config.set("enable.auto.commit", false);
config.set("group.id", group_id);
return config;
}
};
const string ConsumerTest::KAFKA_TOPIC = "cppkafka_test1";
TEST_F(ConsumerTest, AssignmentCallback) {
vector<TopicPartition> assignment;
int partition = 0;
// Create a consumer and subscribe to the topic
Consumer consumer(make_consumer_config());
consumer.set_assignment_callback([&](const vector<TopicPartition>& topic_partitions) {
assignment = topic_partitions;
});
consumer.subscribe({ KAFKA_TOPIC });
ConsumerRunner runner(consumer, 1, 3);
// Produce a message just so we stop the consumer
Producer producer(make_producer_config());
string payload = "Hello world!";
producer.produce(MessageBuilder(KAFKA_TOPIC).partition(partition).payload(payload));
runner.try_join();
// All 3 partitions should be ours
EXPECT_EQ(3, assignment.size());
set<int> partitions = { 0, 1, 2 };
for (const auto& topic_partition : assignment) {
EXPECT_EQ(KAFKA_TOPIC, topic_partition.get_topic());
EXPECT_TRUE(partitions.erase(topic_partition.get_partition()));
}
EXPECT_EQ(1, runner.get_messages().size());
EXPECT_EQ(vector<string>{ KAFKA_TOPIC }, consumer.get_subscription());
assignment = consumer.get_assignment();
EXPECT_EQ(3, assignment.size());
int64_t low;
int64_t high;
tie(low, high) = consumer.get_offsets({ KAFKA_TOPIC, partition });
EXPECT_GT(high, low);
EXPECT_EQ(high, runner.get_messages().back().get_offset() + 1);
}
TEST_F(ConsumerTest, Rebalance) {
vector<TopicPartition> assignment1;
vector<TopicPartition> assignment2;
bool revocation_called = false;
int partition = 0;
// Create a consumer and subscribe to the topic
Consumer consumer1(make_consumer_config());
consumer1.set_assignment_callback([&](const vector<TopicPartition>& topic_partitions) {
assignment1 = topic_partitions;
});
consumer1.set_revocation_callback([&](const vector<TopicPartition>&) {
revocation_called = true;
});
consumer1.subscribe({ KAFKA_TOPIC });
ConsumerRunner runner1(consumer1, 1, 3);
// Create a second consumer and subscribe to the topic
Consumer consumer2(make_consumer_config());
consumer2.set_assignment_callback([&](const vector<TopicPartition>& topic_partitions) {
assignment2 = topic_partitions;
});
consumer2.subscribe({ KAFKA_TOPIC });
ConsumerRunner runner2(consumer2, 1, 1);
EXPECT_TRUE(revocation_called);
// Produce a message just so we stop the consumer
Producer producer(make_producer_config());
string payload = "Hello world!";
producer.produce(MessageBuilder(KAFKA_TOPIC).partition(partition).payload(payload));
runner1.try_join();
runner2.try_join();
// All 3 partitions should be assigned
EXPECT_EQ(3, assignment1.size() + assignment2.size());
set<int> partitions = { 0, 1, 2 };
for (const auto& topic_partition : assignment1) {
EXPECT_EQ(KAFKA_TOPIC, topic_partition.get_topic());
EXPECT_TRUE(partitions.erase(topic_partition.get_partition()));
}
for (const auto& topic_partition : assignment2) {
EXPECT_EQ(KAFKA_TOPIC, topic_partition.get_topic());
EXPECT_TRUE(partitions.erase(topic_partition.get_partition()));
}
EXPECT_EQ(1, runner1.get_messages().size() + runner2.get_messages().size());
}
TEST_F(ConsumerTest, OffsetCommit) {
int partition = 0;
int64_t message_offset = 0;
bool offset_commit_called = false;
// Create a consumer and subscribe to the topic
Configuration config = make_consumer_config("offset_commit");
config.set_offset_commit_callback([&](Consumer&, Error error,
const TopicPartitionList& topic_partitions) {
offset_commit_called = true;
EXPECT_FALSE(error);
ASSERT_EQ(1, topic_partitions.size());
EXPECT_EQ(KAFKA_TOPIC, topic_partitions[0].get_topic());
EXPECT_EQ(0, topic_partitions[0].get_partition());
EXPECT_EQ(message_offset + 1, topic_partitions[0].get_offset());
});
Consumer consumer(config);
consumer.assign({ { KAFKA_TOPIC, 0 } });
ConsumerRunner runner(consumer, 1, 1);
// Produce a message just so we stop the consumer
Producer producer(make_producer_config());
string payload = "Hello world!";
producer.produce(MessageBuilder(KAFKA_TOPIC).partition(partition).payload(payload));
runner.try_join();
ASSERT_EQ(1, runner.get_messages().size());
const Message& msg = runner.get_messages()[0];
message_offset = msg.get_offset();
consumer.commit(msg);
for (size_t i = 0; i < 3 && !offset_commit_called; ++i) {
consumer.poll();
}
EXPECT_TRUE(offset_commit_called);
}
TEST_F(ConsumerTest, Throttle) {
int partition = 0;
// Create a consumer and subscribe to the topic
Configuration config = make_consumer_config("offset_commit");
Consumer consumer(config);
consumer.assign({ { KAFKA_TOPIC, 0 } });
{
ConsumerRunner runner(consumer, 0, 1);
runner.try_join();
}
// Produce a message just so we stop the consumer
BufferedProducer<string> producer(make_producer_config());
string payload = "Hello world!";
producer.produce(MessageBuilder(KAFKA_TOPIC).partition(partition).payload(payload));
producer.flush();
size_t callback_executed_count = 0;
ConsumerDispatcher dispatcher(consumer);
dispatcher.run(
[&](Message msg) {
callback_executed_count++;
if (callback_executed_count == 3) {
return Message();
}
return move(msg);
},
[&](ConsumerDispatcher::Timeout) {
if (callback_executed_count == 3) {
dispatcher.stop();
}
}
);
EXPECT_EQ(3, callback_executed_count);
}
TEST_F(ConsumerTest, ConsumeBatch) {
int partition = 0;
// Create a consumer and subscribe to the topic
Configuration config = make_consumer_config("test");
Consumer consumer(config);
consumer.assign({ { KAFKA_TOPIC, 0 } });
{
ConsumerRunner runner(consumer, 0, 1);
runner.try_join();
}
// Produce a message just so we stop the consumer
BufferedProducer<string> producer(make_producer_config());
string payload = "Hello world!";
// Produce it twice
producer.produce(MessageBuilder(KAFKA_TOPIC).partition(partition).payload(payload));
producer.produce(MessageBuilder(KAFKA_TOPIC).partition(partition).payload(payload));
producer.flush();
vector<Message> all_messages;
int i = 0;
while (i < 5 && all_messages.size() != 2) {
vector<Message> messages = consumer.poll_batch(2);
all_messages.insert(all_messages.end(), make_move_iterator(messages.begin()),
make_move_iterator(messages.end()));
++i;
}
ASSERT_EQ(2, all_messages.size());
EXPECT_EQ(payload, all_messages[0].get_payload());
EXPECT_EQ(payload, all_messages[1].get_payload());
}
<|endoftext|> |
<commit_before>// This file is part of the dune-pymor project:
// https://github.com/pyMor/dune-pymor
// Copyright Holders: Felix Albrecht, Stephan Rave
// License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause)
#ifdef HAVE_CMAKE_CONFIG
#include "cmake_config.h"
#elif defined (HAVE_CONFIG_H)
#include <config.h>
#endif // HAVE_CMAKE_CONFIG
#include <dune/stuff/test/test_common.hh>
#include <memory>
#include <dune/pymor/la/container/dunedynamic.hh>
#if HAVE_EIGEN
#include <dune/pymor/la/container/eigen.hh>
#endif
typedef testing::Types< Dune::Pymor::LA::DuneDynamicVector
#if HAVE_EIGEN
, Dune::Pymor::LA::EigenDenseVector
#endif
> VectorTypes;
template< class VectorType >
struct VectorTest
: public ::testing::Test
{
void check() const
{
VectorType* vector = VectorType::create(4);
const std::string DUNE_UNUSED(type) = vector->type();
const int DUNE_UNUSED(dim) = vector->dim();
const bool DUNE_UNUSED(almost_equal) = vector->almost_equal(vector);
vector->scal(1.0);
vector->axpy(1.0, vector);
const double DUNE_UNUSED(dot) = vector->dot(vector);
const double DUNE_UNUSED(l1_norm) = vector->l1_norm();
const double DUNE_UNUSED(l2_norm) = vector->l2_norm();
const double DUNE_UNUSED(sup_norm) = vector->sup_norm();
std::vector< int > component_indices(2);
component_indices[0] = 3;
component_indices[1] = 1;
std::vector< double > components = vector->components(component_indices);
assert(components.size() == component_indices.size());
std::vector< double > DUNE_UNUSED(amax) = vector->amax();
assert(amax.size() == 2);
VectorType* add = vector->add(vector);
delete add;
vector->iadd(vector);
VectorType* sub = vector->sub(vector);
delete sub;
vector->isub(vector);
delete vector;
}
}; // struct VectorTest
TYPED_TEST_CASE(VectorTest, VectorTypes);
TYPED_TEST(VectorTest, LA_CONTAINER) {
this->check();
}
int main(int argc, char** argv)
{
test_init(argc, argv);
return RUN_ALL_TESTS();
}
<commit_msg>[test.la_container] added test for static_type()<commit_after>// This file is part of the dune-pymor project:
// https://github.com/pyMor/dune-pymor
// Copyright Holders: Felix Albrecht, Stephan Rave
// License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause)
#ifdef HAVE_CMAKE_CONFIG
#include "cmake_config.h"
#elif defined (HAVE_CONFIG_H)
#include <config.h>
#endif // HAVE_CMAKE_CONFIG
#include <dune/stuff/test/test_common.hh>
#include <dune/pymor/common/exceptions.hh>
#include <dune/pymor/la/container/dunedynamic.hh>
#if HAVE_EIGEN
#include <dune/pymor/la/container/eigen.hh>
#endif
using namespace Dune;
using namespace Dune::Pymor;
typedef testing::Types< Dune::Pymor::LA::DuneDynamicVector
#if HAVE_EIGEN
, Dune::Pymor::LA::EigenDenseVector
#endif
> VectorTypes;
template< class VectorType >
struct VectorTest
: public ::testing::Test
{
void check() const
{
VectorType* vector = VectorType::create(4);
const std::string type = vector->type();
const std::string static_type = vector->static_type();
if (type != static_type) DUNE_PYMOR_THROW(PymorException, "");
const int DUNE_UNUSED(dim) = vector->dim();
const bool DUNE_UNUSED(almost_equal) = vector->almost_equal(vector);
vector->scal(1.0);
vector->axpy(1.0, vector);
const double DUNE_UNUSED(dot) = vector->dot(vector);
const double DUNE_UNUSED(l1_norm) = vector->l1_norm();
const double DUNE_UNUSED(l2_norm) = vector->l2_norm();
const double DUNE_UNUSED(sup_norm) = vector->sup_norm();
std::vector< int > component_indices(2);
component_indices[0] = 3;
component_indices[1] = 1;
std::vector< double > components = vector->components(component_indices);
assert(components.size() == component_indices.size());
std::vector< double > DUNE_UNUSED(amax) = vector->amax();
assert(amax.size() == 2);
VectorType* add = vector->add(vector);
delete add;
vector->iadd(vector);
VectorType* sub = vector->sub(vector);
delete sub;
vector->isub(vector);
delete vector;
}
}; // struct VectorTest
TYPED_TEST_CASE(VectorTest, VectorTypes);
TYPED_TEST(VectorTest, LA_CONTAINER) {
this->check();
}
int main(int argc, char** argv)
{
test_init(argc, argv);
return RUN_ALL_TESTS();
}
<|endoftext|> |
<commit_before>#include "../include/zonotope_volume.hpp"
#include "../include/zonotope_halfspaces.hpp"
/**
* Convert the column-major m-by-n matrix `arr` from a flat array to
* an m-by-n matrix. If `transpose == true`, then instead output the
* transpose of `arr`. The contents of `mat` are entirely overwritten
* (along with its dimensions).
*
*/
template <typename T>
static void array_to_matrix_2(const int m,
const int n,
const bool transpose,
const T* arr,
std::vector<std::vector<T> >& mat) {
mat = std::vector<std::vector<T> > (m, std::vector<T> (n));
if ( transpose ) {
for ( int i = 0; i < m; ++i ) {
for ( int j = 0; j < n; ++j ) {
mat[i][j] = arr[j + i*n];
}
}
} else {
for ( int i = 0; i < m; ++i ) {
for ( int j = 0; j < n; ++j ) {
mat[i][j] = arr[i + j*m];
}
}
}
}
/**
*
* Exported interface
*
*/
extern "C" {
long zonotope_volume_long(int d, int n, long* generators) {
std::vector<std::vector<long> > _generators;
array_to_matrix_2(n, d, true, generators, _generators);
return zonotope_volume(_generators);
}
long* zonotope_halfspaces_long(int d, int n, long* generators) {
std::vector<std::vector<long> > _generators;
array_to_matrix_2(n, d, true, generators, _generators);
std::set<Hyperplane<long> > _halfspaces;
zonotope_halfspaces(_generators, _halfspaces);
long* halfspaces = new long[(d+1) * _halfspaces.size()];
std::set<Hyperplane<long> >::size_type count = 0;
for ( const Hyperplane<long>& h : _halfspaces ) {
halfspaces[count++] = h.offset;
for ( int i = 0; i < d; ++i ) {
halfspaces[count++] = h.normal[i];
}
}
return halfspaces;
}
}
<commit_msg>use malloc instead of new in C interface<commit_after>#include "zonotope_volume.hpp"
#include "zonotope_halfspaces.hpp"
#include <cstdlib>
/**
* Convert the column-major m-by-n matrix `arr` from a flat array to
* an m-by-n matrix. If `transpose == true`, then instead output the
* transpose of `arr`. The contents of `mat` are entirely overwritten
* (along with its dimensions).
*
*/
template <typename T>
static void array_to_matrix_2(const int m,
const int n,
const bool transpose,
const T* arr,
std::vector<std::vector<T> >& mat) {
mat = std::vector<std::vector<T> > (m, std::vector<T> (n));
if ( transpose ) {
for ( int i = 0; i < m; ++i ) {
for ( int j = 0; j < n; ++j ) {
mat[i][j] = arr[j + i*n];
}
}
} else {
for ( int i = 0; i < m; ++i ) {
for ( int j = 0; j < n; ++j ) {
mat[i][j] = arr[i + j*m];
}
}
}
}
/**
*
* Exported interface
*
*/
extern "C" {
long zonotope_volume_long(int d, int n, long* generators) {
std::vector<std::vector<long> > _generators;
array_to_matrix_2(n, d, true, generators, _generators);
return zonotope_volume(_generators);
}
long zonotope_halfspaces_long(int d, int n, long* generators, long** halfspaces) {
std::vector<std::vector<long> > _generators;
array_to_matrix_2(n, d, true, generators, _generators);
std::set<Hyperplane<long> > _halfspaces;
zonotope_halfspaces(_generators, _halfspaces);
(*halfspaces) = (long*)malloc(sizeof(long) * (d+1) * _halfspaces.size());
std::set<Hyperplane<long> >::size_type count = 0;
for ( const Hyperplane<long>& h : _halfspaces ) {
(*halfspaces)[count++] = h.offset;
for ( int i = 0; i < d; ++i ) {
(*halfspaces)[count++] = h.normal[i];
}
}
return _halfspaces.size();
}
}
<|endoftext|> |
<commit_before>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*************************************************************************
*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* Copyright 2000, 2010 Oracle and/or its affiliates.
*
* OpenOffice.org - a multi-platform office productivity suite
*
* 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 __FRAMEWORK_CLASSES_SFXHELPERFUNCTIONS_HXX_
#define __FRAMEWORK_CLASSES_SFXHELPERFUNCTIONS_HXX_
#include <com/sun/star/frame/XFrame.hpp>
#include <rtl/ustring.hxx>
#include <vcl/toolbox.hxx>
#include <vcl/status.hxx>
#include <svtools/toolboxcontroller.hxx>
#include <svtools/statusbarcontroller.hxx>
typedef svt::ToolboxController* ( *pfunc_setToolBoxControllerCreator)( const ::com::sun::star::uno::Reference< ::com::sun::star::frame::XFrame >& rFrame, ToolBox* pToolbox, unsigned short nID, const ::rtl::OUString& aCommandURL );
typedef svt::StatusbarController* ( *pfunc_setStatusBarControllerCreator)( const ::com::sun::star::uno::Reference< ::com::sun::star::frame::XFrame >& rFrame, StatusBar* pStatusBar, unsigned short nID, const ::rtl::OUString& aCommandURL );
typedef void ( *pfunc_getRefreshToolbars)( ::com::sun::star::uno::Reference< ::com::sun::star::frame::XFrame >& rFrame );
typedef void ( *pfunc_createDockingWindow)( const ::com::sun::star::uno::Reference< ::com::sun::star::frame::XFrame >& rFrame, const ::rtl::OUString& rResourceURL );
typedef bool ( *pfunc_isDockingWindowVisible)( const ::com::sun::star::uno::Reference< ::com::sun::star::frame::XFrame >& rFrame, const ::rtl::OUString& rResourceURL );
typedef void ( *pfunc_activateToolPanel)( const ::com::sun::star::uno::Reference< ::com::sun::star::frame::XFrame >& i_rFrame, const ::rtl::OUString& i_rPanelURL );
namespace framework
{
pfunc_setToolBoxControllerCreator SAL_CALL SetToolBoxControllerCreator( pfunc_setToolBoxControllerCreator pSetToolBoxControllerCreator );
svt::ToolboxController* SAL_CALL CreateToolBoxController( const ::com::sun::star::uno::Reference< ::com::sun::star::frame::XFrame >& rFrame, ToolBox* pToolbox, unsigned short nID, const ::rtl::OUString& aCommandURL );
pfunc_setStatusBarControllerCreator SAL_CALL SetStatusBarControllerCreator( pfunc_setStatusBarControllerCreator pSetStatusBarControllerCreator );
svt::StatusbarController* SAL_CALL CreateStatusBarController( const ::com::sun::star::uno::Reference< ::com::sun::star::frame::XFrame >& rFrame, StatusBar* pStatusBar, unsigned short nID, const ::rtl::OUString& aCommandURL );
pfunc_getRefreshToolbars SAL_CALL SetRefreshToolbars( pfunc_getRefreshToolbars pRefreshToolbarsFunc );
void SAL_CALL RefreshToolbars( ::com::sun::star::uno::Reference< ::com::sun::star::frame::XFrame >& rFrame );
pfunc_createDockingWindow SAL_CALL SetDockingWindowCreator( pfunc_createDockingWindow pCreateDockingWindow );
void SAL_CALL CreateDockingWindow( const ::com::sun::star::uno::Reference< ::com::sun::star::frame::XFrame >& rFrame, const ::rtl::OUString& rResourceURL );
pfunc_isDockingWindowVisible SAL_CALL SetIsDockingWindowVisible( pfunc_isDockingWindowVisible pIsDockingWindowVisible );
bool SAL_CALL IsDockingWindowVisible( const ::com::sun::star::uno::Reference< ::com::sun::star::frame::XFrame >& rFrame, const ::rtl::OUString& rResourceURL );
pfunc_activateToolPanel SAL_CALL SetActivateToolPanel( pfunc_activateToolPanel i_pActivator );
void SAL_CALL ActivateToolPanel( const ::com::sun::star::uno::Reference< ::com::sun::star::frame::XFrame >& i_rFrame, const ::rtl::OUString& i_rPanelURL );
}
#endif // __FRAMEWORK_CLASSES_SFXHELPERFUNCTIONS_HXX_
/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<commit_msg>Make this file readable.<commit_after>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*************************************************************************
*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* Copyright 2000, 2010 Oracle and/or its affiliates.
*
* OpenOffice.org - a multi-platform office productivity suite
*
* 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 __FRAMEWORK_CLASSES_SFXHELPERFUNCTIONS_HXX_
#define __FRAMEWORK_CLASSES_SFXHELPERFUNCTIONS_HXX_
#include <com/sun/star/frame/XFrame.hpp>
#include <rtl/ustring.hxx>
#include <vcl/toolbox.hxx>
#include <vcl/status.hxx>
#include <svtools/toolboxcontroller.hxx>
#include <svtools/statusbarcontroller.hxx>
typedef svt::ToolboxController* ( *pfunc_setToolBoxControllerCreator)(
const ::com::sun::star::uno::Reference< ::com::sun::star::frame::XFrame >& rFrame,
ToolBox* pToolbox,
unsigned short nID,
const ::rtl::OUString& aCommandURL );
typedef svt::StatusbarController* ( *pfunc_setStatusBarControllerCreator)(
const ::com::sun::star::uno::Reference< ::com::sun::star::frame::XFrame >& rFrame,
StatusBar* pStatusBar,
unsigned short nID,
const ::rtl::OUString& aCommandURL );
typedef void ( *pfunc_getRefreshToolbars)(
::com::sun::star::uno::Reference< ::com::sun::star::frame::XFrame >& rFrame );
typedef void ( *pfunc_createDockingWindow)(
const ::com::sun::star::uno::Reference< ::com::sun::star::frame::XFrame >& rFrame,
const ::rtl::OUString& rResourceURL );
typedef bool ( *pfunc_isDockingWindowVisible)(
const ::com::sun::star::uno::Reference< ::com::sun::star::frame::XFrame >& rFrame,
const ::rtl::OUString& rResourceURL );
typedef void ( *pfunc_activateToolPanel)(
const ::com::sun::star::uno::Reference< ::com::sun::star::frame::XFrame >& i_rFrame,
const ::rtl::OUString& i_rPanelURL );
namespace framework
{
pfunc_setToolBoxControllerCreator SAL_CALL SetToolBoxControllerCreator( pfunc_setToolBoxControllerCreator pSetToolBoxControllerCreator );
svt::ToolboxController* SAL_CALL CreateToolBoxController(
const ::com::sun::star::uno::Reference< ::com::sun::star::frame::XFrame >& rFrame,
ToolBox* pToolbox,
unsigned short nID,
const ::rtl::OUString& aCommandURL );
pfunc_setStatusBarControllerCreator SAL_CALL SetStatusBarControllerCreator( pfunc_setStatusBarControllerCreator pSetStatusBarControllerCreator );
svt::StatusbarController* SAL_CALL CreateStatusBarController(
const ::com::sun::star::uno::Reference< ::com::sun::star::frame::XFrame >& rFrame,
StatusBar* pStatusBar,
unsigned short nID,
const ::rtl::OUString& aCommandURL );
pfunc_getRefreshToolbars SAL_CALL SetRefreshToolbars( pfunc_getRefreshToolbars pRefreshToolbarsFunc );
void SAL_CALL RefreshToolbars(
::com::sun::star::uno::Reference< ::com::sun::star::frame::XFrame >& rFrame );
pfunc_createDockingWindow SAL_CALL SetDockingWindowCreator( pfunc_createDockingWindow pCreateDockingWindow );
void SAL_CALL CreateDockingWindow(
const ::com::sun::star::uno::Reference< ::com::sun::star::frame::XFrame >& rFrame,
const ::rtl::OUString& rResourceURL );
pfunc_isDockingWindowVisible SAL_CALL SetIsDockingWindowVisible( pfunc_isDockingWindowVisible pIsDockingWindowVisible );
bool SAL_CALL IsDockingWindowVisible(
const ::com::sun::star::uno::Reference< ::com::sun::star::frame::XFrame >& rFrame,
const ::rtl::OUString& rResourceURL );
pfunc_activateToolPanel SAL_CALL SetActivateToolPanel( pfunc_activateToolPanel i_pActivator );
void SAL_CALL ActivateToolPanel(
const ::com::sun::star::uno::Reference< ::com::sun::star::frame::XFrame >& i_rFrame,
const ::rtl::OUString& i_rPanelURL );
}
#endif // __FRAMEWORK_CLASSES_SFXHELPERFUNCTIONS_HXX_
/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<|endoftext|> |
<commit_before>#include <iostream> // for standard I/O
#include <string> // for strings
#include <iomanip> // for controlling float print precision
#include <sstream> // string to number conversion
#include <opencv2/core/core.hpp> // Basic OpenCV structures (cv::Mat, Scalar)
#include <opencv2/imgproc/imgproc.hpp> // Gaussian Blur
#include <opencv2/highgui/highgui.hpp> // OpenCV window I/O
#include <opencv2/gpu/gpu.hpp>
#define STATUS_PER_NUM_FRAMES 50
using namespace std;
using namespace cv;
struct BufferMSSIM // Optimized GPU versions
{ // Data allocations are very expensive on GPU. Use a buffer to solve: allocate once reuse later.
gpu::GpuMat gI1, gI2, gs, t1, t2;
gpu::GpuMat I1_2, I2_2, I1_I2;
vector<gpu::GpuMat> vI1, vI2;
gpu::GpuMat mu1, mu2;
gpu::GpuMat mu1_2, mu2_2, mu1_mu2;
gpu::GpuMat sigma1_2, sigma2_2, sigma12;
gpu::GpuMat t3;
gpu::GpuMat ssim_map;
gpu::GpuMat buf;
};
Scalar getMSSIM_GPU_optimized(const Mat& i1, const Mat& i2, BufferMSSIM& b);
int main(int argc, char *argv[])
{
char c;
int delay = 1;
if (argc < 5)
{
cout << "Not enough parameters" << endl;
cout << "Command: ssim reference_video.avi test_video.avi x y [z]" << endl;
cout << "Where x is start frame of reference video and y is the start frame of test video. [z] (optional) is the number of frames to process. If not specified, app will process to end of any video." << endl;
return -1;
}
const string sourceReference = argv[1], sourceCompareWith = argv[2];
unsigned long refFramesToWait = strtol(argv[3], NULL, 10);
unsigned long testFramesToWait = strtol(argv[4], NULL, 10);
unsigned long framesToProcess = -1;
if (argc >= 6){
framesToProcess = strtol(argv[5], NULL, 10);
}
unsigned long refFrameNum = 0;
unsigned long testFrameNum = 0;
unsigned long comparisonFrameNum = 0; // Frame counter
unsigned long long redChannelTotal = 0;
unsigned long long blueChannelTotal = 0;
unsigned long long greenChannelTotal = 0;
VideoCapture captRefrnc(sourceReference), captUndTst(sourceCompareWith);
if (!captRefrnc.isOpened())
{
cout << "Could not open reference " << sourceReference << endl;
return -1;
}
if (!captUndTst.isOpened())
{
cout << "Could not open case test " << sourceCompareWith << endl;
return -1;
}
Size refS = Size((int)captRefrnc.get(CV_CAP_PROP_FRAME_WIDTH),
(int)captRefrnc.get(CV_CAP_PROP_FRAME_HEIGHT)),
uTSi = Size((int)captUndTst.get(CV_CAP_PROP_FRAME_WIDTH),
(int)captUndTst.get(CV_CAP_PROP_FRAME_HEIGHT));
if (refS != uTSi)
{
cout << "Inputs have different size!!! Closing." << endl;
return -1;
}
string refFilename = argv[1];
string testFilename = argv[2];
string refHeader = "Reference: " + refFilename;
string testHeader = "Test: " + testFilename;
const char* WIN_RF = refHeader.c_str();
const char* WIN_UT = testHeader.c_str();
// Windows
namedWindow(WIN_RF, CV_WINDOW_AUTOSIZE);
namedWindow(WIN_UT, CV_WINDOW_AUTOSIZE);
cvMoveWindow(WIN_RF, 400, 0); //750, 2 (bernat =0)
cvMoveWindow(WIN_UT, refS.width, 0); //1500, 2
cout << "Reference frame resolution: Width=" << refS.width << " Height=" << refS.height
<< " of nr#: " << captRefrnc.get(CV_CAP_PROP_FRAME_COUNT) << endl;
Mat frameReference, frameUnderTest;
Scalar mssimV;
BufferMSSIM bufferMSSIM;
double time = (double)getTickCount();
for (;;) //Show the image captured in the window and repeat
{
//Skip frames until both streams have synchronised on their starting frames
if (refFrameNum <= refFramesToWait || testFrameNum <= testFramesToWait)
{
if (refFrameNum <= refFramesToWait){
captRefrnc >> frameReference;
refFrameNum++;
}
if (testFrameNum <= testFramesToWait){
captUndTst >> frameUnderTest;
testFrameNum++;
}
continue;
}
captRefrnc >> frameReference;
captUndTst >> frameUnderTest;
if (frameReference.empty() || frameUnderTest.empty())
{
cout << "Program ended" << endl;
break;
}
mssimV = getMSSIM_GPU_optimized(frameReference, frameUnderTest, bufferMSSIM);
++comparisonFrameNum;
redChannelTotal += (unsigned long long) (mssimV.val[2] * 10000); //To store up to 2 decimal places
greenChannelTotal += (unsigned long long) (mssimV.val[1] * 10000); //To store up to 2 decimal places
blueChannelTotal += (unsigned long long) (mssimV.val[0] * 10000); //To store up to 2 decimal places
if ((comparisonFrameNum % STATUS_PER_NUM_FRAMES) == 0){
cout << "Finished " << setfill('0') << setw(6) << comparisonFrameNum << " frames,";
double redSimilarity = (redChannelTotal / comparisonFrameNum) / 100.0;
double greenSimilarity = (greenChannelTotal / comparisonFrameNum) / 100.0;
double blueSimilarity = (blueChannelTotal / comparisonFrameNum) / 100.0;
cout << " Similarity so far: "
<< " R " << setiosflags(ios::fixed) << setprecision(2) << redSimilarity << "%"
<< " G " << setiosflags(ios::fixed) << setprecision(2) << greenSimilarity << "%"
<< " B " << setiosflags(ios::fixed) << setprecision(2) << blueSimilarity << "%";
cout << endl;
}
////////////////////////////////// Show Image /////////////////////////////////////////////
imshow(WIN_RF, frameReference);
imshow(WIN_UT, frameUnderTest);
c = (char)cvWaitKey(delay);
if (c == 27) break;
if (framesToProcess >= 0 && comparisonFrameNum >= framesToProcess){
break;
}
}
time = ((double)getTickCount() - time)/ getTickFrequency();
double redSimilarity = (redChannelTotal / comparisonFrameNum) / 100.0;
double greenSimilarity = (greenChannelTotal / comparisonFrameNum) / 100.0;
double blueSimilarity = (blueChannelTotal / comparisonFrameNum) / 100.0;
cout << "Processing time: " << time << " seconds." << endl;
cout << "Ref start frame: " << refFramesToWait << ", Test start frame: " << testFramesToWait << endl;
cout << "Final Results" << endl;
cout << "R " << setiosflags(ios::fixed) << setprecision(2) << redSimilarity << "%"
<< " G " << setiosflags(ios::fixed) << setprecision(2) << greenSimilarity << "%"
<< " B " << setiosflags(ios::fixed) << setprecision(2) << blueSimilarity << "%";
cout << endl;
double average = (redSimilarity + greenSimilarity + blueSimilarity) / 3;
cout << "Similarity = " << average << "%" << endl;
return 0;
}
Scalar getMSSIM_GPU_optimized(const Mat& i1, const Mat& i2, BufferMSSIM& b)
{
const float C1 = 6.5025f, C2 = 58.5225f;
/***************************** INITS **********************************/
b.gI1.upload(i1);
b.gI2.upload(i2);
gpu::Stream stream;
stream.enqueueConvert(b.gI1, b.t1, CV_32F);
stream.enqueueConvert(b.gI2, b.t2, CV_32F);
gpu::split(b.t1, b.vI1, stream);
gpu::split(b.t2, b.vI2, stream);
Scalar mssim;
gpu::GpuMat buf;
for (int i = 0; i < b.gI1.channels(); ++i)
{
gpu::multiply(b.vI2[i], b.vI2[i], b.I2_2, stream); // I2^2
gpu::multiply(b.vI1[i], b.vI1[i], b.I1_2, stream); // I1^2
gpu::multiply(b.vI1[i], b.vI2[i], b.I1_I2, stream); // I1 * I2
gpu::GaussianBlur(b.vI1[i], b.mu1, Size(11, 11), buf, 1.5, 0, BORDER_DEFAULT, -1, stream);
gpu::GaussianBlur(b.vI2[i], b.mu2, Size(11, 11), buf, 1.5, 0, BORDER_DEFAULT, -1, stream);
gpu::multiply(b.mu1, b.mu1, b.mu1_2, stream);
gpu::multiply(b.mu2, b.mu2, b.mu2_2, stream);
gpu::multiply(b.mu1, b.mu2, b.mu1_mu2, stream);
gpu::GaussianBlur(b.I1_2, b.sigma1_2, Size(11, 11), buf, 1.5, 0, BORDER_DEFAULT, -1, stream);
gpu::subtract(b.sigma1_2, b.mu1_2, b.sigma1_2, gpu::GpuMat(), -1, stream);
//b.sigma1_2 -= b.mu1_2; - This would result in an extra data transfer operation
gpu::GaussianBlur(b.I2_2, b.sigma2_2, Size(11, 11), buf, 1.5, 0, BORDER_DEFAULT, -1, stream);
gpu::subtract(b.sigma2_2, b.mu2_2, b.sigma2_2, gpu::GpuMat(), -1, stream);
//b.sigma2_2 -= b.mu2_2;
gpu::GaussianBlur(b.I1_I2, b.sigma12, Size(11, 11), buf, 1.5, 0, BORDER_DEFAULT, -1, stream);
gpu::subtract(b.sigma12, b.mu1_mu2, b.sigma12, gpu::GpuMat(), -1, stream);
//b.sigma12 -= b.mu1_mu2;
//here too it would be an extra data transfer due to call of operator*(Scalar, Mat)
gpu::multiply(b.mu1_mu2, 2, b.t1, 1, -1, stream); //b.t1 = 2 * b.mu1_mu2 + C1;
gpu::add(b.t1, C1, b.t1, gpu::GpuMat(), -1, stream);
gpu::multiply(b.sigma12, 2, b.t2, 1, -1, stream); //b.t2 = 2 * b.sigma12 + C2;
gpu::add(b.t2, C2, b.t2, gpu::GpuMat(), -12, stream);
gpu::multiply(b.t1, b.t2, b.t3, 1, -1, stream); // t3 = ((2*mu1_mu2 + C1).*(2*sigma12 + C2))
gpu::add(b.mu1_2, b.mu2_2, b.t1, gpu::GpuMat(), -1, stream);
gpu::add(b.t1, C1, b.t1, gpu::GpuMat(), -1, stream);
gpu::add(b.sigma1_2, b.sigma2_2, b.t2, gpu::GpuMat(), -1, stream);
gpu::add(b.t2, C2, b.t2, gpu::GpuMat(), -1, stream);
gpu::multiply(b.t1, b.t2, b.t1, 1, -1, stream); // t1 =((mu1_2 + mu2_2 + C1).*(sigma1_2 + sigma2_2 + C2))
gpu::divide(b.t3, b.t1, b.ssim_map, 1, -1, stream); // ssim_map = t3./t1;
stream.waitForCompletion();
Scalar s = gpu::sum(b.ssim_map, b.buf);
mssim.val[i] = s.val[0] / (b.ssim_map.rows * b.ssim_map.cols);
}
return mssim;
}
<commit_msg>delay 10<commit_after>#include <iostream> // for standard I/O
#include <string> // for strings
#include <iomanip> // for controlling float print precision
#include <sstream> // string to number conversion
#include <opencv2/core/core.hpp> // Basic OpenCV structures (cv::Mat, Scalar)
#include <opencv2/imgproc/imgproc.hpp> // Gaussian Blur
#include <opencv2/highgui/highgui.hpp> // OpenCV window I/O
#include <opencv2/gpu/gpu.hpp>
#define STATUS_PER_NUM_FRAMES 50
using namespace std;
using namespace cv;
struct BufferMSSIM // Optimized GPU versions
{ // Data allocations are very expensive on GPU. Use a buffer to solve: allocate once reuse later.
gpu::GpuMat gI1, gI2, gs, t1, t2;
gpu::GpuMat I1_2, I2_2, I1_I2;
vector<gpu::GpuMat> vI1, vI2;
gpu::GpuMat mu1, mu2;
gpu::GpuMat mu1_2, mu2_2, mu1_mu2;
gpu::GpuMat sigma1_2, sigma2_2, sigma12;
gpu::GpuMat t3;
gpu::GpuMat ssim_map;
gpu::GpuMat buf;
};
Scalar getMSSIM_GPU_optimized(const Mat& i1, const Mat& i2, BufferMSSIM& b);
int main(int argc, char *argv[])
{
char c;
int delay = 10;
if (argc < 5)
{
cout << "Not enough parameters" << endl;
cout << "Command: ssim reference_video.avi test_video.avi x y [z]" << endl;
cout << "Where x is start frame of reference video and y is the start frame of test video. [z] (optional) is the number of frames to process. If not specified, app will process to end of any video." << endl;
return -1;
}
const string sourceReference = argv[1], sourceCompareWith = argv[2];
unsigned long refFramesToWait = strtol(argv[3], NULL, 10);
unsigned long testFramesToWait = strtol(argv[4], NULL, 10);
unsigned long framesToProcess = -1;
if (argc >= 6){
framesToProcess = strtol(argv[5], NULL, 10);
}
unsigned long refFrameNum = 0;
unsigned long testFrameNum = 0;
unsigned long comparisonFrameNum = 0; // Frame counter
unsigned long long redChannelTotal = 0;
unsigned long long blueChannelTotal = 0;
unsigned long long greenChannelTotal = 0;
VideoCapture captRefrnc(sourceReference), captUndTst(sourceCompareWith);
if (!captRefrnc.isOpened())
{
cout << "Could not open reference " << sourceReference << endl;
return -1;
}
if (!captUndTst.isOpened())
{
cout << "Could not open case test " << sourceCompareWith << endl;
return -1;
}
Size refS = Size((int)captRefrnc.get(CV_CAP_PROP_FRAME_WIDTH),
(int)captRefrnc.get(CV_CAP_PROP_FRAME_HEIGHT)),
uTSi = Size((int)captUndTst.get(CV_CAP_PROP_FRAME_WIDTH),
(int)captUndTst.get(CV_CAP_PROP_FRAME_HEIGHT));
if (refS != uTSi)
{
cout << "Inputs have different size!!! Closing." << endl;
return -1;
}
string refFilename = argv[1];
string testFilename = argv[2];
string refHeader = "Reference: " + refFilename;
string testHeader = "Test: " + testFilename;
const char* WIN_RF = refHeader.c_str();
const char* WIN_UT = testHeader.c_str();
// Windows
namedWindow(WIN_RF, CV_WINDOW_AUTOSIZE);
namedWindow(WIN_UT, CV_WINDOW_AUTOSIZE);
cvMoveWindow(WIN_RF, 400, 0); //750, 2 (bernat =0)
cvMoveWindow(WIN_UT, refS.width, 0); //1500, 2
cout << "Reference frame resolution: Width=" << refS.width << " Height=" << refS.height
<< " of nr#: " << captRefrnc.get(CV_CAP_PROP_FRAME_COUNT) << endl;
Mat frameReference, frameUnderTest;
Scalar mssimV;
BufferMSSIM bufferMSSIM;
double time = (double)getTickCount();
for (;;) //Show the image captured in the window and repeat
{
//Skip frames until both streams have synchronised on their starting frames
if (refFrameNum <= refFramesToWait || testFrameNum <= testFramesToWait)
{
if (refFrameNum <= refFramesToWait){
captRefrnc >> frameReference;
refFrameNum++;
}
if (testFrameNum <= testFramesToWait){
captUndTst >> frameUnderTest;
testFrameNum++;
}
continue;
}
captRefrnc >> frameReference;
captUndTst >> frameUnderTest;
if (frameReference.empty() || frameUnderTest.empty())
{
cout << "Program ended" << endl;
break;
}
mssimV = getMSSIM_GPU_optimized(frameReference, frameUnderTest, bufferMSSIM);
++comparisonFrameNum;
redChannelTotal += (unsigned long long) (mssimV.val[2] * 10000); //To store up to 2 decimal places
greenChannelTotal += (unsigned long long) (mssimV.val[1] * 10000); //To store up to 2 decimal places
blueChannelTotal += (unsigned long long) (mssimV.val[0] * 10000); //To store up to 2 decimal places
if ((comparisonFrameNum % STATUS_PER_NUM_FRAMES) == 0){
cout << "Finished " << setfill('0') << setw(6) << comparisonFrameNum << " frames,";
double redSimilarity = (redChannelTotal / comparisonFrameNum) / 100.0;
double greenSimilarity = (greenChannelTotal / comparisonFrameNum) / 100.0;
double blueSimilarity = (blueChannelTotal / comparisonFrameNum) / 100.0;
cout << " Similarity so far: "
<< " R " << setiosflags(ios::fixed) << setprecision(2) << redSimilarity << "%"
<< " G " << setiosflags(ios::fixed) << setprecision(2) << greenSimilarity << "%"
<< " B " << setiosflags(ios::fixed) << setprecision(2) << blueSimilarity << "%";
cout << endl;
}
////////////////////////////////// Show Image /////////////////////////////////////////////
imshow(WIN_RF, frameReference);
imshow(WIN_UT, frameUnderTest);
c = (char)cvWaitKey(delay);
if (c == 27) break;
if (framesToProcess >= 0 && comparisonFrameNum >= framesToProcess){
break;
}
}
time = ((double)getTickCount() - time)/ getTickFrequency();
double redSimilarity = (redChannelTotal / comparisonFrameNum) / 100.0;
double greenSimilarity = (greenChannelTotal / comparisonFrameNum) / 100.0;
double blueSimilarity = (blueChannelTotal / comparisonFrameNum) / 100.0;
cout << "Processing time: " << time << " seconds." << endl;
cout << "Ref start frame: " << refFramesToWait << ", Test start frame: " << testFramesToWait << endl;
cout << "Final Results" << endl;
cout << "R " << setiosflags(ios::fixed) << setprecision(2) << redSimilarity << "%"
<< " G " << setiosflags(ios::fixed) << setprecision(2) << greenSimilarity << "%"
<< " B " << setiosflags(ios::fixed) << setprecision(2) << blueSimilarity << "%";
cout << endl;
double average = (redSimilarity + greenSimilarity + blueSimilarity) / 3;
cout << "Similarity = " << average << "%" << endl;
return 0;
}
Scalar getMSSIM_GPU_optimized(const Mat& i1, const Mat& i2, BufferMSSIM& b)
{
const float C1 = 6.5025f, C2 = 58.5225f;
/***************************** INITS **********************************/
b.gI1.upload(i1);
b.gI2.upload(i2);
gpu::Stream stream;
stream.enqueueConvert(b.gI1, b.t1, CV_32F);
stream.enqueueConvert(b.gI2, b.t2, CV_32F);
gpu::split(b.t1, b.vI1, stream);
gpu::split(b.t2, b.vI2, stream);
Scalar mssim;
gpu::GpuMat buf;
for (int i = 0; i < b.gI1.channels(); ++i)
{
gpu::multiply(b.vI2[i], b.vI2[i], b.I2_2, stream); // I2^2
gpu::multiply(b.vI1[i], b.vI1[i], b.I1_2, stream); // I1^2
gpu::multiply(b.vI1[i], b.vI2[i], b.I1_I2, stream); // I1 * I2
gpu::GaussianBlur(b.vI1[i], b.mu1, Size(11, 11), buf, 1.5, 0, BORDER_DEFAULT, -1, stream);
gpu::GaussianBlur(b.vI2[i], b.mu2, Size(11, 11), buf, 1.5, 0, BORDER_DEFAULT, -1, stream);
gpu::multiply(b.mu1, b.mu1, b.mu1_2, stream);
gpu::multiply(b.mu2, b.mu2, b.mu2_2, stream);
gpu::multiply(b.mu1, b.mu2, b.mu1_mu2, stream);
gpu::GaussianBlur(b.I1_2, b.sigma1_2, Size(11, 11), buf, 1.5, 0, BORDER_DEFAULT, -1, stream);
gpu::subtract(b.sigma1_2, b.mu1_2, b.sigma1_2, gpu::GpuMat(), -1, stream);
//b.sigma1_2 -= b.mu1_2; - This would result in an extra data transfer operation
gpu::GaussianBlur(b.I2_2, b.sigma2_2, Size(11, 11), buf, 1.5, 0, BORDER_DEFAULT, -1, stream);
gpu::subtract(b.sigma2_2, b.mu2_2, b.sigma2_2, gpu::GpuMat(), -1, stream);
//b.sigma2_2 -= b.mu2_2;
gpu::GaussianBlur(b.I1_I2, b.sigma12, Size(11, 11), buf, 1.5, 0, BORDER_DEFAULT, -1, stream);
gpu::subtract(b.sigma12, b.mu1_mu2, b.sigma12, gpu::GpuMat(), -1, stream);
//b.sigma12 -= b.mu1_mu2;
//here too it would be an extra data transfer due to call of operator*(Scalar, Mat)
gpu::multiply(b.mu1_mu2, 2, b.t1, 1, -1, stream); //b.t1 = 2 * b.mu1_mu2 + C1;
gpu::add(b.t1, C1, b.t1, gpu::GpuMat(), -1, stream);
gpu::multiply(b.sigma12, 2, b.t2, 1, -1, stream); //b.t2 = 2 * b.sigma12 + C2;
gpu::add(b.t2, C2, b.t2, gpu::GpuMat(), -12, stream);
gpu::multiply(b.t1, b.t2, b.t3, 1, -1, stream); // t3 = ((2*mu1_mu2 + C1).*(2*sigma12 + C2))
gpu::add(b.mu1_2, b.mu2_2, b.t1, gpu::GpuMat(), -1, stream);
gpu::add(b.t1, C1, b.t1, gpu::GpuMat(), -1, stream);
gpu::add(b.sigma1_2, b.sigma2_2, b.t2, gpu::GpuMat(), -1, stream);
gpu::add(b.t2, C2, b.t2, gpu::GpuMat(), -1, stream);
gpu::multiply(b.t1, b.t2, b.t1, 1, -1, stream); // t1 =((mu1_2 + mu2_2 + C1).*(sigma1_2 + sigma2_2 + C2))
gpu::divide(b.t3, b.t1, b.ssim_map, 1, -1, stream); // ssim_map = t3./t1;
stream.waitForCompletion();
Scalar s = gpu::sum(b.ssim_map, b.buf);
mssim.val[i] = s.val[0] / (b.ssim_map.rows * b.ssim_map.cols);
}
return mssim;
}
<|endoftext|> |
<commit_before>/*
* NicoW
* 27.05.12
*/
#include "MenuMap.hpp"
MenuMap::MenuMap(GameManager& game)
: AMenu("menu/Background.png", "menu/Background.png", 0.0f, -1.0f, 3600.0f, game)
{
this->_tags.push_back(new Tag("menu/RandomNormal.png", "menu/RandomHighlit.png", true, false, /**/TokenMenu::MAP, 800.0f, 0.0f, 3800.0f));
this->_tags.push_back(new Tag("menu/LoadNormal.png", "menu/LoadHighlit.png", false, false, /**/TokenMenu::LOADMAP, 800.0f, 0.0f, 3850.0f));
this->_tags.push_back(new Tag("menu/BackNormal.png", "menu/BackHighlit.png", false, false, /**/TokenMenu::IA, 800.0f, 0.0f, 3900.0f));
}
MenuMap::~MenuMap(void)
{
}
double MenuMap::getCenterX(void) const
{
return (800.0f);
}
double MenuMap::getCenterY(void) const
{
return (4050.0f);
}
void MenuMap::update(gdl::GameClock const& clock, gdl::Input& input)
{
for (size_t i = 0; i < this->_keyEvent.size(); ++i)
if (input.isKeyDown(this->_keyEvent[i].first))
(this->*_keyEvent[i].second)(clock);
}
<commit_msg>map random a ameliorer<commit_after>/*
* NicoW
* 27.05.12
*/
#include "MenuMap.hpp"
MenuMap::MenuMap(GameManager& game)
: AMenu("menu/Background.png", "menu/Background.png", 0.0f, -1.0f, 3600.0f, game)
{
this->_tags.push_back(new Tag("menu/RandomNormal.png", "menu/RandomHighlit.png", true, false, TokenMenu::CREATEGAME, 800.0f, 0.0f, 3800.0f));
this->_tags.push_back(new Tag("menu/LoadNormal.png", "menu/LoadHighlit.png", false, false, TokenMenu::LOADMAP, 800.0f, 0.0f, 3850.0f));
this->_tags.push_back(new Tag("menu/BackNormal.png", "menu/BackHighlit.png", false, false, TokenMenu::IA, 800.0f, 0.0f, 3900.0f));
}
MenuMap::~MenuMap(void)
{
}
double MenuMap::getCenterX(void) const
{
return (800.0f);
}
double MenuMap::getCenterY(void) const
{
return (4050.0f);
}
void MenuMap::update(gdl::GameClock const& clock, gdl::Input& input)
{
for (size_t i = 0; i < this->_keyEvent.size(); ++i)
if (input.isKeyDown(this->_keyEvent[i].first))
(this->*_keyEvent[i].second)(clock);
if (this->_curToken == TokenMenu::CREATEGAME)
{
int size = this->_gameManager._nbPlayers * 5;
this->_gameManager._match._map = new Map(size, size, 2, 2);
}
}
<|endoftext|> |
<commit_before>/***************************************************************************//**
* \file delta.cpp
* \author Anush Krishnan (anus@bu.edu)
* \author Olivier Mesnard (mesnardo@gwu.edu)
* \author Pi-Yueh Chuang (pychuang@gwu.edu)
* \brief implementations of descritized delta functions.
*/
// PetIBM
#include "petibm/delta.h"
namespace petibm
{
namespace delta
{
/** \copydoc delta::Roma_et_al(const PetscReal &, const PetscReal &). */
PetscReal Roma_et_al(const PetscReal &rx, const PetscReal &drx)
{
PetscReal r = std::abs(rx) / drx;
if (r > 1.5)
return 0.0;
if (r > 0.5 && r <= 1.5)
return (5.0 - 3.0 * r -
sqrt(-3.0 * (1.0 - r) * (1.0 - r) + 1.0)) / (6.0 * drx);
return (1.0 + sqrt(-3.0 * r * r + 1.0)) / (3.0 * drx);
} // Roma_et_al
/** \copydoc delta::Roma_et_al(const PetscReal &, const PetscReal &,
* const PetscReal &, const PetscReal &). */
PetscReal Roma_et_al(
const PetscReal &rx, const PetscReal &drx,
const PetscReal &ry, const PetscReal &dry)
{
return delta::Roma_et_al(rx, drx) * delta::Roma_et_al(ry, dry);
} // Roma_et_al
/** \copydoc delta::Roma_et_al(const PetscReal &, const PetscReal &,
* const PetscReal &, const PetscReal &, const PetscReal &,
* const PetscReal &). */
PetscReal Roma_et_al(
const PetscReal &rx, const PetscReal &drx,
const PetscReal &ry, const PetscReal &dry,
const PetscReal &rz, const PetscReal &drz)
{
return delta::Roma_et_al(rx, drx) * delta::Roma_et_al(ry, dry) *
delta::Roma_et_al(rz, drz);
} // Roma_et_al
} // end of namespace delta
} // end of namespace petibm
<commit_msg>use math function from C++ STL<commit_after>/***************************************************************************//**
* \file delta.cpp
* \author Anush Krishnan (anus@bu.edu)
* \author Olivier Mesnard (mesnardo@gwu.edu)
* \author Pi-Yueh Chuang (pychuang@gwu.edu)
* \brief implementations of descritized delta functions.
*/
// STL
# include <cmath>
// PetIBM
#include <petibm/delta.h>
namespace petibm
{
namespace delta
{
/** \copydoc delta::Roma_et_al(const PetscReal &, const PetscReal &). */
PetscReal Roma_et_al(const PetscReal &rx, const PetscReal &drx)
{
PetscReal r = std::abs(rx) / drx;
if (r > 1.5)
return 0.0;
if (r > 0.5 && r <= 1.5)
return (5.0 - 3.0 * r -
std::sqrt(-3.0 * (1.0 - r) * (1.0 - r) + 1.0)) / (6.0 * drx);
return (1.0 + std::sqrt(-3.0 * r * r + 1.0)) / (3.0 * drx);
} // Roma_et_al
/** \copydoc delta::Roma_et_al(const PetscReal &, const PetscReal &,
* const PetscReal &, const PetscReal &). */
PetscReal Roma_et_al(
const PetscReal &rx, const PetscReal &drx,
const PetscReal &ry, const PetscReal &dry)
{
return delta::Roma_et_al(rx, drx) * delta::Roma_et_al(ry, dry);
} // Roma_et_al
/** \copydoc delta::Roma_et_al(const PetscReal &, const PetscReal &,
* const PetscReal &, const PetscReal &, const PetscReal &,
* const PetscReal &). */
PetscReal Roma_et_al(
const PetscReal &rx, const PetscReal &drx,
const PetscReal &ry, const PetscReal &dry,
const PetscReal &rz, const PetscReal &drz)
{
return delta::Roma_et_al(rx, drx) * delta::Roma_et_al(ry, dry) *
delta::Roma_et_al(rz, drz);
} // Roma_et_al
} // end of namespace delta
} // end of namespace petibm
<|endoftext|> |
<commit_before>/*
Copyright 2008 Brain Research Institute, Melbourne, Australia
Written by J-Donald Tournier, 27/11/09.
This file is part of MRtrix.
MRtrix is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
MRtrix 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 MRtrix. If not, see <http://www.gnu.org/licenses/>.
*/
#include "command.h"
#include "progressbar.h"
#include "memory.h"
#include "image/buffer.h"
#include "image/buffer_preload.h"
#include "image/buffer_scratch.h"
#include "image/iterator.h"
#include "image/threaded_loop.h"
#include "image/utils.h"
#include "image/voxel.h"
#include "math/math.h"
#include <limits>
#include <vector>
using namespace MR;
using namespace App;
const char* operations[] = {
"mean",
"sum",
"product",
"rms",
"var",
"std",
"min",
"max",
"absmax", // Maximum of absolute values
"magmax", // Value for which the magnitude is the maximum (i.e. preserves signed-ness)
NULL
};
void usage ()
{
DESCRIPTION
+ "compute summary statistic on image intensities either across images, "
"or along a specified axis for a single image. Supported operations are:"
+ "mean, sum, product, rms (root-mean-square value), var (unbiased variance), "
"std (unbiased standard deviation), min, max, absmax (maximum absolute value), "
"magmax (value with maximum absolute value, preserving its sign)."
+ "See also 'mrcalc' to compute per-voxel operations.";
ARGUMENTS
+ Argument ("input", "the input image.").type_image_in ().allow_multiple()
+ Argument ("operation", "the operation to apply, one of: " + join(operations, ", ") + ".").type_choice (operations)
+ Argument ("output", "the output image.").type_image_out ();
OPTIONS
+ Option ("axis", "perform operation along a specified axis of a single input image")
+ Argument ("index").type_integer();
}
typedef float value_type;
typedef Image::BufferPreload<value_type> PreloadBufferType;
typedef PreloadBufferType::voxel_type PreloadVoxelType;
typedef Image::Buffer<value_type> BufferType;
typedef BufferType::voxel_type VoxelType;
class Mean {
public:
Mean () : sum (0.0), count (0) { }
void operator() (value_type val) {
if (std::isfinite (val)) {
sum += val;
++count;
}
}
value_type result () const {
if (!count)
return NAN;
return sum / count;
}
double sum;
size_t count;
};
class Sum {
public:
Sum () : sum (0.0) { }
void operator() (value_type val) {
if (std::isfinite (val))
sum += val;
}
value_type result () const {
return sum;
}
double sum;
};
class Product {
public:
Product () : product (0.0) { }
void operator() (value_type val) {
if (std::isfinite (val))
product += val;
}
value_type result () const {
return product;
}
double product;
};
class RMS {
public:
RMS() : sum (0.0), count (0) { }
void operator() (value_type val) {
if (std::isfinite (val)) {
sum += Math::pow2 (val);
++count;
}
}
value_type result() const {
if (!count)
return NAN;
return std::sqrt(sum / count);
}
double sum;
size_t count;
};
class Var {
public:
Var () : sum (0.0), sum_sqr (0.0), count (0) { }
void operator() (value_type val) {
if (std::isfinite (val)) {
sum += val;
sum_sqr += Math::pow2 (val);
++count;
}
}
value_type result () const {
if (count < 2)
return NAN;
return (sum_sqr - Math::pow2 (sum) / static_cast<double> (count)) / (static_cast<double> (count) - 1.0);
}
double sum, sum_sqr;
size_t count;
};
class Std : public Var {
public:
Std() : Var() { }
value_type result () const { return std::sqrt (Var::result()); }
};
class Min {
public:
Min () : min (std::numeric_limits<value_type>::infinity()) { }
void operator() (value_type val) {
if (std::isfinite (val) && val < min)
min = val;
}
value_type result () const { return std::isfinite (min) ? min : NAN; }
value_type min;
};
class Max {
public:
Max () : max (-std::numeric_limits<value_type>::infinity()) { }
void operator() (value_type val) {
if (std::isfinite (val) && val > max)
max = val;
}
value_type result () const { return std::isfinite (max) ? max : NAN; }
value_type max;
};
class AbsMax {
public:
AbsMax () : max (-std::numeric_limits<value_type>::infinity()) { }
void operator() (value_type val) {
if (std::isfinite (val) && std::abs(val) > max)
max = std::abs(val);
}
value_type result () const { return std::isfinite (max) ? max : NAN; }
value_type max;
};
class MagMax {
public:
MagMax () : max (-std::numeric_limits<value_type>::infinity()) { }
MagMax (const int i) : max (-std::numeric_limits<value_type>::infinity()) { }
void operator() (value_type val) {
if (std::isfinite (val) && (!std::isfinite (max) || std::abs(val) > std::abs (max)))
max = val;
}
value_type result () const { return std::isfinite (max) ? max : NAN; }
value_type max;
};
template <class Operation>
class AxisKernel {
public:
AxisKernel (size_t axis) : axis (axis) { }
template <class InputVoxelType, class OutputVoxelType>
void operator() (InputVoxelType& in, OutputVoxelType& out) {
Operation op;
for (in[axis] = 0; in[axis] < in.dim(axis); ++in[axis])
op (in.value());
out.value() = op.result();
}
protected:
const size_t axis;
};
class ImageKernelBase {
public:
ImageKernelBase (const std::string& path) :
output_path (path) { }
virtual ~ImageKernelBase() { }
virtual void process (const Image::Header& image_in) = 0;
protected:
const std::string output_path;
};
template <class Operation>
class ImageKernel : public ImageKernelBase {
protected:
class InitFunctor {
public:
template <class VoxelType>
void operator() (VoxelType& out) const { out.value() = Operation(); }
};
class ProcessFunctor {
public:
template <class VoxelType1, class VoxelType2>
void operator() (VoxelType1& out, VoxelType2& in) const {
Operation op = out.value();
op (in.value());
out.value() = op;
}
};
class ResultFunctor {
public:
template <class VoxelType1, class VoxelType2>
void operator() (VoxelType1& out, VoxelType2& in) const {
Operation op = in.value();
out.value() = op.result();
}
};
public:
ImageKernel (const Image::Header& header, const std::string& path) :
ImageKernelBase (path),
header (header),
buffer (header) {
Image::ThreadedLoop (buffer).run (InitFunctor(), buffer.voxel());
}
~ImageKernel()
{
Image::Buffer<value_type> out (output_path, header);
Image::ThreadedLoop (buffer).run (ResultFunctor(), out.voxel(), buffer.voxel());
}
void process (const Image::Header& image_in)
{
Image::Buffer<value_type> in (image_in);
Image::ThreadedLoop (buffer).run (ProcessFunctor(), buffer.voxel(), in.voxel());
}
protected:
const Image::Header& header;
Image::BufferScratch<Operation> buffer;
};
void run ()
{
const size_t num_inputs = argument.size() - 2;
const int op = argument[num_inputs];
const std::string& output_path = argument.back();
Options opt = get_options ("axis");
if (opt.size()) {
if (num_inputs != 1)
throw Exception ("Option -axis only applies if a single input image is used");
const size_t axis = opt[0][0];
PreloadBufferType buffer_in (argument[0], Image::Stride::contiguous_along_axis (axis));
if (axis >= buffer_in.ndim())
throw Exception ("Cannot perform operation along axis " + str (axis) + "; image only has " + str(buffer_in.ndim()) + " axes");
Image::Header header_out (buffer_in);
header_out.datatype() = DataType::Float32;
header_out.dim(axis) = 1;
Image::squeeze_dim (header_out);
BufferType buffer_out (output_path, header_out);
auto vox_in = buffer_in.voxel();
auto vox_out = buffer_out.voxel();
Image::ThreadedLoop loop (std::string("computing ") + operations[op] + " along axis " + str(axis) + "...", buffer_out);
switch (op) {
case 0: loop.run (AxisKernel<Mean> (axis), vox_in, vox_out); return;
case 1: loop.run (AxisKernel<Sum> (axis), vox_in, vox_out); return;
case 2: loop.run (AxisKernel<Product>(axis), vox_in, vox_out); return;
case 3: loop.run (AxisKernel<RMS> (axis), vox_in, vox_out); return;
case 4: loop.run (AxisKernel<Var> (axis), vox_in, vox_out); return;
case 5: loop.run (AxisKernel<Std> (axis), vox_in, vox_out); return;
case 6: loop.run (AxisKernel<Min> (axis), vox_in, vox_out); return;
case 7: loop.run (AxisKernel<Max> (axis), vox_in, vox_out); return;
case 8: loop.run (AxisKernel<AbsMax> (axis), vox_in, vox_out); return;
case 9: loop.run (AxisKernel<MagMax> (axis), vox_in, vox_out); return;
default: assert (0);
}
} else {
if (num_inputs < 2)
throw Exception ("mrmath requires either multiple input images, or the -axis option to be provided");
// Pre-load all image headers
std::vector<std::unique_ptr<Image::Header>> headers_in;
// Header of first input image is the template to which all other input images are compared
headers_in.push_back (std::unique_ptr<Image::Header> (new Image::Header (argument[0])));
Image::Header header (*headers_in[0]);
// Wipe any excess unary-dimensional axes
while (header.dim (header.ndim() - 1) == 1)
header.set_ndim (header.ndim() - 1);
// Verify that dimensions of all input images adequately match
for (size_t i = 1; i != num_inputs; ++i) {
const std::string path = argument[i];
headers_in.push_back (std::unique_ptr<Image::Header> (new Image::Header (path)));
const Image::Header& temp (*headers_in[i]);
if (temp.ndim() < header.ndim())
throw Exception ("Image " + path + " has fewer axes than first imput image " + header.name());
for (size_t axis = 0; axis != header.ndim(); ++axis) {
if (temp.dim(axis) != header.dim(axis))
throw Exception ("Dimensions of image " + path + " do not match those of first input image " + header.name());
}
for (size_t axis = header.ndim(); axis != temp.ndim(); ++axis) {
if (temp.dim(axis) != 1)
throw Exception ("Image " + path + " has axis with non-unary dimension beyond first input image " + header.name());
}
}
// Instantiate a kernel depending on the operation requested
std::unique_ptr<ImageKernelBase> kernel;
switch (op) {
case 0: kernel.reset (new ImageKernel<Mean> (header, output_path)); break;
case 1: kernel.reset (new ImageKernel<Sum> (header, output_path)); break;
case 2: kernel.reset (new ImageKernel<Product> (header, output_path)); break;
case 3: kernel.reset (new ImageKernel<RMS> (header, output_path)); break;
case 4: kernel.reset (new ImageKernel<Var> (header, output_path)); break;
case 5: kernel.reset (new ImageKernel<Std> (header, output_path)); break;
case 6: kernel.reset (new ImageKernel<Min> (header, output_path)); break;
case 7: kernel.reset (new ImageKernel<Max> (header, output_path)); break;
case 8: kernel.reset (new ImageKernel<AbsMax> (header, output_path)); break;
case 9: kernel.reset (new ImageKernel<MagMax> (header, output_path)); break;
default: assert (0);
}
// Feed the input images to the kernel one at a time
{
ProgressBar progress (std::string("computing ") + operations[op] + " across "
+ str(headers_in.size()) + " images...", num_inputs);
for (size_t i = 0; i != headers_in.size(); ++i) {
kernel->process (*headers_in[i]);
++progress;
}
}
// Image output is handled by the kernel destructor
}
}
<commit_msg>added median to mrmath. performance could be improved...<commit_after>/*
Copyright 2008 Brain Research Institute, Melbourne, Australia
Written by J-Donald Tournier, 27/11/09.
This file is part of MRtrix.
MRtrix is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
MRtrix 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 MRtrix. If not, see <http://www.gnu.org/licenses/>.
*/
#include "command.h"
#include "progressbar.h"
#include "memory.h"
#include "image/buffer.h"
#include "image/buffer_preload.h"
#include "image/buffer_scratch.h"
#include "image/iterator.h"
#include "image/threaded_loop.h"
#include "image/utils.h"
#include "image/voxel.h"
#include "math/math.h"
#include "math/median.h"
#include <limits>
#include <vector>
using namespace MR;
using namespace App;
const char* operations[] = {
"mean",
"median",
"sum",
"product",
"rms",
"var",
"std",
"min",
"max",
"absmax", // Maximum of absolute values
"magmax", // Value for which the magnitude is the maximum (i.e. preserves signed-ness)
NULL
};
void usage ()
{
DESCRIPTION
+ "compute summary statistic on image intensities either across images, "
"or along a specified axis for a single image. Supported operations are:"
+ "mean, median, sum, product, rms (root-mean-square value), var (unbiased variance), "
"std (unbiased standard deviation), min, max, absmax (maximum absolute value), "
"magmax (value with maximum absolute value, preserving its sign)."
+ "See also 'mrcalc' to compute per-voxel operations.";
ARGUMENTS
+ Argument ("input", "the input image.").type_image_in ().allow_multiple()
+ Argument ("operation", "the operation to apply, one of: " + join(operations, ", ") + ".").type_choice (operations)
+ Argument ("output", "the output image.").type_image_out ();
OPTIONS
+ Option ("axis", "perform operation along a specified axis of a single input image")
+ Argument ("index").type_integer();
}
typedef float value_type;
typedef Image::BufferPreload<value_type> PreloadBufferType;
typedef PreloadBufferType::voxel_type PreloadVoxelType;
typedef Image::Buffer<value_type> BufferType;
typedef BufferType::voxel_type VoxelType;
class Mean {
public:
Mean () : sum (0.0), count (0) { }
void operator() (value_type val) {
if (std::isfinite (val)) {
sum += val;
++count;
}
}
value_type result () const {
if (!count)
return NAN;
return sum / count;
}
double sum;
size_t count;
};
class Median {
public:
Median () : count (0) { }
void operator() (value_type val) {
if (std::isfinite (val)) {
values.push_back(val);
++count;
}
}
value_type result () const {
if (!count){
return NAN;
}
std::vector<value_type> v(values); // Why do I need this copy?
return Math::median(v);
}
size_t count;
std::vector<value_type> values;
};
class Sum {
public:
Sum () : sum (0.0) { }
void operator() (value_type val) {
if (std::isfinite (val))
sum += val;
}
value_type result () const {
return sum;
}
double sum;
};
class Product {
public:
Product () : product (0.0) { }
void operator() (value_type val) {
if (std::isfinite (val))
product += val;
}
value_type result () const {
return product;
}
double product;
};
class RMS {
public:
RMS() : sum (0.0), count (0) { }
void operator() (value_type val) {
if (std::isfinite (val)) {
sum += Math::pow2 (val);
++count;
}
}
value_type result() const {
if (!count)
return NAN;
return std::sqrt(sum / count);
}
double sum;
size_t count;
};
class Var {
public:
Var () : sum (0.0), sum_sqr (0.0), count (0) { }
void operator() (value_type val) {
if (std::isfinite (val)) {
sum += val;
sum_sqr += Math::pow2 (val);
++count;
}
}
value_type result () const {
if (count < 2)
return NAN;
return (sum_sqr - Math::pow2 (sum) / static_cast<double> (count)) / (static_cast<double> (count) - 1.0);
}
double sum, sum_sqr;
size_t count;
};
class Std : public Var {
public:
Std() : Var() { }
value_type result () const { return std::sqrt (Var::result()); }
};
class Min {
public:
Min () : min (std::numeric_limits<value_type>::infinity()) { }
void operator() (value_type val) {
if (std::isfinite (val) && val < min)
min = val;
}
value_type result () const { return std::isfinite (min) ? min : NAN; }
value_type min;
};
class Max {
public:
Max () : max (-std::numeric_limits<value_type>::infinity()) { }
void operator() (value_type val) {
if (std::isfinite (val) && val > max)
max = val;
}
value_type result () const { return std::isfinite (max) ? max : NAN; }
value_type max;
};
class AbsMax {
public:
AbsMax () : max (-std::numeric_limits<value_type>::infinity()) { }
void operator() (value_type val) {
if (std::isfinite (val) && std::abs(val) > max)
max = std::abs(val);
}
value_type result () const { return std::isfinite (max) ? max : NAN; }
value_type max;
};
class MagMax {
public:
MagMax () : max (-std::numeric_limits<value_type>::infinity()) { }
MagMax (const int i) : max (-std::numeric_limits<value_type>::infinity()) { }
void operator() (value_type val) {
if (std::isfinite (val) && (!std::isfinite (max) || std::abs(val) > std::abs (max)))
max = val;
}
value_type result () const { return std::isfinite (max) ? max : NAN; }
value_type max;
};
template <class Operation>
class AxisKernel {
public:
AxisKernel (size_t axis) : axis (axis) { }
template <class InputVoxelType, class OutputVoxelType>
void operator() (InputVoxelType& in, OutputVoxelType& out) {
Operation op;
for (in[axis] = 0; in[axis] < in.dim(axis); ++in[axis])
op (in.value());
out.value() = op.result();
}
protected:
const size_t axis;
};
class ImageKernelBase {
public:
ImageKernelBase (const std::string& path) :
output_path (path) { }
virtual ~ImageKernelBase() { }
virtual void process (const Image::Header& image_in) = 0;
protected:
const std::string output_path;
};
template <class Operation>
class ImageKernel : public ImageKernelBase {
protected:
class InitFunctor {
public:
template <class VoxelType>
void operator() (VoxelType& out) const { out.value() = Operation(); }
};
class ProcessFunctor {
public:
template <class VoxelType1, class VoxelType2>
void operator() (VoxelType1& out, VoxelType2& in) const {
Operation op = out.value();
op (in.value());
out.value() = op;
}
};
class ResultFunctor {
public:
template <class VoxelType1, class VoxelType2>
void operator() (VoxelType1& out, VoxelType2& in) const {
Operation op = in.value();
out.value() = op.result();
}
};
public:
ImageKernel (const Image::Header& header, const std::string& path) :
ImageKernelBase (path),
header (header),
buffer (header) {
Image::ThreadedLoop (buffer).run (InitFunctor(), buffer.voxel());
}
~ImageKernel()
{
Image::Buffer<value_type> out (output_path, header);
Image::ThreadedLoop (buffer).run (ResultFunctor(), out.voxel(), buffer.voxel());
}
void process (const Image::Header& image_in)
{
Image::Buffer<value_type> in (image_in);
Image::ThreadedLoop (buffer).run (ProcessFunctor(), buffer.voxel(), in.voxel());
}
protected:
const Image::Header& header;
Image::BufferScratch<Operation> buffer;
};
void run ()
{
const size_t num_inputs = argument.size() - 2;
const int op = argument[num_inputs];
const std::string& output_path = argument.back();
Options opt = get_options ("axis");
if (opt.size()) {
if (num_inputs != 1)
throw Exception ("Option -axis only applies if a single input image is used");
const size_t axis = opt[0][0];
PreloadBufferType buffer_in (argument[0], Image::Stride::contiguous_along_axis (axis));
if (axis >= buffer_in.ndim())
throw Exception ("Cannot perform operation along axis " + str (axis) + "; image only has " + str(buffer_in.ndim()) + " axes");
Image::Header header_out (buffer_in);
header_out.datatype() = DataType::Float32;
header_out.dim(axis) = 1;
Image::squeeze_dim (header_out);
BufferType buffer_out (output_path, header_out);
auto vox_in = buffer_in.voxel();
auto vox_out = buffer_out.voxel();
Image::ThreadedLoop loop (std::string("computing ") + operations[op] + " along axis " + str(axis) + "...", buffer_out);
switch (op) {
case 0: loop.run (AxisKernel<Mean> (axis), vox_in, vox_out); return;
case 1: loop.run (AxisKernel<Median> (axis), vox_in, vox_out); return;
case 2: loop.run (AxisKernel<Sum> (axis), vox_in, vox_out); return;
case 3: loop.run (AxisKernel<Product>(axis), vox_in, vox_out); return;
case 4: loop.run (AxisKernel<RMS> (axis), vox_in, vox_out); return;
case 5: loop.run (AxisKernel<Var> (axis), vox_in, vox_out); return;
case 6: loop.run (AxisKernel<Std> (axis), vox_in, vox_out); return;
case 7: loop.run (AxisKernel<Min> (axis), vox_in, vox_out); return;
case 8: loop.run (AxisKernel<Max> (axis), vox_in, vox_out); return;
case 9: loop.run (AxisKernel<AbsMax> (axis), vox_in, vox_out); return;
case 10: loop.run (AxisKernel<MagMax> (axis), vox_in, vox_out); return;
default: assert (0);
}
} else {
if (num_inputs < 2)
throw Exception ("mrmath requires either multiple input images, or the -axis option to be provided");
// Pre-load all image headers
std::vector<std::unique_ptr<Image::Header>> headers_in;
// Header of first input image is the template to which all other input images are compared
headers_in.push_back (std::unique_ptr<Image::Header> (new Image::Header (argument[0])));
Image::Header header (*headers_in[0]);
// Wipe any excess unary-dimensional axes
while (header.dim (header.ndim() - 1) == 1)
header.set_ndim (header.ndim() - 1);
// Verify that dimensions of all input images adequately match
for (size_t i = 1; i != num_inputs; ++i) {
const std::string path = argument[i];
headers_in.push_back (std::unique_ptr<Image::Header> (new Image::Header (path)));
const Image::Header& temp (*headers_in[i]);
if (temp.ndim() < header.ndim())
throw Exception ("Image " + path + " has fewer axes than first imput image " + header.name());
for (size_t axis = 0; axis != header.ndim(); ++axis) {
if (temp.dim(axis) != header.dim(axis))
throw Exception ("Dimensions of image " + path + " do not match those of first input image " + header.name());
}
for (size_t axis = header.ndim(); axis != temp.ndim(); ++axis) {
if (temp.dim(axis) != 1)
throw Exception ("Image " + path + " has axis with non-unary dimension beyond first input image " + header.name());
}
}
// Instantiate a kernel depending on the operation requested
std::unique_ptr<ImageKernelBase> kernel;
switch (op) {
case 0: kernel.reset (new ImageKernel<Mean> (header, output_path)); break;
case 1: kernel.reset (new ImageKernel<Median> (header, output_path)); break;
case 2: kernel.reset (new ImageKernel<Sum> (header, output_path)); break;
case 3: kernel.reset (new ImageKernel<Product> (header, output_path)); break;
case 4: kernel.reset (new ImageKernel<RMS> (header, output_path)); break;
case 5: kernel.reset (new ImageKernel<Var> (header, output_path)); break;
case 6: kernel.reset (new ImageKernel<Std> (header, output_path)); break;
case 7: kernel.reset (new ImageKernel<Min> (header, output_path)); break;
case 8: kernel.reset (new ImageKernel<Max> (header, output_path)); break;
case 9: kernel.reset (new ImageKernel<AbsMax> (header, output_path)); break;
case 10: kernel.reset (new ImageKernel<MagMax> (header, output_path)); break;
default: assert (0);
}
// Feed the input images to the kernel one at a time
{
ProgressBar progress (std::string("computing ") + operations[op] + " across "
+ str(headers_in.size()) + " images...", num_inputs);
for (size_t i = 0; i != headers_in.size(); ++i) {
kernel->process (*headers_in[i]);
++progress;
}
}
// Image output is handled by the kernel destructor
}
}
<|endoftext|> |
<commit_before>#ifndef CLOVER_UTIL_DYN_ARRAY_HPP
#define CLOVER_UTIL_DYN_ARRAY_HPP
#include "build.hpp"
#include "util/ensure.hpp"
#include "util/hash.hpp"
namespace clover {
namespace util {
/// Substituting std::vector with `DynArray` was a good choice, because
/// - std::vector<bool> is broken, needed a workaround
/// - replacing std::vector with this reduced compile time by 40s (j8)
template <typename T, template <typename> class Ator= std::allocator>
class DynArray {
public:
using Value= T;
using AtorT= Ator<T>;
using This= DynArray<T, Ator>;
using Iter= T*;
/// @todo Rename to match naming conventions
using cIter= const T*;
DynArray()= default;
~DynArray()
{
ensure(capacity_ >= size_);
for (auto& m : *this)
m.~Value();
ator.deallocate(data_, capacity_);
}
DynArray(SizeType size)
{ resize(size); }
DynArray(std::initializer_list<T> l)
{ reserve(l.size()); for (auto& m : l) pushBack(m); }
DynArray(const AtorT& ator)
: ator(ator) { }
DynArray(const DynArray& other)
{ operator=(other); }
DynArray(DynArray&& other)
{ operator=(std::move(other)); }
DynArray& operator=(const DynArray& t)
{
clear(); /// @todo Don't clear
reserve(t.size_);
for (SizeType i= 0; i < t.size_; ++i)
new (data_ + i) Value(t.data_[i]);
size_= t.size_;
return *this;
}
DynArray& operator=(DynArray&& t)
{
if (this != &t) {
data_= t.data_;
size_= t.size_;
capacity_= t.capacity_;
t.data_= nullptr;
t.size_= 0;
t.capacity_= 0;
}
return *this;
}
Value& operator[](SizeType i){ return data_[i]; }
const Value& operator[](SizeType i) const { return data_[i]; }
Value& at(SizeType i)
{ ensure(i < size_); return data_[i]; }
const Value& at(SizeType i) const
{ ensure(i < size_); return data_[i]; }
private:
void enlarge()
{
SizeType new_capacity= 0;
if (capacity_ == 0)
new_capacity= 16;
else
new_capacity= capacity_*2;
ensure(new_capacity >= size_ + 1);
T* new_data= ator.allocate(new_capacity);
for (SizeType i= 0; i < size_; ++i)
new (new_data + i) Value(std::move(data_[i]));
ator.deallocate(data_, capacity_);
data_= new_data;
capacity_= new_capacity;
}
public:
void pushBack(const Value& t)
{
if (size_ == capacity_)
enlarge();
new (data_ + size_) Value(t);
++size_;
}
void pushBack(Value&& t)
{
if (size_ == capacity_)
enlarge();
new (data_ + size_) Value(std::forward<T>(t));
++size_;
}
void pushBack(const DynArray& v)
{ for (auto& m : v) pushBack(m); }
template<typename... Args>
void emplaceBack(Args&&... args)
{
if (size_ == capacity_)
enlarge();
new (data_ + size_) Value(std::forward<Args>(args)...);
++size_;
}
SizeType size() const { return size_; }
bool empty() const { return size_ == 0; }
void clear()
{
// Following std::vector, although separate destruct() and
// clear() would be better
for (auto& m : *this)
m.~T();
size_= 0;
}
private:
void resizeCapacity(SizeType new_capacity)
{
if (capacity_ == new_capacity)
return;
Value* new_data= ator.allocate(new_capacity);
for (SizeType i= 0; i < new_capacity && i < size_; ++i)
new (new_data + i) Value(std::move(data_[i])); // Copy objects to new buffer
for (SizeType i= new_capacity; i < size_; ++i)
data_[i].~Value(); // Destroy those who didn't fit
ator.deallocate(data_, capacity_);
data_= new_data;
capacity_= new_capacity;
}
public:
void resize(SizeType new_size)
{
if (new_size == size_)
return;
resizeCapacity(new_size);
if (new_size > size_) {
for (SizeType i= size_; i < new_size; ++i)
new (data_ + i) Value();
}
size_= new_size;
}
void resize(SizeType new_size, const Value& value)
{
if (new_size == size_)
return;
resizeCapacity(new_size);
if (new_size > size_) {
for (SizeType i= size_; i < new_size; ++i)
new (data_ + i) Value(value);
}
size_= new_size;
}
void reserve(SizeType new_capacity)
{
if (new_capacity <= size_)
return;
resizeCapacity(new_capacity);
}
Iter begin() { return data_; }
Iter end() { return data_ + size_; }
cIter begin() const { return data_; }
cIter end() const { return data_ + size_; }
T* data() { return data_; }
const T* data() const { return data_; }
T& front() { return *data_; }
T& back() { return *(data_ + size_ - 1); }
const T& front() const { return *data_; }
const T& back() const { return *(data_ + size_ - 1); }
Iter insert(Iter it, const T& t)
{
if (empty() || it == end()) {
pushBack(t);
return end() - 1;
}
SizeType i_to_inserted= it - data_;
if (size_ == capacity_)
enlarge(); // This is inefficient (but simple)
it= data_ + i_to_inserted;
new (data_ + size_) Value(std::move(data_[size_ - 1]));
for (SizeType i= size_ - 1; i > i_to_inserted; --i)
data_[i]= std::move(data_[i - 1]);
it->~Value();
new (it) Value(t);
++size_;
return data_ + i_to_inserted;
}
Iter erase(Iter it) { return erase(it, it + 1); }
Iter erase(Iter b, Iter e)
{
if (b == e)
return b;
SizeType gap= e - b;
for (auto it= b; it + gap != end(); ++it)
*it= std::move(*(it + gap));
for (auto it= end() - gap; it != end(); ++it)
it->~Value();
size_ -= gap;
return b;
}
void popBack() { erase(end() - 1); }
void popFront() { erase(begin()); }
/// @todo Remove these, can be implemented outside
SizeType count(const T& t) const
{
SizeType a= 0;
for (SizeType i= 0; i < size_; ++i)
if(data_[i] == t)
++a;
return a;
}
cIter find(const T& t) const
{
for (cIter it= begin(); it != end(); ++it)
if (*it == t) return it;
return end();
}
Iter find(const T& t)
{
for (Iter it= begin(); it != end(); ++it)
if (*it == t) return it;
return end();
}
void remove(const T& t)
{
auto it= find(t);
debug_ensure(it != end());
erase(it);
}
DynArray<T> appended(const This& v) const
{ DynArray<T> ret(*this); ret.pushBack(v); return ret; }
void append(const This& other)
{ *this= appended(other); }
template <typename Archive>
void serialize(Archive& ar, const uint32 version)
{
if (Archive::is_saving::value) {
ar & size_;
for (auto& m : *this)
ar & m;
} else {
SizeType s;
ar & s;
resize(s);
for (auto& m : *this)
ar & m;
}
}
private:
Value* data_= nullptr;
SizeType size_= 0;
SizeType capacity_= 0;
AtorT ator;
};
template<typename T, template <typename> class Ator>
struct Hash32<DynArray<T, Ator>> {
uint32 operator()(const DynArray<T, Ator>& arr) const {
if (arr.empty()) return 0;
return rawArrayHash(arr.data(), arr.size());
}
};
template <typename T, template <typename> class Ator>
void fastInsert(DynArray<T, Ator>& container, T value){
container.pushBack(std::move(value));
}
} // util
} // clover
#endif // CLOVER_UTIL_DYN_ARRAY_HPP
<commit_msg>Fixed leak in DynArray<commit_after>#ifndef CLOVER_UTIL_DYN_ARRAY_HPP
#define CLOVER_UTIL_DYN_ARRAY_HPP
#include "build.hpp"
#include "util/ensure.hpp"
#include "util/hash.hpp"
namespace clover {
namespace util {
/// Substituting std::vector with `DynArray` was a good choice, because
/// - std::vector<bool> is broken, needed a workaround
/// - replacing std::vector with this reduced compile time by 40s (j8)
template <typename T, template <typename> class Ator= std::allocator>
class DynArray {
public:
using Value= T;
using AtorT= Ator<T>;
using This= DynArray<T, Ator>;
using Iter= T*;
/// @todo Rename to match naming conventions
using cIter= const T*;
DynArray()= default;
~DynArray()
{
ensure(capacity_ >= size_);
for (auto& m : *this)
m.~Value();
ator.deallocate(data_, capacity_);
}
DynArray(SizeType size)
{ resize(size); }
DynArray(std::initializer_list<T> l)
{ reserve(l.size()); for (auto& m : l) pushBack(m); }
DynArray(const AtorT& ator)
: ator(ator) { }
DynArray(const DynArray& other)
{ operator=(other); }
DynArray(DynArray&& other)
{ operator=(std::move(other)); }
DynArray& operator=(const DynArray& t)
{
clear(); /// @todo Don't clear
reserve(t.size_);
for (SizeType i= 0; i < t.size_; ++i)
new (data_ + i) Value(t.data_[i]);
size_= t.size_;
return *this;
}
DynArray& operator=(DynArray&& t)
{
if (this != &t) {
data_= t.data_;
size_= t.size_;
capacity_= t.capacity_;
t.data_= nullptr;
t.size_= 0;
t.capacity_= 0;
}
return *this;
}
Value& operator[](SizeType i){ return data_[i]; }
const Value& operator[](SizeType i) const { return data_[i]; }
Value& at(SizeType i)
{ ensure(i < size_); return data_[i]; }
const Value& at(SizeType i) const
{ ensure(i < size_); return data_[i]; }
private:
void enlarge()
{
SizeType new_capacity= 0;
if (capacity_ == 0)
new_capacity= 16;
else
new_capacity= capacity_*2;
ensure(new_capacity >= size_ + 1);
T* new_data= ator.allocate(new_capacity);
for (SizeType i= 0; i < size_; ++i)
new (new_data + i) Value(std::move(data_[i]));
for (auto& m : *this)
m.~Value();
ator.deallocate(data_, capacity_);
data_= new_data;
capacity_= new_capacity;
}
public:
void pushBack(const Value& t)
{
if (size_ == capacity_)
enlarge();
new (data_ + size_) Value(t);
++size_;
}
void pushBack(Value&& t)
{
if (size_ == capacity_)
enlarge();
new (data_ + size_) Value(std::forward<T>(t));
++size_;
}
void pushBack(const DynArray& v)
{ for (auto& m : v) pushBack(m); }
template<typename... Args>
void emplaceBack(Args&&... args)
{
if (size_ == capacity_)
enlarge();
new (data_ + size_) Value(std::forward<Args>(args)...);
++size_;
}
SizeType size() const { return size_; }
bool empty() const { return size_ == 0; }
void clear()
{
// Following std::vector, although separate destruct() and
// clear() would be better
for (auto& m : *this)
m.~Value();
size_= 0;
}
private:
void resizeCapacity(SizeType new_capacity)
{
if (capacity_ == new_capacity)
return;
Value* new_data= ator.allocate(new_capacity);
for (SizeType i= 0; i < new_capacity && i < size_; ++i)
new (new_data + i) Value(std::move(data_[i])); // Copy objects to new buffer
for (auto& m : *this)
m.~Value(); // Destroy old, including those who didn't fit
ator.deallocate(data_, capacity_);
data_= new_data;
capacity_= new_capacity;
}
public:
void resize(SizeType new_size)
{
if (new_size == size_)
return;
resizeCapacity(new_size);
if (new_size > size_) {
for (SizeType i= size_; i < new_size; ++i)
new (data_ + i) Value();
}
size_= new_size;
}
void resize(SizeType new_size, const Value& value)
{
if (new_size == size_)
return;
resizeCapacity(new_size);
if (new_size > size_) {
for (SizeType i= size_; i < new_size; ++i)
new (data_ + i) Value(value);
}
size_= new_size;
}
void reserve(SizeType new_capacity)
{
if (new_capacity <= size_)
return;
resizeCapacity(new_capacity);
}
Iter begin() { return data_; }
Iter end() { return data_ + size_; }
cIter begin() const { return data_; }
cIter end() const { return data_ + size_; }
T* data() { return data_; }
const T* data() const { return data_; }
T& front() { return *data_; }
T& back() { return *(data_ + size_ - 1); }
const T& front() const { return *data_; }
const T& back() const { return *(data_ + size_ - 1); }
Iter insert(Iter it, const T& t)
{
if (empty() || it == end()) {
pushBack(t);
return end() - 1;
}
SizeType i_to_inserted= it - data_;
if (size_ == capacity_)
enlarge(); // This is inefficient (but simple)
it= data_ + i_to_inserted;
new (data_ + size_) Value(std::move(data_[size_ - 1]));
for (SizeType i= size_ - 1; i > i_to_inserted; --i)
data_[i]= std::move(data_[i - 1]);
it->~Value();
new (it) Value(t);
++size_;
return data_ + i_to_inserted;
}
Iter erase(Iter it) { return erase(it, it + 1); }
Iter erase(Iter b, Iter e)
{
if (b == e)
return b;
SizeType gap= e - b;
for (auto it= b; it + gap != end(); ++it)
*it= std::move(*(it + gap));
for (auto it= end() - gap; it != end(); ++it)
it->~Value();
size_ -= gap;
return b;
}
void popBack() { erase(end() - 1); }
void popFront() { erase(begin()); }
/// @todo Remove these, can be implemented outside
SizeType count(const T& t) const
{
SizeType a= 0;
for (SizeType i= 0; i < size_; ++i)
if(data_[i] == t)
++a;
return a;
}
cIter find(const T& t) const
{
for (cIter it= begin(); it != end(); ++it)
if (*it == t) return it;
return end();
}
Iter find(const T& t)
{
for (Iter it= begin(); it != end(); ++it)
if (*it == t) return it;
return end();
}
void remove(const T& t)
{
auto it= find(t);
debug_ensure(it != end());
erase(it);
}
DynArray<T> appended(const This& v) const
{ DynArray<T> ret(*this); ret.pushBack(v); return ret; }
void append(const This& other)
{ *this= appended(other); }
template <typename Archive>
void serialize(Archive& ar, const uint32 version)
{
if (Archive::is_saving::value) {
ar & size_;
for (auto& m : *this)
ar & m;
} else {
SizeType s;
ar & s;
resize(s);
for (auto& m : *this)
ar & m;
}
}
private:
Value* data_= nullptr;
SizeType size_= 0;
SizeType capacity_= 0;
AtorT ator;
};
template<typename T, template <typename> class Ator>
struct Hash32<DynArray<T, Ator>> {
uint32 operator()(const DynArray<T, Ator>& arr) const {
if (arr.empty()) return 0;
return rawArrayHash(arr.data(), arr.size());
}
};
template <typename T, template <typename> class Ator>
void fastInsert(DynArray<T, Ator>& container, T value){
container.pushBack(std::move(value));
}
} // util
} // clover
#endif // CLOVER_UTIL_DYN_ARRAY_HPP
<|endoftext|> |
<commit_before>/* =====
* Fetch
* =====
*
*/
// Glew must be included before OpenGL
#ifdef _WIN32
//#include <GL/glew.h>
#define INIT_EXTENSIONS \
assert(glewInit()==GLEW_OK)
#else
#define INIT_EXTENSIONS
#endif
#include <QtWidgets>
#include <QtOpenGL>
#include <assert.h>
#include "util/util-gl.h"
#include "util/util-qt.h"
#include "common.h"
#include "devices/Microscope.h"
#include "tasks/microscope-interaction.h"
#include "ui/MainWindow.h"
#include <stdio.h>
#include <google/protobuf/text_format.h>
#include <google/protobuf/io/tokenizer.h>
#include <string>
/*
* Global state
*/
fetch::device::Microscope* gp_microscope;
fetch::task::microscope::Interaction g_microscope_default_task;
/*
* Shutdown callbacks
*/
unsigned int QtShutdownCallback(void)
{ QCoreApplication::exit(0); // Pass success (0), since I don't know what else to do
return 0;
}
unsigned int KillMicroscopeCallback(void)
{
if(gp_microscope) { delete gp_microscope; gp_microscope=NULL;}
return 0;
}
class MyErrorCollector:public google::protobuf::io::ErrorCollector
{ public:
virtual void AddError(int line, int col, const std::string & message) {warning("Protobuf: Error - at line %d(%d):"ENDL"\t%s"ENDL,line,col,message.c_str());}
virtual void AddWarning(int line, int col, const std::string & message) {warning("Protobuf: Warning - at line %d(%d):"ENDL"\t%s"ENDL,line,col,message.c_str());}
};
void Init(void)
{
QSettings settings;
gp_microscope = NULL;
fetch::cfg::device::Microscope* g_config=new fetch::cfg::device::Microscope(); // Don't free, should have application lifetime
fetch::cfg::device::Microscope* cfg_as_set_by_file = new fetch::cfg::device::Microscope(); //DGA: Use this to keep track of cfg as it is in the file Don't free, should have application lifetime
//Shutdown
Register_New_Shutdown_Callback(KillMicroscopeCallback);
Register_New_Shutdown_Callback(QtShutdownCallback);
//Set Session Directory
{
bool ok=0;
char buf[1024]={0};
int session_id=settings.value("session_id").toInt(&ok);
if(!ok)
session_id=0;
session_id=(session_id+1)&0xffff; // limit to 65k sessions
settings.setValue("session_id",session_id);
snprintf(buf,sizeof(buf),"Session-%05d",session_id);
CreateDirectoryA(buf,0);
SetCurrentDirectoryA(buf);
}
//Logging
Reporting_Setup_Log_To_VSDebugger_Console();
Reporting_Setup_Log_To_Filename("lastrun.log");
Reporting_Setup_Log_To_Qt();
google::protobuf::TextFormat::Parser parser;
MyErrorCollector e;
parser.RecordErrorsTo(&e);
{ QFile cfgfile(settings.value(fetch::ui::MainWindow::defaultConfigPathKey,":/config/microscope").toString());
if( cfgfile.open(QIODevice::ReadOnly) && cfgfile.isReadable() )
{ QByteArray contents=cfgfile.readAll();
qDebug() << contents;
if(parser.ParseFromString(contents.constData(),g_config) && parser.ParseFromString(contents.constData(),cfg_as_set_by_file)) //DGA: Added cfg_as_set_by_file part to load in data
{ QByteArray buf=cfgfile.fileName().toLocal8Bit();
debug("Config file loaded from %s\n",buf.data());
goto Success;
}
}
}
{
//try again from default
QFile cfgfile(":/config/microscope");
Guarded_Assert(cfgfile.open(QIODevice::ReadOnly));
Guarded_Assert(cfgfile.isReadable());
Guarded_Assert(parser.ParseFromString(cfgfile.readAll().constData(),g_config));
Guarded_Assert(parser.ParseFromString(cfgfile.readAll().constData(),cfg_as_set_by_file)); //DGA: Added cfg_as_set_by_file part to load in data
{ QByteArray buf=cfgfile.fileName().toLocal8Bit();
debug("Config file loaded from %s\n",buf.data());
}
settings.setValue(fetch::ui::MainWindow::defaultConfigPathKey,":/config/microscope");
}
//cfgfile.setTextModeEnabled(true);
Success:
gp_microscope = new fetch::device::Microscope(g_config);
gp_microscope->cfg_as_set_by_file = cfg_as_set_by_file; //DGA: Set the microscope variable cfg_as_set_by_file to store the current state of the cfg as it is in the file
}
int main(int argc, char *argv[])
{ //[deprecated] -- QGL::setPreferredPaintEngine(QPaintEngine::OpenGL);
QCoreApplication::setOrganizationName("Howard Hughes Medical Institute");
QCoreApplication::setOrganizationDomain("janelia.hhmi.org");
QCoreApplication::setApplicationName("Fetch");
qDebug()<<QCoreApplication::libraryPaths();
QApplication app(argc,argv);
Init();
fetch::ui::MainWindow mainwindow(gp_microscope);
mainwindow.setWindowTitle("Fetch V1.22BetaForJohan"); //DGA: Window title now includes version number.
gp_microscope->onUpdate(); // force update so gui gets notified - have to do this mostly for stage listeners ...
mainwindow.show();
unsigned int eflag = app.exec();
eflag |= Shutdown_Soft();
//debug("Press <Enter> to exit.\r\n");
//getchar();
return eflag;
}
<commit_msg>fix/BetaForJohan: Updated version number.<commit_after>/* =====
* Fetch
* =====
*
*/
// Glew must be included before OpenGL
#ifdef _WIN32
//#include <GL/glew.h>
#define INIT_EXTENSIONS \
assert(glewInit()==GLEW_OK)
#else
#define INIT_EXTENSIONS
#endif
#include <QtWidgets>
#include <QtOpenGL>
#include <assert.h>
#include "util/util-gl.h"
#include "util/util-qt.h"
#include "common.h"
#include "devices/Microscope.h"
#include "tasks/microscope-interaction.h"
#include "ui/MainWindow.h"
#include <stdio.h>
#include <google/protobuf/text_format.h>
#include <google/protobuf/io/tokenizer.h>
#include <string>
/*
* Global state
*/
fetch::device::Microscope* gp_microscope;
fetch::task::microscope::Interaction g_microscope_default_task;
/*
* Shutdown callbacks
*/
unsigned int QtShutdownCallback(void)
{ QCoreApplication::exit(0); // Pass success (0), since I don't know what else to do
return 0;
}
unsigned int KillMicroscopeCallback(void)
{
if(gp_microscope) { delete gp_microscope; gp_microscope=NULL;}
return 0;
}
class MyErrorCollector:public google::protobuf::io::ErrorCollector
{ public:
virtual void AddError(int line, int col, const std::string & message) {warning("Protobuf: Error - at line %d(%d):"ENDL"\t%s"ENDL,line,col,message.c_str());}
virtual void AddWarning(int line, int col, const std::string & message) {warning("Protobuf: Warning - at line %d(%d):"ENDL"\t%s"ENDL,line,col,message.c_str());}
};
void Init(void)
{
QSettings settings;
gp_microscope = NULL;
fetch::cfg::device::Microscope* g_config=new fetch::cfg::device::Microscope(); // Don't free, should have application lifetime
fetch::cfg::device::Microscope* cfg_as_set_by_file = new fetch::cfg::device::Microscope(); //DGA: Use this to keep track of cfg as it is in the file Don't free, should have application lifetime
//Shutdown
Register_New_Shutdown_Callback(KillMicroscopeCallback);
Register_New_Shutdown_Callback(QtShutdownCallback);
//Set Session Directory
{
bool ok=0;
char buf[1024]={0};
int session_id=settings.value("session_id").toInt(&ok);
if(!ok)
session_id=0;
session_id=(session_id+1)&0xffff; // limit to 65k sessions
settings.setValue("session_id",session_id);
snprintf(buf,sizeof(buf),"Session-%05d",session_id);
CreateDirectoryA(buf,0);
SetCurrentDirectoryA(buf);
}
//Logging
Reporting_Setup_Log_To_VSDebugger_Console();
Reporting_Setup_Log_To_Filename("lastrun.log");
Reporting_Setup_Log_To_Qt();
google::protobuf::TextFormat::Parser parser;
MyErrorCollector e;
parser.RecordErrorsTo(&e);
{ QFile cfgfile(settings.value(fetch::ui::MainWindow::defaultConfigPathKey,":/config/microscope").toString());
if( cfgfile.open(QIODevice::ReadOnly) && cfgfile.isReadable() )
{ QByteArray contents=cfgfile.readAll();
qDebug() << contents;
if(parser.ParseFromString(contents.constData(),g_config) && parser.ParseFromString(contents.constData(),cfg_as_set_by_file)) //DGA: Added cfg_as_set_by_file part to load in data
{ QByteArray buf=cfgfile.fileName().toLocal8Bit();
debug("Config file loaded from %s\n",buf.data());
goto Success;
}
}
}
{
//try again from default
QFile cfgfile(":/config/microscope");
Guarded_Assert(cfgfile.open(QIODevice::ReadOnly));
Guarded_Assert(cfgfile.isReadable());
Guarded_Assert(parser.ParseFromString(cfgfile.readAll().constData(),g_config));
Guarded_Assert(parser.ParseFromString(cfgfile.readAll().constData(),cfg_as_set_by_file)); //DGA: Added cfg_as_set_by_file part to load in data
{ QByteArray buf=cfgfile.fileName().toLocal8Bit();
debug("Config file loaded from %s\n",buf.data());
}
settings.setValue(fetch::ui::MainWindow::defaultConfigPathKey,":/config/microscope");
}
//cfgfile.setTextModeEnabled(true);
Success:
gp_microscope = new fetch::device::Microscope(g_config);
gp_microscope->cfg_as_set_by_file = cfg_as_set_by_file; //DGA: Set the microscope variable cfg_as_set_by_file to store the current state of the cfg as it is in the file
}
int main(int argc, char *argv[])
{ //[deprecated] -- QGL::setPreferredPaintEngine(QPaintEngine::OpenGL);
QCoreApplication::setOrganizationName("Howard Hughes Medical Institute");
QCoreApplication::setOrganizationDomain("janelia.hhmi.org");
QCoreApplication::setApplicationName("Fetch");
qDebug()<<QCoreApplication::libraryPaths();
QApplication app(argc,argv);
Init();
fetch::ui::MainWindow mainwindow(gp_microscope);
mainwindow.setWindowTitle("Fetch V1.23BetaForJohan"); //DGA: Window title now includes version number.
gp_microscope->onUpdate(); // force update so gui gets notified - have to do this mostly for stage listeners ...
mainwindow.show();
unsigned int eflag = app.exec();
eflag |= Shutdown_Soft();
//debug("Press <Enter> to exit.\r\n");
//getchar();
return eflag;
}
<|endoftext|> |
<commit_before>// Copyright (c) 2011-2015 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "bantablemodel.h"
#include "clientmodel.h"
#include "guiconstants.h"
#include "guiutil.h"
#include "net.h"
#include "sync.h"
#include "utiltime.h"
#include <QDebug>
#include <QList>
#include <QTimer>
#include <boost/date_time/posix_time/posix_time.hpp>
#include <boost/date_time/c_local_time_adjustor.hpp>
// private implementation
class BanTablePriv
{
public:
/** Local cache of peer information */
QList<CCombinedBan> cachedBanlist;
/** Column to sort nodes by */
int sortColumn;
/** Order (ascending or descending) to sort nodes by */
Qt::SortOrder sortOrder;
/** Pull a full list of banned nodes from CNode into our cache */
void refreshBanlist()
{
std::map<CSubNet, int64_t> banMap;
CNode::GetBanned(banMap);
cachedBanlist.clear();
#if QT_VERSION >= 0x040700
cachedBanlist.reserve(banMap.size());
#endif
std::map<CSubNet, int64_t>::iterator iter;
for (iter = banMap.begin(); iter != banMap.end(); ++iter) {
CCombinedBan banEntry;
banEntry.subnet = iter->first;
banEntry.bantil = iter->second;
cachedBanlist.append(banEntry);
}
}
int size()
{
return cachedBanlist.size();
}
CCombinedBan *index(int idx)
{
if(idx >= 0 && idx < cachedBanlist.size()) {
return &cachedBanlist[idx];
} else {
return 0;
}
}
};
BanTableModel::BanTableModel(ClientModel *parent) :
QAbstractTableModel(parent),
clientModel(parent),
timer(0)
{
columns << tr("IP/Netmask") << tr("Banned Until");
priv = new BanTablePriv();
// default to unsorted
priv->sortColumn = -1;
// set up timer for auto refresh
timer = new QTimer();
connect(timer, SIGNAL(timeout()), SLOT(refresh()));
timer->setInterval(MODEL_UPDATE_DELAY);
// load initial data
refresh();
}
void BanTableModel::startAutoRefresh()
{
timer->start();
}
void BanTableModel::stopAutoRefresh()
{
timer->stop();
}
int BanTableModel::rowCount(const QModelIndex &parent) const
{
Q_UNUSED(parent);
return priv->size();
}
int BanTableModel::columnCount(const QModelIndex &parent) const
{
Q_UNUSED(parent);
return columns.length();;
}
QVariant BanTableModel::data(const QModelIndex &index, int role) const
{
if(!index.isValid())
return QVariant();
CCombinedBan *rec = static_cast<CCombinedBan*>(index.internalPointer());
if (role == Qt::DisplayRole) {
switch(index.column())
{
case Address:
return QString::fromStdString(rec->subnet.ToString());
case Bantime:
//show time in users local timezone, not 64bit compatible!
//TODO find a way to support 64bit timestamps
boost::posix_time::ptime pt1 = boost::posix_time::from_time_t(rec->bantil);
boost::posix_time::ptime pt2 = boost::date_time::c_local_adjustor<boost::posix_time::ptime>::utc_to_local(pt1);
std::stringstream ss;
ss << pt2;
return QString::fromStdString(ss.str());
}
} else if (role == Qt::TextAlignmentRole) {
if (index.column() == Bantime)
return (int)(Qt::AlignRight | Qt::AlignVCenter);
}
return QVariant();
}
QVariant BanTableModel::headerData(int section, Qt::Orientation orientation, int role) const
{
if(orientation == Qt::Horizontal)
{
if(role == Qt::DisplayRole && section < columns.size())
{
return columns[section];
}
}
return QVariant();
}
Qt::ItemFlags BanTableModel::flags(const QModelIndex &index) const
{
if(!index.isValid())
return 0;
Qt::ItemFlags retval = Qt::ItemIsSelectable | Qt::ItemIsEnabled;
return retval;
}
QModelIndex BanTableModel::index(int row, int column, const QModelIndex &parent) const
{
Q_UNUSED(parent);
CCombinedBan *data = priv->index(row);
if (data)
{
return createIndex(row, column, data);
}
else
{
return QModelIndex();
}
}
void BanTableModel::refresh()
{
emit layoutAboutToBeChanged();
priv->refreshBanlist();
emit layoutChanged();
}
void BanTableModel::sort(int column, Qt::SortOrder order)
{
priv->sortColumn = column;
priv->sortOrder = order;
refresh();
}
bool BanTableModel::shouldShow()
{
if (priv->size() > 0)
return true;
return false;
}<commit_msg>[Qt] bantable fix timestamp 64bit issue<commit_after>// Copyright (c) 2011-2015 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "bantablemodel.h"
#include "clientmodel.h"
#include "guiconstants.h"
#include "guiutil.h"
#include "net.h"
#include "sync.h"
#include "utiltime.h"
#include <QDebug>
#include <QList>
#include <QTimer>
#include <boost/date_time/posix_time/posix_time.hpp>
#include <boost/date_time/c_local_time_adjustor.hpp>
// private implementation
class BanTablePriv
{
public:
/** Local cache of peer information */
QList<CCombinedBan> cachedBanlist;
/** Column to sort nodes by */
int sortColumn;
/** Order (ascending or descending) to sort nodes by */
Qt::SortOrder sortOrder;
/** Pull a full list of banned nodes from CNode into our cache */
void refreshBanlist()
{
std::map<CSubNet, int64_t> banMap;
CNode::GetBanned(banMap);
cachedBanlist.clear();
#if QT_VERSION >= 0x040700
cachedBanlist.reserve(banMap.size());
#endif
std::map<CSubNet, int64_t>::iterator iter;
for (iter = banMap.begin(); iter != banMap.end(); ++iter) {
CCombinedBan banEntry;
banEntry.subnet = iter->first;
banEntry.bantil = iter->second;
cachedBanlist.append(banEntry);
}
}
int size()
{
return cachedBanlist.size();
}
CCombinedBan *index(int idx)
{
if(idx >= 0 && idx < cachedBanlist.size()) {
return &cachedBanlist[idx];
} else {
return 0;
}
}
};
BanTableModel::BanTableModel(ClientModel *parent) :
QAbstractTableModel(parent),
clientModel(parent),
timer(0)
{
columns << tr("IP/Netmask") << tr("Banned Until");
priv = new BanTablePriv();
// default to unsorted
priv->sortColumn = -1;
// set up timer for auto refresh
timer = new QTimer();
connect(timer, SIGNAL(timeout()), SLOT(refresh()));
timer->setInterval(MODEL_UPDATE_DELAY);
// load initial data
refresh();
}
void BanTableModel::startAutoRefresh()
{
timer->start();
}
void BanTableModel::stopAutoRefresh()
{
timer->stop();
}
int BanTableModel::rowCount(const QModelIndex &parent) const
{
Q_UNUSED(parent);
return priv->size();
}
int BanTableModel::columnCount(const QModelIndex &parent) const
{
Q_UNUSED(parent);
return columns.length();;
}
QVariant BanTableModel::data(const QModelIndex &index, int role) const
{
if(!index.isValid())
return QVariant();
CCombinedBan *rec = static_cast<CCombinedBan*>(index.internalPointer());
if (role == Qt::DisplayRole) {
switch(index.column())
{
case Address:
return QString::fromStdString(rec->subnet.ToString());
case Bantime:
QDateTime date = QDateTime::fromMSecsSinceEpoch(0);
date = date.addSecs(rec->bantil);
return date.toString(Qt::SystemLocaleShortDate);
}
} else if (role == Qt::TextAlignmentRole) {
if (index.column() == Bantime)
return (int)(Qt::AlignRight | Qt::AlignVCenter);
}
return QVariant();
}
QVariant BanTableModel::headerData(int section, Qt::Orientation orientation, int role) const
{
if(orientation == Qt::Horizontal)
{
if(role == Qt::DisplayRole && section < columns.size())
{
return columns[section];
}
}
return QVariant();
}
Qt::ItemFlags BanTableModel::flags(const QModelIndex &index) const
{
if(!index.isValid())
return 0;
Qt::ItemFlags retval = Qt::ItemIsSelectable | Qt::ItemIsEnabled;
return retval;
}
QModelIndex BanTableModel::index(int row, int column, const QModelIndex &parent) const
{
Q_UNUSED(parent);
CCombinedBan *data = priv->index(row);
if (data)
{
return createIndex(row, column, data);
}
else
{
return QModelIndex();
}
}
void BanTableModel::refresh()
{
emit layoutAboutToBeChanged();
priv->refreshBanlist();
emit layoutChanged();
}
void BanTableModel::sort(int column, Qt::SortOrder order)
{
priv->sortColumn = column;
priv->sortOrder = order;
refresh();
}
bool BanTableModel::shouldShow()
{
if (priv->size() > 0)
return true;
return false;
}<|endoftext|> |
<commit_before>/******************************************************************************
* Copyright (c) 2000-2016 Ericsson Telecom AB
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Balasko, Jeno
* Baranyi, Botond
* Beres, Szabolcs
* Delic, Adam
* Forstner, Matyas
* Herrlin, Thomas
* Raduly, Csaba
* Szabados, Kristof
* Szabo, Janos Zoltan – initial implementation
* Szalai, Gabor
*
******************************************************************************/
#include "Error.hh"
#include "TitanLoggerApi.hh"
#include <stdarg.h>
#include <stdint.h>
#include "../common/memory.h"
#include "Logger.hh"
#include "Runtime.hh"
#include "Charstring.hh"
#ifdef LINUX
#include <ucontext.h>
#include <dlfcn.h>
#include <execinfo.h>
#ifndef NO_CPP_DEMANGLE
#include <cxxabi.h>
using namespace __cxxabiv1;
#endif
#endif
#ifdef LINUX
const size_t MAX_DEPTH=100;
void stacktrace(const ucontext_t& ctx)
{
TTCN_Logger::log_event_str("\nStack trace:\n");
(void)ctx;
void *array[MAX_DEPTH];
size_t size;
char **strings;
size_t i;
size = backtrace (array, MAX_DEPTH);
strings = backtrace_symbols (array, size);
//printf ("Obtained %lu stack frames.\n", (unsigned long)size);
for (i = 0; i < size; i++) {
const char * symname = strings[i];
const char *begin = 0, *end = 0;
// The format is: /path/to/exe(_Z11mangledname+0xBAAD) [0x...]
// Mangled name starts here ---^ ends here--^
for (const char *j = symname; *j; ++j) {
if (*j == '(')
begin = j+1;
else if (*j == '+')
end = j;
}
char *dem = 0;
if (begin && end) {
size_t len = end - begin;
char *mangled = (char*)malloc(len + 1);
memcpy(mangled, begin, len);
mangled[len] = '\0';
int status;
dem = __cxa_demangle(mangled, NULL, 0, &status);
if(status == 0 && dem)
symname = dem;
}
if (TTCN_Logger::is_logger_up()) {
TTCN_Logger::log_event ("%2lu: %s%s\n", (unsigned long)i, symname, (end ? end : ""));
}
else {
fprintf (stderr, "%2lu: %s%s\n", (unsigned long)i, symname, (end ? end : ""));
}
if (dem)
free(dem);
}
free (strings);
}
void where_am_i(TTCN_Logger::Severity sev = TTCN_Logger::USER_UNQUALIFIED)
{
ucontext_t uc;
int er = getcontext(&uc);
if (!er) {
TTCN_Logger::begin_event(sev);
stacktrace(uc);
TTCN_Logger::end_event();
}
else {
perror("getcontext");
}
}
static void signal_segv(int signum, siginfo_t* info, void*ptr) {
static const char *si_codes[3] = {"", "SEGV_MAPERR", "SEGV_ACCERR"};
ucontext_t *ucontext = (ucontext_t*)ptr;
fprintf(stderr, "\n\n!!! Segmentation Fault !!!\n\n");
fprintf(stderr, "info.si_signo = %d\n", signum);
fprintf(stderr, "info.si_errno = %d\n", info->si_errno);
fprintf(stderr, "info.si_code = %d (%s)\n", info->si_code, si_codes[info->si_code]);
fprintf(stderr, "info.si_addr = %p\n", info->si_addr);
TTCN_Logger::begin_event(TTCN_Logger::ERROR_UNQUALIFIED);
stacktrace(*ucontext);
TTCN_Logger::end_event();
fprintf(stderr, "\nGoodbye, cruel world!\n");
exit(-1);
}
int setup_sigsegv() {
struct sigaction action;
memset(&action, 0, sizeof(action));
action.sa_sigaction = signal_segv;
action.sa_flags = SA_SIGINFO;
if(sigaction(SIGSEGV, &action, NULL) < 0) {
perror("sigaction");
return 0;
}
return 1;
}
static void __attribute((constructor)) init(void) {
setup_sigsegv();
}
#elif defined(SOLARIS) || defined(SOLARIS8)
/*
walks up call stack, printing library:routine+offset for each routine
*/
#include <dlfcn.h>
#include <setjmp.h>
#include<sys/types.h>
#include <sys/reg.h>
#include <sys/frame.h>
#if defined(sparc) || defined(__sparc)
#define FLUSHWIN() asm("ta 3");
#define FRAME_PTR_INDEX 1
#define SKIP_FRAMES 0
#endif
#if defined(i386) || defined(__i386)
#define FLUSHWIN()
#define FRAME_PTR_INDEX 3
#define SKIP_FRAMES 1
#endif
#if defined(ppc) || defined(__ppc)
#define FLUSHWIN()
#define FRAME_PTR_INDEX 0
#define SKIP_FRAMES 2
#endif
#include <cxxabi.h>
/*
this function walks up call stack, calling user-supplied
function once for each stack frame, passing the pc and the user-supplied
usrarg as the argument.
*/
int cs_operate(int (*func)(void *, void *), void * usrarg)
{
struct frame *sp;
jmp_buf env;
int i;
int * iptr;
FLUSHWIN();
setjmp(env);
iptr = (int*) env;
sp = (struct frame *) iptr[FRAME_PTR_INDEX];
for(i=0;i<SKIP_FRAMES && sp;i++)
sp = (struct frame*) sp->fr_savfp;
i = 0;
while(sp && sp->fr_savpc && ++i && (*func)((void*)sp->fr_savpc, usrarg)) {
sp = (struct frame*) sp->fr_savfp;
}
return(i);
}
void print_my_stack()
{
int print_address(void *, void *);
cs_operate(print_address, NULL);
}
int print_address(void *pc, void * usrarg)
{
Dl_info info;
const char * func;
const char * lib;
if(dladdr(pc, & info) == 0) {
func = "??";
lib = "??";
}
else {
lib = info.dli_fname;
func = info.dli_sname;
}
size_t len = strlen(lib);
for (--len; len > 0; --len) {
if (lib[len] == '/') break;
}
if (len > 0) lib += ++len;
int status = 42;
char *demangled = abi::__cxa_demangle(func, NULL, 0, &status);
if (status == 0) func = demangled;
if (TTCN_Logger::is_logger_up()) {
TTCN_Logger::log_event("%s:%s+%p\n",
lib,
func,
(void *)((uintptr_t)pc - (uintptr_t)info.dli_saddr)
);
}
else {
fprintf(stderr, "%s:%s+%p\n",
lib,
func,
(void *)((uintptr_t)pc - (uintptr_t)info.dli_saddr)
);
}
if (status == 0) free(demangled);
return(1);
}
void where_am_i(TTCN_Logger::Severity sev = TTCN_Logger::USER_UNQUALIFIED)
{
TTCN_Logger::begin_event(sev);
print_my_stack();
TTCN_Logger::end_event();
}
#else
void where_am_i(TTCN_Logger::Severity /*sev*/ = TTCN_Logger::USER_UNQUALIFIED)
{
// You are on your own
}
#endif // LINUX
TTCN_Error::~TTCN_Error()
{
Free(error_msg);
}
void TTCN_error(const char *err_msg, ...)
{
if (TTCN_Runtime::is_in_ttcn_try_block()) {
// Add location data as if it were logged
char* error_str = TTCN_Location::print_location(
TTCN_Logger::SINFO_STACK == TTCN_Logger::get_source_info_format(),
TTCN_Logger::SINFO_NONE != TTCN_Logger::get_source_info_format(),
TTCN_Logger::get_log_entity_name());
if (error_str) {
error_str = mputstr(error_str, " ");
}
error_str = mputstr(error_str, "Dynamic test case error: ");
va_list p_var;
va_start(p_var, err_msg);
error_str = mputprintf_va_list(error_str, err_msg, p_var);
va_end(p_var);
throw TTCN_Error(error_str);
} else {
TTCN_Logger::begin_event(TTCN_Logger::ERROR_UNQUALIFIED);
if (TTCN_Logger::SINFO_NONE == TTCN_Logger::get_source_info_format())
{
//Always print some location info in case of dynamic testcase error
char * loc = TTCN_Location::print_location(false, true, false);
if (loc) {
TTCN_Logger::log_event_str(loc);
TTCN_Logger::log_event_str(": ");
Free(loc);
}
}
TTCN_Logger::log_event_str("Dynamic test case error: ");
va_list p_var;
va_start(p_var, err_msg);
TTCN_Logger::log_event_va_list(err_msg, p_var);
va_end(p_var);
TTCN_Logger::OS_error();
TTCN_Logger::end_event();
#ifndef NDEBUG
// the current implementation of the stack trace printout is misleading and cause more
// trouble and misunderstanding than it solves
// So it disabled in production compilation
// It remains active in debug compilation
where_am_i(TTCN_Logger::ERROR_UNQUALIFIED);
#endif
TTCN_Runtime::set_error_verdict();
TTCN_Logger::log_executor_runtime(
TitanLoggerApi::ExecutorRuntime_reason::performing__error__recovery);
throw TC_Error();
}
}
void TTCN_error_begin(const char *err_msg, ...)
{
if (TTCN_Runtime::is_in_ttcn_try_block()) {
TTCN_Logger::begin_event_log2str();
// Add location data as if it were logged
char* loc = TTCN_Location::print_location(
TTCN_Logger::SINFO_STACK == TTCN_Logger::get_source_info_format(),
TTCN_Logger::SINFO_NONE != TTCN_Logger::get_source_info_format(),
TTCN_Logger::get_log_entity_name());
if (loc) {
TTCN_Logger::log_event_str(loc);
TTCN_Logger::log_event_str(" ");
Free(loc);
}
TTCN_Logger::log_event_str("Dynamic test case error: ");
va_list p_var;
va_start(p_var, err_msg);
TTCN_Logger::log_event_va_list(err_msg, p_var);
va_end(p_var);
} else {
TTCN_Logger::begin_event(TTCN_Logger::ERROR_UNQUALIFIED);
TTCN_Logger::log_event_str("Dynamic test case error: ");
va_list p_var;
va_start(p_var, err_msg);
TTCN_Logger::log_event_va_list(err_msg, p_var);
va_end(p_var);
}
}
void TTCN_error_end()
{
if (TTCN_Runtime::is_in_ttcn_try_block()) {
CHARSTRING error_str = TTCN_Logger::end_event_log2str();
throw TTCN_Error(mcopystr((const char*)error_str));
} else {
TTCN_Logger::OS_error();
TTCN_Logger::end_event();
TTCN_Runtime::set_error_verdict();
TTCN_Logger::log_executor_runtime(
TitanLoggerApi::ExecutorRuntime_reason::performing__error__recovery);
throw TC_Error();
}
}
void TTCN_warning(const char *warning_msg, ...)
{
TTCN_Logger::begin_event(TTCN_Logger::WARNING_UNQUALIFIED);
TTCN_Logger::log_event_str("Warning: ");
va_list p_var;
va_start(p_var, warning_msg);
TTCN_Logger::log_event_va_list(warning_msg, p_var);
va_end(p_var);
TTCN_Logger::end_event();
}
void TTCN_warning_begin(const char *warning_msg, ...)
{
TTCN_Logger::begin_event(TTCN_Logger::WARNING_UNQUALIFIED);
TTCN_Logger::log_event_str("Warning: ");
va_list p_var;
va_start(p_var, warning_msg);
TTCN_Logger::log_event_va_list(warning_msg, p_var);
va_end(p_var);
}
void TTCN_warning_end()
{
TTCN_Logger::end_event();
}
void TTCN_pattern_error(const char *error_msg, ...)
{
va_list p_var;
va_start(p_var, error_msg);
char *error_str = mprintf_va_list(error_msg, p_var);
va_end(p_var);
try {
TTCN_error("Charstring pattern: %s", error_str);
} catch (...) {
Free(error_str);
throw;
}
}
void TTCN_pattern_warning(const char *warning_msg, ...)
{
va_list p_var;
va_start(p_var, warning_msg);
char *warning_str = mprintf_va_list(warning_msg, p_var);
va_end(p_var);
TTCN_warning("Charstring pattern: %s", warning_str);
Free(warning_str);
}
<commit_msg>Fix Solaris x86-64 support (req: Thomas Herrlin)<commit_after>/******************************************************************************
* Copyright (c) 2000-2016 Ericsson Telecom AB
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Balasko, Jeno
* Baranyi, Botond
* Beres, Szabolcs
* Delic, Adam
* Forstner, Matyas
* Herrlin, Thomas
* Raduly, Csaba
* Szabados, Kristof
* Szabo, Janos Zoltan – initial implementation
* Szalai, Gabor
*
******************************************************************************/
#include "Error.hh"
#include "TitanLoggerApi.hh"
#include <stdarg.h>
#include <stdint.h>
#include "../common/memory.h"
#include "Logger.hh"
#include "Runtime.hh"
#include "Charstring.hh"
#ifdef LINUX
#include <ucontext.h>
#include <dlfcn.h>
#include <execinfo.h>
#ifndef NO_CPP_DEMANGLE
#include <cxxabi.h>
using namespace __cxxabiv1;
#endif
#endif
#ifdef LINUX
const size_t MAX_DEPTH=100;
void stacktrace(const ucontext_t& ctx)
{
TTCN_Logger::log_event_str("\nStack trace:\n");
(void)ctx;
void *array[MAX_DEPTH];
size_t size;
char **strings;
size_t i;
size = backtrace (array, MAX_DEPTH);
strings = backtrace_symbols (array, size);
//printf ("Obtained %lu stack frames.\n", (unsigned long)size);
for (i = 0; i < size; i++) {
const char * symname = strings[i];
const char *begin = 0, *end = 0;
// The format is: /path/to/exe(_Z11mangledname+0xBAAD) [0x...]
// Mangled name starts here ---^ ends here--^
for (const char *j = symname; *j; ++j) {
if (*j == '(')
begin = j+1;
else if (*j == '+')
end = j;
}
char *dem = 0;
if (begin && end) {
size_t len = end - begin;
char *mangled = (char*)malloc(len + 1);
memcpy(mangled, begin, len);
mangled[len] = '\0';
int status;
dem = __cxa_demangle(mangled, NULL, 0, &status);
if(status == 0 && dem)
symname = dem;
}
if (TTCN_Logger::is_logger_up()) {
TTCN_Logger::log_event ("%2lu: %s%s\n", (unsigned long)i, symname, (end ? end : ""));
}
else {
fprintf (stderr, "%2lu: %s%s\n", (unsigned long)i, symname, (end ? end : ""));
}
if (dem)
free(dem);
}
free (strings);
}
void where_am_i(TTCN_Logger::Severity sev = TTCN_Logger::USER_UNQUALIFIED)
{
ucontext_t uc;
int er = getcontext(&uc);
if (!er) {
TTCN_Logger::begin_event(sev);
stacktrace(uc);
TTCN_Logger::end_event();
}
else {
perror("getcontext");
}
}
static void signal_segv(int signum, siginfo_t* info, void*ptr) {
static const char *si_codes[3] = {"", "SEGV_MAPERR", "SEGV_ACCERR"};
ucontext_t *ucontext = (ucontext_t*)ptr;
fprintf(stderr, "\n\n!!! Segmentation Fault !!!\n\n");
fprintf(stderr, "info.si_signo = %d\n", signum);
fprintf(stderr, "info.si_errno = %d\n", info->si_errno);
fprintf(stderr, "info.si_code = %d (%s)\n", info->si_code, si_codes[info->si_code]);
fprintf(stderr, "info.si_addr = %p\n", info->si_addr);
TTCN_Logger::begin_event(TTCN_Logger::ERROR_UNQUALIFIED);
stacktrace(*ucontext);
TTCN_Logger::end_event();
fprintf(stderr, "\nGoodbye, cruel world!\n");
exit(-1);
}
int setup_sigsegv() {
struct sigaction action;
memset(&action, 0, sizeof(action));
action.sa_sigaction = signal_segv;
action.sa_flags = SA_SIGINFO;
if(sigaction(SIGSEGV, &action, NULL) < 0) {
perror("sigaction");
return 0;
}
return 1;
}
static void __attribute((constructor)) init(void) {
setup_sigsegv();
}
#elif defined(SOLARIS) || defined(SOLARIS8)
/*
walks up call stack, printing library:routine+offset for each routine
*/
#include <dlfcn.h>
#include <setjmp.h>
#include<sys/types.h>
#include <sys/reg.h>
#include <sys/frame.h>
#if defined(sparc) || defined(__sparc)
#define FLUSHWIN() asm("ta 3");
#define FRAME_PTR_INDEX 1
#define SKIP_FRAMES 0
#endif
#if defined(i386) || defined(__i386)
#define FLUSHWIN()
#define FRAME_PTR_INDEX 3
#define SKIP_FRAMES 1
#endif
// TODO: Values for __x86_64 are only guesses, not tested.
#if defined(__x86_64)
#define FLUSHWIN()
#define FRAME_PTR_INDEX 7
#define SKIP_FRAMES 1
#endif
#if defined(ppc) || defined(__ppc)
#define FLUSHWIN()
#define FRAME_PTR_INDEX 0
#define SKIP_FRAMES 2
#endif
#include <cxxabi.h>
/*
this function walks up call stack, calling user-supplied
function once for each stack frame, passing the pc and the user-supplied
usrarg as the argument.
*/
int cs_operate(int (*func)(void *, void *), void * usrarg)
{
struct frame *sp;
jmp_buf env;
int i;
int * iptr;
FLUSHWIN();
setjmp(env);
iptr = (int*) env;
sp = (struct frame *) iptr[FRAME_PTR_INDEX];
for(i=0;i<SKIP_FRAMES && sp;i++)
sp = (struct frame*) sp->fr_savfp;
i = 0;
while(sp && sp->fr_savpc && ++i && (*func)((void*)sp->fr_savpc, usrarg)) {
sp = (struct frame*) sp->fr_savfp;
}
return(i);
}
void print_my_stack()
{
int print_address(void *, void *);
cs_operate(print_address, NULL);
}
int print_address(void *pc, void * usrarg)
{
Dl_info info;
const char * func;
const char * lib;
if(dladdr(pc, & info) == 0) {
func = "??";
lib = "??";
}
else {
lib = info.dli_fname;
func = info.dli_sname;
}
size_t len = strlen(lib);
for (--len; len > 0; --len) {
if (lib[len] == '/') break;
}
if (len > 0) lib += ++len;
int status = 42;
char *demangled = abi::__cxa_demangle(func, NULL, 0, &status);
if (status == 0) func = demangled;
if (TTCN_Logger::is_logger_up()) {
TTCN_Logger::log_event("%s:%s+%p\n",
lib,
func,
(void *)((uintptr_t)pc - (uintptr_t)info.dli_saddr)
);
}
else {
fprintf(stderr, "%s:%s+%p\n",
lib,
func,
(void *)((uintptr_t)pc - (uintptr_t)info.dli_saddr)
);
}
if (status == 0) free(demangled);
return(1);
}
void where_am_i(TTCN_Logger::Severity sev = TTCN_Logger::USER_UNQUALIFIED)
{
TTCN_Logger::begin_event(sev);
print_my_stack();
TTCN_Logger::end_event();
}
#else
void where_am_i(TTCN_Logger::Severity /*sev*/ = TTCN_Logger::USER_UNQUALIFIED)
{
// You are on your own
}
#endif // LINUX
TTCN_Error::~TTCN_Error()
{
Free(error_msg);
}
void TTCN_error(const char *err_msg, ...)
{
if (TTCN_Runtime::is_in_ttcn_try_block()) {
// Add location data as if it were logged
char* error_str = TTCN_Location::print_location(
TTCN_Logger::SINFO_STACK == TTCN_Logger::get_source_info_format(),
TTCN_Logger::SINFO_NONE != TTCN_Logger::get_source_info_format(),
TTCN_Logger::get_log_entity_name());
if (error_str) {
error_str = mputstr(error_str, " ");
}
error_str = mputstr(error_str, "Dynamic test case error: ");
va_list p_var;
va_start(p_var, err_msg);
error_str = mputprintf_va_list(error_str, err_msg, p_var);
va_end(p_var);
throw TTCN_Error(error_str);
} else {
TTCN_Logger::begin_event(TTCN_Logger::ERROR_UNQUALIFIED);
if (TTCN_Logger::SINFO_NONE == TTCN_Logger::get_source_info_format())
{
//Always print some location info in case of dynamic testcase error
char * loc = TTCN_Location::print_location(false, true, false);
if (loc) {
TTCN_Logger::log_event_str(loc);
TTCN_Logger::log_event_str(": ");
Free(loc);
}
}
TTCN_Logger::log_event_str("Dynamic test case error: ");
va_list p_var;
va_start(p_var, err_msg);
TTCN_Logger::log_event_va_list(err_msg, p_var);
va_end(p_var);
TTCN_Logger::OS_error();
TTCN_Logger::end_event();
#ifndef NDEBUG
// the current implementation of the stack trace printout is misleading and cause more
// trouble and misunderstanding than it solves
// So it disabled in production compilation
// It remains active in debug compilation
where_am_i(TTCN_Logger::ERROR_UNQUALIFIED);
#endif
TTCN_Runtime::set_error_verdict();
TTCN_Logger::log_executor_runtime(
TitanLoggerApi::ExecutorRuntime_reason::performing__error__recovery);
throw TC_Error();
}
}
void TTCN_error_begin(const char *err_msg, ...)
{
if (TTCN_Runtime::is_in_ttcn_try_block()) {
TTCN_Logger::begin_event_log2str();
// Add location data as if it were logged
char* loc = TTCN_Location::print_location(
TTCN_Logger::SINFO_STACK == TTCN_Logger::get_source_info_format(),
TTCN_Logger::SINFO_NONE != TTCN_Logger::get_source_info_format(),
TTCN_Logger::get_log_entity_name());
if (loc) {
TTCN_Logger::log_event_str(loc);
TTCN_Logger::log_event_str(" ");
Free(loc);
}
TTCN_Logger::log_event_str("Dynamic test case error: ");
va_list p_var;
va_start(p_var, err_msg);
TTCN_Logger::log_event_va_list(err_msg, p_var);
va_end(p_var);
} else {
TTCN_Logger::begin_event(TTCN_Logger::ERROR_UNQUALIFIED);
TTCN_Logger::log_event_str("Dynamic test case error: ");
va_list p_var;
va_start(p_var, err_msg);
TTCN_Logger::log_event_va_list(err_msg, p_var);
va_end(p_var);
}
}
void TTCN_error_end()
{
if (TTCN_Runtime::is_in_ttcn_try_block()) {
CHARSTRING error_str = TTCN_Logger::end_event_log2str();
throw TTCN_Error(mcopystr((const char*)error_str));
} else {
TTCN_Logger::OS_error();
TTCN_Logger::end_event();
TTCN_Runtime::set_error_verdict();
TTCN_Logger::log_executor_runtime(
TitanLoggerApi::ExecutorRuntime_reason::performing__error__recovery);
throw TC_Error();
}
}
void TTCN_warning(const char *warning_msg, ...)
{
TTCN_Logger::begin_event(TTCN_Logger::WARNING_UNQUALIFIED);
TTCN_Logger::log_event_str("Warning: ");
va_list p_var;
va_start(p_var, warning_msg);
TTCN_Logger::log_event_va_list(warning_msg, p_var);
va_end(p_var);
TTCN_Logger::end_event();
}
void TTCN_warning_begin(const char *warning_msg, ...)
{
TTCN_Logger::begin_event(TTCN_Logger::WARNING_UNQUALIFIED);
TTCN_Logger::log_event_str("Warning: ");
va_list p_var;
va_start(p_var, warning_msg);
TTCN_Logger::log_event_va_list(warning_msg, p_var);
va_end(p_var);
}
void TTCN_warning_end()
{
TTCN_Logger::end_event();
}
void TTCN_pattern_error(const char *error_msg, ...)
{
va_list p_var;
va_start(p_var, error_msg);
char *error_str = mprintf_va_list(error_msg, p_var);
va_end(p_var);
try {
TTCN_error("Charstring pattern: %s", error_str);
} catch (...) {
Free(error_str);
throw;
}
}
void TTCN_pattern_warning(const char *warning_msg, ...)
{
va_list p_var;
va_start(p_var, warning_msg);
char *warning_str = mprintf_va_list(warning_msg, p_var);
va_end(p_var);
TTCN_warning("Charstring pattern: %s", warning_str);
Free(warning_str);
}
<|endoftext|> |
<commit_before>/*
Copyright libCellML Contributors
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 "libcellml/model.h"
#include <algorithm>
#include <fstream>
#include <map>
#include <sstream>
#include <stack>
#include <utility>
#include <vector>
#include "libcellml/component.h"
#include "libcellml/importsource.h"
#include "libcellml/parser.h"
#include "libcellml/variable.h"
#include "libcellml/units.h"
namespace libcellml {
/**
* @brief The Model::ModelImpl struct.
*
* This struct is the private implementation struct for the Model class. Separating
* the implementation from the definition allows for greater flexibility when
* distributing the code.
*/
struct Model::ModelImpl
{
std::vector<UnitsPtr>::iterator findUnits(const std::string &name);
std::vector<UnitsPtr>::iterator findUnits(const UnitsPtr &units);
std::vector<UnitsPtr> mUnits;
};
std::vector<UnitsPtr>::iterator Model::ModelImpl::findUnits(const std::string &name)
{
return std::find_if(mUnits.begin(), mUnits.end(),
[=](const UnitsPtr &u) -> bool { return u->getName() == name; });
}
std::vector<UnitsPtr>::iterator Model::ModelImpl::findUnits(const UnitsPtr &units)
{
return std::find_if(mUnits.begin(), mUnits.end(),
[=](const UnitsPtr &u) -> bool { return u == units; });
}
Model::Model()
: mPimpl(new ModelImpl())
{
}
Model::~Model()
{
delete mPimpl;
}
Model::Model(const Model &rhs)
: ComponentEntity(rhs)
, mPimpl(new ModelImpl())
{
mPimpl->mUnits = rhs.mPimpl->mUnits;
}
Model::Model(Model &&rhs)
: ComponentEntity(std::move(rhs))
,mPimpl(rhs.mPimpl)
{
rhs.mPimpl = nullptr;
}
Model& Model::operator=(Model m)
{
ComponentEntity::operator= (m);
m.swap(*this);
return *this;
}
void Model::swap(Model &rhs)
{
std::swap(this->mPimpl, rhs.mPimpl);
}
void Model::doAddComponent(const ComponentPtr &c)
{
// Check for cycles.
if (!hasParent(c.get())) {
c->setParent(this);
ComponentEntity::doAddComponent(c);
}
}
void Model::addUnits(const UnitsPtr &units)
{
mPimpl->mUnits.push_back(units);
}
bool Model::removeUnits(size_t index)
{
bool status = false;
if (index < mPimpl->mUnits.size()) {
mPimpl->mUnits.erase(mPimpl->mUnits.begin() + index);
status = true;
}
return status;
}
bool Model::removeUnits(const std::string &name)
{
bool status = false;
auto result = mPimpl->findUnits(name);
if (result != mPimpl->mUnits.end()) {
mPimpl->mUnits.erase(result);
status = true;
}
return status;
}
bool Model::removeUnits(const UnitsPtr &units)
{
bool status = false;
auto result = mPimpl->findUnits(units);
if (result != mPimpl->mUnits.end()) {
mPimpl->mUnits.erase(result);
status = true;
}
return status;
}
void Model::removeAllUnits()
{
mPimpl->mUnits.clear();
}
bool Model::hasUnits(const std::string &name) const
{
return mPimpl->findUnits(name) != mPimpl->mUnits.end();
}
bool Model::hasUnits(const UnitsPtr &units) const
{
return mPimpl->findUnits(units) != mPimpl->mUnits.end();
}
UnitsPtr Model::getUnits(size_t index) const
{
UnitsPtr units = nullptr;
if (index < mPimpl->mUnits.size()) {
units = mPimpl->mUnits.at(index);
}
return units;
}
UnitsPtr Model::getUnits(const std::string &name) const
{
UnitsPtr units = nullptr;
auto result = mPimpl->findUnits(name);
if (result != mPimpl->mUnits.end()) {
units = *result;
}
return units;
}
UnitsPtr Model::takeUnits(size_t index)
{
UnitsPtr units = nullptr;
if (index < mPimpl->mUnits.size()) {
units = mPimpl->mUnits.at(index);
removeUnits(index);
units->clearParent();
}
return units;
}
UnitsPtr Model::takeUnits(const std::string &name)
{
return takeUnits(mPimpl->findUnits(name) - mPimpl->mUnits.begin());
}
bool Model::replaceUnits(size_t index, const UnitsPtr &units)
{
bool status = false;
if (removeUnits(index)) {
mPimpl->mUnits.insert(mPimpl->mUnits.begin() + index, units);
status = true;
}
return status;
}
bool Model::replaceUnits(const std::string &name, const UnitsPtr &units)
{
return replaceUnits(mPimpl->findUnits(name) - mPimpl->mUnits.begin(), units);
}
bool Model::replaceUnits(const UnitsPtr &oldUnits, const UnitsPtr &newUnits)
{
return replaceUnits(mPimpl->findUnits(oldUnits) - mPimpl->mUnits.begin(), newUnits);
}
size_t Model::unitsCount() const
{
return mPimpl->mUnits.size();
}
typedef std::shared_ptr<ImportedEntity> ImportedEntityPtr;
/**
* @brief Resolve the path of the given filename using the given base.
*
* Resolves the full path to the given @p filename using the @p base.
*
* This function is only intended to work with local files. It may not
* work with bases that use the 'file://' prefix.
*
* @param filename The @c std::string relative path from the base path.
* @param base The @c std::string location on local disk for determining the full path from.
* @return The full path from the @p base location to the @p filename
*/
std::string resolvePath(const std::string &filename, const std::string &base)
{
// we can be naive here as we know what we are dealing with
std::string path = base.substr(0, base.find_last_of('/')+1) + filename;
return path;
}
void resolveImport(ImportedEntityPtr importedEntity,
const std::string &baseFile)
{
if (importedEntity->isImport()) {
libcellml::ImportSourcePtr importSource = importedEntity->getImportSource();
if (!importSource->hasModel()) {
std::string url = resolvePath(importSource->getUrl(), baseFile);
std::ifstream t(url);
if (t.good()) {
std::stringstream buffer;
buffer << t.rdbuf();
libcellml::Parser p;
libcellml::ModelPtr model = p.parseModel(buffer.str());
if (model) {
importSource->setModel(model);
model->resolveImports(url);
}
}
}
}
}
void recurseResolveComponentImports(ComponentPtr component, const std::string &baseFile);
void resolveComponentImports(ComponentPtr parentComponent, const std::string &baseFile)
{
for (size_t n = 0; n < parentComponent->componentCount(); ++n)
{
libcellml::ComponentPtr component = parentComponent->getComponent(n);
recurseResolveComponentImports(component, baseFile);
}
}
void recurseResolveComponentImports(ComponentPtr component, const std::string &baseFile)
{
if (component->isImport()) {
resolveImport(component, baseFile);
} else {
resolveComponentImports(component, baseFile);
}
}
void Model::resolveImports(const std::string &baseFile)
{
for (size_t n = 0; n < unitsCount(); ++n)
{
libcellml::UnitsPtr units = getUnits(n);
resolveImport(units, baseFile);
}
for (size_t n = 0; n < componentCount(); ++n)
{
libcellml::ComponentPtr component = getComponent(n);
recurseResolveComponentImports(component, baseFile);
}
}
bool isUnresolvedImport(ImportedEntityPtr importedEntity)
{
bool unresolvedImport = false;
if (importedEntity->isImport()) {
libcellml::ImportSourcePtr importedSource = importedEntity->getImportSource();
if (!importedSource->hasModel()) {
unresolvedImport = true;
}
}
return unresolvedImport;
}
bool hasUnresolvedComponentImports(libcellml::ComponentPtr component);
bool recurseForUnresolvedComponentImports(ComponentPtr parentComponent)
{
bool unresolvedImports = false;
for (size_t n = 0; n < parentComponent->componentCount() && !unresolvedImports; ++n)
{
libcellml::ComponentPtr component = parentComponent->getComponent(n);
unresolvedImports = hasUnresolvedComponentImports(component);
}
return unresolvedImports;
}
bool hasUnresolvedComponentImports(libcellml::ComponentPtr component)
{
bool unresolvedImports = false;
if (component->isImport()) {
unresolvedImports = isUnresolvedImport(component);
if (!unresolvedImports) {
// Check that the imported component can import all it needs from it's model.
libcellml::ImportSourcePtr importedSource = component->getImportSource();
if (importedSource->hasModel()) {
ModelPtr importedModel = importedSource->getModel();
ComponentPtr importedComponent = importedModel->getComponent(component->getImportReference());
unresolvedImports = hasUnresolvedComponentImports(importedComponent);
}
}
} else {
unresolvedImports = recurseForUnresolvedComponentImports(component);
}
return unresolvedImports;
}
bool Model::hasUnresolvedImports() const
{
bool unresolvedImports = false;
for (size_t n = 0; n < unitsCount() && !unresolvedImports; ++n)
{
libcellml::UnitsPtr units = getUnits(n);
unresolvedImports = isUnresolvedImport(units);
}
for (size_t n = 0; n < componentCount() && !unresolvedImports; ++n)
{
libcellml::ComponentPtr component = getComponent(n);
unresolvedImports = hasUnresolvedComponentImports(component);
}
return unresolvedImports;
}
}
<commit_msg>model.cpp: renamed some variables and removed some spaces here and there.<commit_after>/*
Copyright libCellML Contributors
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 "libcellml/model.h"
#include <algorithm>
#include <fstream>
#include <map>
#include <sstream>
#include <stack>
#include <utility>
#include <vector>
#include "libcellml/component.h"
#include "libcellml/importsource.h"
#include "libcellml/parser.h"
#include "libcellml/variable.h"
#include "libcellml/units.h"
namespace libcellml {
/**
* @brief The Model::ModelImpl struct.
*
* This struct is the private implementation struct for the Model class. Separating
* the implementation from the definition allows for greater flexibility when
* distributing the code.
*/
struct Model::ModelImpl
{
std::vector<UnitsPtr>::iterator findUnits(const std::string &name);
std::vector<UnitsPtr>::iterator findUnits(const UnitsPtr &units);
std::vector<UnitsPtr> mUnits;
};
std::vector<UnitsPtr>::iterator Model::ModelImpl::findUnits(const std::string &name)
{
return std::find_if(mUnits.begin(), mUnits.end(),
[=](const UnitsPtr &u) -> bool { return u->getName() == name; });
}
std::vector<UnitsPtr>::iterator Model::ModelImpl::findUnits(const UnitsPtr &units)
{
return std::find_if(mUnits.begin(), mUnits.end(),
[=](const UnitsPtr &u) -> bool { return u == units; });
}
Model::Model()
: mPimpl(new ModelImpl())
{
}
Model::~Model()
{
delete mPimpl;
}
Model::Model(const Model &rhs)
: ComponentEntity(rhs)
, mPimpl(new ModelImpl())
{
mPimpl->mUnits = rhs.mPimpl->mUnits;
}
Model::Model(Model &&rhs)
: ComponentEntity(std::move(rhs))
,mPimpl(rhs.mPimpl)
{
rhs.mPimpl = nullptr;
}
Model& Model::operator=(Model m)
{
ComponentEntity::operator= (m);
m.swap(*this);
return *this;
}
void Model::swap(Model &rhs)
{
std::swap(this->mPimpl, rhs.mPimpl);
}
void Model::doAddComponent(const ComponentPtr &c)
{
// Check for cycles.
if (!hasParent(c.get())) {
c->setParent(this);
ComponentEntity::doAddComponent(c);
}
}
void Model::addUnits(const UnitsPtr &units)
{
mPimpl->mUnits.push_back(units);
}
bool Model::removeUnits(size_t index)
{
bool status = false;
if (index < mPimpl->mUnits.size()) {
mPimpl->mUnits.erase(mPimpl->mUnits.begin() + index);
status = true;
}
return status;
}
bool Model::removeUnits(const std::string &name)
{
bool status = false;
auto result = mPimpl->findUnits(name);
if (result != mPimpl->mUnits.end()) {
mPimpl->mUnits.erase(result);
status = true;
}
return status;
}
bool Model::removeUnits(const UnitsPtr &units)
{
bool status = false;
auto result = mPimpl->findUnits(units);
if (result != mPimpl->mUnits.end()) {
mPimpl->mUnits.erase(result);
status = true;
}
return status;
}
void Model::removeAllUnits()
{
mPimpl->mUnits.clear();
}
bool Model::hasUnits(const std::string &name) const
{
return mPimpl->findUnits(name) != mPimpl->mUnits.end();
}
bool Model::hasUnits(const UnitsPtr &units) const
{
return mPimpl->findUnits(units) != mPimpl->mUnits.end();
}
UnitsPtr Model::getUnits(size_t index) const
{
UnitsPtr units = nullptr;
if (index < mPimpl->mUnits.size()) {
units = mPimpl->mUnits.at(index);
}
return units;
}
UnitsPtr Model::getUnits(const std::string &name) const
{
UnitsPtr units = nullptr;
auto result = mPimpl->findUnits(name);
if (result != mPimpl->mUnits.end()) {
units = *result;
}
return units;
}
UnitsPtr Model::takeUnits(size_t index)
{
UnitsPtr units = nullptr;
if (index < mPimpl->mUnits.size()) {
units = mPimpl->mUnits.at(index);
removeUnits(index);
units->clearParent();
}
return units;
}
UnitsPtr Model::takeUnits(const std::string &name)
{
return takeUnits(mPimpl->findUnits(name) - mPimpl->mUnits.begin());
}
bool Model::replaceUnits(size_t index, const UnitsPtr &units)
{
bool status = false;
if (removeUnits(index)) {
mPimpl->mUnits.insert(mPimpl->mUnits.begin() + index, units);
status = true;
}
return status;
}
bool Model::replaceUnits(const std::string &name, const UnitsPtr &units)
{
return replaceUnits(mPimpl->findUnits(name) - mPimpl->mUnits.begin(), units);
}
bool Model::replaceUnits(const UnitsPtr &oldUnits, const UnitsPtr &newUnits)
{
return replaceUnits(mPimpl->findUnits(oldUnits) - mPimpl->mUnits.begin(), newUnits);
}
size_t Model::unitsCount() const
{
return mPimpl->mUnits.size();
}
typedef std::shared_ptr<ImportedEntity> ImportedEntityPtr;
/**
* @brief Resolve the path of the given filename using the given base.
*
* Resolves the full path to the given @p filename using the @p base.
*
* This function is only intended to work with local files. It may not
* work with bases that use the 'file://' prefix.
*
* @param filename The @c std::string relative path from the base path.
* @param base The @c std::string location on local disk for determining the full path from.
* @return The full path from the @p base location to the @p filename
*/
std::string resolvePath(const std::string &filename, const std::string &base)
{
// We can be naive here as we know what we are dealing with
std::string path = base.substr(0, base.find_last_of('/')+1) + filename;
return path;
}
void resolveImport(ImportedEntityPtr importedEntity,
const std::string &baseFile)
{
if (importedEntity->isImport()) {
libcellml::ImportSourcePtr importSource = importedEntity->getImportSource();
if (!importSource->hasModel()) {
std::string url = resolvePath(importSource->getUrl(), baseFile);
std::ifstream file(url);
if (file.good()) {
std::stringstream buffer;
buffer << file.rdbuf();
libcellml::Parser parser;
libcellml::ModelPtr model = parser.parseModel(buffer.str());
if (model) {
importSource->setModel(model);
model->resolveImports(url);
}
}
}
}
}
void recurseResolveComponentImports(ComponentPtr component, const std::string &baseFile);
void resolveComponentImports(ComponentPtr parentComponent, const std::string &baseFile)
{
for (size_t n = 0; n < parentComponent->componentCount(); ++n)
{
libcellml::ComponentPtr component = parentComponent->getComponent(n);
recurseResolveComponentImports(component, baseFile);
}
}
void recurseResolveComponentImports(ComponentPtr component, const std::string &baseFile)
{
if (component->isImport()) {
resolveImport(component, baseFile);
} else {
resolveComponentImports(component, baseFile);
}
}
void Model::resolveImports(const std::string &baseFile)
{
for (size_t n = 0; n < unitsCount(); ++n)
{
libcellml::UnitsPtr units = getUnits(n);
resolveImport(units, baseFile);
}
for (size_t n = 0; n < componentCount(); ++n)
{
libcellml::ComponentPtr component = getComponent(n);
recurseResolveComponentImports(component, baseFile);
}
}
bool isUnresolvedImport(ImportedEntityPtr importedEntity)
{
bool unresolvedImport = false;
if (importedEntity->isImport()) {
libcellml::ImportSourcePtr importedSource = importedEntity->getImportSource();
if (!importedSource->hasModel()) {
unresolvedImport = true;
}
}
return unresolvedImport;
}
bool hasUnresolvedComponentImports(libcellml::ComponentPtr component);
bool recurseForUnresolvedComponentImports(ComponentPtr parentComponent)
{
bool unresolvedImports = false;
for (size_t n = 0; n < parentComponent->componentCount() && !unresolvedImports; ++n)
{
libcellml::ComponentPtr component = parentComponent->getComponent(n);
unresolvedImports = hasUnresolvedComponentImports(component);
}
return unresolvedImports;
}
bool hasUnresolvedComponentImports(libcellml::ComponentPtr component)
{
bool unresolvedImports = false;
if (component->isImport()) {
unresolvedImports = isUnresolvedImport(component);
if (!unresolvedImports) {
// Check that the imported component can import all it needs from it's model.
libcellml::ImportSourcePtr importedSource = component->getImportSource();
if (importedSource->hasModel()) {
ModelPtr importedModel = importedSource->getModel();
ComponentPtr importedComponent = importedModel->getComponent(component->getImportReference());
unresolvedImports = hasUnresolvedComponentImports(importedComponent);
}
}
} else {
unresolvedImports = recurseForUnresolvedComponentImports(component);
}
return unresolvedImports;
}
bool Model::hasUnresolvedImports() const
{
bool unresolvedImports = false;
for (size_t n = 0; n < unitsCount() && !unresolvedImports; ++n)
{
libcellml::UnitsPtr units = getUnits(n);
unresolvedImports = isUnresolvedImport(units);
}
for (size_t n = 0; n < componentCount() && !unresolvedImports; ++n)
{
libcellml::ComponentPtr component = getComponent(n);
unresolvedImports = hasUnresolvedComponentImports(component);
}
return unresolvedImports;
}
}
<|endoftext|> |
<commit_before>
#ifndef __FRAMEWORK_RECORDING_DISPATCHRECORDER_HXX_
#define __FRAMEWORK_RECORDING_DISPATCHRECORDER_HXX_
/** Attention: stl headers must(!) be included at first. Otherwhise it can make trouble
with solaris headers ...
*/
#include <vector>
// own includes
#ifndef __FRAMEWORK_THREADHELP_THREADHELPBASE_HXX_
#include <threadhelp/threadhelpbase.hxx>
#endif
#ifndef __FRAMEWORK_MACROS_XINTERFACE_HXX_
#include <macros/xinterface.hxx>
#endif
#ifndef __FRAMEWORK_MACROS_XTYPEPROVIDER_HXX_
#include <macros/xtypeprovider.hxx>
#endif
#ifndef __FRAMEWORK_MACROS_XSERVICEINFO_HXX_
#include <macros/xserviceinfo.hxx>
#endif
#ifndef __FRAMEWORK_MACROS_DEBUG_HXX_
#include <macros/debug.hxx>
#endif
#ifndef __FRAMEWORK_MACROS_GENERIC_HXX_
#include <macros/generic.hxx>
#endif
#ifndef __FRAMEWORK_GENERAL_H_
#include <general.h>
#endif
#ifndef _RTL_USTRING_HXX_
#include <rtl/ustring.hxx>
#endif
#ifndef _RTL_USTRBUF_HXX_
#include <rtl/ustrbuf.hxx>
#endif
#ifndef _COM_SUN_STAR_LANG_XTYPEPROVIDER_HPP_
#include <com/sun/star/lang/XTypeProvider.hpp>
#endif
#ifndef _COM_SUN_STAR_FRAME_XDISPATCHRECORDER_HPP_
#include <com/sun/star/frame/XDispatchRecorder.hpp>
#endif
#ifndef _COM_SUN_STAR_FRAME_DISPATCHSTATEMENT_HPP_
#include <com/sun/star/frame/DispatchStatement.hpp>
#endif
#ifndef _COM_SUN_STAR_CONTAINER_XINDEXREPLACE_HPP_
#include <com/sun/star/container/XIndexReplace.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_XMULTISERVICEFACTORY_HPP_
#include <com/sun/star/lang/XMultiServiceFactory.HPP>
#endif
#ifndef _COM_SUN_STAR_UTIL_URL_HPP_
#include <com/sun/star/util/URL.hpp>
#endif
#ifndef _COM_SUN_STAR_BEANS_PROPERTYVALUE_HPP_
#include <com/sun/star/beans/PropertyValue.hpp>
#endif
#ifndef _COM_SUN_STAR_UNO_RUNTIMEEXCEPTION_HDL_
#include <com/sun/star/uno/RuntimeException.hdl>
#endif
#ifndef _COM_SUN_STAR_SCRIPT_XTYPECONVERTER_HPP_
#include <com/sun/star/script/XTypeConverter.hpp>
#endif
#ifndef _CPPUHELPER_WEAK_HXX_
#include <cppuhelper/weak.hxx>
#endif
namespace framework{
typedef ::std::vector < com::sun::star::frame::DispatchStatement > DispatchStatementList;
class DispatchRecorder
: private ThreadHelpBase
, public css::lang::XTypeProvider
, public css::lang::XServiceInfo
, public css::frame::XDispatchRecorder
, public css::container::XIndexReplace
, public ::cppu::OWeakObject
{
// private member
private:
css::uno::Reference< css::lang::XMultiServiceFactory > m_xSMGR ;
DispatchStatementList m_aStatements;
sal_Int32 m_nRecordingID ;
css::uno::Reference< css::script::XTypeConverter > m_xConverter;
// public interface
public:
DispatchRecorder( const css::uno::Reference< css::lang::XMultiServiceFactory >& xSMGR );
~DispatchRecorder();
// XInterface, XTypeProvider, XServiceInfo
DECLARE_XINTERFACE
DECLARE_XTYPEPROVIDER
DECLARE_XSERVICEINFO
// XDispatchRecorder
virtual void SAL_CALL startRecording ( const css::uno::Reference< css::frame::XFrame >& xFrame ) throw( css::uno::RuntimeException );
virtual void SAL_CALL recordDispatch ( const css::util::URL& aURL, const css::uno::Sequence< css::beans::PropertyValue >& lArguments ) throw( css::uno::RuntimeException );
virtual void SAL_CALL recordDispatchAsComment( const css::util::URL& aURL, const css::uno::Sequence< css::beans::PropertyValue >& lArguments ) throw( css::uno::RuntimeException );
virtual void SAL_CALL endRecording () throw( css::uno::RuntimeException );
virtual ::rtl::OUString SAL_CALL getRecordedMacro () throw( css::uno::RuntimeException );
virtual com::sun::star::uno::Type SAL_CALL getElementType() throw (::com::sun::star::uno::RuntimeException);
virtual sal_Bool SAL_CALL hasElements() throw (::com::sun::star::uno::RuntimeException);
virtual sal_Int32 SAL_CALL getCount() throw (::com::sun::star::uno::RuntimeException);
virtual com::sun::star::uno::Any SAL_CALL getByIndex(long int) throw (com::sun::star::uno::RuntimeException, com::sun::star::lang::WrappedTargetException, com::sun::star::lang::IndexOutOfBoundsException);
virtual void SAL_CALL replaceByIndex(long int, const com::sun::star::uno::Any&) throw (::com::sun::star::lang::IllegalArgumentException, ::com::sun::star::lang::IndexOutOfBoundsException, ::com::sun::star::lang::WrappedTargetException, ::com::sun::star::uno::RuntimeException);
// private functions
private:
void SAL_CALL implts_recordMacro( const ::rtl::OUString& aURL,
const css::uno::Sequence< css::beans::PropertyValue >& lArguments,
sal_Bool bAsComment, ::rtl::OUStringBuffer& );
void SAL_CALL AppendToBuffer( css::uno::Any aValue, ::rtl::OUStringBuffer& aArgumentBuffer );
}; // class DispatcRecorder
} // namespace framework
#endif // define __FRAMEWORK...
<commit_msg>INTEGRATION: CWS long2int (1.6.532); FILE MERGED 2005/10/26 18:07:14 kendy 1.6.532.1: #i56715# Trivial long/ULONG -> sal_Int32/sal_uInt32 patches extracted from ooo64bit02 CWS.<commit_after>
#ifndef __FRAMEWORK_RECORDING_DISPATCHRECORDER_HXX_
#define __FRAMEWORK_RECORDING_DISPATCHRECORDER_HXX_
/** Attention: stl headers must(!) be included at first. Otherwhise it can make trouble
with solaris headers ...
*/
#include <vector>
// own includes
#ifndef __FRAMEWORK_THREADHELP_THREADHELPBASE_HXX_
#include <threadhelp/threadhelpbase.hxx>
#endif
#ifndef __FRAMEWORK_MACROS_XINTERFACE_HXX_
#include <macros/xinterface.hxx>
#endif
#ifndef __FRAMEWORK_MACROS_XTYPEPROVIDER_HXX_
#include <macros/xtypeprovider.hxx>
#endif
#ifndef __FRAMEWORK_MACROS_XSERVICEINFO_HXX_
#include <macros/xserviceinfo.hxx>
#endif
#ifndef __FRAMEWORK_MACROS_DEBUG_HXX_
#include <macros/debug.hxx>
#endif
#ifndef __FRAMEWORK_MACROS_GENERIC_HXX_
#include <macros/generic.hxx>
#endif
#ifndef __FRAMEWORK_GENERAL_H_
#include <general.h>
#endif
#ifndef _RTL_USTRING_HXX_
#include <rtl/ustring.hxx>
#endif
#ifndef _RTL_USTRBUF_HXX_
#include <rtl/ustrbuf.hxx>
#endif
#ifndef _COM_SUN_STAR_LANG_XTYPEPROVIDER_HPP_
#include <com/sun/star/lang/XTypeProvider.hpp>
#endif
#ifndef _COM_SUN_STAR_FRAME_XDISPATCHRECORDER_HPP_
#include <com/sun/star/frame/XDispatchRecorder.hpp>
#endif
#ifndef _COM_SUN_STAR_FRAME_DISPATCHSTATEMENT_HPP_
#include <com/sun/star/frame/DispatchStatement.hpp>
#endif
#ifndef _COM_SUN_STAR_CONTAINER_XINDEXREPLACE_HPP_
#include <com/sun/star/container/XIndexReplace.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_XMULTISERVICEFACTORY_HPP_
#include <com/sun/star/lang/XMultiServiceFactory.HPP>
#endif
#ifndef _COM_SUN_STAR_UTIL_URL_HPP_
#include <com/sun/star/util/URL.hpp>
#endif
#ifndef _COM_SUN_STAR_BEANS_PROPERTYVALUE_HPP_
#include <com/sun/star/beans/PropertyValue.hpp>
#endif
#ifndef _COM_SUN_STAR_UNO_RUNTIMEEXCEPTION_HDL_
#include <com/sun/star/uno/RuntimeException.hdl>
#endif
#ifndef _COM_SUN_STAR_SCRIPT_XTYPECONVERTER_HPP_
#include <com/sun/star/script/XTypeConverter.hpp>
#endif
#ifndef _CPPUHELPER_WEAK_HXX_
#include <cppuhelper/weak.hxx>
#endif
namespace framework{
typedef ::std::vector < com::sun::star::frame::DispatchStatement > DispatchStatementList;
class DispatchRecorder
: private ThreadHelpBase
, public css::lang::XTypeProvider
, public css::lang::XServiceInfo
, public css::frame::XDispatchRecorder
, public css::container::XIndexReplace
, public ::cppu::OWeakObject
{
// private member
private:
css::uno::Reference< css::lang::XMultiServiceFactory > m_xSMGR ;
DispatchStatementList m_aStatements;
sal_Int32 m_nRecordingID ;
css::uno::Reference< css::script::XTypeConverter > m_xConverter;
// public interface
public:
DispatchRecorder( const css::uno::Reference< css::lang::XMultiServiceFactory >& xSMGR );
~DispatchRecorder();
// XInterface, XTypeProvider, XServiceInfo
DECLARE_XINTERFACE
DECLARE_XTYPEPROVIDER
DECLARE_XSERVICEINFO
// XDispatchRecorder
virtual void SAL_CALL startRecording ( const css::uno::Reference< css::frame::XFrame >& xFrame ) throw( css::uno::RuntimeException );
virtual void SAL_CALL recordDispatch ( const css::util::URL& aURL, const css::uno::Sequence< css::beans::PropertyValue >& lArguments ) throw( css::uno::RuntimeException );
virtual void SAL_CALL recordDispatchAsComment( const css::util::URL& aURL, const css::uno::Sequence< css::beans::PropertyValue >& lArguments ) throw( css::uno::RuntimeException );
virtual void SAL_CALL endRecording () throw( css::uno::RuntimeException );
virtual ::rtl::OUString SAL_CALL getRecordedMacro () throw( css::uno::RuntimeException );
virtual com::sun::star::uno::Type SAL_CALL getElementType() throw (::com::sun::star::uno::RuntimeException);
virtual sal_Bool SAL_CALL hasElements() throw (::com::sun::star::uno::RuntimeException);
virtual sal_Int32 SAL_CALL getCount() throw (::com::sun::star::uno::RuntimeException);
virtual com::sun::star::uno::Any SAL_CALL getByIndex(sal_Int32) throw (com::sun::star::uno::RuntimeException, com::sun::star::lang::WrappedTargetException, com::sun::star::lang::IndexOutOfBoundsException);
virtual void SAL_CALL replaceByIndex(sal_Int32, const com::sun::star::uno::Any&) throw (::com::sun::star::lang::IllegalArgumentException, ::com::sun::star::lang::IndexOutOfBoundsException, ::com::sun::star::lang::WrappedTargetException, ::com::sun::star::uno::RuntimeException);
// private functions
private:
void SAL_CALL implts_recordMacro( const ::rtl::OUString& aURL,
const css::uno::Sequence< css::beans::PropertyValue >& lArguments,
sal_Bool bAsComment, ::rtl::OUStringBuffer& );
void SAL_CALL AppendToBuffer( css::uno::Any aValue, ::rtl::OUStringBuffer& aArgumentBuffer );
}; // class DispatcRecorder
} // namespace framework
#endif // define __FRAMEWORK...
<|endoftext|> |
<commit_before>/*
* DBUSTL - DBus Template Library
*
* Copyright (C) 2008 Fabien Chevalier <fabchevalier@free.fr>
*
*
* This file is part of the DBus Template Library.
*
* The DBus Template 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.
*
* DBus Template 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 DBus Template Library. If not, see <http://www.gnu.org/licenses/>.
*
*/
#include <dbustl-1/Message>
#include <cassert>
namespace dbustl {
Message::Message(DBusMessage *msg)
: _msg(msg), _valid(true), _iteratorInitialized(false), _parsedArguments(0)
{
}
Message::Message(const Message& other)
{
if(other._msg) {
dbus_message_ref(other._msg);
}
_msg = other._msg;
_valid = other._valid;
_iteratorInitialized = other._iteratorInitialized;
_parsedArguments = other._parsedArguments;
};
Message::~Message()
{
if(_msg) {
dbus_message_unref(_msg);
}
};
Message& Message::operator=(Message& other) {
if(other._msg) {
dbus_message_ref(other._msg);
}
if(_msg) {
dbus_message_unref(_msg);
}
_valid = other._valid;
_iteratorInitialized = other._iteratorInitialized;
_parsedArguments = other._parsedArguments;
_msg = other._msg;
return *this;
};
Message& Message::operator=(DBusMessage *msg) {
if(_msg) {
dbus_message_unref(_msg);
}
_valid = true;
_iteratorInitialized = false;
_parsedArguments = 0;
_msg = msg;
return *this;
};
std::string Message::member() const
{
const char * mem = NULL;
if(_msg) {
mem = dbus_message_get_member(_msg);
}
return mem != NULL ? mem : "";
}
std::string Message::interface() const
{
const char * intf = NULL;
if(_msg) {
intf = dbus_message_get_interface(_msg);
}
return intf != NULL ? intf : "";
}
bool Message::serializationInit()
{
assert(_msg);
if(!_iteratorInitialized) {
dbus_message_iter_init_append(_msg, &_it);
_iteratorInitialized = true;
}
//If message is already screwed up, we just discard the other arguments
return _valid;
}
bool Message::deSerializationInit(int *arg_type)
{
assert(_msg);
if(_iteratorInitialized) {
dbus_message_iter_next(&_it);
}
else {
dbus_message_iter_init(_msg, &_it);
_iteratorInitialized = true;
}
//If we are past the end, we mark the message as invalid
int type = dbus_message_iter_get_arg_type(&_it);
if(type != DBUS_TYPE_INVALID) {
*arg_type = type;
}
else {
_valid = false;
}
return _valid;
}
}
<commit_msg>Removed bogus semicolon<commit_after>/*
* DBUSTL - DBus Template Library
*
* Copyright (C) 2008 Fabien Chevalier <fabchevalier@free.fr>
*
*
* This file is part of the DBus Template Library.
*
* The DBus Template 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.
*
* DBus Template 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 DBus Template Library. If not, see <http://www.gnu.org/licenses/>.
*
*/
#include <dbustl-1/Message>
#include <cassert>
namespace dbustl {
Message::Message(DBusMessage *msg)
: _msg(msg), _valid(true), _iteratorInitialized(false), _parsedArguments(0)
{
}
Message::Message(const Message& other)
{
if(other._msg) {
dbus_message_ref(other._msg);
}
_msg = other._msg;
_valid = other._valid;
_iteratorInitialized = other._iteratorInitialized;
_parsedArguments = other._parsedArguments;
}
Message::~Message()
{
if(_msg) {
dbus_message_unref(_msg);
}
}
Message& Message::operator=(Message& other) {
if(other._msg) {
dbus_message_ref(other._msg);
}
if(_msg) {
dbus_message_unref(_msg);
}
_valid = other._valid;
_iteratorInitialized = other._iteratorInitialized;
_parsedArguments = other._parsedArguments;
_msg = other._msg;
return *this;
}
Message& Message::operator=(DBusMessage *msg) {
if(_msg) {
dbus_message_unref(_msg);
}
_valid = true;
_iteratorInitialized = false;
_parsedArguments = 0;
_msg = msg;
return *this;
}
std::string Message::member() const
{
const char * mem = NULL;
if(_msg) {
mem = dbus_message_get_member(_msg);
}
return mem != NULL ? mem : "";
}
std::string Message::interface() const
{
const char * intf = NULL;
if(_msg) {
intf = dbus_message_get_interface(_msg);
}
return intf != NULL ? intf : "";
}
bool Message::serializationInit()
{
assert(_msg);
if(!_iteratorInitialized) {
dbus_message_iter_init_append(_msg, &_it);
_iteratorInitialized = true;
}
//If message is already screwed up, we just discard the other arguments
return _valid;
}
bool Message::deSerializationInit(int *arg_type)
{
assert(_msg);
if(_iteratorInitialized) {
dbus_message_iter_next(&_it);
}
else {
dbus_message_iter_init(_msg, &_it);
_iteratorInitialized = true;
}
//If we are past the end, we mark the message as invalid
int type = dbus_message_iter_get_arg_type(&_it);
if(type != DBUS_TYPE_INVALID) {
*arg_type = type;
}
else {
_valid = false;
}
return _valid;
}
}
<|endoftext|> |
<commit_before>// Copyright (c) 2011-2020 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include <qt/bantablemodel.h>
#include <interfaces/node.h>
#include <net_types.h> // For banmap_t
#include <utility>
#include <QDateTime>
#include <QList>
#include <QLocale>
#include <QModelIndex>
#include <QVariant>
bool BannedNodeLessThan::operator()(const CCombinedBan& left, const CCombinedBan& right) const
{
const CCombinedBan* pLeft = &left;
const CCombinedBan* pRight = &right;
if (order == Qt::DescendingOrder)
std::swap(pLeft, pRight);
switch(column)
{
case BanTableModel::Address:
return pLeft->subnet.ToString().compare(pRight->subnet.ToString()) < 0;
case BanTableModel::Bantime:
return pLeft->banEntry.nBanUntil < pRight->banEntry.nBanUntil;
}
return false;
}
// private implementation
class BanTablePriv
{
public:
/** Local cache of peer information */
QList<CCombinedBan> cachedBanlist;
/** Column to sort nodes by (default to unsorted) */
int sortColumn{-1};
/** Order (ascending or descending) to sort nodes by */
Qt::SortOrder sortOrder;
/** Pull a full list of banned nodes from CNode into our cache */
void refreshBanlist(interfaces::Node& node)
{
banmap_t banMap;
node.getBanned(banMap);
cachedBanlist.clear();
cachedBanlist.reserve(banMap.size());
for (const auto& entry : banMap)
{
CCombinedBan banEntry;
banEntry.subnet = entry.first;
banEntry.banEntry = entry.second;
cachedBanlist.append(banEntry);
}
if (sortColumn >= 0)
// sort cachedBanlist (use stable sort to prevent rows jumping around unnecessarily)
std::stable_sort(cachedBanlist.begin(), cachedBanlist.end(), BannedNodeLessThan(sortColumn, sortOrder));
}
int size() const
{
return cachedBanlist.size();
}
CCombinedBan *index(int idx)
{
if (idx >= 0 && idx < cachedBanlist.size())
return &cachedBanlist[idx];
return nullptr;
}
};
BanTableModel::BanTableModel(interfaces::Node& node, QObject* parent) :
QAbstractTableModel(parent),
m_node(node)
{
columns << tr("IP/Netmask") << tr("Banned Until");
priv.reset(new BanTablePriv());
// load initial data
refresh();
}
BanTableModel::~BanTableModel()
{
// Intentionally left empty
}
int BanTableModel::rowCount(const QModelIndex &parent) const
{
if (parent.isValid()) {
return 0;
}
return priv->size();
}
int BanTableModel::columnCount(const QModelIndex &parent) const
{
if (parent.isValid()) {
return 0;
}
return columns.length();
}
QVariant BanTableModel::data(const QModelIndex &index, int role) const
{
if(!index.isValid())
return QVariant();
CCombinedBan *rec = static_cast<CCombinedBan*>(index.internalPointer());
if (role == Qt::DisplayRole) {
switch(index.column())
{
case Address:
return QString::fromStdString(rec->subnet.ToString());
case Bantime:
QDateTime date = QDateTime::fromMSecsSinceEpoch(0);
date = date.addSecs(rec->banEntry.nBanUntil);
return QLocale::system().toString(date, QLocale::LongFormat);
}
}
return QVariant();
}
QVariant BanTableModel::headerData(int section, Qt::Orientation orientation, int role) const
{
if(orientation == Qt::Horizontal)
{
if(role == Qt::DisplayRole && section < columns.size())
{
return columns[section];
}
}
return QVariant();
}
Qt::ItemFlags BanTableModel::flags(const QModelIndex &index) const
{
if (!index.isValid()) return Qt::NoItemFlags;
Qt::ItemFlags retval = Qt::ItemIsSelectable | Qt::ItemIsEnabled;
return retval;
}
QModelIndex BanTableModel::index(int row, int column, const QModelIndex &parent) const
{
Q_UNUSED(parent);
CCombinedBan *data = priv->index(row);
if (data)
return createIndex(row, column, data);
return QModelIndex();
}
void BanTableModel::refresh()
{
Q_EMIT layoutAboutToBeChanged();
priv->refreshBanlist(m_node);
Q_EMIT layoutChanged();
}
void BanTableModel::sort(int column, Qt::SortOrder order)
{
priv->sortColumn = column;
priv->sortOrder = order;
refresh();
}
bool BanTableModel::shouldShow()
{
return priv->size() > 0;
}
<commit_msg>qt, refactor: Use enum type as switch argument in BanTableModel<commit_after>// Copyright (c) 2011-2020 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include <qt/bantablemodel.h>
#include <interfaces/node.h>
#include <net_types.h> // For banmap_t
#include <utility>
#include <QDateTime>
#include <QList>
#include <QLocale>
#include <QModelIndex>
#include <QVariant>
bool BannedNodeLessThan::operator()(const CCombinedBan& left, const CCombinedBan& right) const
{
const CCombinedBan* pLeft = &left;
const CCombinedBan* pRight = &right;
if (order == Qt::DescendingOrder)
std::swap(pLeft, pRight);
switch (static_cast<BanTableModel::ColumnIndex>(column)) {
case BanTableModel::Address:
return pLeft->subnet.ToString().compare(pRight->subnet.ToString()) < 0;
case BanTableModel::Bantime:
return pLeft->banEntry.nBanUntil < pRight->banEntry.nBanUntil;
} // no default case, so the compiler can warn about missing cases
assert(false);
}
// private implementation
class BanTablePriv
{
public:
/** Local cache of peer information */
QList<CCombinedBan> cachedBanlist;
/** Column to sort nodes by (default to unsorted) */
int sortColumn{-1};
/** Order (ascending or descending) to sort nodes by */
Qt::SortOrder sortOrder;
/** Pull a full list of banned nodes from CNode into our cache */
void refreshBanlist(interfaces::Node& node)
{
banmap_t banMap;
node.getBanned(banMap);
cachedBanlist.clear();
cachedBanlist.reserve(banMap.size());
for (const auto& entry : banMap)
{
CCombinedBan banEntry;
banEntry.subnet = entry.first;
banEntry.banEntry = entry.second;
cachedBanlist.append(banEntry);
}
if (sortColumn >= 0)
// sort cachedBanlist (use stable sort to prevent rows jumping around unnecessarily)
std::stable_sort(cachedBanlist.begin(), cachedBanlist.end(), BannedNodeLessThan(sortColumn, sortOrder));
}
int size() const
{
return cachedBanlist.size();
}
CCombinedBan *index(int idx)
{
if (idx >= 0 && idx < cachedBanlist.size())
return &cachedBanlist[idx];
return nullptr;
}
};
BanTableModel::BanTableModel(interfaces::Node& node, QObject* parent) :
QAbstractTableModel(parent),
m_node(node)
{
columns << tr("IP/Netmask") << tr("Banned Until");
priv.reset(new BanTablePriv());
// load initial data
refresh();
}
BanTableModel::~BanTableModel()
{
// Intentionally left empty
}
int BanTableModel::rowCount(const QModelIndex &parent) const
{
if (parent.isValid()) {
return 0;
}
return priv->size();
}
int BanTableModel::columnCount(const QModelIndex &parent) const
{
if (parent.isValid()) {
return 0;
}
return columns.length();
}
QVariant BanTableModel::data(const QModelIndex &index, int role) const
{
if(!index.isValid())
return QVariant();
CCombinedBan *rec = static_cast<CCombinedBan*>(index.internalPointer());
const auto column = static_cast<ColumnIndex>(index.column());
if (role == Qt::DisplayRole) {
switch (column) {
case Address:
return QString::fromStdString(rec->subnet.ToString());
case Bantime:
QDateTime date = QDateTime::fromMSecsSinceEpoch(0);
date = date.addSecs(rec->banEntry.nBanUntil);
return QLocale::system().toString(date, QLocale::LongFormat);
} // no default case, so the compiler can warn about missing cases
assert(false);
}
return QVariant();
}
QVariant BanTableModel::headerData(int section, Qt::Orientation orientation, int role) const
{
if(orientation == Qt::Horizontal)
{
if(role == Qt::DisplayRole && section < columns.size())
{
return columns[section];
}
}
return QVariant();
}
Qt::ItemFlags BanTableModel::flags(const QModelIndex &index) const
{
if (!index.isValid()) return Qt::NoItemFlags;
Qt::ItemFlags retval = Qt::ItemIsSelectable | Qt::ItemIsEnabled;
return retval;
}
QModelIndex BanTableModel::index(int row, int column, const QModelIndex &parent) const
{
Q_UNUSED(parent);
CCombinedBan *data = priv->index(row);
if (data)
return createIndex(row, column, data);
return QModelIndex();
}
void BanTableModel::refresh()
{
Q_EMIT layoutAboutToBeChanged();
priv->refreshBanlist(m_node);
Q_EMIT layoutChanged();
}
void BanTableModel::sort(int column, Qt::SortOrder order)
{
priv->sortColumn = column;
priv->sortOrder = order;
refresh();
}
bool BanTableModel::shouldShow()
{
return priv->size() > 0;
}
<|endoftext|> |
<commit_before>#pragma once
#include <type_traits>
namespace stx {
namespace detail {
template<typename T>
struct pointer_to_struct {
using type = T*;
};
template<typename T>
struct pointer_to_struct<T[]> {
using type = T*;
};
} // namespace detail
template<typename T>
using pointer_to = typename detail::pointer_to_struct<T>::type;
template<typename T>
using remove_pointer = typename std::remove_pointer<T>::type;
template<typename T> constexpr static
bool is_array = std::is_array<T>::value;
template<typename T>
struct default_delete {
using pointer = pointer_to<T>;
inline
void operator()(pointer p) const noexcept {
delete p;
}
};
} // namespace stx
<commit_msg>Fixed default_delete for arrays<commit_after>#pragma once
#include <type_traits>
namespace stx {
namespace detail {
template<typename T>
struct pointer_to_struct {
using type = T*;
};
template<typename T>
struct pointer_to_struct<T[]> {
using type = T*;
};
} // namespace detail
template<typename T>
using pointer_to = typename detail::pointer_to_struct<T>::type;
template<typename T>
using remove_pointer = typename std::remove_pointer<T>::type;
template<typename T> constexpr static
bool is_array = std::is_array<T>::value;
template<typename T>
struct default_delete {
using pointer = pointer_to<T>;
inline
void operator()(pointer p) const noexcept {
if(std::is_array<T>::value)
delete[] p;
else
delete p;
}
};
} // namespace stx
<|endoftext|> |
<commit_before>#include "File.h"
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <stdio.h> // REMOVE
#define DATAPAGE_OFFSET(idx) (INDEXPAGE_OFFSET+indexPageSize+idx*dataPageSize)
File::File()
{
uint32_t i;
prev = this;
next = this;
indexPageSize = DEFAULT_INDEXPAGE_SIZE;
dataPageSize = DEFAULT_DATAPAGE_SIZE;
numDataPageSlots = DEFAULT_NUM_DATAPAGES;
isOverflowing = false;
newFile = true;
indexPage.SetOffset(INDEXPAGE_OFFSET);
indexPage.SetPageSize(indexPageSize);
indexPage.SetNumDataPageSlots(numDataPageSlots);
dataPages = (DataPage**) malloc(sizeof(DataPage*) * numDataPageSlots);
for (i = 0; i < numDataPageSlots; i++)
dataPages[i] = NULL;
numDataPages = 0;
fd = -1;
}
File::~File()
{
free(dataPages);
}
void File::Open(char* filepath_)
{
struct stat st;
filepath.Write(filepath_);
filepath.NullTerminate();
fd = open(filepath.GetBuffer(), O_RDWR | O_CREAT, S_IRUSR | S_IWUSR);
if (fd < 0)
ASSERT_FAIL();
fstat(fd, &st);
if (st.st_size > 0)
Read();
}
void File::Flush()
{
}
void File::Close()
{
close(fd);
fd = -1;
}
bool File::Get(ReadBuffer& key, ReadBuffer& value)
{
int32_t index;
index = Locate(key);
if (index < 0)
return false;
return dataPages[index]->Get(key, value);
}
bool File::Set(ReadBuffer& key, ReadBuffer& value, bool copy)
{
int32_t index;
ReadBuffer rb;
if (key.GetLength() + value.GetLength() > DATAPAGE_MAX_KV_SIZE(dataPageSize))
return false;
index = Locate(key);
if (index < 0)
{
index = 0;
assert(dataPages[index] == NULL);
dataPages[index] = new DataPage;
dataPages[index]->SetOffset(DATAPAGE_OFFSET(index));
dataPages[index]->SetPageSize(dataPageSize);
numDataPages++;
indexPage.Add(key, index, true); // TODO
MarkPageDirty(&indexPage);
}
dataPages[index]->Set(key, value, copy);
MarkPageDirty(dataPages[index]);
// update index:
rb = dataPages[index]->FirstKey();
if (ReadBuffer::LessThan(key, rb))
{
indexPage.Update(key, index, copy);
MarkPageDirty(&indexPage);
}
if (dataPages[index]->IsOverflowing())
SplitDataPage(index);
return true;
}
void File::Delete(ReadBuffer& key)
{
int32_t index;
index = Locate(key);
if (index < 0)
return;
dataPages[index]->Delete(key);
MarkPageDirty(dataPages[index]);
if (dataPages[index]->IsEmpty())
{
indexPage.Remove(dataPages[index]->FirstKey());
MarkPageDirty(&indexPage);
}
}
ReadBuffer File::FirstKey()
{
return indexPage.FirstKey();
}
bool File::IsOverflowing()
{
return isOverflowing || indexPage.IsOverflowing();
}
File* File::SplitFile()
{
File* newFile;
uint32_t index, newIndex, num;
assert(numDataPageSlots == numDataPages);
newFile = new File;
newFile->indexPageSize = indexPageSize;
newFile->dataPageSize = dataPageSize;
newFile->numDataPageSlots = numDataPageSlots;
newFile->indexPage.SetPageSize(indexPageSize);
newFile->indexPage.SetNumDataPageSlots(numDataPageSlots);
ReorderPages();
num = numDataPages;
for (index = numDataPageSlots / 2, newIndex = 0; index < num; index++, newIndex++)
{
newFile->dataPages[newIndex] = dataPages[index];
dataPages[index] = NULL;
newFile->dataPages[newIndex]->SetOffset(DATAPAGE_OFFSET(newIndex));
numDataPages--;
newFile->numDataPages++;
indexPage.Remove(newFile->dataPages[newIndex]->FirstKey());
newFile->indexPage.Add(newFile->dataPages[newIndex]->FirstKey(), newIndex, true);
}
isOverflowing = false;
for (index = 0; index < numDataPages; index++)
{
if (dataPages[index]->IsOverflowing())
SplitDataPage(index);
}
assert(isOverflowing == false);
newFile->isOverflowing = false;
for (index = 0; index < newFile->numDataPages; index++)
{
if (newFile->dataPages[index]->IsOverflowing())
newFile->SplitDataPage(index);
}
assert(newFile->isOverflowing == false);
ReorderFile();
newFile->ReorderFile();
return newFile;
}
void File::Read()
{
char* p;
unsigned i;
int length;
Buffer buffer;
ReadBuffer readBuffer;
newFile = false;
buffer.Allocate(12);
if (pread(fd, (void*) buffer.GetBuffer(), 12, 0) < 0)
ASSERT_FAIL();
p = buffer.GetBuffer();
indexPageSize = FromLittle32(*((uint32_t*) p));
p += 4;
dataPageSize = FromLittle32(*((uint32_t*) p));
p += 4;
numDataPageSlots = FromLittle32(*((uint32_t*) p));
p += 4;
indexPage.SetOffset(INDEXPAGE_OFFSET);
indexPage.SetPageSize(indexPageSize);
indexPage.SetNumDataPageSlots(numDataPageSlots);
buffer.Allocate(indexPageSize);
length = pread(fd, (void*) buffer.GetBuffer(), indexPageSize, INDEXPAGE_OFFSET);
if (length < 0)
ASSERT_FAIL();
buffer.SetLength(length);
readBuffer.Wrap(buffer);
indexPage.Read(readBuffer);
if (dataPages != NULL)
free(dataPages);
dataPages = (DataPage**) malloc(sizeof(DataPage*) * numDataPageSlots);
for (i = 0; i < numDataPageSlots; i++)
dataPages[i] = NULL;
numDataPages = indexPage.NumEntries();
}
void File::ReadRest()
{
KeyIndex* it;
// TODO make sure this IO occurs in order!
for (it = indexPage.keys.First(); it != NULL; it = indexPage.keys.Next(it))
if (dataPages[it->index] == NULL)
LoadDataPage(it->index);
}
void File::Write()
{
Buffer buffer;
Page* it;
char* p;
if (newFile)
{
buffer.Allocate(12);
p = buffer.GetBuffer();
*((uint32_t*) p) = ToLittle32(indexPageSize);
p += 4;
*((uint32_t*) p) = ToLittle32(dataPageSize);
p += 4;
*((uint32_t*) p) = ToLittle32(numDataPageSlots);
p += 4;
if (pwrite(fd, (const void *) buffer.GetBuffer(), 12, 0) < 0)
ASSERT_FAIL();
}
// TODO: write these in offset order
for (it = dirtyPages.First(); it != NULL; it = dirtyPages.Remove(it))
{
buffer.Allocate(it->GetPageSize());
buffer.Zero();
// printf("writing at offset %u\n", it->GetOffset());
it->Write(buffer);
if (pwrite(fd, buffer.GetBuffer(), it->GetPageSize(), it->GetOffset()) < 0)
ASSERT_FAIL();
it->SetDirty(false);
}
}
int32_t File::Locate(ReadBuffer& key)
{
int32_t index;
index = indexPage.Locate(key);
if (index < 0)
return index; // not in file
if (dataPages[index] == NULL)
LoadDataPage(index);
return index;
}
void File::LoadDataPage(uint32_t index)
{
Buffer buffer;
ReadBuffer readBuffer;
int length;
dataPages[index] = new DataPage;
dataPages[index]->SetOffset(DATAPAGE_OFFSET(index));
dataPages[index]->SetPageSize(dataPageSize);
// printf("loading data page at index %u\n", index);
buffer.Allocate(dataPageSize);
// printf("reading page %u from %u\n", index, DATAPAGE_OFFSET(index));
length = pread(fd, buffer.GetBuffer(), dataPageSize, DATAPAGE_OFFSET(index));
if (length < 0)
ASSERT_FAIL();
buffer.SetLength(length);
readBuffer.Wrap(buffer);
dataPages[index]->Read(readBuffer);
}
void File::MarkPageDirty(Page* page)
{
if (!page->IsDirty())
{
page->SetDirty(true);
dirtyPages.Append(page);
}
}
void File::SplitDataPage(uint32_t index)
{
uint32_t newIndex;
DataPage* newPage;
if (numDataPages < numDataPageSlots)
{
newPage = dataPages[index]->SplitDataPage();
numDataPages++;
newIndex = indexPage.NextFreeDataPage();
newPage->SetOffset(DATAPAGE_OFFSET(newIndex));
assert(dataPages[newIndex] == NULL);
dataPages[newIndex] = newPage;
indexPage.Add(newPage->FirstKey(), newIndex, true); // TODO
// if (newPage->MustSplit())
// {
// if (numDataPages < numDataPageSlots)
// {
// newPage = newPage->Split();
// assert(newPage->MustSplit() == false);
// TOOD
// newIndex = indexPage.NextFreeDataPage();
// indexPage.Add(newPage->FirstKey(), newIndex, true);
// }
// else
// mustSplit = true;
// }
}
else
isOverflowing = true;
}
void File::ReorderPages()
{
uint32_t newIndex, oldIndex, i;
KeyIndex* it;
DataPage** newDataPages;
newDataPages = (DataPage**) calloc(numDataPageSlots, sizeof(DataPage*));
for (it = indexPage.keys.First(), newIndex = 0; it != NULL; it = indexPage.keys.Next(it), newIndex++)
{
oldIndex = it->index;
assert(dataPages[oldIndex] != NULL);
it->index = newIndex;
newDataPages[newIndex] = dataPages[oldIndex];
newDataPages[newIndex]->SetOffset(DATAPAGE_OFFSET(newIndex));
}
free(dataPages);
dataPages = newDataPages;
indexPage.freeDataPages.Clear();
for (i = numDataPages; i < numDataPageSlots; i++)
indexPage.freeDataPages.Add(i);
}
void File::ReorderFile()
{
uint32_t index;
dirtyPages.Clear();
ReorderPages();
indexPage.SetDirty(false);
MarkPageDirty(&indexPage);
for (index = 0; index < numDataPages; index++)
{
dataPages[index]->SetDirty(false);
MarkPageDirty(dataPages[index]);
}
}
<commit_msg>Fixed memleak in File.<commit_after>#include "File.h"
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <stdio.h> // REMOVE
#define DATAPAGE_OFFSET(idx) (INDEXPAGE_OFFSET+indexPageSize+idx*dataPageSize)
File::File()
{
uint32_t i;
prev = this;
next = this;
indexPageSize = DEFAULT_INDEXPAGE_SIZE;
dataPageSize = DEFAULT_DATAPAGE_SIZE;
numDataPageSlots = DEFAULT_NUM_DATAPAGES;
isOverflowing = false;
newFile = true;
indexPage.SetOffset(INDEXPAGE_OFFSET);
indexPage.SetPageSize(indexPageSize);
indexPage.SetNumDataPageSlots(numDataPageSlots);
dataPages = (DataPage**) malloc(sizeof(DataPage*) * numDataPageSlots);
for (i = 0; i < numDataPageSlots; i++)
dataPages[i] = NULL;
numDataPages = 0;
fd = -1;
}
File::~File()
{
for (uint32_t u = 0; u < numDataPages; u++)
delete dataPages[u];
free(dataPages);
}
void File::Open(char* filepath_)
{
struct stat st;
filepath.Write(filepath_);
filepath.NullTerminate();
fd = open(filepath.GetBuffer(), O_RDWR | O_CREAT, S_IRUSR | S_IWUSR);
if (fd < 0)
ASSERT_FAIL();
fstat(fd, &st);
if (st.st_size > 0)
Read();
}
void File::Flush()
{
}
void File::Close()
{
close(fd);
fd = -1;
}
bool File::Get(ReadBuffer& key, ReadBuffer& value)
{
int32_t index;
index = Locate(key);
if (index < 0)
return false;
return dataPages[index]->Get(key, value);
}
bool File::Set(ReadBuffer& key, ReadBuffer& value, bool copy)
{
int32_t index;
ReadBuffer rb;
if (key.GetLength() + value.GetLength() > DATAPAGE_MAX_KV_SIZE(dataPageSize))
return false;
index = Locate(key);
if (index < 0)
{
index = 0;
assert(dataPages[index] == NULL);
dataPages[index] = new DataPage;
dataPages[index]->SetOffset(DATAPAGE_OFFSET(index));
dataPages[index]->SetPageSize(dataPageSize);
numDataPages++;
indexPage.Add(key, index, true); // TODO
MarkPageDirty(&indexPage);
}
dataPages[index]->Set(key, value, copy);
MarkPageDirty(dataPages[index]);
// update index:
rb = dataPages[index]->FirstKey();
if (ReadBuffer::LessThan(key, rb))
{
indexPage.Update(key, index, copy);
MarkPageDirty(&indexPage);
}
if (dataPages[index]->IsOverflowing())
SplitDataPage(index);
return true;
}
void File::Delete(ReadBuffer& key)
{
int32_t index;
index = Locate(key);
if (index < 0)
return;
dataPages[index]->Delete(key);
MarkPageDirty(dataPages[index]);
if (dataPages[index]->IsEmpty())
{
indexPage.Remove(dataPages[index]->FirstKey());
MarkPageDirty(&indexPage);
}
}
ReadBuffer File::FirstKey()
{
return indexPage.FirstKey();
}
bool File::IsOverflowing()
{
return isOverflowing || indexPage.IsOverflowing();
}
File* File::SplitFile()
{
File* newFile;
uint32_t index, newIndex, num;
assert(numDataPageSlots == numDataPages);
newFile = new File;
newFile->indexPageSize = indexPageSize;
newFile->dataPageSize = dataPageSize;
newFile->numDataPageSlots = numDataPageSlots;
newFile->indexPage.SetPageSize(indexPageSize);
newFile->indexPage.SetNumDataPageSlots(numDataPageSlots);
ReorderPages();
num = numDataPages;
for (index = numDataPageSlots / 2, newIndex = 0; index < num; index++, newIndex++)
{
newFile->dataPages[newIndex] = dataPages[index];
dataPages[index] = NULL;
newFile->dataPages[newIndex]->SetOffset(DATAPAGE_OFFSET(newIndex));
numDataPages--;
newFile->numDataPages++;
indexPage.Remove(newFile->dataPages[newIndex]->FirstKey());
newFile->indexPage.Add(newFile->dataPages[newIndex]->FirstKey(), newIndex, true);
}
isOverflowing = false;
for (index = 0; index < numDataPages; index++)
{
if (dataPages[index]->IsOverflowing())
SplitDataPage(index);
}
assert(isOverflowing == false);
newFile->isOverflowing = false;
for (index = 0; index < newFile->numDataPages; index++)
{
if (newFile->dataPages[index]->IsOverflowing())
newFile->SplitDataPage(index);
}
assert(newFile->isOverflowing == false);
ReorderFile();
newFile->ReorderFile();
return newFile;
}
void File::Read()
{
char* p;
unsigned i;
int length;
Buffer buffer;
ReadBuffer readBuffer;
newFile = false;
buffer.Allocate(12);
if (pread(fd, (void*) buffer.GetBuffer(), 12, 0) < 0)
ASSERT_FAIL();
p = buffer.GetBuffer();
indexPageSize = FromLittle32(*((uint32_t*) p));
p += 4;
dataPageSize = FromLittle32(*((uint32_t*) p));
p += 4;
numDataPageSlots = FromLittle32(*((uint32_t*) p));
p += 4;
indexPage.SetOffset(INDEXPAGE_OFFSET);
indexPage.SetPageSize(indexPageSize);
indexPage.SetNumDataPageSlots(numDataPageSlots);
buffer.Allocate(indexPageSize);
length = pread(fd, (void*) buffer.GetBuffer(), indexPageSize, INDEXPAGE_OFFSET);
if (length < 0)
ASSERT_FAIL();
buffer.SetLength(length);
readBuffer.Wrap(buffer);
indexPage.Read(readBuffer);
if (dataPages != NULL)
free(dataPages);
dataPages = (DataPage**) malloc(sizeof(DataPage*) * numDataPageSlots);
for (i = 0; i < numDataPageSlots; i++)
dataPages[i] = NULL;
numDataPages = indexPage.NumEntries();
}
void File::ReadRest()
{
KeyIndex* it;
// TODO make sure this IO occurs in order!
for (it = indexPage.keys.First(); it != NULL; it = indexPage.keys.Next(it))
if (dataPages[it->index] == NULL)
LoadDataPage(it->index);
}
void File::Write()
{
Buffer buffer;
Page* it;
char* p;
if (newFile)
{
buffer.Allocate(12);
p = buffer.GetBuffer();
*((uint32_t*) p) = ToLittle32(indexPageSize);
p += 4;
*((uint32_t*) p) = ToLittle32(dataPageSize);
p += 4;
*((uint32_t*) p) = ToLittle32(numDataPageSlots);
p += 4;
if (pwrite(fd, (const void *) buffer.GetBuffer(), 12, 0) < 0)
ASSERT_FAIL();
}
// TODO: write these in offset order
for (it = dirtyPages.First(); it != NULL; it = dirtyPages.Remove(it))
{
buffer.Allocate(it->GetPageSize());
buffer.Zero();
// printf("writing at offset %u\n", it->GetOffset());
it->Write(buffer);
if (pwrite(fd, buffer.GetBuffer(), it->GetPageSize(), it->GetOffset()) < 0)
ASSERT_FAIL();
it->SetDirty(false);
}
}
int32_t File::Locate(ReadBuffer& key)
{
int32_t index;
index = indexPage.Locate(key);
if (index < 0)
return index; // not in file
if (dataPages[index] == NULL)
LoadDataPage(index);
return index;
}
void File::LoadDataPage(uint32_t index)
{
Buffer buffer;
ReadBuffer readBuffer;
int length;
dataPages[index] = new DataPage;
dataPages[index]->SetOffset(DATAPAGE_OFFSET(index));
dataPages[index]->SetPageSize(dataPageSize);
// printf("loading data page at index %u\n", index);
buffer.Allocate(dataPageSize);
// printf("reading page %u from %u\n", index, DATAPAGE_OFFSET(index));
length = pread(fd, buffer.GetBuffer(), dataPageSize, DATAPAGE_OFFSET(index));
if (length < 0)
ASSERT_FAIL();
buffer.SetLength(length);
readBuffer.Wrap(buffer);
dataPages[index]->Read(readBuffer);
}
void File::MarkPageDirty(Page* page)
{
if (!page->IsDirty())
{
page->SetDirty(true);
dirtyPages.Append(page);
}
}
void File::SplitDataPage(uint32_t index)
{
uint32_t newIndex;
DataPage* newPage;
if (numDataPages < numDataPageSlots)
{
newPage = dataPages[index]->SplitDataPage();
numDataPages++;
newIndex = indexPage.NextFreeDataPage();
newPage->SetOffset(DATAPAGE_OFFSET(newIndex));
assert(dataPages[newIndex] == NULL);
dataPages[newIndex] = newPage;
indexPage.Add(newPage->FirstKey(), newIndex, true); // TODO
// if (newPage->MustSplit())
// {
// if (numDataPages < numDataPageSlots)
// {
// newPage = newPage->Split();
// assert(newPage->MustSplit() == false);
// TOOD
// newIndex = indexPage.NextFreeDataPage();
// indexPage.Add(newPage->FirstKey(), newIndex, true);
// }
// else
// mustSplit = true;
// }
}
else
isOverflowing = true;
}
void File::ReorderPages()
{
uint32_t newIndex, oldIndex, i;
KeyIndex* it;
DataPage** newDataPages;
newDataPages = (DataPage**) calloc(numDataPageSlots, sizeof(DataPage*));
for (it = indexPage.keys.First(), newIndex = 0; it != NULL; it = indexPage.keys.Next(it), newIndex++)
{
oldIndex = it->index;
assert(dataPages[oldIndex] != NULL);
it->index = newIndex;
newDataPages[newIndex] = dataPages[oldIndex];
newDataPages[newIndex]->SetOffset(DATAPAGE_OFFSET(newIndex));
}
free(dataPages);
dataPages = newDataPages;
indexPage.freeDataPages.Clear();
for (i = numDataPages; i < numDataPageSlots; i++)
indexPage.freeDataPages.Add(i);
}
void File::ReorderFile()
{
uint32_t index;
dirtyPages.Clear();
ReorderPages();
indexPage.SetDirty(false);
MarkPageDirty(&indexPage);
for (index = 0; index < numDataPages; index++)
{
dataPages[index]->SetDirty(false);
MarkPageDirty(dataPages[index]);
}
}
<|endoftext|> |
<commit_before>// Copyright Paul Dardeau, SwampBits LLC 2014
// BSD License
#include "GUIDisplayEngineWindow.h"
using namespace tataille;
//******************************************************************************
bool GUIDisplayEngineWindow::registerControl(ControlInfo* ci,
DisplayEngineWidget* widget) {
return false;
}
//******************************************************************************
DisplayEngineWidget* GUIDisplayEngineWindow::controlFromCid(const ControlId& cid) {
DisplayEngineWidget* widget = NULL;
if (cid.controlId > -1) {
auto it = m_mapIntToWidgets.find(cid.controlId);
if (it != m_mapIntToWidgets.end()) {
widget = (*it).second;
}
}
return widget;
}
//******************************************************************************
bool GUIDisplayEngineWindow::hideWindow() {
return setVisible(false);
}
//******************************************************************************
bool GUIDisplayEngineWindow::showWindow() {
return setVisible(true);
}
//******************************************************************************
bool GUIDisplayEngineWindow::setFocus(const ControlId& cid) {
DisplayEngineWidget* control = controlFromCid(cid);
if (control != NULL) {
control->setFocus();
return true;
}
return false;
}
//******************************************************************************
bool GUIDisplayEngineWindow::hideControl(const ControlId& cid) {
return setVisible(false, cid);
}
//******************************************************************************
bool GUIDisplayEngineWindow::showControl(const ControlId& cid) {
return setVisible(true, cid);
}
//******************************************************************************
bool GUIDisplayEngineWindow::hideGroup(const std::string& groupName) {
return setVisible(false, groupName);
}
//******************************************************************************
bool GUIDisplayEngineWindow::showGroup(const std::string& groupName) {
return setVisible(true, groupName);
}
//******************************************************************************
bool GUIDisplayEngineWindow::setVisible(bool isVisible, const ControlId& cid) {
DisplayEngineWidget* control = controlFromCid(cid);
if (control != NULL) {
control->setVisible(isVisible);
return true;
}
return false;
}
//******************************************************************************
bool GUIDisplayEngineWindow::setVisible(bool isVisible,
const std::string& groupName) {
auto itGroupControls = m_mapGroupControls.find(groupName);
if (itGroupControls != m_mapGroupControls.end()) {
std::vector<ControlId>& listControls = (*itGroupControls).second;
for (ControlId& cid : listControls) {
setVisible(isVisible, cid);
}
return true;
}
return false;
}
//******************************************************************************
bool GUIDisplayEngineWindow::enableControl(const ControlId& cid) {
return setEnabled(true, cid);
}
//******************************************************************************
bool GUIDisplayEngineWindow::disableControl(const ControlId& cid) {
return setEnabled(false, cid);
}
//******************************************************************************
bool GUIDisplayEngineWindow::enableGroup(const std::string& groupName) {
return setEnabled(true, groupName);
}
//******************************************************************************
bool GUIDisplayEngineWindow::disableGroup(const std::string& groupName) {
return setEnabled(false, groupName);
}
//******************************************************************************
bool GUIDisplayEngineWindow::setEnabled(bool isEnabled, const ControlId& cid) {
DisplayEngineWidget* control = controlFromCid(cid);
if (control != NULL) {
control->setEnabled(isEnabled);
return true;
}
return false;
}
//******************************************************************************
bool GUIDisplayEngineWindow::setEnabled(bool isEnabled,
const std::string& groupName) {
auto itGroupControls = m_mapGroupControls.find(groupName);
if (itGroupControls != m_mapGroupControls.end()) {
std::vector<ControlId>& listControls = (*itGroupControls).second;
for (ControlId& cid : listControls) {
setEnabled(isEnabled, cid);
}
return true;
}
return false;
}
//******************************************************************************
bool GUIDisplayEngineWindow::setSize(const Size& controlSize,
const ControlId& cid) {
DisplayEngineWidget* control = controlFromCid(cid);
if (control != NULL) {
control->setSize(controlSize);
return true;
}
return false;
}
//******************************************************************************
bool GUIDisplayEngineWindow::setPos(const Point& point, const ControlId& cid) {
DisplayEngineWidget* control = controlFromCid(cid);
if (control != NULL) {
control->setPos(point);
return true;
}
return false;
}
//******************************************************************************
bool GUIDisplayEngineWindow::setRect(const Rect& rect, const ControlId& cid) {
DisplayEngineWidget* control = controlFromCid(cid);
if (control != NULL) {
control->setRect(rect);
return true;
}
return false;
}
//******************************************************************************
bool GUIDisplayEngineWindow::setCheckBoxHandler(CheckBoxHandler* handler,
const ControlId& cid) {
if (cid.isValid() && (handler != NULL)) {
m_mapCheckBoxHandlers[cid.controlId] = handler;
return true;
}
return false;
}
//******************************************************************************
bool GUIDisplayEngineWindow::setComboBoxHandler(ComboBoxHandler* handler,
const ControlId& cid) {
if (cid.isValid() && (handler != NULL)) {
m_mapComboBoxHandlers[cid.controlId] = handler;
return true;
}
return false;
}
//******************************************************************************
bool GUIDisplayEngineWindow::setListBoxHandler(ListBoxHandler* handler,
const ControlId& cid) {
if (cid.isValid() && (handler != NULL)) {
m_mapListBoxHandlers[cid.controlId] = handler;
return true;
}
return false;
}
//******************************************************************************
bool GUIDisplayEngineWindow::setListViewHandler(ListViewHandler* handler,
const ControlId& cid) {
if (cid.isValid() && (handler != NULL)) {
m_mapListViewHandlers[cid.controlId] = handler;
return true;
}
return false;
}
//******************************************************************************
bool GUIDisplayEngineWindow::setPushButtonHandler(PushButtonHandler* handler,
const ControlId& cid) {
if (cid.isValid() && (handler != NULL)) {
m_mapPushButtonHandlers[cid.controlId] = handler;
return true;
}
return false;
}
//******************************************************************************
bool GUIDisplayEngineWindow::setSliderHandler(SliderHandler* handler,
const ControlId& cid) {
if (cid.isValid() && (handler != NULL)) {
m_mapSliderHandlers[cid.controlId] = handler;
return true;
}
return false;
}
//******************************************************************************
bool GUIDisplayEngineWindow::setTabViewHandler(TabViewHandler* handler,
const ControlId& cid) {
if (cid.isValid() && (handler != NULL)) {
m_mapTabViewHandlers[cid.controlId] = handler;
return true;
}
return false;
}
//******************************************************************************
<commit_msg>downgrade to c++98<commit_after>// Copyright Paul Dardeau, SwampBits LLC 2014
// BSD License
#include "GUIDisplayEngineWindow.h"
using namespace tataille;
//******************************************************************************
bool GUIDisplayEngineWindow::registerControl(ControlInfo* ci,
DisplayEngineWidget* widget) {
return false;
}
//******************************************************************************
DisplayEngineWidget* GUIDisplayEngineWindow::controlFromCid(const ControlId& cid) {
DisplayEngineWidget* widget = NULL;
if (cid.controlId > -1) {
std::unordered_map<int, DisplayEngineWidget*>::iterator it =
m_mapIntToWidgets.find(cid.controlId);
if (it != m_mapIntToWidgets.end()) {
widget = (*it).second;
}
}
return widget;
}
//******************************************************************************
bool GUIDisplayEngineWindow::hideWindow() {
return setVisible(false);
}
//******************************************************************************
bool GUIDisplayEngineWindow::showWindow() {
return setVisible(true);
}
//******************************************************************************
bool GUIDisplayEngineWindow::setFocus(const ControlId& cid) {
DisplayEngineWidget* control = controlFromCid(cid);
if (control != NULL) {
control->setFocus();
return true;
}
return false;
}
//******************************************************************************
bool GUIDisplayEngineWindow::hideControl(const ControlId& cid) {
return setVisible(false, cid);
}
//******************************************************************************
bool GUIDisplayEngineWindow::showControl(const ControlId& cid) {
return setVisible(true, cid);
}
//******************************************************************************
bool GUIDisplayEngineWindow::hideGroup(const std::string& groupName) {
return setVisible(false, groupName);
}
//******************************************************************************
bool GUIDisplayEngineWindow::showGroup(const std::string& groupName) {
return setVisible(true, groupName);
}
//******************************************************************************
bool GUIDisplayEngineWindow::setVisible(bool isVisible, const ControlId& cid) {
DisplayEngineWidget* control = controlFromCid(cid);
if (control != NULL) {
control->setVisible(isVisible);
return true;
}
return false;
}
//******************************************************************************
bool GUIDisplayEngineWindow::setVisible(bool isVisible,
const std::string& groupName) {
std::unordered_map<std::string, std::vector<ControlId> >::iterator itGroupControls = m_mapGroupControls.find(groupName);
if (itGroupControls != m_mapGroupControls.end()) {
std::vector<ControlId>& listControls = (*itGroupControls).second;
std::vector<ControlId>::iterator itControls = listControls.begin();
const std::vector<ControlId>::const_iterator itControlsEnd =
listControls.end();
for (; itControls != itControlsEnd; itControls++) {
ControlId& cid = *itControls;
setVisible(isVisible, cid);
}
return true;
}
return false;
}
//******************************************************************************
bool GUIDisplayEngineWindow::enableControl(const ControlId& cid) {
return setEnabled(true, cid);
}
//******************************************************************************
bool GUIDisplayEngineWindow::disableControl(const ControlId& cid) {
return setEnabled(false, cid);
}
//******************************************************************************
bool GUIDisplayEngineWindow::enableGroup(const std::string& groupName) {
return setEnabled(true, groupName);
}
//******************************************************************************
bool GUIDisplayEngineWindow::disableGroup(const std::string& groupName) {
return setEnabled(false, groupName);
}
//******************************************************************************
bool GUIDisplayEngineWindow::setEnabled(bool isEnabled, const ControlId& cid) {
DisplayEngineWidget* control = controlFromCid(cid);
if (control != NULL) {
control->setEnabled(isEnabled);
return true;
}
return false;
}
//******************************************************************************
bool GUIDisplayEngineWindow::setEnabled(bool isEnabled,
const std::string& groupName) {
std::unordered_map<std::string, std::vector<ControlId> >::iterator itGroupControls = m_mapGroupControls.find(groupName);
if (itGroupControls != m_mapGroupControls.end()) {
std::vector<ControlId>& listControls = (*itGroupControls).second;
std::vector<ControlId>::iterator itControls = listControls.begin();
const std::vector<ControlId>::const_iterator itControlsEnd =
listControls.end();
for (; itControls != itControlsEnd; itControls++) {
ControlId& cid = *itControls;
setEnabled(isEnabled, cid);
}
return true;
}
return false;
}
//******************************************************************************
bool GUIDisplayEngineWindow::setSize(const Size& controlSize,
const ControlId& cid) {
DisplayEngineWidget* control = controlFromCid(cid);
if (control != NULL) {
control->setSize(controlSize);
return true;
}
return false;
}
//******************************************************************************
bool GUIDisplayEngineWindow::setPos(const Point& point, const ControlId& cid) {
DisplayEngineWidget* control = controlFromCid(cid);
if (control != NULL) {
control->setPos(point);
return true;
}
return false;
}
//******************************************************************************
bool GUIDisplayEngineWindow::setRect(const Rect& rect, const ControlId& cid) {
DisplayEngineWidget* control = controlFromCid(cid);
if (control != NULL) {
control->setRect(rect);
return true;
}
return false;
}
//******************************************************************************
bool GUIDisplayEngineWindow::setCheckBoxHandler(CheckBoxHandler* handler,
const ControlId& cid) {
if (cid.isValid() && (handler != NULL)) {
m_mapCheckBoxHandlers[cid.controlId] = handler;
return true;
}
return false;
}
//******************************************************************************
bool GUIDisplayEngineWindow::setComboBoxHandler(ComboBoxHandler* handler,
const ControlId& cid) {
if (cid.isValid() && (handler != NULL)) {
m_mapComboBoxHandlers[cid.controlId] = handler;
return true;
}
return false;
}
//******************************************************************************
bool GUIDisplayEngineWindow::setListBoxHandler(ListBoxHandler* handler,
const ControlId& cid) {
if (cid.isValid() && (handler != NULL)) {
m_mapListBoxHandlers[cid.controlId] = handler;
return true;
}
return false;
}
//******************************************************************************
bool GUIDisplayEngineWindow::setListViewHandler(ListViewHandler* handler,
const ControlId& cid) {
if (cid.isValid() && (handler != NULL)) {
m_mapListViewHandlers[cid.controlId] = handler;
return true;
}
return false;
}
//******************************************************************************
bool GUIDisplayEngineWindow::setPushButtonHandler(PushButtonHandler* handler,
const ControlId& cid) {
if (cid.isValid() && (handler != NULL)) {
m_mapPushButtonHandlers[cid.controlId] = handler;
return true;
}
return false;
}
//******************************************************************************
bool GUIDisplayEngineWindow::setSliderHandler(SliderHandler* handler,
const ControlId& cid) {
if (cid.isValid() && (handler != NULL)) {
m_mapSliderHandlers[cid.controlId] = handler;
return true;
}
return false;
}
//******************************************************************************
bool GUIDisplayEngineWindow::setTabViewHandler(TabViewHandler* handler,
const ControlId& cid) {
if (cid.isValid() && (handler != NULL)) {
m_mapTabViewHandlers[cid.controlId] = handler;
return true;
}
return false;
}
//******************************************************************************
<|endoftext|> |
<commit_before>// Copyright (c) 2011-2014 The Bitcoin developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "utilitydialog.h"
#include "ui_aboutdialog.h"
#include "ui_helpmessagedialog.h"
#include "bitcoingui.h"
#include "clientmodel.h"
#include "guiutil.h"
#include "clientversion.h"
#include "init.h"
#include "util.h"
#include <QLabel>
#include <QVBoxLayout>
/** "About" dialog box */
AboutDialog::AboutDialog(QWidget *parent) :
QDialog(parent),
ui(new Ui::AboutDialog)
{
ui->setupUi(this);
// Set current copyright year
ui->copyrightLabel->setText(tr("Copyright") + QString(" © 2009-%1 ").arg(COPYRIGHT_YEAR) + tr("The Bitcoin Core developers"));
}
void AboutDialog::setModel(ClientModel *model)
{
if(model)
{
QString version = model->formatFullVersion();
/* On x86 add a bit specifier to the version so that users can distinguish between
* 32 and 64 bit builds. On other architectures, 32/64 bit may be more ambigious.
*/
#if defined(__x86_64__)
version += " " + tr("(%1-bit)").arg(64);
#elif defined(__i386__ )
version += " " + tr("(%1-bit)").arg(32);
#endif
ui->versionLabel->setText(version);
}
}
AboutDialog::~AboutDialog()
{
delete ui;
}
void AboutDialog::on_buttonBox_accepted()
{
close();
}
/** "Help message" dialog box */
HelpMessageDialog::HelpMessageDialog(QWidget *parent) :
QDialog(parent),
ui(new Ui::HelpMessageDialog)
{
ui->setupUi(this);
GUIUtil::restoreWindowGeometry("nHelpMessageDialogWindow", this->size(), this);
header = tr("Bitcoin Core") + " " + tr("version") + " " +
QString::fromStdString(FormatFullVersion()) + "\n\n" +
tr("Usage:") + "\n" +
" bitcoin-qt [" + tr("command-line options") + "] " + "\n";
coreOptions = QString::fromStdString(HelpMessage(HMM_BITCOIN_QT));
uiOptions = tr("UI options") + ":\n" +
" -choosedatadir " + tr("Choose data directory on startup (default: 0)") + "\n" +
" -lang=<lang> " + tr("Set language, for example \"de_DE\" (default: system locale)") + "\n" +
" -min " + tr("Start minimized") + "\n" +
" -rootcertificates=<file> " + tr("Set SSL root certificates for payment request (default: -system-)") + "\n" +
" -splash " + tr("Show splash screen on startup (default: 1)");
ui->helpMessageLabel->setFont(GUIUtil::bitcoinAddressFont());
// Set help message text
ui->helpMessageLabel->setText(header + "\n" + coreOptions + "\n" + uiOptions);
}
HelpMessageDialog::~HelpMessageDialog()
{
GUIUtil::saveWindowGeometry("nHelpMessageDialogWindow", this);
delete ui;
}
void HelpMessageDialog::printToConsole()
{
// On other operating systems, the expected action is to print the message to the console.
QString strUsage = header + "\n" + coreOptions + "\n" + uiOptions + "\n";
fprintf(stdout, "%s", strUsage.toStdString().c_str());
}
void HelpMessageDialog::showOrPrint()
{
#if defined(WIN32)
// On Windows, show a message box, as there is no stderr/stdout in windowed applications
exec();
#else
// On other operating systems, print help text to console
printToConsole();
#endif
}
void HelpMessageDialog::on_okButton_accepted()
{
close();
}
/** "Shutdown" window */
void ShutdownWindow::showShutdownWindow(BitcoinGUI *window)
{
if (!window)
return;
// Show a simple window indicating shutdown status
QWidget *shutdownWindow = new QWidget();
QVBoxLayout *layout = new QVBoxLayout();
layout->addWidget(new QLabel(
tr("Bitcoin Core is shutting down...") + "<br /><br />" +
tr("Do not shut down the computer until this window disappears.")));
shutdownWindow->setLayout(layout);
// Center shutdown window at where main window was
const QPoint global = window->mapToGlobal(window->rect().center());
shutdownWindow->move(global.x() - shutdownWindow->width() / 2, global.y() - shutdownWindow->height() / 2);
shutdownWindow->show();
}
<commit_msg>set shutdown title to main window title<commit_after>// Copyright (c) 2011-2014 The Bitcoin developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "utilitydialog.h"
#include "ui_aboutdialog.h"
#include "ui_helpmessagedialog.h"
#include "bitcoingui.h"
#include "clientmodel.h"
#include "guiutil.h"
#include "clientversion.h"
#include "init.h"
#include "util.h"
#include <QLabel>
#include <QVBoxLayout>
/** "About" dialog box */
AboutDialog::AboutDialog(QWidget *parent) :
QDialog(parent),
ui(new Ui::AboutDialog)
{
ui->setupUi(this);
// Set current copyright year
ui->copyrightLabel->setText(tr("Copyright") + QString(" © 2009-%1 ").arg(COPYRIGHT_YEAR) + tr("The Bitcoin Core developers"));
}
void AboutDialog::setModel(ClientModel *model)
{
if(model)
{
QString version = model->formatFullVersion();
/* On x86 add a bit specifier to the version so that users can distinguish between
* 32 and 64 bit builds. On other architectures, 32/64 bit may be more ambigious.
*/
#if defined(__x86_64__)
version += " " + tr("(%1-bit)").arg(64);
#elif defined(__i386__ )
version += " " + tr("(%1-bit)").arg(32);
#endif
ui->versionLabel->setText(version);
}
}
AboutDialog::~AboutDialog()
{
delete ui;
}
void AboutDialog::on_buttonBox_accepted()
{
close();
}
/** "Help message" dialog box */
HelpMessageDialog::HelpMessageDialog(QWidget *parent) :
QDialog(parent),
ui(new Ui::HelpMessageDialog)
{
ui->setupUi(this);
GUIUtil::restoreWindowGeometry("nHelpMessageDialogWindow", this->size(), this);
header = tr("Bitcoin Core") + " " + tr("version") + " " +
QString::fromStdString(FormatFullVersion()) + "\n\n" +
tr("Usage:") + "\n" +
" bitcoin-qt [" + tr("command-line options") + "] " + "\n";
coreOptions = QString::fromStdString(HelpMessage(HMM_BITCOIN_QT));
uiOptions = tr("UI options") + ":\n" +
" -choosedatadir " + tr("Choose data directory on startup (default: 0)") + "\n" +
" -lang=<lang> " + tr("Set language, for example \"de_DE\" (default: system locale)") + "\n" +
" -min " + tr("Start minimized") + "\n" +
" -rootcertificates=<file> " + tr("Set SSL root certificates for payment request (default: -system-)") + "\n" +
" -splash " + tr("Show splash screen on startup (default: 1)");
ui->helpMessageLabel->setFont(GUIUtil::bitcoinAddressFont());
// Set help message text
ui->helpMessageLabel->setText(header + "\n" + coreOptions + "\n" + uiOptions);
}
HelpMessageDialog::~HelpMessageDialog()
{
GUIUtil::saveWindowGeometry("nHelpMessageDialogWindow", this);
delete ui;
}
void HelpMessageDialog::printToConsole()
{
// On other operating systems, the expected action is to print the message to the console.
QString strUsage = header + "\n" + coreOptions + "\n" + uiOptions + "\n";
fprintf(stdout, "%s", strUsage.toStdString().c_str());
}
void HelpMessageDialog::showOrPrint()
{
#if defined(WIN32)
// On Windows, show a message box, as there is no stderr/stdout in windowed applications
exec();
#else
// On other operating systems, print help text to console
printToConsole();
#endif
}
void HelpMessageDialog::on_okButton_accepted()
{
close();
}
/** "Shutdown" window */
void ShutdownWindow::showShutdownWindow(BitcoinGUI *window)
{
if (!window)
return;
// Show a simple window indicating shutdown status
QWidget *shutdownWindow = new QWidget();
QVBoxLayout *layout = new QVBoxLayout();
layout->addWidget(new QLabel(
tr("Bitcoin Core is shutting down...") + "<br /><br />" +
tr("Do not shut down the computer until this window disappears.")));
shutdownWindow->setLayout(layout);
shutdownWindow->setWindowTitle(window->windowTitle());
// Center shutdown window at where main window was
const QPoint global = window->mapToGlobal(window->rect().center());
shutdownWindow->move(global.x() - shutdownWindow->width() / 2, global.y() - shutdownWindow->height() / 2);
shutdownWindow->show();
}
<|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: wizardmachine.hxx,v $
*
* $Revision: 1.3 $
*
* last change: $Author: vg $ $Date: 2007-05-22 19:32:34 $
*
* 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 _SVTOOLS_WIZARDMACHINE_HXX_
#define _SVTOOLS_WIZARDMACHINE_HXX_
#ifndef INCLUDED_SVTDLLAPI_H
#include "svtools/svtdllapi.h"
#endif
#ifndef _SVT_WIZDLG_HXX
#include <svtools/wizdlg.hxx>
#endif
#ifndef _SV_BUTTON_HXX
#include <vcl/button.hxx>
#endif
#ifndef _SV_TABPAGE_HXX
#include <vcl/tabpage.hxx>
#endif
#ifndef _COMPHELPER_STLTYPES_HXX_
#include <comphelper/stl_types.hxx>
#endif
class Bitmap;
//.........................................................................
namespace svt
{
//.........................................................................
// wizard buttons
#define WZB_NEXT 0x0001
#define WZB_PREVIOUS 0x0002
#define WZB_FINISH 0x0004
#define WZB_CANCEL 0x0008
#define WZB_HELP 0x0010
// wizard states
#define WZS_INVALID_STATE ((WizardState)-1)
//=====================================================================
//= WizardTypes
//=====================================================================
struct WizardTypes
{
typedef sal_Int16 WizardState;
enum CommitPageReason
{
eTravelForward, // traveling forward (maybe with skipping pages)
eTravelBackward, // traveling backward (maybe with skipping pages)
eFinish, // the wizard is about to be finished
eValidate, // the data should be validated only, no traveling wll happen
eValidateNoUI // the data should be validated only, without displaying error messages and other UI
};
};
class SAL_NO_VTABLE IWizardPage : public WizardTypes
{
public:
// access control
struct GrantAccess
{
friend class OWizardMachine;
protected:
GrantAccess() { }
};
/// compatibility only. Superseded by CommitPageReason
enum COMMIT_REASON
{
CR_TRAVEL_NEXT = eTravelForward,
CR_TRAVEL_PREVIOUS = eTravelBackward,
CR_FINISH = eFinish,
CR_VALIDATE = eValidate,
CR_VALIDATE_NOUI = eValidateNoUI
};
public:
//-----------------------------------------------------------------
// methods which, though public, are acessible for the OWizardMachine only
virtual void enableHeader( const Bitmap& _rBitmap, sal_Int32 _nPixelHeight, GrantAccess ) = 0;
// This methods behave somewhat different than ActivatePage/DeactivatePage
// The latter are handled by the base class itself whenever changing the pages is in the offing,
// i.e., when it's already decided which page is the next.
// We may have situations where the next page depends on the state of the current, which needs
// to be committed for this.
// So initializePage and commitPage are designated to initialitzing/committing data on the page.
virtual void initializePage() = 0;
virtual sal_Bool commitPage(COMMIT_REASON _eReason) = 0;
};
//=====================================================================
//= OWizardPage
//=====================================================================
class OWizardMachine;
struct WizardPageImplData;
class SVT_DLLPUBLIC OWizardPage : public TabPage, public IWizardPage
{
private:
WizardPageImplData* m_pImpl;
public:
/** @param _pParent
if the OWizardPage is used in an OWizardMachine, this parameter
must be the OWizardMachine (which is derived from Window)
*/
OWizardPage( Window* _pParent, WinBits _nStyle = 0 );
OWizardPage( Window* _pParent, const ResId& _rResId );
~OWizardPage();
// This methods behave somewhat different than ActivatePage/DeactivatePage
// The latter are handled by the base class itself whenever changing the pages is in the offing,
// i.e., when it's already decided which page is the next.
// We may have situations where the next page depends on the state of the current, which needs
// to be committed for this.
// So initializePage and commitPage are designated to initialitzing/committing data on the page.
virtual void initializePage();
virtual sal_Bool commitPage(IWizardPage::COMMIT_REASON _eReason);
//-----------------------------------------------------------------
// methods which, though public, are acessible for the OWizardMachine only
virtual void enableHeader( const Bitmap& _rBitmap, sal_Int32 _nPixelHeight, IWizardPage::GrantAccess );
protected:
// TabPage overridables
virtual void ActivatePage();
/** checks whether or not the header is enabled
The header can only be enabled by the OWizardMachine the page belongs to. This way, it is ensured
that <em>all</em> or <em>none</em> of the pages have a header.
*/
sal_Bool isHeaderEnabled( ) const;
/** sets the text of the header.
To be called if the header is enabled only.
@see isHeaderEnabled
*/
void setHeaderText( const String& _rHeaderText );
protected:
/** called from within ActivatePage, enables the wizards "Next" button depending on the return value of
<member>determineNextButtonState</member>
*/
void implCheckNextButton();
/** determines whether or not the <em>Next</em> button should be enabled in the current situation.
The default implementation always returns <TRUE/>.
*/
virtual sal_Bool determineNextButtonState();
};
//=====================================================================
//= OWizardMachine
//=====================================================================
struct WizardMachineImplData;
/** implements some kind of finite automata, where the states of the automata exactly correlate
with tab pages.
That is, the machine can have up to n states, where at each point in time exactly one state is
the current one. A state being current is represented as one of n tab pages being displayed
currently.
The class handles the UI for traveling between the states (e.g. it administrates the <em>Next</em> and
<em>Previous</em> buttons which you usually find in a wizard.
Derived classes have to implement the travel logic by overriding <member>determineNextState</member>,
which has to determine the state which follows the current state. Since this may depend
on the actual data presented in the wizard (e.g. checkboxes checked, or something like this),
they can implement non-linear traveling this way.
*/
class SVT_DLLPUBLIC OWizardMachine : public WizardDialog, public WizardTypes
{
private:
// restrict access to some aspects of our base class
SVT_DLLPRIVATE void AddPage( TabPage* pPage ) { WizardDialog::AddPage(pPage); }
SVT_DLLPRIVATE void RemovePage( TabPage* pPage ) { WizardDialog::RemovePage(pPage); }
SVT_DLLPRIVATE void SetPage( USHORT nLevel, TabPage* pPage ) { WizardDialog::SetPage(nLevel, pPage); }
// TabPage* GetPage( USHORT nLevel ) const { return WizardDialog::GetPage(nLevel); }
// TODO: probably the complete page handling (next, previous etc.) should be prohibited ...
// IMPORTANT:
// traveling pages should not be done by calling these base class member, some mechanisms of this class
// here (e.g. committing page data) depend on having full control over page traveling.
// So use the travelXXX methods if you need to travel
protected:
OKButton* m_pFinish;
CancelButton* m_pCancel;
PushButton* m_pNextPage;
PushButton* m_pPrevPage;
HelpButton* m_pHelp;
private:
WizardMachineImplData*
m_pImpl;
// hold members in this structure to allow keeping compatible when members are added
SVT_DLLPRIVATE void addButtons(Window* _pParent, sal_uInt32 _nButtonFlags);
SVT_DLLPRIVATE long calcRightHelpOffset(sal_uInt32 _nButtonFlags);
public:
/** ctor
The ctor does not call FreeResource, this is the resposibility of the derived class.
For the button flags, use any combination of the WZB_* flags.
*/
OWizardMachine(Window* _pParent, const ResId& _rRes, sal_uInt32 _nButtonFlags, sal_Bool _bCheckButtonStates = sal_False, sal_Bool _bRoadmapMode = sal_False, sal_Int16 _nLeftAlignCount = 0 );
~OWizardMachine();
/// enable (or disable) buttons
void enableButtons(sal_uInt32 _nWizardButtonFlags, sal_Bool _bEnable);
/// set the default style for a button
void defaultButton(sal_uInt32 _nWizardButtonFlags);
/// set the default style for a button
void defaultButton(PushButton* _pNewDefButton);
/// set the base of the title to use - the title of the current page is appended
void setTitleBase(const String& _rTitleBase);
const String& getTitleBase() const;
protected:
// WizardDialog overridables
virtual void ActivatePage();
virtual long DeactivatePage();
// our own overridables
/// to override to create new pages
virtual TabPage* createPage(WizardState _nState) = 0;
/// will be called when a new page is about to be displayed
virtual void enterState(WizardState _nState);
/** will be called when the current state is about to be left for the given reason
The base implementation in this class will simply call <member>OWizardPage::commitPage</member>
for the current page, and return whatever this call returns.
@param _eReason
The reason why the state is to be left.
@return
<TRUE/> if and only if the page is allowed to be left
*/
virtual sal_Bool prepareLeaveCurrentState( CommitPageReason _eReason );
/** will be called when the given state is left
This is the very last possibility for derived classes to veto the deactivation
of a page.
@todo Normally, we would not need the return value here - derived classes now have
the possibility to veto page deactivations in <member>prepareLeaveCurrentState</member>. However,
changing this return type is too incompatible at the moment ...
@return
<TRUE/> if and only if the page is allowed to be left
*/
virtual sal_Bool leaveState( WizardState _nState );
/** determine the next state to travel from the given one
The default behaviour is linear traveling, overwrite this to change it
Return WZS_INVALID_STATE to prevent traveling.
*/
virtual WizardState determineNextState(WizardState _nCurrentState);
/** called when the finish button is pressed
<p>By default, only the base class' Finnish method (which is not virtual) is called</p>
*/
virtual sal_Bool onFinish(sal_Int32 _nResult);
/** enables a header bitmap
Usually, wizards contain a header. This header is as wide as the dialog and positioned at the very top.
In addition, it contains a (rather small) bitmap on the left side, and right next to this bitmap, a short
text describing the current page.
If you call this method, this header is automatically created on every page. In addition, all
other controls on the pages are moved below the header. The title of every page is used as text
for the header.
This method must not be called if there are already pages created.
@param _rBitmap
the bitmap to use for the header
@param _nPixelHeight
the height of the header in pixels.<br/>
If -1 is passed, the default of 30 APPFONT units will be used.
*/
void enableHeader( const Bitmap& _rBitmap, sal_Int32 _nPixelHeight = -1 );
/// travel to the next state
sal_Bool travelNext();
/// travel to the previous state
sal_Bool travelPrevious();
/**
removes a page from the history. Should be called when the page is being disabled
*/
void removePageFromHistory( WizardState nToRemove );
/** skip a state
The method behaves as if from the current state, <arg>_nSteps</arg> <method>travelNext</method>s were
called, but without actually creating or displaying the ntermediate pages. Only the
(<arg>_nSteps</arg> + 1)th page is created.
The skipped states appear in the state history, so <method>travelPrevious</method> will make use of them.
A very essential precondition for using this method is that your <method>determineNextState</method>
method is able to determine the next state without actually having the page of the current state.
@return
<TRUE/> if and only if traveling was successfull
@see skipUntil
@see skipBackwardUntil
*/
sal_Bool skip( sal_Int32 _nSteps = 1 );
/** skips one or more states, until a given state is reached
The method behaves as if from the current state, <method>travelNext</method>s were called
successively, until <arg>_nTargetState</arg> is reached, but without actually creating or
displaying the ntermediate pages.
The skipped states appear in the state history, so <method>travelPrevious</method> will make use of them.
@return
<TRUE/> if and only if traveling was successfull
@see skip
@see skipBackwardUntil
*/
sal_Bool skipUntil( WizardState _nTargetState );
/** moves back one or more states, until a given state is reached
This method allows traveling backwards more than one state without actually showing the intermediate
states.
For instance, if you want to travel two steps backward at a time, you could used
two travelPrevious calls, but this would <em>show</em> both pages, which is not necessary,
since you're interested in the target page only. Using <member>skipBackwardUntil</member> reliefs
you from this.
@return
<TRUE/> if and only if traveling was successfull
@see skipUntil
@see skip
*/
sal_Bool skipBackwardUntil( WizardState _nTargetState );
/** returns the current state of the machine
Vulgo, this is the identifier of the current tab page :)
*/
WizardState getCurrentState() const { return WizardDialog::GetCurLevel(); }
virtual IWizardPage* getWizardPage(TabPage* _pCurrentPage) const;
/** prevent nested calls of links next/previous or page change with the roadmap control
*/
bool IsInCallOfLink() const;
void SetInCallOfLink( bool bSet );
private:
// long OnNextPage( PushButton* );
DECL_DLLPRIVATE_LINK(OnNextPage, PushButton*);
DECL_DLLPRIVATE_LINK(OnPrevPage, PushButton*);
DECL_DLLPRIVATE_LINK(OnFinish, PushButton*);
SVT_DLLPRIVATE void implResetDefault(Window* _pWindow);
SVT_DLLPRIVATE void implUpdateTitle();
};
//.........................................................................
} // namespace svt
//.........................................................................
#endif // _SVTOOLS_WIZARDMACHINE_HXX_
<commit_msg>INTEGRATION: CWS odbmacros2 (1.3.212); FILE MERGED 2008/02/14 21:47:59 fs 1.3.212.5.2.1: #i49133# +getStateHistory 2008/02/11 11:06:00 fs 1.3.212.5: IWizardPage is COMMIT_REASON is deprecated - replace usages with CommitPageReason, while I have an svtools-incompatible CWS 2008/02/04 19:47:07 fs 1.3.212.4: more re-factoring: implUpdateNextButton superseded by update(Dialog)TravelUI 2008/01/30 13:18:34 fs 1.3.212.3: canAdvance made const 2008/01/21 12:26:54 fs 1.3.212.2: canAdvance signature changed, to be able to override it in RoadmapWizard 2008/01/15 09:47:08 fs 1.3.212.1: some re-factoring to prepare the migration UI for #i49133#<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: wizardmachine.hxx,v $
*
* $Revision: 1.4 $
*
* last change: $Author: kz $ $Date: 2008-03-06 19:22:55 $
*
* 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 _SVTOOLS_WIZARDMACHINE_HXX_
#define _SVTOOLS_WIZARDMACHINE_HXX_
#ifndef INCLUDED_SVTDLLAPI_H
#include "svtools/svtdllapi.h"
#endif
#ifndef _SVT_WIZDLG_HXX
#include <svtools/wizdlg.hxx>
#endif
#ifndef _SV_BUTTON_HXX
#include <vcl/button.hxx>
#endif
#ifndef _SV_TABPAGE_HXX
#include <vcl/tabpage.hxx>
#endif
#ifndef _COMPHELPER_STLTYPES_HXX_
#include <comphelper/stl_types.hxx>
#endif
class Bitmap;
//.........................................................................
namespace svt
{
//.........................................................................
// wizard buttons
#define WZB_NEXT 0x0001
#define WZB_PREVIOUS 0x0002
#define WZB_FINISH 0x0004
#define WZB_CANCEL 0x0008
#define WZB_HELP 0x0010
// wizard states
#define WZS_INVALID_STATE ((WizardState)-1)
//=====================================================================
//= WizardTypes
//=====================================================================
struct WizardTypes
{
typedef sal_Int16 WizardState;
enum CommitPageReason
{
eTravelForward, // traveling forward (maybe with skipping pages)
eTravelBackward, // traveling backward (maybe with skipping pages)
eFinish, // the wizard is about to be finished
eValidate, // the data should be validated only, no traveling wll happen
eValidateNoUI // the data should be validated only, without displaying error messages and other UI
};
};
class SAL_NO_VTABLE IWizardPage : public WizardTypes
{
public:
//-----------------------------------------------------------------
// This methods behave somewhat different than ActivatePage/DeactivatePage
// The latter are handled by the base class itself whenever changing the pages is in the offing,
// i.e., when it's already decided which page is the next.
// We may have situations where the next page depends on the state of the current, which needs
// to be committed for this.
// So initializePage and commitPage are designated to initialitzing/committing data on the page.
virtual void initializePage() = 0;
virtual sal_Bool commitPage( CommitPageReason _eReason ) = 0;
};
//=====================================================================
//= OWizardPage
//=====================================================================
class OWizardMachine;
struct WizardPageImplData;
class SVT_DLLPUBLIC OWizardPage : public TabPage, public IWizardPage
{
private:
WizardPageImplData* m_pImpl;
public:
/** @param _pParent
if the OWizardPage is used in an OWizardMachine, this parameter
must be the OWizardMachine (which is derived from Window)
*/
OWizardPage( Window* _pParent, WinBits _nStyle = 0 );
OWizardPage( Window* _pParent, const ResId& _rResId );
~OWizardPage();
// This methods behave somewhat different than ActivatePage/DeactivatePage
// The latter are handled by the base class itself whenever changing the pages is in the offing,
// i.e., when it's already decided which page is the next.
// We may have situations where the next page depends on the state of the current, which needs
// to be committed for this.
// So initializePage and commitPage are designated to initialitzing/committing data on the page.
virtual void initializePage();
virtual sal_Bool commitPage( CommitPageReason _eReason );
/** determines whether or not it is allowed to advance to a next page
You should make this dependent on the current state of the page only, not on
states on other pages of the whole dialog.
The default implementation always returns <TRUE/>.
*/
virtual bool canAdvance() const;
protected:
// TabPage overridables
virtual void ActivatePage();
/** updates the travel-related UI elements of the OWizardMachine we live in (if any)
If the parent of the tab page is a OWizardMachine, then updateTravelUI at this instance
is called. Otherwise, nothing happens.
*/
void updateDialogTravelUI();
};
//=====================================================================
//= OWizardMachine
//=====================================================================
struct WizardMachineImplData;
/** implements some kind of finite automata, where the states of the automata exactly correlate
with tab pages.
That is, the machine can have up to n states, where at each point in time exactly one state is
the current one. A state being current is represented as one of n tab pages being displayed
currently.
The class handles the UI for traveling between the states (e.g. it administrates the <em>Next</em> and
<em>Previous</em> buttons which you usually find in a wizard.
Derived classes have to implement the travel logic by overriding <member>determineNextState</member>,
which has to determine the state which follows the current state. Since this may depend
on the actual data presented in the wizard (e.g. checkboxes checked, or something like this),
they can implement non-linear traveling this way.
*/
class SVT_DLLPUBLIC OWizardMachine : public WizardDialog, public WizardTypes
{
private:
// restrict access to some aspects of our base class
SVT_DLLPRIVATE void AddPage( TabPage* pPage ) { WizardDialog::AddPage(pPage); }
SVT_DLLPRIVATE void RemovePage( TabPage* pPage ) { WizardDialog::RemovePage(pPage); }
SVT_DLLPRIVATE void SetPage( USHORT nLevel, TabPage* pPage ) { WizardDialog::SetPage(nLevel, pPage); }
// TabPage* GetPage( USHORT nLevel ) const { return WizardDialog::GetPage(nLevel); }
// TODO: probably the complete page handling (next, previous etc.) should be prohibited ...
// IMPORTANT:
// traveling pages should not be done by calling these base class member, some mechanisms of this class
// here (e.g. committing page data) depend on having full control over page traveling.
// So use the travelXXX methods if you need to travel
protected:
OKButton* m_pFinish;
CancelButton* m_pCancel;
PushButton* m_pNextPage;
PushButton* m_pPrevPage;
HelpButton* m_pHelp;
private:
WizardMachineImplData*
m_pImpl;
// hold members in this structure to allow keeping compatible when members are added
SVT_DLLPRIVATE void addButtons(Window* _pParent, sal_uInt32 _nButtonFlags);
SVT_DLLPRIVATE long calcRightHelpOffset(sal_uInt32 _nButtonFlags);
public:
/** ctor
The ctor does not call FreeResource, this is the resposibility of the derived class.
For the button flags, use any combination of the WZB_* flags.
*/
OWizardMachine(Window* _pParent, const ResId& _rRes, sal_uInt32 _nButtonFlags );
~OWizardMachine();
/// enable (or disable) buttons
void enableButtons(sal_uInt32 _nWizardButtonFlags, sal_Bool _bEnable);
/// set the default style for a button
void defaultButton(sal_uInt32 _nWizardButtonFlags);
/// set the default style for a button
void defaultButton(PushButton* _pNewDefButton);
/// set the base of the title to use - the title of the current page is appended
void setTitleBase(const String& _rTitleBase);
const String& getTitleBase() const;
/// determines whether there is a next state to which we can advance
virtual bool canAdvance() const;
/** updates the user interface which deals with traveling in the wizard
The default implementation simply checks whether both the current page and the wizard
itself allow to advance to the next state (<code>canAdvance</code>), and enables the "Next"
button if and only if this is the case.
*/
virtual void updateTravelUI();
protected:
// WizardDialog overridables
virtual void ActivatePage();
virtual long DeactivatePage();
// our own overridables
/// to override to create new pages
virtual TabPage* createPage(WizardState _nState) = 0;
/// will be called when a new page is about to be displayed
virtual void enterState(WizardState _nState);
/** will be called when the current state is about to be left for the given reason
The base implementation in this class will simply call <member>OWizardPage::commitPage</member>
for the current page, and return whatever this call returns.
@param _eReason
The reason why the state is to be left.
@return
<TRUE/> if and only if the page is allowed to be left
*/
virtual sal_Bool prepareLeaveCurrentState( CommitPageReason _eReason );
/** will be called when the given state is left
This is the very last possibility for derived classes to veto the deactivation
of a page.
@todo Normally, we would not need the return value here - derived classes now have
the possibility to veto page deactivations in <member>prepareLeaveCurrentState</member>. However,
changing this return type is too incompatible at the moment ...
@return
<TRUE/> if and only if the page is allowed to be left
*/
virtual sal_Bool leaveState( WizardState _nState );
/** determine the next state to travel from the given one
The default behaviour is linear traveling, overwrite this to change it
Return WZS_INVALID_STATE to prevent traveling.
*/
virtual WizardState determineNextState( WizardState _nCurrentState ) const;
/** called when the finish button is pressed
<p>By default, only the base class' Finnish method (which is not virtual) is called</p>
*/
virtual sal_Bool onFinish(sal_Int32 _nResult);
/// travel to the next state
sal_Bool travelNext();
/// travel to the previous state
sal_Bool travelPrevious();
/** enables the automatic enabled/disabled state of the "Next" button
If this is <TRUE/>, then upon entering a new state, the "Next" button will automatically be
enabled if and only if determineNextState does not return WZS_INVALID_STATE.
*/
void enableAutomaticNextButtonState( bool _bEnable = true );
bool isAutomaticNextButtonStateEnabled() const;
/** removes a page from the history. Should be called when the page is being disabled
*/
void removePageFromHistory( WizardState nToRemove );
/** skip a state
The method behaves as if from the current state, <arg>_nSteps</arg> <method>travelNext</method>s were
called, but without actually creating or displaying the ntermediate pages. Only the
(<arg>_nSteps</arg> + 1)th page is created.
The skipped states appear in the state history, so <method>travelPrevious</method> will make use of them.
A very essential precondition for using this method is that your <method>determineNextState</method>
method is able to determine the next state without actually having the page of the current state.
@return
<TRUE/> if and only if traveling was successfull
@see skipUntil
@see skipBackwardUntil
*/
sal_Bool skip( sal_Int32 _nSteps = 1 );
/** skips one or more states, until a given state is reached
The method behaves as if from the current state, <method>travelNext</method>s were called
successively, until <arg>_nTargetState</arg> is reached, but without actually creating or
displaying the ntermediate pages.
The skipped states appear in the state history, so <method>travelPrevious</method> will make use of them.
@return
<TRUE/> if and only if traveling was successfull
@see skip
@see skipBackwardUntil
*/
sal_Bool skipUntil( WizardState _nTargetState );
/** moves back one or more states, until a given state is reached
This method allows traveling backwards more than one state without actually showing the intermediate
states.
For instance, if you want to travel two steps backward at a time, you could used
two travelPrevious calls, but this would <em>show</em> both pages, which is not necessary,
since you're interested in the target page only. Using <member>skipBackwardUntil</member> reliefs
you from this.
@return
<TRUE/> if and only if traveling was successfull
@see skipUntil
@see skip
*/
sal_Bool skipBackwardUntil( WizardState _nTargetState );
/** returns the current state of the machine
Vulgo, this is the identifier of the current tab page :)
*/
WizardState getCurrentState() const { return WizardDialog::GetCurLevel(); }
virtual IWizardPage* getWizardPage(TabPage* _pCurrentPage) const;
public:
class AccessGuard { friend class WizardTravelSuspension; private: AccessGuard() { } };
void suspendTraveling( AccessGuard );
void resumeTraveling( AccessGuard );
bool isTravelingSuspended() const;
private:
// long OnNextPage( PushButton* );
DECL_DLLPRIVATE_LINK(OnNextPage, PushButton*);
DECL_DLLPRIVATE_LINK(OnPrevPage, PushButton*);
DECL_DLLPRIVATE_LINK(OnFinish, PushButton*);
SVT_DLLPRIVATE void implResetDefault(Window* _pWindow);
SVT_DLLPRIVATE void implUpdateTitle();
};
/// helper class to temporarily suspend any traveling in the wizard
class WizardTravelSuspension
{
public:
WizardTravelSuspension( OWizardMachine& _rWizard )
:m_rWizard( _rWizard )
{
m_rWizard.suspendTraveling( OWizardMachine::AccessGuard() );
}
~WizardTravelSuspension()
{
m_rWizard.resumeTraveling( OWizardMachine::AccessGuard() );
}
private:
OWizardMachine& m_rWizard;
};
//.........................................................................
} // namespace svt
//.........................................................................
#endif // _SVTOOLS_WIZARDMACHINE_HXX_
<|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: itemholder2.cxx,v $
*
* $Revision: 1.7 $
*
* last change: $Author: rt $ $Date: 2005-09-08 14:40:47 $
*
* 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
*
************************************************************************/
#ifdef SVL_DLLIMPLEMENTATION
#undef SVL_DLLIMPLEMENTATION
#endif
#define SVT_DLLIMPLEMENTATION
#include "itemholder2.hxx"
//-----------------------------------------------
// includes
#ifndef _COMPHELPER_PROCESSFACTORY_HXX_
#include <comphelper/processfactory.hxx>
#endif
#ifndef _COM_SUN_STAR_LANG_XCOMPONENT_HPP_
#include <com/sun/star/lang/XComponent.hpp>
#endif
#include <helpopt.hxx>
#include <syslocaleoptions.hxx>
#include <undoopt.hxx>
#include <useroptions.hxx>
#include <tools/debug.hxx>
//-----------------------------------------------
// namespaces
namespace css = ::com::sun::star;
//-----------------------------------------------
// declarations
//-----------------------------------------------
ItemHolder2::ItemHolder2()
: ItemHolderMutexBase()
{
try
{
css::uno::Reference< css::lang::XMultiServiceFactory > xSMGR = ::comphelper::getProcessServiceFactory();
css::uno::Reference< css::lang::XComponent > xCfg(
xSMGR->createInstance(::rtl::OUString::createFromAscii("com.sun.star.configuration.ConfigurationProvider")),
css::uno::UNO_QUERY);
if (xCfg.is())
xCfg->addEventListener(static_cast< css::lang::XEventListener* >(this));
}
// #i37892 got errorhandling from ConfigManager::GetConfigurationProvider()
catch(css::uno::RuntimeException& rREx)
{
throw rREx;
}
#ifdef DBG_UTIL
catch(css::uno::Exception& rEx)
{
static sal_Bool bMessage = sal_True;
if(bMessage)
{
bMessage = sal_False;
::rtl::OString sMsg("CreateInstance with arguments exception: ");
sMsg += ::rtl::OString(rEx.Message.getStr(),
rEx.Message.getLength(),
RTL_TEXTENCODING_ASCII_US);
DBG_ERROR(sMsg.getStr());
}
}
#else
catch(css::uno::Exception&){}
#endif
}
//-----------------------------------------------
ItemHolder2::~ItemHolder2()
{
impl_releaseAllItems();
}
//-----------------------------------------------
ItemHolder2* ItemHolder2::getGlobalItemHolder()
{
static ItemHolder2* pHolder = new ItemHolder2();
return pHolder;
}
//-----------------------------------------------
void ItemHolder2::holdConfigItem(EItem eItem)
{
::osl::ResettableMutexGuard aLock(m_aLock);
TItems::const_iterator pIt;
for ( pIt = m_lItems.begin();
pIt != m_lItems.end() ;
++pIt )
{
const TItemInfo& rInfo = *pIt;
if (rInfo.eItem == eItem)
return;
}
TItemInfo aNewItem;
aNewItem.eItem = eItem;
impl_newItem(aNewItem);
if (aNewItem.pItem)
m_lItems.push_back(aNewItem);
}
//-----------------------------------------------
void SAL_CALL ItemHolder2::disposing(const css::lang::EventObject& aEvent)
throw(css::uno::RuntimeException)
{
impl_releaseAllItems();
}
//-----------------------------------------------
void ItemHolder2::impl_releaseAllItems()
{
::osl::ResettableMutexGuard aLock(m_aLock);
TItems::iterator pIt;
for ( pIt = m_lItems.begin();
pIt != m_lItems.end() ;
++pIt )
{
TItemInfo& rInfo = *pIt;
impl_deleteItem(rInfo);
}
m_lItems.clear();
}
//-----------------------------------------------
void ItemHolder2::impl_newItem(TItemInfo& rItem)
{
switch(rItem.eItem)
{
case E_SYSLOCALEOPTIONS :
rItem.pItem = new SvtSysLocaleOptions();
break;
case E_UNDOOPTIONS :
rItem.pItem = new SvtUndoOptions();
break;
case E_USEROPTIONS :
rItem.pItem = new SvtUserOptions();
break;
case E_HELPOPTIONS :
rItem.pItem = new SvtHelpOptions();
break;
}
}
//-----------------------------------------------
void ItemHolder2::impl_deleteItem(TItemInfo& rItem)
{
if (!rItem.pItem)
return;
switch(rItem.eItem)
{
case E_SYSLOCALEOPTIONS :
delete (SvtSysLocaleOptions*)rItem.pItem;
break;
case E_UNDOOPTIONS :
delete (SvtUndoOptions*)rItem.pItem;
break;
case E_USEROPTIONS :
delete (SvtUserOptions*)rItem.pItem;
break;
case E_HELPOPTIONS :
delete (SvtHelpOptions*)rItem.pItem;
break;
}
rItem.pItem = 0;
}
<commit_msg>INTEGRATION: CWS perform06 (1.7.60); FILE MERGED 2005/10/25 08:04:03 as 1.7.60.1: #i56589# hold config items alive till office die<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: itemholder2.cxx,v $
*
* $Revision: 1.8 $
*
* last change: $Author: rt $ $Date: 2005-11-11 08:50:34 $
*
* 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
*
************************************************************************/
#ifdef SVL_DLLIMPLEMENTATION
#undef SVL_DLLIMPLEMENTATION
#endif
#define SVT_DLLIMPLEMENTATION
#include "itemholder2.hxx"
//-----------------------------------------------
// includes
#ifndef _COMPHELPER_PROCESSFACTORY_HXX_
#include <comphelper/processfactory.hxx>
#endif
#ifndef _COM_SUN_STAR_LANG_XCOMPONENT_HPP_
#include <com/sun/star/lang/XComponent.hpp>
#endif
#include <accessibilityoptions.hxx>
#include <apearcfg.hxx>
#include <cjkoptions.hxx>
#include <colorcfg.hxx>
#include <ctloptions.hxx>
#include <fontsubstconfig.hxx>
#include <helpopt.hxx>
#include <languageoptions.hxx>
#include <misccfg.hxx>
#include <printoptions.hxx>
#include <syslocaleoptions.hxx>
#include <undoopt.hxx>
#include <useroptions.hxx>
#include <tools/debug.hxx>
//-----------------------------------------------
// namespaces
namespace css = ::com::sun::star;
//-----------------------------------------------
// declarations
//-----------------------------------------------
ItemHolder2::ItemHolder2()
: ItemHolderMutexBase()
{
try
{
css::uno::Reference< css::lang::XMultiServiceFactory > xSMGR = ::comphelper::getProcessServiceFactory();
css::uno::Reference< css::lang::XComponent > xCfg(
xSMGR->createInstance(::rtl::OUString::createFromAscii("com.sun.star.configuration.ConfigurationProvider")),
css::uno::UNO_QUERY);
if (xCfg.is())
xCfg->addEventListener(static_cast< css::lang::XEventListener* >(this));
}
// #i37892 got errorhandling from ConfigManager::GetConfigurationProvider()
catch(css::uno::RuntimeException& rREx)
{
throw rREx;
}
#ifdef DBG_UTIL
catch(css::uno::Exception& rEx)
{
static sal_Bool bMessage = sal_True;
if(bMessage)
{
bMessage = sal_False;
::rtl::OString sMsg("CreateInstance with arguments exception: ");
sMsg += ::rtl::OString(rEx.Message.getStr(),
rEx.Message.getLength(),
RTL_TEXTENCODING_ASCII_US);
DBG_ERROR(sMsg.getStr());
}
}
#else
catch(css::uno::Exception&){}
#endif
}
//-----------------------------------------------
ItemHolder2::~ItemHolder2()
{
impl_releaseAllItems();
}
//-----------------------------------------------
void ItemHolder2::holdConfigItem(EItem eItem)
{
static ItemHolder2* pHolder = new ItemHolder2();
pHolder->impl_addItem(eItem);
}
//-----------------------------------------------
void SAL_CALL ItemHolder2::disposing(const css::lang::EventObject& aEvent)
throw(css::uno::RuntimeException)
{
impl_releaseAllItems();
}
//-----------------------------------------------
void ItemHolder2::impl_addItem(EItem eItem)
{
::osl::ResettableMutexGuard aLock(m_aLock);
TItems::const_iterator pIt;
for ( pIt = m_lItems.begin();
pIt != m_lItems.end() ;
++pIt )
{
const TItemInfo& rInfo = *pIt;
if (rInfo.eItem == eItem)
return;
}
TItemInfo aNewItem;
aNewItem.eItem = eItem;
impl_newItem(aNewItem);
if (aNewItem.pItem)
m_lItems.push_back(aNewItem);
}
//-----------------------------------------------
void ItemHolder2::impl_releaseAllItems()
{
::osl::ResettableMutexGuard aLock(m_aLock);
TItems::iterator pIt;
for ( pIt = m_lItems.begin();
pIt != m_lItems.end() ;
++pIt )
{
TItemInfo& rInfo = *pIt;
impl_deleteItem(rInfo);
}
m_lItems.clear();
}
//-----------------------------------------------
void ItemHolder2::impl_newItem(TItemInfo& rItem)
{
switch(rItem.eItem)
{
case E_ACCESSIBILITYOPTIONS :
rItem.pItem = new SvtAccessibilityOptions();
break;
case E_APEARCFG :
// no ref count rItem.pItem = new SvtTabAppearanceCfg();
break;
case E_CJKOPTIONS :
rItem.pItem = new SvtCJKOptions();
break;
case E_COLORCFG :
rItem.pItem = new ::svtools::ColorConfig();
break;
case E_CTLOPTIONS :
rItem.pItem = new SvtCTLOptions();
break;
case E_FONTSUBSTCONFIG :
// no ref count rItem.pItem = new SvtFontSubstConfig();
break;
case E_HELPOPTIONS :
rItem.pItem = new SvtHelpOptions();
break;
case E_LANGUAGEOPTIONS :
// capsulate CTL and CJL options ! rItem.pItem = new SvtLanguageOptions();
break;
case E_MISCCFG :
// no ref count rItem.pItem = new SfxMiscCfg();
break;
case E_PRINTOPTIONS :
rItem.pItem = new SvtPrinterOptions();
break;
case E_PRINTFILEOPTIONS :
rItem.pItem = new SvtPrintFileOptions();
break;
case E_SYSLOCALEOPTIONS :
rItem.pItem = new SvtSysLocaleOptions();
break;
case E_UNDOOPTIONS :
rItem.pItem = new SvtUndoOptions();
break;
case E_USEROPTIONS :
rItem.pItem = new SvtUserOptions();
break;
}
}
//-----------------------------------------------
void ItemHolder2::impl_deleteItem(TItemInfo& rItem)
{
if (rItem.pItem)
{
delete rItem.pItem;
rItem.pItem = 0;
}
/*
switch(rItem.eItem)
{
case E_SYSLOCALEOPTIONS :
delete (SvtSysLocaleOptions*)rItem.pItem;
break;
case E_UNDOOPTIONS :
delete (SvtUndoOptions*)rItem.pItem;
break;
case E_USEROPTIONS :
delete (SvtUserOptions*)rItem.pItem;
break;
case E_HELPOPTIONS :
delete (SvtHelpOptions*)rItem.pItem;
break;
}
*/
}
<|endoftext|> |
<commit_before>/*************************************************************************
*
* $RCSfile: hyperlabel.cxx,v $
*
* $Revision: 1.4 $
*
* last change: $Author: kz $ $Date: 2004-11-26 20:40:27 $
*
* 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 EXPRESS 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 SVTOOLS_ROADMAP_HXX
#include "hyperlabel.hxx"
#endif
#ifndef _SV_BITMAP_HXX
#include <vcl/bitmap.hxx>
#endif
#ifndef _TOOLS_COLOR_HXX
#include <tools/color.hxx>
#endif
#ifndef _VCL_TABPAGE_HXX
#include <vcl/tabpage.hxx>
#endif
//.........................................................................
namespace svt
{
//.........................................................................
//=====================================================================
//= FontChanger
//=====================================================================
class FontChanger
{
protected:
OutputDevice* m_pDev;
public:
FontChanger( OutputDevice* _pDev, const Font& _rNewFont )
:m_pDev( _pDev )
{
m_pDev->Push( PUSH_FONT );
m_pDev->SetFont( _rNewFont );
}
~FontChanger()
{
m_pDev->Pop( );
}
};
class HyperLabelImpl
{
public:
sal_Int16 ID;
sal_Int32 Index;
sal_Bool bInteractive;
Size m_aMinSize;
sal_Bool m_bHyperMode;
HyperLabelImpl();
};
//---------------------------------------------------------------------
HyperLabelImpl::HyperLabelImpl()
{
}
HyperLabel::HyperLabel( Window* _pParent, const ResId& _rId )
:FixedText( _pParent, _rId )
,m_pImpl( NULL )
{
implInit(_pParent);
}
HyperLabel::HyperLabel( Window* _pParent, WinBits _nWinStyle )
:FixedText( _pParent, _nWinStyle )
,m_pImpl( NULL )
{
implInit(_pParent);
}
sal_Int32 HyperLabel::GetLogicWidth()
{
Size rLogicLocSize = PixelToLogic( m_pImpl->m_aMinSize, MAP_APPFONT );
return rLogicLocSize.Width();
}
void HyperLabel::SetLabelAndSize(::rtl::OUString _rText, const Size& _rNewSize )
{
Size rLocSize = _rNewSize;
Size rLogicLocSize = PixelToLogic( _rNewSize, MAP_APPFONT );
SetLabel( _rText );
ImplCalcMinimumSize( rLocSize );
rLocSize.Height() = ( m_pImpl->m_aMinSize.Height());
// else
// rLocSize = LogicToPixel( Size( rLogicLocSize.Width(), LABELBASEMAPHEIGHT ), MAP_APPFONT );
SetSizePixel( rLocSize );
Show();
}
sal_Bool HyperLabel::ImplCalcMinimumSize(const Size& _rCompSize )
{
sal_Bool b_AdjustMinWidth = sal_False;
m_pImpl->m_aMinSize = CalcMinimumSize( );
if ( m_pImpl->m_aMinSize.Width() >= _rCompSize.Width() ) // the MinimumSize is used to size the FocusRectangle
{
m_pImpl->m_aMinSize.Width() = _rCompSize.Width(); // and for the MouseMove method
m_pImpl->m_aMinSize = CalcMinimumSize(_rCompSize.Width() );
b_AdjustMinWidth = sal_True;
}
m_pImpl->m_aMinSize.Height() += 2;
m_pImpl->m_aMinSize.Width() += 1;
return b_AdjustMinWidth;
}
void HyperLabel::implInit(Window* _pParent)
{
const StyleSettings& rStyleSettings = GetSettings().GetStyleSettings();
m_pImpl = new HyperLabelImpl;
ToggleBackgroundColor( COL_TRANSPARENT );
Show();
}
void HyperLabel::ToggleBackgroundColor( const Color& _rGBColor )
{
const StyleSettings& rStyleSettings = GetSettings().GetStyleSettings();
SetControlBackground( _rGBColor );
if (_rGBColor == COL_TRANSPARENT)
SetTextColor( rStyleSettings.GetFieldTextColor( ) );
else
SetTextColor( rStyleSettings.GetHighlightTextColor( ) );
}
void HyperLabel::MouseMove( const MouseEvent& rMEvt )
{
Font aFont = GetControlFont( );
const Color aColor = GetTextColor();
if (rMEvt.IsLeaveWindow())
{
DeactivateHyperMode(aFont, aColor);
}
else
{
Point aPoint = GetPointerPosPixel();
if (aPoint.X() < m_pImpl->m_aMinSize.Width())
{
if ( IsEnabled() && (m_pImpl->bInteractive) )
{
ActivateHyperMode( aFont, aColor);
return;
}
}
DeactivateHyperMode(aFont, aColor);
}
}
void HyperLabel::ActivateHyperMode(Font aFont, const Color aColor)
{
aFont.SetUnderline(UNDERLINE_SINGLE);
m_pImpl->m_bHyperMode = sal_True;
SetPointer( POINTER_REFHAND );
SetControlFont( aFont);
SetTextColor( aColor);
}
void HyperLabel::DeactivateHyperMode(Font aFont, const Color aColor)
{
m_pImpl->m_bHyperMode = sal_False;
aFont.SetUnderline(UNDERLINE_NONE);
SetPointer( POINTER_ARROW );
SetControlFont( aFont);
SetTextColor( aColor);
}
void HyperLabel::MouseButtonDown( const MouseEvent& rMEvt )
{
if ( m_pImpl->m_bHyperMode && m_pImpl->bInteractive )
{
maClickHdl.Call( this );
}
}
void HyperLabel::GetFocus()
{
if ( IsEnabled() && m_pImpl->bInteractive )
{
Point aPoint(0,0);
Rectangle rRect(aPoint, Size( m_pImpl->m_aMinSize.Width(), GetSizePixel().Height() ) );
ShowFocus( rRect );
}
}
void HyperLabel::LoseFocus()
{
HideFocus();
}
HyperLabel::~HyperLabel( )
{
delete m_pImpl;
}
void HyperLabel::SetInteractive( sal_Bool _bInteractive )
{
m_pImpl->bInteractive = ( _bInteractive && IsEnabled() );
}
void HyperLabel::SetHyperLabelPosition(sal_uInt16 XPos, sal_uInt16 YPos)
{
SetPosPixel( LogicToPixel( Point( XPos, YPos ), MAP_APPFONT ) );
}
Point HyperLabel::GetLogicalPosition()
{
Point aPoint = GetPosPixel( );
return PixelToLogic( aPoint, MAP_APPFONT );
}
sal_Int16 HyperLabel::GetID() const
{
return m_pImpl->ID;
}
sal_Int32 HyperLabel::GetIndex() const
{
return m_pImpl->Index;
}
void HyperLabel::SetID( sal_Int16 _ID )
{
m_pImpl->ID = _ID;
}
void HyperLabel::SetIndex( sal_Int32 _Index )
{
m_pImpl->Index = _Index;
}
::rtl::OUString HyperLabel::GetLabel( )
{
return GetText();
}
void HyperLabel::SetLabel( ::rtl::OUString _rText )
{
SetText(_rText);
Show();
}
//------------------------------------------------------------------------------
void HyperLabel::DataChanged( const DataChangedEvent& rDCEvt )
{
const StyleSettings& rStyleSettings = GetSettings().GetStyleSettings();
FixedText::DataChanged( rDCEvt );
if ((( rDCEvt.GetType() == DATACHANGED_SETTINGS ) ||
( rDCEvt.GetType() == DATACHANGED_DISPLAY )) &&
( rDCEvt.GetFlags() & SETTINGS_STYLE ))
{
const Color& rGBColor = GetControlBackground();
if (rGBColor == COL_TRANSPARENT)
SetTextColor( rStyleSettings.GetFieldTextColor( ) );
else
{
SetControlBackground(rStyleSettings.GetHighlightColor());
SetTextColor( rStyleSettings.GetHighlightTextColor( ) );
}
Invalidate();
}
}
//.........................................................................
} // namespace svt
//.........................................................................
<commit_msg>INTEGRATION: CWS vcl34 (1.4.48); FILE MERGED 2005/01/07 14:36:19 dv 1.4.48.1: #i38359# Use some extra space for proper painting of focus rect<commit_after>/*************************************************************************
*
* $RCSfile: hyperlabel.cxx,v $
*
* $Revision: 1.5 $
*
* last change: $Author: rt $ $Date: 2005-01-31 09:25:36 $
*
* 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 EXPRESS 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 SVTOOLS_ROADMAP_HXX
#include "hyperlabel.hxx"
#endif
#ifndef _SV_BITMAP_HXX
#include <vcl/bitmap.hxx>
#endif
#ifndef _TOOLS_COLOR_HXX
#include <tools/color.hxx>
#endif
#ifndef _VCL_TABPAGE_HXX
#include <vcl/tabpage.hxx>
#endif
//.........................................................................
namespace svt
{
//.........................................................................
//=====================================================================
//= FontChanger
//=====================================================================
class FontChanger
{
protected:
OutputDevice* m_pDev;
public:
FontChanger( OutputDevice* _pDev, const Font& _rNewFont )
:m_pDev( _pDev )
{
m_pDev->Push( PUSH_FONT );
m_pDev->SetFont( _rNewFont );
}
~FontChanger()
{
m_pDev->Pop( );
}
};
class HyperLabelImpl
{
public:
sal_Int16 ID;
sal_Int32 Index;
sal_Bool bInteractive;
Size m_aMinSize;
sal_Bool m_bHyperMode;
HyperLabelImpl();
};
//---------------------------------------------------------------------
HyperLabelImpl::HyperLabelImpl()
{
}
HyperLabel::HyperLabel( Window* _pParent, const ResId& _rId )
:FixedText( _pParent, _rId )
,m_pImpl( NULL )
{
implInit(_pParent);
}
HyperLabel::HyperLabel( Window* _pParent, WinBits _nWinStyle )
:FixedText( _pParent, _nWinStyle )
,m_pImpl( NULL )
{
implInit(_pParent);
}
sal_Int32 HyperLabel::GetLogicWidth()
{
Size rLogicLocSize = PixelToLogic( m_pImpl->m_aMinSize, MAP_APPFONT );
return rLogicLocSize.Width();
}
void HyperLabel::SetLabelAndSize(::rtl::OUString _rText, const Size& _rNewSize )
{
Size rLocSize = _rNewSize;
Size rLogicLocSize = PixelToLogic( _rNewSize, MAP_APPFONT );
SetLabel( _rText );
ImplCalcMinimumSize( rLocSize );
rLocSize.Height() = ( m_pImpl->m_aMinSize.Height());
// else
// rLocSize = LogicToPixel( Size( rLogicLocSize.Width(), LABELBASEMAPHEIGHT ), MAP_APPFONT );
SetSizePixel( rLocSize );
Show();
}
sal_Bool HyperLabel::ImplCalcMinimumSize(const Size& _rCompSize )
{
sal_Bool b_AdjustMinWidth = sal_False;
m_pImpl->m_aMinSize = CalcMinimumSize( );
if ( m_pImpl->m_aMinSize.Width() >= _rCompSize.Width() ) // the MinimumSize is used to size the FocusRectangle
{
m_pImpl->m_aMinSize.Width() = _rCompSize.Width(); // and for the MouseMove method
m_pImpl->m_aMinSize = CalcMinimumSize(_rCompSize.Width() );
b_AdjustMinWidth = sal_True;
}
m_pImpl->m_aMinSize.Height() += 2;
m_pImpl->m_aMinSize.Width() += 1;
return b_AdjustMinWidth;
}
void HyperLabel::implInit(Window* _pParent)
{
const StyleSettings& rStyleSettings = GetSettings().GetStyleSettings();
m_pImpl = new HyperLabelImpl;
ToggleBackgroundColor( COL_TRANSPARENT );
WinBits nWinStyle = GetStyle();
nWinStyle |= WB_EXTRAOFFSET;
SetStyle( nWinStyle );
Show();
}
void HyperLabel::ToggleBackgroundColor( const Color& _rGBColor )
{
const StyleSettings& rStyleSettings = GetSettings().GetStyleSettings();
SetControlBackground( _rGBColor );
if (_rGBColor == COL_TRANSPARENT)
SetTextColor( rStyleSettings.GetFieldTextColor( ) );
else
SetTextColor( rStyleSettings.GetHighlightTextColor( ) );
}
void HyperLabel::MouseMove( const MouseEvent& rMEvt )
{
Font aFont = GetControlFont( );
const Color aColor = GetTextColor();
if (rMEvt.IsLeaveWindow())
{
DeactivateHyperMode(aFont, aColor);
}
else
{
Point aPoint = GetPointerPosPixel();
if (aPoint.X() < m_pImpl->m_aMinSize.Width())
{
if ( IsEnabled() && (m_pImpl->bInteractive) )
{
ActivateHyperMode( aFont, aColor);
return;
}
}
DeactivateHyperMode(aFont, aColor);
}
}
void HyperLabel::ActivateHyperMode(Font aFont, const Color aColor)
{
aFont.SetUnderline(UNDERLINE_SINGLE);
m_pImpl->m_bHyperMode = sal_True;
SetPointer( POINTER_REFHAND );
SetControlFont( aFont);
SetTextColor( aColor);
}
void HyperLabel::DeactivateHyperMode(Font aFont, const Color aColor)
{
m_pImpl->m_bHyperMode = sal_False;
aFont.SetUnderline(UNDERLINE_NONE);
SetPointer( POINTER_ARROW );
SetControlFont( aFont);
SetTextColor( aColor);
}
void HyperLabel::MouseButtonDown( const MouseEvent& rMEvt )
{
if ( m_pImpl->m_bHyperMode && m_pImpl->bInteractive )
{
maClickHdl.Call( this );
}
}
void HyperLabel::GetFocus()
{
if ( IsEnabled() && m_pImpl->bInteractive )
{
Point aPoint(0,0);
Rectangle rRect(aPoint, Size( m_pImpl->m_aMinSize.Width(), GetSizePixel().Height() ) );
ShowFocus( rRect );
}
}
void HyperLabel::LoseFocus()
{
HideFocus();
}
HyperLabel::~HyperLabel( )
{
delete m_pImpl;
}
void HyperLabel::SetInteractive( sal_Bool _bInteractive )
{
m_pImpl->bInteractive = ( _bInteractive && IsEnabled() );
}
void HyperLabel::SetHyperLabelPosition(sal_uInt16 XPos, sal_uInt16 YPos)
{
SetPosPixel( LogicToPixel( Point( XPos, YPos ), MAP_APPFONT ) );
}
Point HyperLabel::GetLogicalPosition()
{
Point aPoint = GetPosPixel( );
return PixelToLogic( aPoint, MAP_APPFONT );
}
sal_Int16 HyperLabel::GetID() const
{
return m_pImpl->ID;
}
sal_Int32 HyperLabel::GetIndex() const
{
return m_pImpl->Index;
}
void HyperLabel::SetID( sal_Int16 _ID )
{
m_pImpl->ID = _ID;
}
void HyperLabel::SetIndex( sal_Int32 _Index )
{
m_pImpl->Index = _Index;
}
::rtl::OUString HyperLabel::GetLabel( )
{
return GetText();
}
void HyperLabel::SetLabel( ::rtl::OUString _rText )
{
SetText(_rText);
Show();
}
//------------------------------------------------------------------------------
void HyperLabel::DataChanged( const DataChangedEvent& rDCEvt )
{
const StyleSettings& rStyleSettings = GetSettings().GetStyleSettings();
FixedText::DataChanged( rDCEvt );
if ((( rDCEvt.GetType() == DATACHANGED_SETTINGS ) ||
( rDCEvt.GetType() == DATACHANGED_DISPLAY )) &&
( rDCEvt.GetFlags() & SETTINGS_STYLE ))
{
const Color& rGBColor = GetControlBackground();
if (rGBColor == COL_TRANSPARENT)
SetTextColor( rStyleSettings.GetFieldTextColor( ) );
else
{
SetControlBackground(rStyleSettings.GetHighlightColor());
SetTextColor( rStyleSettings.GetHighlightTextColor( ) );
}
Invalidate();
}
}
//.........................................................................
} // namespace svt
//.........................................................................
<|endoftext|> |
<commit_before> /*************************************************************************
*
* $RCSfile: accfootnote.cxx,v $
*
* $Revision: 1.7 $
*
* last change: $Author: hr $ $Date: 2003-03-27 15:39:18 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the "License"); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#ifdef PRECOMPILED
#include "core_pch.hxx"
#endif
#pragma hdrstop
#ifndef _VOS_MUTEX_HXX_ //autogen
#include <vos/mutex.hxx>
#endif
#ifndef _DRAFTS_COM_SUN_STAR_ACCESSIBILITY_ACCESSIBLEROLE_HPP_
#include <drafts/com/sun/star/accessibility/AccessibleRole.hpp>
#endif
#ifndef _DRAFTS_COM_SUN_STAR_ACCESSIBILITY_ACCESSIBLESTATETYPE_HPP_
#include <drafts/com/sun/star/accessibility/AccessibleStateType.hpp>
#endif
#ifndef _UTL_ACCESSIBLESTATESETHELPER_HXX_
#include <unotools/accessiblestatesethelper.hxx>
#endif
#ifndef _COM_SUN_STAR_UNO_RUNTIMEEXCEPTION_HPP_
#include <com/sun/star/uno/RuntimeException.hpp>
#endif
#ifndef _RTL_UUID_H_
#include <rtl/uuid.h>
#endif
#ifndef _SV_SVAPP_HXX //autogen
#include <vcl/svapp.hxx>
#endif
#ifndef _FTNFRM_HXX
#include <ftnfrm.hxx>
#endif
#ifndef _FMTFTN_HXX //autogen
#include <fmtftn.hxx>
#endif
#ifndef _TXTFTN_HXX //autogen
#include <txtftn.hxx>
#endif
#ifndef _VIEWSH_HXX
#include <viewsh.hxx>
#endif
#ifndef _PAGEFRM_HXX
//#include <pagefrm.hxx>
#endif
#ifndef _PAGEDESC_HXX
//#include <pagedesc.hxx>
#endif
#ifndef _FLDBAS_HXX
//#include <fldbas.hxx>
#endif
#ifndef _ACCMAP_HXX
#include <accmap.hxx>
#endif
#ifndef _ACCFOOTNOTE_HXX
#include "accfootnote.hxx"
#endif
#ifndef _ACCESS_HRC
#include "access.hrc"
#endif
using namespace ::com::sun::star::lang;
using namespace ::com::sun::star::uno;
using namespace ::drafts::com::sun::star::accessibility;
using namespace ::rtl;
const sal_Char sServiceNameFootnote[] = "drafts.com.sun.star.text.AccessibleFootnoteView";
const sal_Char sServiceNameEndnote[] = "drafts.com.sun.star.text.AccessibleEndnoteView";
const sal_Char sImplementationNameFootnote[] = "com.sun.star.comp.Writer.SwAccessibleFootnoteView";
const sal_Char sImplementationNameEndnote[] = "com.sun.star.comp.Writer.SwAccessibleEndnoteView";
SwAccessibleFootnote::SwAccessibleFootnote(
SwAccessibleMap *pMap,
sal_Bool bIsEndnote,
sal_Int32 nFootEndNote,
const SwFtnFrm *pFtnFrm ) :
SwAccessibleContext( pMap,
bIsEndnote ? AccessibleRole::ENDNOTE : AccessibleRole::FOOTNOTE,
pFtnFrm )
{
vos::OGuard aGuard(Application::GetSolarMutex());
sal_uInt16 nResId = bIsEndnote ? STR_ACCESS_ENDNOTE_NAME
: STR_ACCESS_FOOTNOTE_NAME;
OUString sArg( OUString::valueOf( nFootEndNote ) );
SetName( GetResource( nResId, &sArg ) );
}
SwAccessibleFootnote::~SwAccessibleFootnote()
{
}
OUString SAL_CALL SwAccessibleFootnote::getAccessibleDescription (void)
throw (::com::sun::star::uno::RuntimeException)
{
vos::OGuard aGuard(Application::GetSolarMutex());
CHECK_FOR_DEFUNC( XAccessibleContext )
sal_uInt16 nResId = AccessibleRole::ENDNOTE == GetRole()
? STR_ACCESS_ENDNOTE_DESC
: STR_ACCESS_FOOTNOTE_DESC ;
OUString sArg;
const SwTxtFtn *pTxtFtn =
static_cast< const SwFtnFrm *>( GetFrm() )->GetAttr();
if( pTxtFtn )
{
const SwDoc *pDoc = GetMap()->GetShell()->GetDoc();
sArg = pTxtFtn->GetFtn().GetViewNumStr( *pDoc );
}
return GetResource( nResId, &sArg );
}
OUString SAL_CALL SwAccessibleFootnote::getImplementationName()
throw( RuntimeException )
{
if( AccessibleRole::ENDNOTE == GetRole() )
return OUString(RTL_CONSTASCII_USTRINGPARAM(sImplementationNameEndnote));
else
return OUString(RTL_CONSTASCII_USTRINGPARAM(sImplementationNameFootnote));
}
sal_Bool SAL_CALL SwAccessibleFootnote::supportsService(
const ::rtl::OUString& sTestServiceName)
throw (::com::sun::star::uno::RuntimeException)
{
if( sTestServiceName.equalsAsciiL( sAccessibleServiceName,
sizeof(sAccessibleServiceName)-1 ) )
return sal_True;
else if( AccessibleRole::ENDNOTE == GetRole() )
return sTestServiceName.equalsAsciiL( sServiceNameEndnote, sizeof(sServiceNameEndnote)-1 );
else
return sTestServiceName.equalsAsciiL( sServiceNameFootnote, sizeof(sServiceNameFootnote)-1 );
}
Sequence< OUString > SAL_CALL SwAccessibleFootnote::getSupportedServiceNames()
throw( ::com::sun::star::uno::RuntimeException )
{
Sequence< OUString > aRet(2);
OUString* pArray = aRet.getArray();
if( AccessibleRole::ENDNOTE == GetRole() )
pArray[0] = OUString( RTL_CONSTASCII_USTRINGPARAM(sServiceNameEndnote) );
else
pArray[0] = OUString( RTL_CONSTASCII_USTRINGPARAM(sServiceNameFootnote) );
pArray[1] = OUString( RTL_CONSTASCII_USTRINGPARAM(sAccessibleServiceName) );
return aRet;
}
Sequence< sal_Int8 > SAL_CALL SwAccessibleFootnote::getImplementationId()
throw(RuntimeException)
{
vos::OGuard aGuard(Application::GetSolarMutex());
static Sequence< sal_Int8 > aId( 16 );
static sal_Bool bInit = sal_False;
if(!bInit)
{
rtl_createUuid( (sal_uInt8 *)(aId.getArray() ), 0, sal_True );
bInit = sal_True;
}
return aId;
}
sal_Bool SwAccessibleFootnote::IsEndnote( const SwFtnFrm *pFtnFrm )
{
const SwTxtFtn *pTxtFtn = pFtnFrm ->GetAttr();
return pTxtFtn && pTxtFtn->GetFtn().IsEndNote() ;
}
<commit_msg>INTEGRATION: CWS os8 (1.6.2.1.48); FILE MERGED 2003/04/03 07:09:20 os 1.6.2.1.48.1: #108583# precompiled headers removed<commit_after> /*************************************************************************
*
* $RCSfile: accfootnote.cxx,v $
*
* $Revision: 1.8 $
*
* last change: $Author: vg $ $Date: 2003-04-17 13:35:23 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the "License"); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#pragma hdrstop
#ifndef _VOS_MUTEX_HXX_ //autogen
#include <vos/mutex.hxx>
#endif
#ifndef _DRAFTS_COM_SUN_STAR_ACCESSIBILITY_ACCESSIBLEROLE_HPP_
#include <drafts/com/sun/star/accessibility/AccessibleRole.hpp>
#endif
#ifndef _DRAFTS_COM_SUN_STAR_ACCESSIBILITY_ACCESSIBLESTATETYPE_HPP_
#include <drafts/com/sun/star/accessibility/AccessibleStateType.hpp>
#endif
#ifndef _UTL_ACCESSIBLESTATESETHELPER_HXX_
#include <unotools/accessiblestatesethelper.hxx>
#endif
#ifndef _COM_SUN_STAR_UNO_RUNTIMEEXCEPTION_HPP_
#include <com/sun/star/uno/RuntimeException.hpp>
#endif
#ifndef _RTL_UUID_H_
#include <rtl/uuid.h>
#endif
#ifndef _SV_SVAPP_HXX //autogen
#include <vcl/svapp.hxx>
#endif
#ifndef _FTNFRM_HXX
#include <ftnfrm.hxx>
#endif
#ifndef _FMTFTN_HXX //autogen
#include <fmtftn.hxx>
#endif
#ifndef _TXTFTN_HXX //autogen
#include <txtftn.hxx>
#endif
#ifndef _VIEWSH_HXX
#include <viewsh.hxx>
#endif
#ifndef _PAGEFRM_HXX
//#include <pagefrm.hxx>
#endif
#ifndef _PAGEDESC_HXX
//#include <pagedesc.hxx>
#endif
#ifndef _FLDBAS_HXX
//#include <fldbas.hxx>
#endif
#ifndef _ACCMAP_HXX
#include <accmap.hxx>
#endif
#ifndef _ACCFOOTNOTE_HXX
#include "accfootnote.hxx"
#endif
#ifndef _ACCESS_HRC
#include "access.hrc"
#endif
using namespace ::com::sun::star::lang;
using namespace ::com::sun::star::uno;
using namespace ::drafts::com::sun::star::accessibility;
using namespace ::rtl;
const sal_Char sServiceNameFootnote[] = "drafts.com.sun.star.text.AccessibleFootnoteView";
const sal_Char sServiceNameEndnote[] = "drafts.com.sun.star.text.AccessibleEndnoteView";
const sal_Char sImplementationNameFootnote[] = "com.sun.star.comp.Writer.SwAccessibleFootnoteView";
const sal_Char sImplementationNameEndnote[] = "com.sun.star.comp.Writer.SwAccessibleEndnoteView";
SwAccessibleFootnote::SwAccessibleFootnote(
SwAccessibleMap *pMap,
sal_Bool bIsEndnote,
sal_Int32 nFootEndNote,
const SwFtnFrm *pFtnFrm ) :
SwAccessibleContext( pMap,
bIsEndnote ? AccessibleRole::ENDNOTE : AccessibleRole::FOOTNOTE,
pFtnFrm )
{
vos::OGuard aGuard(Application::GetSolarMutex());
sal_uInt16 nResId = bIsEndnote ? STR_ACCESS_ENDNOTE_NAME
: STR_ACCESS_FOOTNOTE_NAME;
OUString sArg( OUString::valueOf( nFootEndNote ) );
SetName( GetResource( nResId, &sArg ) );
}
SwAccessibleFootnote::~SwAccessibleFootnote()
{
}
OUString SAL_CALL SwAccessibleFootnote::getAccessibleDescription (void)
throw (::com::sun::star::uno::RuntimeException)
{
vos::OGuard aGuard(Application::GetSolarMutex());
CHECK_FOR_DEFUNC( XAccessibleContext )
sal_uInt16 nResId = AccessibleRole::ENDNOTE == GetRole()
? STR_ACCESS_ENDNOTE_DESC
: STR_ACCESS_FOOTNOTE_DESC ;
OUString sArg;
const SwTxtFtn *pTxtFtn =
static_cast< const SwFtnFrm *>( GetFrm() )->GetAttr();
if( pTxtFtn )
{
const SwDoc *pDoc = GetMap()->GetShell()->GetDoc();
sArg = pTxtFtn->GetFtn().GetViewNumStr( *pDoc );
}
return GetResource( nResId, &sArg );
}
OUString SAL_CALL SwAccessibleFootnote::getImplementationName()
throw( RuntimeException )
{
if( AccessibleRole::ENDNOTE == GetRole() )
return OUString(RTL_CONSTASCII_USTRINGPARAM(sImplementationNameEndnote));
else
return OUString(RTL_CONSTASCII_USTRINGPARAM(sImplementationNameFootnote));
}
sal_Bool SAL_CALL SwAccessibleFootnote::supportsService(
const ::rtl::OUString& sTestServiceName)
throw (::com::sun::star::uno::RuntimeException)
{
if( sTestServiceName.equalsAsciiL( sAccessibleServiceName,
sizeof(sAccessibleServiceName)-1 ) )
return sal_True;
else if( AccessibleRole::ENDNOTE == GetRole() )
return sTestServiceName.equalsAsciiL( sServiceNameEndnote, sizeof(sServiceNameEndnote)-1 );
else
return sTestServiceName.equalsAsciiL( sServiceNameFootnote, sizeof(sServiceNameFootnote)-1 );
}
Sequence< OUString > SAL_CALL SwAccessibleFootnote::getSupportedServiceNames()
throw( ::com::sun::star::uno::RuntimeException )
{
Sequence< OUString > aRet(2);
OUString* pArray = aRet.getArray();
if( AccessibleRole::ENDNOTE == GetRole() )
pArray[0] = OUString( RTL_CONSTASCII_USTRINGPARAM(sServiceNameEndnote) );
else
pArray[0] = OUString( RTL_CONSTASCII_USTRINGPARAM(sServiceNameFootnote) );
pArray[1] = OUString( RTL_CONSTASCII_USTRINGPARAM(sAccessibleServiceName) );
return aRet;
}
Sequence< sal_Int8 > SAL_CALL SwAccessibleFootnote::getImplementationId()
throw(RuntimeException)
{
vos::OGuard aGuard(Application::GetSolarMutex());
static Sequence< sal_Int8 > aId( 16 );
static sal_Bool bInit = sal_False;
if(!bInit)
{
rtl_createUuid( (sal_uInt8 *)(aId.getArray() ), 0, sal_True );
bInit = sal_True;
}
return aId;
}
sal_Bool SwAccessibleFootnote::IsEndnote( const SwFtnFrm *pFtnFrm )
{
const SwTxtFtn *pTxtFtn = pFtnFrm ->GetAttr();
return pTxtFtn && pTxtFtn->GetFtn().IsEndNote() ;
}
<|endoftext|> |
<commit_before>/*************************************************************************
*
* $RCSfile: writerhelper.cxx,v $
*
* $Revision: 1.2 $
*
* last change: $Author: obo $ $Date: 2003-09-01 12:39:39 $
*
* 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): _______________________________________
*
*
************************************************************************/
/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil -*- */
#ifndef SW_WRITERHELPER
#include "writerhelper.hxx"
#endif
#include <algorithm> //std::swap
#include <functional> //std::binary_function
#ifndef _DOC_HXX
#include <doc.hxx> //SwDoc
#endif
#ifndef _SVDOBJ_HXX
#include <svx/svdobj.hxx> //SdrObject
#endif
#ifndef _SVDOOLE2_HXX
#include <svx/svdoole2.hxx> //SdrOle2Obj
#endif
#ifndef _SVX_FMGLOB_HXX
#include <svx/fmglob.hxx> //FmFormInventor
#endif
namespace
{
//Utility to sort SwTxtFmtColl's by their outline numbering level
class outlinecmp : public
std::binary_function<const SwTxtFmtColl*, const SwTxtFmtColl*, bool>
{
public:
bool operator()(const SwTxtFmtColl *pA, const SwTxtFmtColl *pB) const
{
return pB->GetOutlineLevel() < pB->GetOutlineLevel();
}
};
}
namespace sw
{
namespace hack
{
void SetLayer::SendObjectToHell(SdrObject &rObject) const
{
SetObjectLayer(rObject, eHell);
}
void SetLayer::SendObjectToHeaven(SdrObject &rObject) const
{
SetObjectLayer(rObject, eHeaven);
}
void SetLayer::SetObjectLayer(SdrObject &rObject, Layer eLayer) const
{
if (FmFormInventor == rObject.GetObjInventor())
rObject.SetLayer(mnFormLayer);
else
{
switch (eLayer)
{
case eHeaven:
rObject.SetLayer(mnHeavenLayer);
break;
case eHell:
rObject.SetLayer(mnHellLayer);
break;
}
}
}
//SetLayer boilerplate begin
void SetLayer::Swap(SetLayer& rOther) throw()
{
std::swap(mnHeavenLayer, rOther.mnHeavenLayer);
std::swap(mnHellLayer, rOther.mnHellLayer);
std::swap(mnFormLayer, rOther.mnFormLayer);
}
SetLayer::SetLayer(const SwDoc &rDoc)
: mnHeavenLayer(rDoc.GetHeavenId()),
mnHellLayer(rDoc.GetHellId()),
mnFormLayer(rDoc.GetControlsId())
{
}
SetLayer::SetLayer(const SetLayer& rOther) throw()
: mnHeavenLayer(rOther.mnHeavenLayer),
mnHellLayer(rOther.mnHellLayer),
mnFormLayer(rOther.mnFormLayer)
{
}
SetLayer& SetLayer::operator=(const SetLayer& rOther) throw()
{
SetLayer aTemp(rOther);
Swap(aTemp);
return *this;
}
//SetLayer boilerplate end
DrawingOLEAdaptor::DrawingOLEAdaptor(SdrOle2Obj &rObj,
SvPersist &rPers)
: mxIPRef(rObj.GetObjRef()),
msOrigPersistName(rObj.GetPersistName()), mrPers(rPers)
{
rObj.SetPersistName(String());
rObj.SetObjRef(SvInPlaceObjectRef());
}
bool DrawingOLEAdaptor::TransferToDoc(const String &rName)
{
ASSERT(mxIPRef.Is(), "Transferring invalid object to doc");
if (!mxIPRef.Is())
return false;
SvInfoObjectRef refObj = new SvEmbeddedInfoObject(mxIPRef, rName);
bool bSuccess = mrPers.Move(refObj, rName);
if (bSuccess)
{
SvPersist *pO = mxIPRef;
ASSERT(!pO->IsModified(), "Not expected to be modified here");
if (pO->IsModified())
{
pO->DoSave();
pO->DoSaveCompleted();
}
mxIPRef.Clear();
bSuccess = mrPers.Unload(pO);
}
return bSuccess;
}
DrawingOLEAdaptor::~DrawingOLEAdaptor()
{
if (mxIPRef.Is())
{
if (SvInfoObject* pInfo = mrPers.Find(msOrigPersistName))
{
pInfo->SetDeleted(TRUE);
pInfo->SetObj(0);
}
mxIPRef->DoClose();
mrPers.Remove(mxIPRef);
mxIPRef.Clear();
}
}
}
namespace util
{
ParaStyles GetParaStyles(const SwDoc &rDoc)
{
ParaStyles aStyles;
typedef ParaStyles::size_type mysizet;
const SwTxtFmtColls *pColls = rDoc.GetTxtFmtColls();
mysizet nCount = pColls ? pColls->Count() : 0;
aStyles.reserve(nCount);
for (mysizet nI = 0; nI < nCount; ++nI)
aStyles.push_back((*pColls)[nI]);
return aStyles;
}
void SortByOutline(ParaStyles &rStyles)
{
std::sort(rStyles.begin(), rStyles.end(), outlinecmp());
}
}
}
/* vi:set tabstop=4 shiftwidth=4 expandtab: */
<commit_msg>INTEGRATION: CWS killarneyfilterteam13 (1.2.4); FILE MERGED 2003/09/16 10:29:29 cmc 1.2.4.2: #110379# A start node could 2003/09/08 15:26:27 cmc 1.2.4.1: #112027# #110379# rename and move suitably generic method to nice sensibly documented area<commit_after>/*************************************************************************
*
* $RCSfile: writerhelper.cxx,v $
*
* $Revision: 1.3 $
*
* last change: $Author: rt $ $Date: 2003-09-25 07:41:30 $
*
* 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): _______________________________________
*
*
************************************************************************/
/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil -*- */
#ifndef SW_WRITERHELPER
#include "writerhelper.hxx"
#endif
#include <algorithm> //std::swap
#include <functional> //std::binary_function
#ifndef _DOC_HXX
#include <doc.hxx> //SwDoc
#endif
#ifndef _SWTABLE_HXX
#include <swtable.hxx> //SwTable
#endif
#ifndef _FRMFMT_HXX
#include <frmfmt.hxx> //SwFrmFmt
#endif
#ifndef _SVDOBJ_HXX
#include <svx/svdobj.hxx> //SdrObject
#endif
#ifndef _SVDOOLE2_HXX
#include <svx/svdoole2.hxx> //SdrOle2Obj
#endif
#ifndef _SVX_FMGLOB_HXX
#include <svx/fmglob.hxx> //FmFormInventor
#endif
#ifndef _SVX_BRKITEM_HXX
#include <svx/brkitem.hxx> //SvxFmtBreakItem
#endif
namespace
{
//Utility to sort SwTxtFmtColl's by their outline numbering level
class outlinecmp : public
std::binary_function<const SwTxtFmtColl*, const SwTxtFmtColl*, bool>
{
public:
bool operator()(const SwTxtFmtColl *pA, const SwTxtFmtColl *pB) const
{
return pB->GetOutlineLevel() < pB->GetOutlineLevel();
}
};
}
namespace sw
{
namespace hack
{
void SetLayer::SendObjectToHell(SdrObject &rObject) const
{
SetObjectLayer(rObject, eHell);
}
void SetLayer::SendObjectToHeaven(SdrObject &rObject) const
{
SetObjectLayer(rObject, eHeaven);
}
void SetLayer::SetObjectLayer(SdrObject &rObject, Layer eLayer) const
{
if (FmFormInventor == rObject.GetObjInventor())
rObject.SetLayer(mnFormLayer);
else
{
switch (eLayer)
{
case eHeaven:
rObject.SetLayer(mnHeavenLayer);
break;
case eHell:
rObject.SetLayer(mnHellLayer);
break;
}
}
}
//SetLayer boilerplate begin
void SetLayer::Swap(SetLayer& rOther) throw()
{
std::swap(mnHeavenLayer, rOther.mnHeavenLayer);
std::swap(mnHellLayer, rOther.mnHellLayer);
std::swap(mnFormLayer, rOther.mnFormLayer);
}
SetLayer::SetLayer(const SwDoc &rDoc)
: mnHeavenLayer(rDoc.GetHeavenId()),
mnHellLayer(rDoc.GetHellId()),
mnFormLayer(rDoc.GetControlsId())
{
}
SetLayer::SetLayer(const SetLayer& rOther) throw()
: mnHeavenLayer(rOther.mnHeavenLayer),
mnHellLayer(rOther.mnHellLayer),
mnFormLayer(rOther.mnFormLayer)
{
}
SetLayer& SetLayer::operator=(const SetLayer& rOther) throw()
{
SetLayer aTemp(rOther);
Swap(aTemp);
return *this;
}
//SetLayer boilerplate end
DrawingOLEAdaptor::DrawingOLEAdaptor(SdrOle2Obj &rObj,
SvPersist &rPers)
: mxIPRef(rObj.GetObjRef()),
msOrigPersistName(rObj.GetPersistName()), mrPers(rPers)
{
rObj.SetPersistName(String());
rObj.SetObjRef(SvInPlaceObjectRef());
}
bool DrawingOLEAdaptor::TransferToDoc(const String &rName)
{
ASSERT(mxIPRef.Is(), "Transferring invalid object to doc");
if (!mxIPRef.Is())
return false;
SvInfoObjectRef refObj = new SvEmbeddedInfoObject(mxIPRef, rName);
bool bSuccess = mrPers.Move(refObj, rName);
if (bSuccess)
{
SvPersist *pO = mxIPRef;
ASSERT(!pO->IsModified(), "Not expected to be modified here");
if (pO->IsModified())
{
pO->DoSave();
pO->DoSaveCompleted();
}
mxIPRef.Clear();
bSuccess = mrPers.Unload(pO);
}
return bSuccess;
}
DrawingOLEAdaptor::~DrawingOLEAdaptor()
{
if (mxIPRef.Is())
{
if (SvInfoObject* pInfo = mrPers.Find(msOrigPersistName))
{
pInfo->SetDeleted(TRUE);
pInfo->SetObj(0);
}
mxIPRef->DoClose();
mrPers.Remove(mxIPRef);
mxIPRef.Clear();
}
}
}
namespace util
{
ParaStyles GetParaStyles(const SwDoc &rDoc)
{
ParaStyles aStyles;
typedef ParaStyles::size_type mysizet;
const SwTxtFmtColls *pColls = rDoc.GetTxtFmtColls();
mysizet nCount = pColls ? pColls->Count() : 0;
aStyles.reserve(nCount);
for (mysizet nI = 0; nI < nCount; ++nI)
aStyles.push_back((*pColls)[nI]);
return aStyles;
}
void SortByOutline(ParaStyles &rStyles)
{
std::sort(rStyles.begin(), rStyles.end(), outlinecmp());
}
bool HasPageBreak(const SwNode &rNd)
{
const SvxFmtBreakItem *pBreak = 0;
if (rNd.IsTableNode() && rNd.GetTableNode())
{
const SwTable& rTable = rNd.GetTableNode()->GetTable();
const SwFrmFmt* pApply = rTable.GetFrmFmt();
ASSERT(pApply, "impossible");
if (pApply)
pBreak = &(ItemGet<SvxFmtBreakItem>(*pApply, RES_BREAK));
}
else if (const SwCntntNode *pNd = rNd.GetCntntNode())
pBreak = &(ItemGet<SvxFmtBreakItem>(*pNd, RES_BREAK));
if (pBreak && pBreak->GetBreak() == SVX_BREAK_PAGE_BEFORE)
return true;
return false;
}
}
}
/* vi:set tabstop=4 shiftwidth=4 expandtab: */
<|endoftext|> |
<commit_before>/*************************************************************************
*
* $RCSfile: mmdocselectpage.cxx,v $
*
* $Revision: 1.4 $
*
* last change: $Author: rt $ $Date: 2004-09-29 09:31:12 $
*
* 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): _______________________________________
*
*
************************************************************************/
#ifdef SW_DLLIMPLEMENTATION
#undef SW_DLLIMPLEMENTATION
#endif
#pragma hdrstop
#ifndef INCLUDED_SVTOOLS_PATHOPTIONS_HXX
#include <svtools/pathoptions.hxx>
#endif
#ifndef _FILEDLGHELPER_HXX
#include <sfx2/filedlghelper.hxx>
#endif
#ifndef _SFXNEW_HXX
#include <sfx2/new.hxx>
#endif
#ifndef _SFX_DOCFILT_HACK_HXX
#include <sfx2/docfilt.hxx>
#endif
#ifndef _SFX_FCONTNR_HXX
#include <sfx2/fcontnr.hxx>
#endif
#ifndef _SFX_OBJFAC_HXX
#include <sfx2/docfac.hxx>
#endif
#ifndef _SV_MSGBOX_HXX
#include <vcl/msgbox.hxx>
#endif
#ifndef _SWVIEW_HXX
#include <view.hxx>
#endif
#ifndef _DOCSH_HXX
#include <docsh.hxx>
#endif
#ifndef _MAILMERGEDOCSELECTPAGE_HXX
#include <mmdocselectpage.hxx>
#endif
#ifndef _MAILMERGEWIZARD_HXX
#include <mailmergewizard.hxx>
#endif
#ifndef _SWTYPES_HXX
#include <swtypes.hxx>
#endif
#ifndef _SHELLIO_HXX
#include <shellio.hxx>
#endif
#ifndef _SW_ABSTDLG_HXX
#include <swabstdlg.hxx>
#endif
#ifndef _MMCONFIGITEM_HXX
#include <mmconfigitem.hxx>
#endif
#include <dbui.hrc>
#include <mmdocselectpage.hrc>
#ifndef _COM_SUN_STAR_UI_DIALOGS_XFILEPICKER_HPP_
#include <com/sun/star/ui/dialogs/XFilePicker.hpp>
#endif
#ifndef _COM_SUN_STAR_UI_DIALOGS_XFILTERMANAGER_HPP_
#include <com/sun/star/ui/dialogs/XFilterManager.hpp>
#endif
using namespace com::sun::star::ui::dialogs;
using namespace ::com::sun::star;
using namespace ::com::sun::star::uno;
using namespace svt;
/*-- 02.04.2004 09:40:14---------------------------------------------------
-----------------------------------------------------------------------*/
SwMailMergeDocSelectPage::SwMailMergeDocSelectPage( SwMailMergeWizard* _pParent ) :
svt::OWizardPage(_pParent, SW_RES(DLG_MM_DOCSELECT_PAGE)),
#pragma warning (disable : 4355)
m_aHeaderFI(this, ResId( FI_HEADER ) ),
m_aHowToFT (this, ResId( FT_HOWTO )),
m_aCurrentDocRB (this, ResId( RB_CURRENTDOC )),
m_aNewDocRB (this, ResId( RB_NEWDOC )),
m_aLoadDocRB (this, ResId( RB_LOADDOC )),
m_aBrowseDocPB (this, ResId( PB_LOADDOC )),
m_aLoadTemplateRB (this, ResId( RB_LOADTEMPLATE )),
m_aBrowseTemplatePB (this, ResId( PB_BROWSETEMPLATE )),
m_aRecentDocRB (this, ResId( RB_RECENTDOC )),
m_aRecentDocLB (this, ResId( LB_RECENTDOC )),
#pragma warning (default : 4355)
m_pWizard(_pParent)
{
FreeResource();
m_aCurrentDocRB.Check();
DocSelectHdl(&m_aNewDocRB);
Link aDocSelectLink = LINK(this, SwMailMergeDocSelectPage, DocSelectHdl);
m_aCurrentDocRB.SetClickHdl(aDocSelectLink);
m_aNewDocRB.SetClickHdl(aDocSelectLink);
m_aLoadDocRB.SetClickHdl(aDocSelectLink);
m_aLoadTemplateRB.SetClickHdl(aDocSelectLink);
m_aRecentDocRB.SetClickHdl(aDocSelectLink);
Link aFileSelectHdl = LINK(this, SwMailMergeDocSelectPage, FileSelectHdl);
m_aBrowseDocPB.SetClickHdl(aFileSelectHdl);
m_aBrowseTemplatePB.SetClickHdl(aFileSelectHdl);
const uno::Sequence< ::rtl::OUString >& rDocs =
m_pWizard->GetConfigItem().GetSavedDocuments();
for(sal_Int32 nDoc = 0; nDoc < rDocs.getLength(); ++nDoc)
{
//insert in reverse order
m_aRecentDocLB.InsertEntry(rDocs[nDoc], 0);
}
m_aRecentDocLB.SelectEntryPos(0);
if(!rDocs.getLength())
{
m_aRecentDocRB.Enable(sal_False);
}
}
/*-- 02.04.2004 09:40:14---------------------------------------------------
-----------------------------------------------------------------------*/
SwMailMergeDocSelectPage::~SwMailMergeDocSelectPage()
{
}
/*-- 05.04.2004 14:21:48---------------------------------------------------
-----------------------------------------------------------------------*/
IMPL_LINK(SwMailMergeDocSelectPage, DocSelectHdl, RadioButton*, pButton)
{
m_aRecentDocLB.Enable(&m_aRecentDocRB == pButton);
sal_Bool bEnableNext = m_aNewDocRB.IsChecked() || m_aCurrentDocRB.IsChecked() ||
(m_sLoadFileName.Len() && (m_aLoadDocRB.IsChecked() || m_aLoadTemplateRB.IsChecked())) ||
m_aRecentDocLB.GetSelectEntry().Len();
m_pWizard->enableButtons( WZB_NEXT, bEnableNext );
return 0;
}
/*-- 05.04.2004 14:25:12---------------------------------------------------
-----------------------------------------------------------------------*/
IMPL_LINK(SwMailMergeDocSelectPage, FileSelectHdl, PushButton*, pButton)
{
bool bTemplate = &m_aBrowseTemplatePB == pButton;
if(bTemplate)
{
m_aLoadTemplateRB.Check();
SfxNewFileDialog* pNewFileDlg = new SfxNewFileDialog(this, 0);
//pNewFileDlg->SetTemplateFlags(nFlags);
USHORT nRet = pNewFileDlg->Execute();
if(RET_TEMPLATE_LOAD == nRet)
bTemplate = false;
else if(RET_CANCEL != nRet)
m_sLoadFileName = pNewFileDlg->GetTemplateFileName();
delete pNewFileDlg;
}
else
m_aLoadDocRB.Check();
if(!bTemplate)
{
sfx2::FileDialogHelper aDlgHelper( TemplateDescription::FILEOPEN_SIMPLE, 0 );
Reference < XFilePicker > xFP = aDlgHelper.GetFilePicker();
xFP->setDisplayDirectory( SvtPathOptions().GetWorkPath() );
SfxObjectFactory &rFact = m_pWizard->GetSwView()->GetDocShell()->GetFactory();
SfxFilterMatcher aMatcher( String::CreateFromAscii(rFact.GetShortName()) );
SfxFilterMatcherIter aIter( &aMatcher );
Reference<XFilterManager> xFltMgr(xFP, UNO_QUERY);
const SfxFilter* pFlt = aIter.First();
while( pFlt )
{
if( pFlt && pFlt->IsAllowedAsTemplate() )
{
const String sWild = ((WildCard&)pFlt->GetWildcard()).GetWildCard();
xFltMgr->appendFilter( pFlt->GetUIName(), sWild );
}
if( pFlt->GetUserData().EqualsAscii( GetFILTER_XML() ))
xFltMgr->setCurrentFilter( pFlt->GetUIName() ) ;
pFlt = aIter.Next();
}
if( ERRCODE_NONE == aDlgHelper.Execute() )
{
m_sLoadFileName = xFP->getFiles().getConstArray()[0];
}
}
m_pWizard->enableButtons( WZB_NEXT, m_sLoadFileName.Len() > 0 );
return 0;
}
/*-- 06.04.2004 12:52:24---------------------------------------------------
-----------------------------------------------------------------------*/
sal_Bool SwMailMergeDocSelectPage::commitPage(COMMIT_REASON _eReason)
{
if(_eReason == CR_TRAVEL_NEXT)
{
sal_Bool bCloseDialog = sal_True;
if(m_sLoadFileName.Len() &&
(m_aLoadDocRB.IsChecked() || m_aLoadTemplateRB.IsChecked()))
m_pWizard->SetReloadDocument(m_sLoadFileName);
else if(m_aNewDocRB.IsChecked())
m_pWizard->SetReloadDocument(String());
else if(m_aRecentDocRB.IsChecked())
{
m_pWizard->SetReloadDocument(m_aRecentDocLB.GetSelectEntry());
}
else
bCloseDialog = sal_False;
if(bCloseDialog)
{
m_pWizard->SetRestartPage(MM_OUTPUTTYPETPAGE);
m_pWizard->EndDialog(RET_LOAD_DOC);
}
}
return sal_True;
}
<commit_msg>INTEGRATION: CWS os49 (1.4.212); FILE MERGED 2005/01/17 15:10:03 mbu 1.4.212.1: i40125<commit_after>/*************************************************************************
*
* $RCSfile: mmdocselectpage.cxx,v $
*
* $Revision: 1.5 $
*
* last change: $Author: vg $ $Date: 2005-03-07 17:36:06 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the "License"); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#ifdef SW_DLLIMPLEMENTATION
#undef SW_DLLIMPLEMENTATION
#endif
#pragma hdrstop
#ifndef INCLUDED_SVTOOLS_PATHOPTIONS_HXX
#include <svtools/pathoptions.hxx>
#endif
#ifndef _FILEDLGHELPER_HXX
#include <sfx2/filedlghelper.hxx>
#endif
#ifndef _SFXNEW_HXX
#include <sfx2/new.hxx>
#endif
#ifndef _SFX_DOCFILT_HACK_HXX
#include <sfx2/docfilt.hxx>
#endif
#ifndef _SFX_FCONTNR_HXX
#include <sfx2/fcontnr.hxx>
#endif
#ifndef _SFX_OBJFAC_HXX
#include <sfx2/docfac.hxx>
#endif
#ifndef _SV_MSGBOX_HXX
#include <vcl/msgbox.hxx>
#endif
#ifndef _SWVIEW_HXX
#include <view.hxx>
#endif
#ifndef _DOCSH_HXX
#include <docsh.hxx>
#endif
#ifndef _MAILMERGEDOCSELECTPAGE_HXX
#include <mmdocselectpage.hxx>
#endif
#ifndef _MAILMERGEWIZARD_HXX
#include <mailmergewizard.hxx>
#endif
#ifndef _SWTYPES_HXX
#include <swtypes.hxx>
#endif
#ifndef _SHELLIO_HXX
#include <shellio.hxx>
#endif
#ifndef _SW_ABSTDLG_HXX
#include <swabstdlg.hxx>
#endif
#ifndef _MMCONFIGITEM_HXX
#include <mmconfigitem.hxx>
#endif
#include <dbui.hrc>
#include <mmdocselectpage.hrc>
#ifndef _COM_SUN_STAR_UI_DIALOGS_XFILEPICKER_HPP_
#include <com/sun/star/ui/dialogs/XFilePicker.hpp>
#endif
#ifndef _COM_SUN_STAR_UI_DIALOGS_XFILTERMANAGER_HPP_
#include <com/sun/star/ui/dialogs/XFilterManager.hpp>
#endif
using namespace com::sun::star::ui::dialogs;
using namespace ::com::sun::star;
using namespace ::com::sun::star::uno;
using namespace svt;
/*-- 02.04.2004 09:40:14---------------------------------------------------
-----------------------------------------------------------------------*/
SwMailMergeDocSelectPage::SwMailMergeDocSelectPage( SwMailMergeWizard* _pParent ) :
svt::OWizardPage(_pParent, SW_RES(DLG_MM_DOCSELECT_PAGE)),
#pragma warning (disable : 4355)
m_aHeaderFI(this, ResId( FI_HEADER ) ),
m_aHowToFT (this, ResId( FT_HOWTO )),
m_aCurrentDocRB (this, ResId( RB_CURRENTDOC )),
m_aNewDocRB (this, ResId( RB_NEWDOC )),
m_aLoadDocRB (this, ResId( RB_LOADDOC )),
m_aBrowseDocPB (this, ResId( PB_LOADDOC )),
m_aLoadTemplateRB (this, ResId( RB_LOADTEMPLATE )),
m_aBrowseTemplatePB (this, ResId( PB_BROWSETEMPLATE )),
m_aRecentDocRB (this, ResId( RB_RECENTDOC )),
m_aRecentDocLB (this, ResId( LB_RECENTDOC )),
#pragma warning (default : 4355)
m_pWizard(_pParent)
{
FreeResource();
m_aCurrentDocRB.Check();
DocSelectHdl(&m_aNewDocRB);
Link aDocSelectLink = LINK(this, SwMailMergeDocSelectPage, DocSelectHdl);
m_aCurrentDocRB.SetClickHdl(aDocSelectLink);
m_aNewDocRB.SetClickHdl(aDocSelectLink);
m_aLoadDocRB.SetClickHdl(aDocSelectLink);
m_aLoadTemplateRB.SetClickHdl(aDocSelectLink);
m_aRecentDocRB.SetClickHdl(aDocSelectLink);
Link aFileSelectHdl = LINK(this, SwMailMergeDocSelectPage, FileSelectHdl);
m_aBrowseDocPB.SetClickHdl(aFileSelectHdl);
m_aBrowseTemplatePB.SetClickHdl(aFileSelectHdl);
const uno::Sequence< ::rtl::OUString >& rDocs =
m_pWizard->GetConfigItem().GetSavedDocuments();
for(sal_Int32 nDoc = 0; nDoc < rDocs.getLength(); ++nDoc)
{
//insert in reverse order
m_aRecentDocLB.InsertEntry(rDocs[nDoc], 0);
}
m_aRecentDocLB.SelectEntryPos(0);
if(!rDocs.getLength())
{
m_aRecentDocRB.Enable(sal_False);
}
}
/*-- 02.04.2004 09:40:14---------------------------------------------------
-----------------------------------------------------------------------*/
SwMailMergeDocSelectPage::~SwMailMergeDocSelectPage()
{
}
/*-- 05.04.2004 14:21:48---------------------------------------------------
-----------------------------------------------------------------------*/
IMPL_LINK(SwMailMergeDocSelectPage, DocSelectHdl, RadioButton*, pButton)
{
m_aRecentDocLB.Enable(&m_aRecentDocRB == pButton);
sal_Bool bEnableNext = m_aNewDocRB.IsChecked() || m_aCurrentDocRB.IsChecked() ||
(m_sLoadFileName.Len() && (m_aLoadDocRB.IsChecked() || m_aLoadTemplateRB.IsChecked())) ||
m_aRecentDocLB.GetSelectEntry().Len();
m_pWizard->enableButtons( WZB_NEXT, bEnableNext );
return 0;
}
/*-- 05.04.2004 14:25:12---------------------------------------------------
-----------------------------------------------------------------------*/
IMPL_LINK(SwMailMergeDocSelectPage, FileSelectHdl, PushButton*, pButton)
{
bool bTemplate = &m_aBrowseTemplatePB == pButton;
if(bTemplate)
{
m_aLoadTemplateRB.Check();
SfxNewFileDialog* pNewFileDlg = new SfxNewFileDialog(this, 0);
//pNewFileDlg->SetTemplateFlags(nFlags);
USHORT nRet = pNewFileDlg->Execute();
if(RET_TEMPLATE_LOAD == nRet)
bTemplate = false;
else if(RET_CANCEL != nRet)
m_sLoadFileName = pNewFileDlg->GetTemplateFileName();
delete pNewFileDlg;
}
else
m_aLoadDocRB.Check();
if(!bTemplate)
{
sfx2::FileDialogHelper aDlgHelper( TemplateDescription::FILEOPEN_SIMPLE, 0 );
Reference < XFilePicker > xFP = aDlgHelper.GetFilePicker();
xFP->setDisplayDirectory( SvtPathOptions().GetWorkPath() );
SfxObjectFactory &rFact = m_pWizard->GetSwView()->GetDocShell()->GetFactory();
SfxFilterMatcher aMatcher( String::CreateFromAscii(rFact.GetShortName()) );
SfxFilterMatcherIter aIter( &aMatcher );
Reference<XFilterManager> xFltMgr(xFP, UNO_QUERY);
const SfxFilter* pFlt = aIter.First();
while( pFlt )
{
if( pFlt && pFlt->IsAllowedAsTemplate() )
{
const String sWild = ((WildCard&)pFlt->GetWildcard()).GetWildCard();
xFltMgr->appendFilter( pFlt->GetUIName(), sWild );
// #i40125
if(pFlt->GetFilterFlags() & SFX_FILTER_DEFAULT)
xFltMgr->setCurrentFilter( pFlt->GetUIName() ) ;
}
pFlt = aIter.Next();
}
if( ERRCODE_NONE == aDlgHelper.Execute() )
{
m_sLoadFileName = xFP->getFiles().getConstArray()[0];
}
}
m_pWizard->enableButtons( WZB_NEXT, m_sLoadFileName.Len() > 0 );
return 0;
}
/*-- 06.04.2004 12:52:24---------------------------------------------------
-----------------------------------------------------------------------*/
sal_Bool SwMailMergeDocSelectPage::commitPage(COMMIT_REASON _eReason)
{
if(_eReason == CR_TRAVEL_NEXT)
{
sal_Bool bCloseDialog = sal_True;
if(m_sLoadFileName.Len() &&
(m_aLoadDocRB.IsChecked() || m_aLoadTemplateRB.IsChecked()))
m_pWizard->SetReloadDocument(m_sLoadFileName);
else if(m_aNewDocRB.IsChecked())
m_pWizard->SetReloadDocument(String());
else if(m_aRecentDocRB.IsChecked())
{
m_pWizard->SetReloadDocument(m_aRecentDocLB.GetSelectEntry());
}
else
bCloseDialog = sal_False;
if(bCloseDialog)
{
m_pWizard->SetRestartPage(MM_OUTPUTTYPETPAGE);
m_pWizard->EndDialog(RET_LOAD_DOC);
}
}
return sal_True;
}
<|endoftext|> |
<commit_before>//
// Logger-Android.cpp
// ee-core
//
// Created by Zinge on 7/6/16.
//
//
#include <android/log.h>
#include "Logger.hpp"
#include "LogLevel.hpp"
namespace ee {
namespace core {
void Logger::log(const LogLevel& level, const std::string& tag,
const std::string& message) {
__android_log_print(level.priority, tag.c_str(), message.c_str());
}
} // namespace core
} // namespace ee<commit_msg>- fix format warning.<commit_after>//
// Logger-Android.cpp
// ee-core
//
// Created by Zinge on 7/6/16.
//
//
#include <android/log.h>
#include "Logger.hpp"
#include "LogLevel.hpp"
namespace ee {
namespace core {
void Logger::log(const LogLevel& level, const std::string& tag,
const std::string& message) {
__android_log_print(level.priority, tag.c_str(), "%s", message.c_str());
}
} // namespace core
} // namespace ee<|endoftext|> |
<commit_before>#ifndef Metric_arith
#define Metric_arith
#include <array>
#include <limits>
#include <string>
#include <utility>
#include <algorithm>
#include <stdexcept>
#include <cinttypes>
#include <cstdint>
#include "algorithm.hpp"
namespace arithmetic
{
template <typename number> inline
number operator+(number a, const number &b)
{
return a += b;
}
template <typename number> inline
number operator-(number a, const number &b)
{
return a -= b;
}
template <typename number> inline
number operator*(number a, const number &b)
{
return a *= b;
}
template <typename number> inline
number operator/(number a, const number &b)
{
return a /= b;
}
template <typename number> inline
number operator%(number a, const number &b)
{
return a %= b;
}
template <typename number> inline
number operator++(number &a, int postfix)
{
number b = a;
++a;
return b;
}
template <typename number> inline
number operator--(number &a, int postfix)
{
number b = a;
--a;
return b;
}
template <typename number> inline
number operator<<(number a, unsigned b)
{
return a <<= b;
}
template <typename number> inline
number operator>>(number a, unsigned b)
{
return a >>= b;
}
using namespace std::rel_ops;
template <size_t size> class integer
{
using base = uint8_t;
using int_t = intmax_t;
using uint_t = uintmax_t;
using divide = std::imaxdiv;
using overflow = std::overflow_error;
using underflow = std::underflow_error;
static const uint_t max = std::numeric_limits<base>::max();
static const uint_t mod = max + 1;
std::array<base, size> digits;
public:
integer operator+=(const integer &that)
{
uint_t carry = 0;
for (size_t i = 0; i < size; ++i) {
uint_t num = digits[i] + that.digits[i] + carry;
if (max < num) {
auto div = divide(num, mod);
digits[i] = div.rem;
carry = div.quot;
} else {
digits[i] = num;
carry = 0;
}
}
if (carry) {
throw overflow("+");
}
return *this;
}
integer operator-=(const integer &that)
{
uint_t carry = 0;
for (size_t i = 0; i < size; ++i) {
int_t num = digits[i] - that.digits[i] - carry;
carry = 0;
while (num < 0) {
num += mod;
++carry;
}
digits[i] = num;
}
if (carry) {
throw underflow("-");
}
return *this;
}
integer operator*=(const integer &that)
{
uint_t carry = 0;
uint_t sums[size*2] = {0};
for (size_t i = 0; i < size; ++i) {
for (size_t j = 0; j < size; ++j) {
uint_t num = digits[i] * that.digits[j] + carry;
if (max < num) {
auto div = divide(num, mod);
sums[i + j] += div.rem;
carry = div.quot;
} else {
sums[i + j] += num;
carry = 0;
}
}
digits[i] = sums[i];
sums[size + i] += carry;
carry = 0;
}
return *this;
}
integer operator/=(const integer &that)
{
integer quot;
while (*this >= that) {
*this -= that;
++quot;
}
swap(quot);
return *this;
}
integer operator%=(const integer &that)
{
while (*this >= that) {
*this -= that;
}
return *this;
}
integer operator++()
{
for (base &dig : digits) {
if (dig < max) {
++dig;
break;
}
dig = 0;
}
return *this;
}
integer operator--()
{
for (base &dig : digits) {
if (0 < dig) {
--dig;
break;
}
dig = max;
}
return *this;
}
bool operator==(const integer &that)
{
return digits == that.digits;
}
bool operator<(const integer &that)
{
bool equal = true;
for (size_t i = 0; i < size; ++i) {
if (digits[i] > that.digits[i]) {
return false;
}
if (digits[i] < that.digits[i]) {
equal = false;
}
}
return !equal;
}
bool operator!()
{
auto zero = [](base dig){return !dig;};
return algorithm::all_of(digits, zero);
}
integer operator=(const std::string &string)
{
digits.fill(0);
for (char byte : string) {
uint_t carry = byte - '0';
for (size_t i = 0; i < size; ++i) {
carry += digits[i] * 10;
if (max < carry) {
auto div = divide(carry, mod);
digits[i] = div.rem;
carry = div.quot;
} else {
digits[i] = carry;
carry = 0;
}
}
if (carry) {
throw overflow("=string");
}
}
return *this;
}
integer operator=(uint_t num)
{
digits.fill(0);
size_t index = 0;
while (num) {
auto div = divide(num, mod);
digits[index] = div.rem;
num = div.quot;
++index;
if (size == index) {
throw overflow("=int");
}
}
return *this;
}
operator std::string() const
{
//TODO
std::string string;
for (base dig : digits) {
string += ":" + std::to_string(dig);
}
return string;
}
operator uint_t() const
{
size_t index = 0;
uint_t num = 0, order = 1;
while (index < size) {
num += order * digits[index];
order *= mod;
++index;
//should detect overflow
}
return num;
}
integer()
{
digits.fill(0);
}
integer(uint_t num)
{
*this = num;
}
integer(const std::string &string)
{
*this = string;
}
inline void swap(integer &that)
{
digits.swap(that.digits);
}
};
}; // namespace arithmetic
#endif // Metric_arithmetic
<commit_msg>Fixed use of std::imaxdiv<commit_after>#ifndef Metric_arith
#define Metric_arith
#include <array>
#include <limits>
#include <string>
#include <utility>
#include <algorithm>
#include <stdexcept>
#include <cinttypes>
#include <cstdint>
#include "algorithm.hpp"
namespace arithmetic
{
template <typename number> inline
number operator+(number a, const number &b)
{
return a += b;
}
template <typename number> inline
number operator-(number a, const number &b)
{
return a -= b;
}
template <typename number> inline
number operator*(number a, const number &b)
{
return a *= b;
}
template <typename number> inline
number operator/(number a, const number &b)
{
return a /= b;
}
template <typename number> inline
number operator%(number a, const number &b)
{
return a %= b;
}
template <typename number> inline
number operator++(number &a, int postfix)
{
number b = a;
++a;
return b;
}
template <typename number> inline
number operator--(number &a, int postfix)
{
number b = a;
--a;
return b;
}
template <typename number> inline
number operator<<(number a, unsigned b)
{
return a <<= b;
}
template <typename number> inline
number operator>>(number a, unsigned b)
{
return a >>= b;
}
using namespace std::rel_ops;
template <size_t size> class integer
{
using base = uint8_t;
using int_t = intmax_t;
using uint_t = uintmax_t;
using overflow = std::overflow_error;
using underflow = std::underflow_error;
static const uint_t max = std::numeric_limits<base>::max();
static const uint_t mod = max + 1;
std::array<base, size> digits;
public:
integer operator+=(const integer &that)
{
uint_t carry = 0;
for (size_t i = 0; i < size; ++i) {
uint_t num = digits[i] + that.digits[i] + carry;
if (max < num) {
auto div = std::imaxdiv(num, mod);
digits[i] = div.rem;
carry = div.quot;
} else {
digits[i] = num;
carry = 0;
}
}
if (carry) {
throw overflow("+");
}
return *this;
}
integer operator-=(const integer &that)
{
uint_t carry = 0;
for (size_t i = 0; i < size; ++i) {
int_t num = digits[i] - that.digits[i] - carry;
carry = 0;
while (num < 0) {
num += mod;
++carry;
}
digits[i] = num;
}
if (carry) {
throw underflow("-");
}
return *this;
}
integer operator*=(const integer &that)
{
uint_t carry = 0;
uint_t sums[size*2] = {0};
for (size_t i = 0; i < size; ++i) {
for (size_t j = 0; j < size; ++j) {
uint_t num = digits[i] * that.digits[j] + carry;
if (max < num) {
auto div = std::imaxdiv(num, mod);
sums[i + j] += div.rem;
carry = div.quot;
} else {
sums[i + j] += num;
carry = 0;
}
}
digits[i] = sums[i];
sums[size + i] += carry;
carry = 0;
}
return *this;
}
integer operator/=(const integer &that)
{
integer quot;
while (*this >= that) {
*this -= that;
++quot;
}
swap(quot);
return *this;
}
integer operator%=(const integer &that)
{
while (*this >= that) {
*this -= that;
}
return *this;
}
integer operator++()
{
for (base &dig : digits) {
if (dig < max) {
++dig;
break;
}
dig = 0;
}
return *this;
}
integer operator--()
{
for (base &dig : digits) {
if (0 < dig) {
--dig;
break;
}
dig = max;
}
return *this;
}
bool operator==(const integer &that)
{
return digits == that.digits;
}
bool operator<(const integer &that)
{
bool equal = true;
for (size_t i = 0; i < size; ++i) {
if (digits[i] > that.digits[i]) {
return false;
}
if (digits[i] < that.digits[i]) {
equal = false;
}
}
return !equal;
}
bool operator!()
{
auto zero = [](base dig){return !dig;};
return algorithm::all_of(digits, zero);
}
integer operator=(const std::string &string)
{
digits.fill(0);
for (char byte : string) {
uint_t carry = byte - '0';
for (size_t i = 0; i < size; ++i) {
carry += digits[i] * 10;
if (max < carry) {
auto div = std::imaxdiv(carry, mod);
digits[i] = div.rem;
carry = div.quot;
} else {
digits[i] = carry;
carry = 0;
}
}
if (carry) {
throw overflow("=string");
}
}
return *this;
}
integer operator=(uint_t num)
{
digits.fill(0);
size_t index = 0;
while (num) {
auto div = std::imaxdiv(num, mod);
digits[index] = div.rem;
num = div.quot;
++index;
if (size == index) {
throw overflow("=int");
}
}
return *this;
}
operator std::string() const
{
//TODO
std::string string;
for (base dig : digits) {
string += ":" + std::to_string(dig);
}
return string;
}
operator uint_t() const
{
size_t index = 0;
uint_t num = 0, order = 1;
while (index < size) {
num += order * digits[index];
order *= mod;
++index;
//should detect overflow
}
return num;
}
integer()
{
digits.fill(0);
}
integer(uint_t num)
{
*this = num;
}
integer(const std::string &string)
{
*this = string;
}
inline void swap(integer &that)
{
digits.swap(that.digits);
}
};
}; // namespace arithmetic
#endif // Metric_arithmetic
<|endoftext|> |
<commit_before>#include "mod_stream.h"
#include "modipulate_common.h"
#include "libmodplug-hacked/modplug.h"
#include <iostream>
#include <stdlib.h>
#include <stdio.h>
#include <string>
#include <malloc.h>
#include <sstream>
#include <math.h>
#include <errno.h>
#include <AL/al.h>
#include <ogg/ogg.h>
using namespace std;
extern void call_note_changed(unsigned channel, int note, int instrument, int sample);
extern void call_pattern_changed(unsigned pattern);
extern void call_row_changed(int row);
ModStreamRow::ModStreamRow() {
change_tempo = -1;
change_pattern = -1;
samples_since_last = 0;
}
void ModStreamRow::add_note(ModStreamNote* n) {
notes.push_back(n);
}
ModStreamNote::ModStreamNote() {
channel = 0;
note = -1;
instrument = -1;
sample = -1;
}
ModStream::ModStream() {
modplug_file = NULL;
file_length = 0;
}
ModStream::~ModStream() {
}
void ModStream::open(string path) {
DPRINT("Opening: %s", path.c_str());
FILE *file;
// Open file and load into memory.
file = fopen(path.c_str(), "rb");
if (!file)
throw string("Unable to open file: " + path);
// Fseek to get file length.
fseek(file, 0, SEEK_END);
file_length = ftell(file);
fseek(file, 0, SEEK_SET);
// Allocate memory
buffer = (char*)malloc(file_length + 1);
if (!buffer) {
fclose(file);
throw string("Out of memory");
}
// Read file contents into buffer.
fread(buffer, file_length, 1, file);
fclose(file);
DPRINT("Loaded mod! File length is: %lu", file_length);
modplug_file = HackedModPlug_Load(buffer, file_length + 1);
if (modplug_file == NULL)
throw("File was loaded, modplug couldn't parse it.");
// Setup playback format.
ModPlug_Settings settings;
ModPlug_GetSettings(&settings);
settings.mFrequency = sampling_rate;
settings.mLoopCount = -1;
ModPlug_SetSettings(&settings);
// Stereo.
format = AL_FORMAT_STEREO16;
// Initialize buffers.
alGenBuffers(NUM_BUFFERS, buffers);
check_error(__LINE__);
alGenSources(1, &source);
check_error(__LINE__);
alSource3f(source, AL_POSITION, 0.0, 0.0, 0.0);
alSource3f(source, AL_VELOCITY, 0.0, 0.0, 0.0);
alSource3f(source, AL_DIRECTION, 0.0, 0.0, 0.0);
alSourcef (source, AL_ROLLOFF_FACTOR, 0.0 );
alSourcei (source, AL_SOURCE_RELATIVE, AL_TRUE );
// Save pointer.
modplug_file->mSoundFile.mod_stream = this;
// Allocate the current row.
current_row = new ModStreamRow();
samples_played = 0;
set_playing(true);
}
void ModStream::close() {
alSourceStop(source);
check_error(__LINE__);
empty();
alDeleteBuffers(NUM_BUFFERS, buffers);
check_error(__LINE__);
alDeleteSources(1, &source);
check_error(__LINE__);
ModPlug_Unload(modplug_file);
}
bool ModStream::playback() {
if (!playing)
return true;
if (is_playing())
return true;
for (int i = 0; i < NUM_BUFFERS; i++)
if (!stream(buffers[i]))
return false;
alSourceQueueBuffers(source, NUM_BUFFERS, buffers);
alSourcePlay(source);
if (clock_gettime(CLOCK_MONOTONIC, &song_start) == -1)
DPRINT("Error getting time: %d", errno);
perform_callbacks();
return true;
}
void ModStream::set_playing(bool is_playing) {
playing = is_playing;
if (is_playing)
alSourcePlay(source);
else
alSourcePause(source);
check_error(__LINE__);
}
bool ModStream::is_playing() {
ALenum state;
alGetSourcei(source, AL_SOURCE_STATE, &state);
check_error(__LINE__);
return AL_PLAYING == state && playing;
}
bool ModStream::update() {
static bool in_update = false; // anti-reentrancy hack
int processed;
bool active = true;
if (!is_playing())
return false;
if (in_update)
return true;
in_update = true;
alGetSourcei(source, AL_BUFFERS_PROCESSED, &processed);
while (processed--) {
ALuint buffer;
alSourceUnqueueBuffers(source, 1, &buffer);
check_error(__LINE__);
active = stream(buffer);
alSourceQueueBuffers(source, 1, &buffer);
check_error(__LINE__);
}
// Activate cached callbacks.
perform_callbacks();
in_update = false;
return active;
}
bool ModStream::stream(ALuint buffer) {
if (!playing)
return false;
char data[BUFFER_SIZE];
int size = HackedModPlug_Read(modplug_file, data, BUFFER_SIZE);
if (size < 0) {
stringstream ss;
ss << "Error reading from modplug " << size;
throw string(ss.str());
} else if (size == 0)
return false; // end of stream
alBufferData(buffer, format, data, size, sampling_rate);
check_error(__LINE__);
return true;
}
void ModStream::empty() {
int queued;
alGetSourcei(source, AL_BUFFERS_QUEUED, &queued);
while(queued--) {
ALuint buffer;
alSourceUnqueueBuffers(source, 1, &buffer);
check_error(__LINE__);
}
}
void ModStream::check_error(int line) {
int error = alGetError();
string serror = "";
switch(error) {
break;
case AL_INVALID_NAME:
serror = "AL_INVALID_NAME";
break;
case AL_INVALID_ENUM:
serror = "AL_INVALID_ENUM";
break;
case AL_INVALID_VALUE:
serror = "AL_INVALID_VALUE";
break;
case AL_INVALID_OPERATION:
serror = "AL_INVALID_OPERATION";
break;
case AL_OUT_OF_MEMORY:
serror = "AL_OUT_OF_MEMORY";
break;
}
if (error != AL_NO_ERROR) {
stringstream ss;
ss << "OpenAL error was raised: ";
if (serror != "")
ss << serror;
else
ss << error;
ss << " at line " << line;
throw string(ss.str());
}
}
// Enable or disable channels.
void ModStream::set_channel_enabled(int channel, bool is_enabled) {
modplug_file->mSoundFile.enabled_channels[channel] = is_enabled;
}
bool ModStream::get_channel_enabled(int channel) {
return modplug_file->mSoundFile.enabled_channels[channel];
}
// Returns the number of channels.
int ModStream::get_num_channels() {
return (int) ModPlug_NumChannels(modplug_file);
}
void ModStream::perform_callbacks() {
// Make sure there's something to do!
if (rows.empty())
return;
// Check time since we started the music.
timespec current_time; // Current time.
timespec since_start; // Time since start.
if (clock_gettime(CLOCK_MONOTONIC, ¤t_time) == -1)
DPRINT("Error getting time: %d", errno);
time_diff(since_start, song_start, current_time);
// Convert time to sample number.
unsigned long long samples_since_start = since_start.tv_sec * sampling_rate +
(unsigned long long) ( ((double) (since_start.tv_nsec) * ((double)sampling_rate) / 1000000000.0)); // 1 / one billion = 1 ns
while (!rows.empty()) {
// Process callbacks from row data.
ModStreamRow* r = rows.front();
unsigned long long sample_counter = samples_played + r->samples_since_last;
cout << "Sample counter: " << sample_counter << endl;
cout << "Samples since start: " << samples_since_start << endl;
if (sample_counter > samples_since_start)
break; // done (for now!)
samples_played += r->samples_since_last;
rows.pop();
// 1. Pattern change callback.
if (r->change_pattern != -1)
call_pattern_changed(r->change_pattern);
// 2. Row change callback.
call_row_changed(r->row);
// 3. Note change callbacks.
if (r->notes.size() > 0) {
list<ModStreamNote*>::iterator it;
for (it = r->notes.begin(); it != r->notes.end(); it++) {
ModStreamNote* n = (*it);
call_note_changed(n->channel, n->note, n->instrument, n->sample);
delete n;
}
}
delete r;
}
}
void ModStream::on_note_change(unsigned channel, int note, int instrument, int sample) {
ModStreamNote* n = new ModStreamNote();
n->channel = channel;
n->note = note;
n->instrument = instrument;
n->sample = sample;
current_row->add_note(n);
}
void ModStream::on_pattern_changed(unsigned pattern) {
current_row->change_pattern = (int) pattern;
}
void ModStream::on_row_changed(int row) {
rows.push(current_row);
current_row = new ModStreamRow();
current_row->row = row;
}
void ModStream::increase_sample_count(int add) {
current_row->samples_since_last += add;
}
std::string ModStream::get_title() {
const char* name = ModPlug_GetName(modplug_file);
return name != NULL ? string(name) : string("");
}
std::string ModStream::get_message() {
const char* message = ModPlug_GetMessage(modplug_file);
return (message != NULL) ? string(message) : string("");
}
double ModStream::get_volume() {
return ((double) (ModPlug_GetMasterVolume(modplug_file) - 1)) / 511.0;
}
void ModStream::set_volume(double vol) {
if (vol < 0.)
vol = 0.;
else if (vol > 1.)
vol = 1.;
ModPlug_SetMasterVolume(modplug_file, round(vol * 511) + 1);
}
unsigned ModStream::get_num_instruments() {
return ModPlug_NumInstruments(modplug_file);
}
std::string ModStream::get_instrument_name(unsigned number) {
std::string ret = "";
unsigned length = ModPlug_InstrumentName(modplug_file, number, NULL);
if (length == 0)
return ret;
char* buffer = new char[length+2];
for (unsigned i = 0; i < length+2; i++)
buffer[i] = 0;
if (length == ModPlug_InstrumentName(modplug_file, number, buffer))
ret = string(buffer);
delete [] buffer;
return ret;
}
unsigned ModStream::get_num_samples() {
return ModPlug_NumSamples(modplug_file);
}
std::string ModStream::get_sample_name(unsigned number) {
std::string ret = "";
unsigned length = ModPlug_SampleName(modplug_file, number, NULL);
if (length == 0)
return ret;
char* buffer = new char[length+2];
for (unsigned i = 0; i < length+2; i++)
buffer[i] = 0;
if (length == ModPlug_SampleName(modplug_file, number, buffer))
ret = string(buffer);
delete [] buffer;
return ret;
}
int ModStream::get_current_row() {
return ModPlug_GetCurrentRow(modplug_file);
}
int ModStream::get_current_pattern() {
return ModPlug_GetCurrentPattern(modplug_file);
}
int ModStream::get_rows_in_pattern(int pattern) {
unsigned int num_rows = 0;
if (NULL == ModPlug_GetPattern(modplug_file, pattern, &num_rows))
return -1;
return (int) num_rows;
}
// Based on code from here:
// http://www.guyrutenberg.com/2007/09/22/profiling-code-using-clock_gettime/
void ModStream::time_diff(timespec& result, const timespec& start, const timespec& end) {
if ((end.tv_nsec-start.tv_nsec)<0) {
result.tv_sec = end.tv_sec-start.tv_sec-1;
result.tv_nsec = 1000000000+end.tv_nsec-start.tv_nsec;
} else {
result.tv_sec = end.tv_sec-start.tv_sec;
result.tv_nsec = end.tv_nsec-start.tv_nsec;
}
}
<commit_msg>Removed debug statements.<commit_after>#include "mod_stream.h"
#include "modipulate_common.h"
#include "libmodplug-hacked/modplug.h"
#include <iostream>
#include <stdlib.h>
#include <stdio.h>
#include <string>
#include <malloc.h>
#include <sstream>
#include <math.h>
#include <errno.h>
#include <AL/al.h>
#include <ogg/ogg.h>
using namespace std;
extern void call_note_changed(unsigned channel, int note, int instrument, int sample);
extern void call_pattern_changed(unsigned pattern);
extern void call_row_changed(int row);
ModStreamRow::ModStreamRow() {
change_tempo = -1;
change_pattern = -1;
samples_since_last = 0;
}
void ModStreamRow::add_note(ModStreamNote* n) {
notes.push_back(n);
}
ModStreamNote::ModStreamNote() {
channel = 0;
note = -1;
instrument = -1;
sample = -1;
}
ModStream::ModStream() {
modplug_file = NULL;
file_length = 0;
}
ModStream::~ModStream() {
}
void ModStream::open(string path) {
DPRINT("Opening: %s", path.c_str());
FILE *file;
// Open file and load into memory.
file = fopen(path.c_str(), "rb");
if (!file)
throw string("Unable to open file: " + path);
// Fseek to get file length.
fseek(file, 0, SEEK_END);
file_length = ftell(file);
fseek(file, 0, SEEK_SET);
// Allocate memory
buffer = (char*)malloc(file_length + 1);
if (!buffer) {
fclose(file);
throw string("Out of memory");
}
// Read file contents into buffer.
fread(buffer, file_length, 1, file);
fclose(file);
DPRINT("Loaded mod! File length is: %lu", file_length);
modplug_file = HackedModPlug_Load(buffer, file_length + 1);
if (modplug_file == NULL)
throw("File was loaded, modplug couldn't parse it.");
// Setup playback format.
ModPlug_Settings settings;
ModPlug_GetSettings(&settings);
settings.mFrequency = sampling_rate;
settings.mLoopCount = -1;
ModPlug_SetSettings(&settings);
// Stereo.
format = AL_FORMAT_STEREO16;
// Initialize buffers.
alGenBuffers(NUM_BUFFERS, buffers);
check_error(__LINE__);
alGenSources(1, &source);
check_error(__LINE__);
alSource3f(source, AL_POSITION, 0.0, 0.0, 0.0);
alSource3f(source, AL_VELOCITY, 0.0, 0.0, 0.0);
alSource3f(source, AL_DIRECTION, 0.0, 0.0, 0.0);
alSourcef (source, AL_ROLLOFF_FACTOR, 0.0 );
alSourcei (source, AL_SOURCE_RELATIVE, AL_TRUE );
// Save pointer.
modplug_file->mSoundFile.mod_stream = this;
// Allocate the current row.
current_row = new ModStreamRow();
samples_played = 0;
set_playing(true);
}
void ModStream::close() {
alSourceStop(source);
check_error(__LINE__);
empty();
alDeleteBuffers(NUM_BUFFERS, buffers);
check_error(__LINE__);
alDeleteSources(1, &source);
check_error(__LINE__);
ModPlug_Unload(modplug_file);
}
bool ModStream::playback() {
if (!playing)
return true;
if (is_playing())
return true;
for (int i = 0; i < NUM_BUFFERS; i++)
if (!stream(buffers[i]))
return false;
alSourceQueueBuffers(source, NUM_BUFFERS, buffers);
alSourcePlay(source);
if (clock_gettime(CLOCK_MONOTONIC, &song_start) == -1)
DPRINT("Error getting time: %d", errno);
perform_callbacks();
return true;
}
void ModStream::set_playing(bool is_playing) {
playing = is_playing;
if (is_playing)
alSourcePlay(source);
else
alSourcePause(source);
check_error(__LINE__);
}
bool ModStream::is_playing() {
ALenum state;
alGetSourcei(source, AL_SOURCE_STATE, &state);
check_error(__LINE__);
return AL_PLAYING == state && playing;
}
bool ModStream::update() {
static bool in_update = false; // anti-reentrancy hack
int processed;
bool active = true;
if (!is_playing())
return false;
if (in_update)
return true;
in_update = true;
alGetSourcei(source, AL_BUFFERS_PROCESSED, &processed);
while (processed--) {
ALuint buffer;
alSourceUnqueueBuffers(source, 1, &buffer);
check_error(__LINE__);
active = stream(buffer);
alSourceQueueBuffers(source, 1, &buffer);
check_error(__LINE__);
}
// Activate cached callbacks.
perform_callbacks();
in_update = false;
return active;
}
bool ModStream::stream(ALuint buffer) {
if (!playing)
return false;
char data[BUFFER_SIZE];
int size = HackedModPlug_Read(modplug_file, data, BUFFER_SIZE);
if (size < 0) {
stringstream ss;
ss << "Error reading from modplug " << size;
throw string(ss.str());
} else if (size == 0)
return false; // end of stream
alBufferData(buffer, format, data, size, sampling_rate);
check_error(__LINE__);
return true;
}
void ModStream::empty() {
int queued;
alGetSourcei(source, AL_BUFFERS_QUEUED, &queued);
while(queued--) {
ALuint buffer;
alSourceUnqueueBuffers(source, 1, &buffer);
check_error(__LINE__);
}
}
void ModStream::check_error(int line) {
int error = alGetError();
string serror = "";
switch(error) {
break;
case AL_INVALID_NAME:
serror = "AL_INVALID_NAME";
break;
case AL_INVALID_ENUM:
serror = "AL_INVALID_ENUM";
break;
case AL_INVALID_VALUE:
serror = "AL_INVALID_VALUE";
break;
case AL_INVALID_OPERATION:
serror = "AL_INVALID_OPERATION";
break;
case AL_OUT_OF_MEMORY:
serror = "AL_OUT_OF_MEMORY";
break;
}
if (error != AL_NO_ERROR) {
stringstream ss;
ss << "OpenAL error was raised: ";
if (serror != "")
ss << serror;
else
ss << error;
ss << " at line " << line;
throw string(ss.str());
}
}
// Enable or disable channels.
void ModStream::set_channel_enabled(int channel, bool is_enabled) {
modplug_file->mSoundFile.enabled_channels[channel] = is_enabled;
}
bool ModStream::get_channel_enabled(int channel) {
return modplug_file->mSoundFile.enabled_channels[channel];
}
// Returns the number of channels.
int ModStream::get_num_channels() {
return (int) ModPlug_NumChannels(modplug_file);
}
void ModStream::perform_callbacks() {
// Make sure there's something to do!
if (rows.empty())
return;
// Check time since we started the music.
timespec current_time; // Current time.
timespec since_start; // Time since start.
if (clock_gettime(CLOCK_MONOTONIC, ¤t_time) == -1)
DPRINT("Error getting time: %d", errno);
time_diff(since_start, song_start, current_time);
// Convert time to sample number.
unsigned long long samples_since_start = since_start.tv_sec * sampling_rate +
(unsigned long long) ( ((double) (since_start.tv_nsec) * ((double)sampling_rate) / 1000000000.0)); // 1 / one billion = 1 ns
while (!rows.empty()) {
// Process callbacks from row data.
ModStreamRow* r = rows.front();
unsigned long long sample_counter = samples_played + r->samples_since_last;
if (sample_counter > samples_since_start)
break; // done (for now!)
samples_played += r->samples_since_last;
rows.pop();
// 1. Pattern change callback.
if (r->change_pattern != -1)
call_pattern_changed(r->change_pattern);
// 2. Row change callback.
call_row_changed(r->row);
// 3. Note change callbacks.
if (r->notes.size() > 0) {
list<ModStreamNote*>::iterator it;
for (it = r->notes.begin(); it != r->notes.end(); it++) {
ModStreamNote* n = (*it);
call_note_changed(n->channel, n->note, n->instrument, n->sample);
delete n;
}
}
delete r;
}
}
void ModStream::on_note_change(unsigned channel, int note, int instrument, int sample) {
ModStreamNote* n = new ModStreamNote();
n->channel = channel;
n->note = note;
n->instrument = instrument;
n->sample = sample;
current_row->add_note(n);
}
void ModStream::on_pattern_changed(unsigned pattern) {
current_row->change_pattern = (int) pattern;
}
void ModStream::on_row_changed(int row) {
rows.push(current_row);
current_row = new ModStreamRow();
current_row->row = row;
}
void ModStream::increase_sample_count(int add) {
current_row->samples_since_last += add;
}
std::string ModStream::get_title() {
const char* name = ModPlug_GetName(modplug_file);
return name != NULL ? string(name) : string("");
}
std::string ModStream::get_message() {
const char* message = ModPlug_GetMessage(modplug_file);
return (message != NULL) ? string(message) : string("");
}
double ModStream::get_volume() {
return ((double) (ModPlug_GetMasterVolume(modplug_file) - 1)) / 511.0;
}
void ModStream::set_volume(double vol) {
if (vol < 0.)
vol = 0.;
else if (vol > 1.)
vol = 1.;
ModPlug_SetMasterVolume(modplug_file, round(vol * 511) + 1);
}
unsigned ModStream::get_num_instruments() {
return ModPlug_NumInstruments(modplug_file);
}
std::string ModStream::get_instrument_name(unsigned number) {
std::string ret = "";
unsigned length = ModPlug_InstrumentName(modplug_file, number, NULL);
if (length == 0)
return ret;
char* buffer = new char[length+2];
for (unsigned i = 0; i < length+2; i++)
buffer[i] = 0;
if (length == ModPlug_InstrumentName(modplug_file, number, buffer))
ret = string(buffer);
delete [] buffer;
return ret;
}
unsigned ModStream::get_num_samples() {
return ModPlug_NumSamples(modplug_file);
}
std::string ModStream::get_sample_name(unsigned number) {
std::string ret = "";
unsigned length = ModPlug_SampleName(modplug_file, number, NULL);
if (length == 0)
return ret;
char* buffer = new char[length+2];
for (unsigned i = 0; i < length+2; i++)
buffer[i] = 0;
if (length == ModPlug_SampleName(modplug_file, number, buffer))
ret = string(buffer);
delete [] buffer;
return ret;
}
int ModStream::get_current_row() {
return ModPlug_GetCurrentRow(modplug_file);
}
int ModStream::get_current_pattern() {
return ModPlug_GetCurrentPattern(modplug_file);
}
int ModStream::get_rows_in_pattern(int pattern) {
unsigned int num_rows = 0;
if (NULL == ModPlug_GetPattern(modplug_file, pattern, &num_rows))
return -1;
return (int) num_rows;
}
// Based on code from here:
// http://www.guyrutenberg.com/2007/09/22/profiling-code-using-clock_gettime/
void ModStream::time_diff(timespec& result, const timespec& start, const timespec& end) {
if ((end.tv_nsec-start.tv_nsec)<0) {
result.tv_sec = end.tv_sec-start.tv_sec-1;
result.tv_nsec = 1000000000+end.tv_nsec-start.tv_nsec;
} else {
result.tv_sec = end.tv_sec-start.tv_sec;
result.tv_nsec = end.tv_nsec-start.tv_nsec;
}
}
<|endoftext|> |
<commit_before>#include <libport/finally.hh>
#include <ast/cloner.hxx>
#include <ast/new-clone.hh>
#include <ast/parametric-ast.hh>
#include <object/symbols.hh>
#include <parser/ast-factory.hh>
#include <parser/parse.hh>
#include <rewrite/desugarer.hh>
#include <rewrite/pattern-binder.hh>
namespace rewrite
{
using parser::ast_call;
using parser::ast_string;
using parser::ast_lvalue_once;
using parser::ast_lvalue_wrap;
Desugarer::Desugarer()
: pattern_(false)
, allow_decl_(false)
, allow_subdecl_(false)
{}
void Desugarer::visit(const ast::And* s)
{
allow_subdecl_ = true;
super_type::visit(s);
}
void
Desugarer::desugar_modifiers(const ast::Assign* assign)
{
const ast::loc& loc = assign->location_get();
const ast::modifiers_type* source = assign->modifiers_get();
ast::rLValue what = assign->what_get().unsafe_cast<ast::LValue>();
ast::rConstBinding binding = what.unsafe_cast<const ast::Binding>();
if (!what)
errors_.error(what->location_get(),
"cannot use modifiers on pattern assignments");
if (binding)
what = binding->what_get();
PARAMETRIC_AST(dict, "Dictionary.new");
ast::rExp modifiers = exp(dict);
foreach (const ast::modifiers_type::value_type& elt, *source)
{
PARAMETRIC_AST(add, "%exp:1.set(%exp:2, %exp:3)");
add % modifiers
% new ast::String(loc, elt.first)
% recurse(elt.second);
modifiers = exp(add);
}
ast::rExp target_value = recurse(assign->value_get());
ast::rLValue tgt = ast_lvalue_once(what);
PARAMETRIC_AST(trajectory,
"TrajectoryGenerator.new("
" closure ( ) { %exp:1 }," // getter
" closure (v) { %exp:2 }," // Setter
" %exp:3," // Target value
" %exp:4" // modifiers
").run"
);
ast::rExp read = new_clone(tgt);
ast::rExp write = new ast::Assignment(loc, new_clone(tgt),
parser::ast_call(loc, SYMBOL(v)));
trajectory
% read
% write
% target_value
% modifiers;
ast::rExp res = ast::rExp(ast_lvalue_wrap(what, exp(trajectory)).get());
if (binding)
{
PARAMETRIC_AST(declare, "var %lvalue:1 | %exp:2");
res = exp(declare % what % res);
}
res->original_set(assign);
result_ = recurse(res);
}
void
Desugarer::visit(const ast::Assign* assign)
{
ast::loc loc = assign->location_get();
// Handle modifiers
if (assign->modifiers_get())
return desugar_modifiers(assign);
assert(!assign->modifiers_get());
// Simple declaration: var x = value
if (ast::rBinding what = assign->what_get().unsafe_cast<ast::Binding>())
{
if (!allow_decl_)
errors_.error(what->location_get(), "declaration not allowed here");
ast::rDeclaration res =
new ast::Declaration(loc, what->what_get(), assign->value_get());
res->constant_set(what->constant_get());
result_ = recurse(res);
return;
}
// Simple assignment: x = value
if (ast::rCall call = assign->what_get().unsafe_cast<ast::Call>())
{
result_ = new ast::Assignment(loc, call, assign->value_get());
result_ = recurse(result_);
return;
}
// Subscript assignment: x[y] = value
if (ast::rSubscript sub =
assign->what_get().unsafe_cast<ast::Subscript>())
{
ast::exps_type* args = maybe_recurse_collection(sub->arguments_get());
args->push_back(recurse(assign->value_get()));
result_ = ast_call(loc, recurse(sub->target_get()),
SYMBOL(SBL_SBR_EQ), args);
return;
}
// Property assignment: x->prop = value
if (ast::rProperty prop =
assign->what_get().unsafe_cast<ast::Property>())
{
result_ = new ast::PropertyWrite(prop->location_get(),
prop->owner_get(),
prop->name_get(),
assign->value_get());
return;
}
PARAMETRIC_AST(rewrite,
"{"
" var '$value' = %exp:2 |"
" var '$pattern' = Pattern.new(%exp:1) |"
" if (!'$pattern'.match('$value'))"
" throw MatchFailure.new() |"
" {"
" %unscope:2 |"
" %exp:3"
" } |"
" '$value'"
"}"
);
ast::rExp pattern = assign->what_get();
rewrite::PatternBinder bind
(ast_call(loc, SYMBOL(DOLLAR_pattern)), loc, true);
bind(pattern.get());
rewrite.location_set(assign->location_get());
ast::rExp res = exp(rewrite
% bind.result_get().unchecked_cast<ast::Exp>()
% assign->value_get()
% bind.bindings_get());
res->location_set(assign->location_get());
result_ = recurse(res);
}
void Desugarer::operator()(const ast::Ast* node)
{
libport::Finally finally;
finally << libport::scoped_set(allow_decl_, allow_subdecl_);
finally << libport::scoped_set(allow_subdecl_, false);
super_type::operator()(node);
}
void
Desugarer::visit(const ast::Binding* binding)
{
if (!allow_decl_)
errors_.error(binding->location_get(), "declaration not allowed here");
ast::loc loc = binding->location_get();
result_ = new ast::Declaration(loc, binding->what_get(), 0);
result_ = recurse(result_);
}
void Desugarer::visit(const ast::Class* c)
{
ast::loc l = c->location_get();
ast::rLValue what = recurse(c->what_get());
libport::Symbol name = what->call()->name_get();
PARAMETRIC_AST(desugar,
"const var %lvalue:1 ="
"{"
" var '$tmp' = Object.clone |"
" %exp:2 |"
" '$tmp'.setSlot(\"type\", %exp:3) |"
" '$tmp'.setSlot(%exp:4, function () { this }) |"
" do ('$tmp')"
" {"
" %exp:5 |"
" } |"
" '$tmp'"
"}"
);
ast::exps_type* protos = maybe_recurse_collection(c->protos_get());
ast::rExp protos_set;
if (protos)
{
PARAMETRIC_AST(setProtos, "'$tmp'.setProtos(%exp:1)");
protos_set = exp(setProtos % new ast::List(l, protos));
}
else
protos_set = new ast::Noop(l, 0);
desugar % what
% protos_set
% ast_string(l, name)
% ast_string(l, libport::Symbol("as" + name.name_get()))
% c->content_get();
allow_subdecl_ = true;
result_ = recurse(exp(desugar));
result_->original_set(c);
}
void Desugarer::visit(const ast::Decrementation* dec)
{
PARAMETRIC_AST(decrement, "(%lvalue:1 -= 1) + 1");
ast::rExp res = recurse(exp(decrement % dec->exp_get()));
res->original_set(dec);
result_ = res;
}
void Desugarer::visit(const ast::Emit* e)
{
ast::rExp event = recurse(e->event_get());
ast::exps_type* args =
maybe_recurse_collection(e->arguments_get());
if (ast::rExp duration = e->duration_get())
{
PARAMETRIC_AST(emit,
"{"
" var '$emit' = %exp:1.trigger(%exps:2) |"
" var '$duration' = %exp:3 |"
" if ('$duration' != inf)"
" Control.finally(closure () { sleep('$duration') },"
" closure () { '$emit'.stop })"
"}");
// FIXME: children desugared twice
result_ = recurse(exp(emit % event % args % duration));
}
else
{
PARAMETRIC_AST(emit, "%exp:1 . 'emit'(%exps:2)");
result_ = exp(emit % event % args);
}
result_->original_set(e);
}
void Desugarer::visit(const ast::Incrementation* inc)
{
PARAMETRIC_AST(increment, "(%lvalue:1 += 1) - 1");
result_ = recurse(exp(increment % inc->exp_get()));
result_->original_set(inc);
}
void Desugarer::visit(const ast::If* s)
{
ast::rExp test;
{
libport::Finally finally;
finally << libport::scoped_set(allow_subdecl_, true);
test = recurse(s->test_get());
}
ast::rScope thenclause = recurse(s->thenclause_get());
ast::rScope elseclause = recurse(s->elseclause_get());
result_ = new ast::If(s->location_get(), test, thenclause, elseclause);
result_->original_set(s);
}
void Desugarer::visit(const ast::OpAssignment* a)
{
PARAMETRIC_AST(desugar, "%lvalue:1 = %exp:2 . %id:3 (%exp:4)");
ast::rLValue what = recurse(a->what_get());
ast::rLValue tgt = ast_lvalue_once(what);
desugar % tgt
% new_clone(tgt)
% a->op_get()
% a->value_get();
result_ = ast_lvalue_wrap(what, exp(desugar));
result_ = recurse(result_);
result_->original_set(a);
}
void Desugarer::visit(const ast::Pipe* s)
{
allow_subdecl_ = true;
super_type::visit(s);
}
void Desugarer::visit(const ast::Scope* s)
{
allow_subdecl_ = true;
super_type::visit(s);
}
void Desugarer::visit(const ast::Stmt* s)
{
allow_subdecl_ = true;
super_type::visit(s);
}
void Desugarer::visit(const ast::Subscript* s)
{
PARAMETRIC_AST(rewrite, "%exp:1 .'[]'(%exps:2)");
// FIXME: arguments desugared twice
rewrite.location_set(s->location_get());
result_ = ast::exp(rewrite
% s->target_get()
% maybe_recurse_collection(s->arguments_get()));
result_ = recurse(result_);
}
void Desugarer::visit(const ast::Try* t)
{
ast::loc loc = t->location_get();
ast::rTry res =
new ast::Try(loc, recurse(t->body_get()), ast::catches_type());
foreach (const ast::rCatch& c, t->handlers_get())
{
const ast::loc& loc = c->location_get();
ast::rCatch desugared;
PARAMETRIC_AST(pattern, "var '$pattern' = Pattern.new(%exp:1)");
if (c->match_get())
{
rewrite::PatternBinder bind(ast_call(loc, SYMBOL(DOLLAR_pattern)), loc);
bind(c->match_get()->pattern_get().get());
ast::rExp p =
exp(pattern % bind.result_get().unchecked_cast<ast::Exp>());
{
allow_subdecl_ = true;
p = recurse(p);
allow_subdecl_ = false;
}
ast::rMatch match =
new ast::Match(loc, p, recurse(c->match_get()->guard_get()));
match->bindings_set(recurse(bind.bindings_get()));
match->original_set(c->match_get());
desugared = new ast::Catch(loc, match, recurse(c->body_get()));
}
else
{
super_type::visit(c.get());
desugared = c.unchecked_cast<ast::Catch>();
}
res->handlers_get().push_back(desugared);
}
result_ = res;
}
void Desugarer::visit(const ast::While* s)
{
allow_subdecl_ = true;
super_type::visit(s);
}
}
<commit_msg>Comment changes.<commit_after>#include <libport/finally.hh>
#include <ast/cloner.hxx>
#include <ast/new-clone.hh>
#include <ast/parametric-ast.hh>
#include <object/symbols.hh>
#include <parser/ast-factory.hh>
#include <parser/parse.hh>
#include <rewrite/desugarer.hh>
#include <rewrite/pattern-binder.hh>
namespace rewrite
{
using parser::ast_call;
using parser::ast_string;
using parser::ast_lvalue_once;
using parser::ast_lvalue_wrap;
Desugarer::Desugarer()
: pattern_(false)
, allow_decl_(false)
, allow_subdecl_(false)
{}
void Desugarer::visit(const ast::And* s)
{
allow_subdecl_ = true;
super_type::visit(s);
}
void
Desugarer::desugar_modifiers(const ast::Assign* assign)
{
const ast::loc& loc = assign->location_get();
const ast::modifiers_type* source = assign->modifiers_get();
ast::rLValue what = assign->what_get().unsafe_cast<ast::LValue>();
ast::rConstBinding binding = what.unsafe_cast<const ast::Binding>();
if (!what)
errors_.error(what->location_get(),
"cannot use modifiers on pattern assignments");
if (binding)
what = binding->what_get();
PARAMETRIC_AST(dict, "Dictionary.new");
ast::rExp modifiers = exp(dict);
foreach (const ast::modifiers_type::value_type& elt, *source)
{
PARAMETRIC_AST(add, "%exp:1.set(%exp:2, %exp:3)");
add % modifiers
% new ast::String(loc, elt.first)
% recurse(elt.second);
modifiers = exp(add);
}
ast::rExp target_value = recurse(assign->value_get());
ast::rLValue tgt = ast_lvalue_once(what);
PARAMETRIC_AST(trajectory,
"TrajectoryGenerator.new("
" closure ( ) { %exp:1 }," // getter
" closure (v) { %exp:2 }," // Setter
" %exp:3," // Target value
" %exp:4" // modifiers
").run"
);
ast::rExp read = new_clone(tgt);
ast::rExp write = new ast::Assignment(loc, new_clone(tgt),
parser::ast_call(loc, SYMBOL(v)));
trajectory
% read
% write
% target_value
% modifiers;
ast::rExp res = ast::rExp(ast_lvalue_wrap(what, exp(trajectory)).get());
if (binding)
{
PARAMETRIC_AST(declare, "var %lvalue:1 | %exp:2");
res = exp(declare % what % res);
}
res->original_set(assign);
result_ = recurse(res);
}
void
Desugarer::visit(const ast::Assign* assign)
{
ast::loc loc = assign->location_get();
// Handle modifiers.
if (assign->modifiers_get())
return desugar_modifiers(assign);
assert(!assign->modifiers_get());
// Simple declaration: var x = value.
if (ast::rBinding what = assign->what_get().unsafe_cast<ast::Binding>())
{
if (!allow_decl_)
errors_.error(what->location_get(), "declaration not allowed here");
ast::rDeclaration res =
new ast::Declaration(loc, what->what_get(), assign->value_get());
res->constant_set(what->constant_get());
result_ = recurse(res);
return;
}
// Simple assignment: x = value.
if (ast::rCall call = assign->what_get().unsafe_cast<ast::Call>())
{
result_ = new ast::Assignment(loc, call, assign->value_get());
result_ = recurse(result_);
return;
}
// Subscript assignment: x[y] = value.
if (ast::rSubscript sub =
assign->what_get().unsafe_cast<ast::Subscript>())
{
ast::exps_type* args = maybe_recurse_collection(sub->arguments_get());
args->push_back(recurse(assign->value_get()));
result_ = ast_call(loc, recurse(sub->target_get()),
SYMBOL(SBL_SBR_EQ), args);
return;
}
// Property assignment: x->prop = value.
if (ast::rProperty prop =
assign->what_get().unsafe_cast<ast::Property>())
{
result_ = new ast::PropertyWrite(prop->location_get(),
prop->owner_get(),
prop->name_get(),
assign->value_get());
return;
}
PARAMETRIC_AST(rewrite,
"{"
" var '$value' = %exp:2 |"
" var '$pattern' = Pattern.new(%exp:1) |"
" if (!'$pattern'.match('$value'))"
" throw MatchFailure.new() |"
" {"
" %unscope:2 |"
" %exp:3"
" } |"
" '$value'"
"}"
);
ast::rExp pattern = assign->what_get();
rewrite::PatternBinder bind
(ast_call(loc, SYMBOL(DOLLAR_pattern)), loc, true);
bind(pattern.get());
rewrite.location_set(assign->location_get());
ast::rExp res = exp(rewrite
% bind.result_get().unchecked_cast<ast::Exp>()
% assign->value_get()
% bind.bindings_get());
res->location_set(assign->location_get());
result_ = recurse(res);
}
void Desugarer::operator()(const ast::Ast* node)
{
libport::Finally finally;
finally << libport::scoped_set(allow_decl_, allow_subdecl_);
finally << libport::scoped_set(allow_subdecl_, false);
super_type::operator()(node);
}
void
Desugarer::visit(const ast::Binding* binding)
{
if (!allow_decl_)
errors_.error(binding->location_get(), "declaration not allowed here");
ast::loc loc = binding->location_get();
result_ = new ast::Declaration(loc, binding->what_get(), 0);
result_ = recurse(result_);
}
void Desugarer::visit(const ast::Class* c)
{
ast::loc l = c->location_get();
ast::rLValue what = recurse(c->what_get());
libport::Symbol name = what->call()->name_get();
PARAMETRIC_AST(desugar,
"const var %lvalue:1 ="
"{"
" var '$tmp' = Object.clone |"
" %exp:2 |"
" '$tmp'.setSlot(\"type\", %exp:3) |"
" '$tmp'.setSlot(%exp:4, function () { this }) |"
" do ('$tmp')"
" {"
" %exp:5 |"
" } |"
" '$tmp'"
"}"
);
ast::exps_type* protos = maybe_recurse_collection(c->protos_get());
ast::rExp protos_set;
if (protos)
{
PARAMETRIC_AST(setProtos, "'$tmp'.setProtos(%exp:1)");
protos_set = exp(setProtos % new ast::List(l, protos));
}
else
protos_set = new ast::Noop(l, 0);
desugar % what
% protos_set
% ast_string(l, name)
% ast_string(l, libport::Symbol("as" + name.name_get()))
% c->content_get();
allow_subdecl_ = true;
result_ = recurse(exp(desugar));
result_->original_set(c);
}
void Desugarer::visit(const ast::Decrementation* dec)
{
PARAMETRIC_AST(decrement, "(%lvalue:1 -= 1) + 1");
ast::rExp res = recurse(exp(decrement % dec->exp_get()));
res->original_set(dec);
result_ = res;
}
void Desugarer::visit(const ast::Emit* e)
{
ast::rExp event = recurse(e->event_get());
ast::exps_type* args =
maybe_recurse_collection(e->arguments_get());
if (ast::rExp duration = e->duration_get())
{
PARAMETRIC_AST(emit,
"{"
" var '$emit' = %exp:1.trigger(%exps:2) |"
" var '$duration' = %exp:3 |"
" if ('$duration' != inf)"
" Control.finally(closure () { sleep('$duration') },"
" closure () { '$emit'.stop })"
"}");
// FIXME: children desugared twice
result_ = recurse(exp(emit % event % args % duration));
}
else
{
PARAMETRIC_AST(emit, "%exp:1 . 'emit'(%exps:2)");
result_ = exp(emit % event % args);
}
result_->original_set(e);
}
void Desugarer::visit(const ast::Incrementation* inc)
{
PARAMETRIC_AST(increment, "(%lvalue:1 += 1) - 1");
result_ = recurse(exp(increment % inc->exp_get()));
result_->original_set(inc);
}
void Desugarer::visit(const ast::If* s)
{
ast::rExp test;
{
libport::Finally finally;
finally << libport::scoped_set(allow_subdecl_, true);
test = recurse(s->test_get());
}
ast::rScope thenclause = recurse(s->thenclause_get());
ast::rScope elseclause = recurse(s->elseclause_get());
result_ = new ast::If(s->location_get(), test, thenclause, elseclause);
result_->original_set(s);
}
void Desugarer::visit(const ast::OpAssignment* a)
{
PARAMETRIC_AST(desugar, "%lvalue:1 = %exp:2 . %id:3 (%exp:4)");
ast::rLValue what = recurse(a->what_get());
ast::rLValue tgt = ast_lvalue_once(what);
desugar % tgt
% new_clone(tgt)
% a->op_get()
% a->value_get();
result_ = ast_lvalue_wrap(what, exp(desugar));
result_ = recurse(result_);
result_->original_set(a);
}
void Desugarer::visit(const ast::Pipe* s)
{
allow_subdecl_ = true;
super_type::visit(s);
}
void Desugarer::visit(const ast::Scope* s)
{
allow_subdecl_ = true;
super_type::visit(s);
}
void Desugarer::visit(const ast::Stmt* s)
{
allow_subdecl_ = true;
super_type::visit(s);
}
void Desugarer::visit(const ast::Subscript* s)
{
PARAMETRIC_AST(rewrite, "%exp:1 .'[]'(%exps:2)");
// FIXME: arguments desugared twice
rewrite.location_set(s->location_get());
result_ = ast::exp(rewrite
% s->target_get()
% maybe_recurse_collection(s->arguments_get()));
result_ = recurse(result_);
}
void Desugarer::visit(const ast::Try* t)
{
ast::loc loc = t->location_get();
ast::rTry res =
new ast::Try(loc, recurse(t->body_get()), ast::catches_type());
foreach (const ast::rCatch& c, t->handlers_get())
{
const ast::loc& loc = c->location_get();
ast::rCatch desugared;
PARAMETRIC_AST(pattern, "var '$pattern' = Pattern.new(%exp:1)");
if (c->match_get())
{
rewrite::PatternBinder bind(ast_call(loc, SYMBOL(DOLLAR_pattern)), loc);
bind(c->match_get()->pattern_get().get());
ast::rExp p =
exp(pattern % bind.result_get().unchecked_cast<ast::Exp>());
{
allow_subdecl_ = true;
p = recurse(p);
allow_subdecl_ = false;
}
ast::rMatch match =
new ast::Match(loc, p, recurse(c->match_get()->guard_get()));
match->bindings_set(recurse(bind.bindings_get()));
match->original_set(c->match_get());
desugared = new ast::Catch(loc, match, recurse(c->body_get()));
}
else
{
super_type::visit(c.get());
desugared = c.unchecked_cast<ast::Catch>();
}
res->handlers_get().push_back(desugared);
}
result_ = res;
}
void Desugarer::visit(const ast::While* s)
{
allow_subdecl_ = true;
super_type::visit(s);
}
}
<|endoftext|> |
<commit_before>/// \file
/// \ingroup tutorial_tmva
/// \notebook -nodraw
/// This macro provides an example of how to use TMVA for k-folds cross
/// evaluation in application.
///
/// This requires that CrossValidation was run with a deterministic split, such
/// as `"...:splitExpr=int([eventID])%int([numFolds]):..."`.
///
/// - Project : TMVA - a ROOT-integrated toolkit for multivariate data analysis
/// - Package : TMVA
/// - Root Macro: TMVACrossValidationApplication
///
/// \macro_output
/// \macro_code
/// \author Kim Albertsson (adapted from code originally by Andreas Hoecker)
#include <cstdlib>
#include <iostream>
#include <map>
#include <string>
#include "TChain.h"
#include "TFile.h"
#include "TTree.h"
#include "TString.h"
#include "TObjString.h"
#include "TSystem.h"
#include "TROOT.h"
#include "TMVA/Factory.h"
#include "TMVA/DataLoader.h"
#include "TMVA/Tools.h"
#include "TMVA/TMVAGui.h"
// Helper function to load data into TTrees.
TTree *fillTree(TTree * tree, Int_t nPoints, Double_t offset, Double_t scale, UInt_t seed = 100)
{
TRandom3 rng(seed);
Float_t x = 0;
Float_t y = 0;
Int_t eventID = 0;
tree->SetBranchAddress("x", &x);
tree->SetBranchAddress("y", &y);
tree->SetBranchAddress("eventID", &eventID);
for (Int_t n = 0; n < nPoints; ++n) {
x = rng.Gaus(offset, scale);
y = rng.Gaus(offset, scale);
// For our simple example it is enough that the id's are uniformly
// distributed and independent of the data.
++eventID;
tree->Fill();
}
// Important: Disconnects the tree from the memory locations of x and y.
tree->ResetBranchAddresses();
return tree;
}
int TMVACrossValidationApplication()
{
// This loads the library
TMVA::Tools::Instance();
// Set up the TMVA::Reader
TMVA::Reader *reader = new TMVA::Reader("!Color:!Silent:!V");
Float_t x;
Float_t y;
Int_t eventID;
reader->AddVariable("x", &x);
reader->AddVariable("y", &y);
reader->AddSpectator("eventID", &eventID);
// Book the serialised methods
TString jobname("TMVACrossEvaluation");
{
TString methodName = "BDTG";
TString weightfile = TString("dataset/weights/") + jobname + "_" + methodName + TString(".weights.xml");
Bool_t weightfileExists = (gSystem->AccessPathName(weightfile) == kFALSE);
if (weightfileExists) {
reader->BookMVA(methodName, weightfile);
} else {
std::cout << "Weightfile for method " << methodName << " not found."
" Did you run TMVACrossValidation with a specified"
" splitExpr?" << std::endl;
exit(0);
}
}
{
TString methodName = "Fisher";
TString weightfile = TString("dataset/weights/") + jobname + "_" + methodName + TString(".weights.xml");
Bool_t weightfileExists = (gSystem->AccessPathName(weightfile) == kFALSE);
if (weightfileExists) {
reader->BookMVA(methodName, weightfile);
} else {
std::cout << "Weightfile for method " << methodName << " not found."
" Did you run TMVACrossValidation with a specified"
" splitExpr?" << std::endl;
exit(0);
}
}
// Load data
TTree *tree = new TTree();
tree->Branch("x", &x, "x/F");
tree->Branch("y", &y, "y/F");
tree->Branch("eventID", &eventID, "eventID/I");
fillTree(tree, 1000, 1.0, 1.0, 100);
fillTree(tree, 1000, -1.0, 1.0, 101);
tree->SetBranchAddress("x", &x);
tree->SetBranchAddress("y", &y);
tree->SetBranchAddress("eventID", &eventID);
// Prepare histograms
Int_t nbin = 100;
TH1F histBDTG{"BDTG", "BDTG", nbin, -1, 1};
TH1F histFisher{"Fisher", "Fisher", nbin, -1, 1};
// Evaluate classifiers
for (Long64_t ievt = 0; ievt < tree->GetEntries(); ievt++) {
tree->GetEntry(ievt);
Double_t valBDTG = reader->EvaluateMVA("BDTG");
Double_t valFisher = reader->EvaluateMVA("Fisher");
histBDTG.Fill(valBDTG);
histFisher.Fill(valFisher);
}
tree->ResetBranchAddresses();
delete tree;
{ // Write histograms to output file
TFile *target = new TFile("TMVACrossEvaluationApp.root", "RECREATE");
histBDTG.Write();
histFisher.Write();
target->Close();
delete target;
}
delete reader;
return 0;
}
//
// This is used if the macro is compiled. If run through ROOT with
// `root -l -b -q MACRO.C` or similar it is unused.
//
int main(int argc, char **argv)
{
TMVACrossValidationApplication();
}
<commit_msg>correct jobname in TMVACrossValidationApplication<commit_after>/// \file
/// \ingroup tutorial_tmva
/// \notebook -nodraw
/// This macro provides an example of how to use TMVA for k-folds cross
/// evaluation in application.
///
/// This requires that CrossValidation was run with a deterministic split, such
/// as `"...:splitExpr=int([eventID])%int([numFolds]):..."`.
///
/// - Project : TMVA - a ROOT-integrated toolkit for multivariate data analysis
/// - Package : TMVA
/// - Root Macro: TMVACrossValidationApplication
///
/// \macro_output
/// \macro_code
/// \author Kim Albertsson (adapted from code originally by Andreas Hoecker)
#include <cstdlib>
#include <iostream>
#include <map>
#include <string>
#include "TChain.h"
#include "TFile.h"
#include "TTree.h"
#include "TString.h"
#include "TObjString.h"
#include "TSystem.h"
#include "TROOT.h"
#include "TMVA/Factory.h"
#include "TMVA/DataLoader.h"
#include "TMVA/Tools.h"
#include "TMVA/TMVAGui.h"
// Helper function to load data into TTrees.
TTree *fillTree(TTree * tree, Int_t nPoints, Double_t offset, Double_t scale, UInt_t seed = 100)
{
TRandom3 rng(seed);
Float_t x = 0;
Float_t y = 0;
Int_t eventID = 0;
tree->SetBranchAddress("x", &x);
tree->SetBranchAddress("y", &y);
tree->SetBranchAddress("eventID", &eventID);
for (Int_t n = 0; n < nPoints; ++n) {
x = rng.Gaus(offset, scale);
y = rng.Gaus(offset, scale);
// For our simple example it is enough that the id's are uniformly
// distributed and independent of the data.
++eventID;
tree->Fill();
}
// Important: Disconnects the tree from the memory locations of x and y.
tree->ResetBranchAddresses();
return tree;
}
int TMVACrossValidationApplication()
{
// This loads the library
TMVA::Tools::Instance();
// Set up the TMVA::Reader
TMVA::Reader *reader = new TMVA::Reader("!Color:!Silent:!V");
Float_t x;
Float_t y;
Int_t eventID;
reader->AddVariable("x", &x);
reader->AddVariable("y", &y);
reader->AddSpectator("eventID", &eventID);
// Book the serialised methods
TString jobname("TMVACrossValidation");
{
TString methodName = "BDTG";
TString weightfile = TString("dataset/weights/") + jobname + "_" + methodName + TString(".weights.xml");
Bool_t weightfileExists = (gSystem->AccessPathName(weightfile) == kFALSE);
if (weightfileExists) {
reader->BookMVA(methodName, weightfile);
} else {
std::cout << "Weightfile for method " << methodName << " not found."
" Did you run TMVACrossValidation with a specified"
" splitExpr?" << std::endl;
exit(0);
}
}
{
TString methodName = "Fisher";
TString weightfile = TString("dataset/weights/") + jobname + "_" + methodName + TString(".weights.xml");
Bool_t weightfileExists = (gSystem->AccessPathName(weightfile) == kFALSE);
if (weightfileExists) {
reader->BookMVA(methodName, weightfile);
} else {
std::cout << "Weightfile for method " << methodName << " not found."
" Did you run TMVACrossValidation with a specified"
" splitExpr?" << std::endl;
exit(0);
}
}
// Load data
TTree *tree = new TTree();
tree->Branch("x", &x, "x/F");
tree->Branch("y", &y, "y/F");
tree->Branch("eventID", &eventID, "eventID/I");
fillTree(tree, 1000, 1.0, 1.0, 100);
fillTree(tree, 1000, -1.0, 1.0, 101);
tree->SetBranchAddress("x", &x);
tree->SetBranchAddress("y", &y);
tree->SetBranchAddress("eventID", &eventID);
// Prepare histograms
Int_t nbin = 100;
TH1F histBDTG{"BDTG", "BDTG", nbin, -1, 1};
TH1F histFisher{"Fisher", "Fisher", nbin, -1, 1};
// Evaluate classifiers
for (Long64_t ievt = 0; ievt < tree->GetEntries(); ievt++) {
tree->GetEntry(ievt);
Double_t valBDTG = reader->EvaluateMVA("BDTG");
Double_t valFisher = reader->EvaluateMVA("Fisher");
histBDTG.Fill(valBDTG);
histFisher.Fill(valFisher);
}
tree->ResetBranchAddresses();
delete tree;
{ // Write histograms to output file
TFile *target = new TFile("TMVACrossEvaluationApp.root", "RECREATE");
histBDTG.Write();
histFisher.Write();
target->Close();
delete target;
}
delete reader;
return 0;
}
//
// This is used if the macro is compiled. If run through ROOT with
// `root -l -b -q MACRO.C` or similar it is unused.
//
int main(int argc, char **argv)
{
TMVACrossValidationApplication();
}
<|endoftext|> |
<commit_before>// Copyright (c) 2015 Vijos Dev Team. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "core/logon.h"
#include <Windows.h>
#include <malloc.h>
#include <vector>
#include "core/sid.h"
using namespace std;
namespace winc {
ResultCode Logon::GetUserSid(Sid **out_sid) const {
if (!is_user_sid_cached_) {
ResultCode rc = InitUserSidCache();
if (rc != WINC_OK)
return rc;
}
*out_sid = &user_sid_cache_;
return WINC_OK;
}
ResultCode Logon::GetGroupSid(Sid **out_sid) const {
if (!is_group_sid_cached_) {
ResultCode rc = InitGroupSidCache();
if (rc != WINC_OK)
return rc;
}
*out_sid = &group_sid_cache_;
return WINC_OK;
}
ResultCode Logon::FilterToken(const SID_AND_ATTRIBUTES *sids,
DWORD sids_count,
HANDLE *out_token) const {
HANDLE new_token;
if (!::CreateRestrictedToken(token_.get(), DISABLE_MAX_PRIVILEGE,
0, NULL, 0, NULL, sids_count,
const_cast<SID_AND_ATTRIBUTES *>(sids),
&new_token))
return WINC_ERROR_LOGON;
*out_token = new_token;
return WINC_OK;
}
ResultCode Logon::InitUserSidCache() const {
DWORD size = sizeof(TOKEN_USER) + SECURITY_MAX_SID_SIZE;
TOKEN_USER *info = reinterpret_cast<TOKEN_USER *>(_alloca(size));
if (!::GetTokenInformation(token_.get(), TokenUser, info, size, &size))
return WINC_ERROR_LOGON;
user_sid_cache_.Init(info->User.Sid);
is_user_sid_cached_ = true;
return WINC_OK;
}
ResultCode Logon::InitGroupSidCache() const {
DWORD size;
if (!::GetTokenInformation(token_.get(), TokenGroups, NULL, 0, &size) &&
::GetLastError() != ERROR_INSUFFICIENT_BUFFER) {
return WINC_ERROR_LOGON;
}
vector<BYTE> buffer(size);
TOKEN_GROUPS *info = reinterpret_cast<TOKEN_GROUPS *>(buffer.data());
if (::GetTokenInformation(token_.get(), TokenGroups, info, size, &size)) {
for (unsigned int i = 0; i < info->GroupCount; ++i) {
if (info->Groups[i].Attributes & SE_GROUP_LOGON_ID) {
group_sid_cache_.Init(info->Groups[i].Sid);
is_group_sid_cached_ = true;
return WINC_OK;
}
}
}
return WINC_ERROR_LOGON;
}
ResultCode LogonWithIntegrity::FilterToken(const SID_AND_ATTRIBUTES *sids,
DWORD sids_count,
HANDLE *out_token) const {
HANDLE new_token;
ResultCode rc = Logon::FilterToken(sids, sids_count, &new_token);
if (rc != WINC_OK)
return rc;
// Set the integrity level of the new token
SID_IDENTIFIER_AUTHORITY authority = SECURITY_MANDATORY_LABEL_AUTHORITY;
Sid sid;
rc = sid.Init(&authority, integrity_level_);
if (rc != WINC_OK) {
::CloseHandle(new_token);
return rc;
}
TOKEN_MANDATORY_LABEL tml;
tml.Label.Sid = sid.data();
tml.Label.Attributes = SE_GROUP_INTEGRITY;
if (!::SetTokenInformation(new_token, TokenIntegrityLevel,
&tml, sizeof(tml) + sid.GetLength())) {
::CloseHandle(new_token);
return rc;
}
*out_token = new_token;
return WINC_OK;
}
ResultCode LogonWithIntegrity::GrantAccess(HANDLE object,
SE_OBJECT_TYPE object_type,
DWORD allowed_access) const {
// Set the integrity level of the object
SID_IDENTIFIER_AUTHORITY authority = SECURITY_MANDATORY_LABEL_AUTHORITY;
Sid sid;
ResultCode rc = sid.Init(&authority, integrity_level_);
if (rc != WINC_OK)
return rc;
vector<BYTE> sacl_buffer(sizeof(ACL) +
FIELD_OFFSET(SYSTEM_MANDATORY_LABEL_ACE, SidStart) +
sid.GetLength());
ACL *acl = reinterpret_cast<ACL *>(sacl_buffer.data());
if (!::InitializeAcl(acl, static_cast<DWORD>(sacl_buffer.size()),
ACL_REVISION))
return WINC_ERROR_LOGON;
acl->AceCount = 1;
SYSTEM_MANDATORY_LABEL_ACE *ace =
reinterpret_cast<SYSTEM_MANDATORY_LABEL_ACE *>(
sacl_buffer.data() + sizeof(ACL));
ace->Header.AceType = SYSTEM_MANDATORY_LABEL_ACE_TYPE;
ace->Header.AceSize = static_cast<WORD>(
FIELD_OFFSET(SYSTEM_MANDATORY_LABEL_ACE, SidStart) + sid.GetLength());
ace->Mask = SYSTEM_MANDATORY_LABEL_NO_WRITE_UP;
if (!::CopySid(sid.GetLength(), &ace->SidStart, sid.data()))
return WINC_ERROR_LOGON;
DWORD ret = ::SetSecurityInfo(object, object_type,
LABEL_SECURITY_INFORMATION,
NULL, NULL, NULL,
reinterpret_cast<PACL>(sacl_buffer.data()));
if (ret != ERROR_SUCCESS)
return WINC_ERROR_LOGON;
return Logon::GrantAccess(object, object_type, allowed_access);
}
ResultCode CurrentLogon::Init(DWORD integrity_level) {
HANDLE token;
if (!::OpenProcessToken(::GetCurrentProcess(),
TOKEN_QUERY | TOKEN_DUPLICATE |
TOKEN_ADJUST_DEFAULT | TOKEN_ASSIGN_PRIMARY,
&token))
return WINC_ERROR_LOGON;
set_token(token);
LogonWithIntegrity::Init(integrity_level);
return WINC_OK;
}
ResultCode UserLogon::Init(const std::wstring &username,
const std::wstring &password,
DWORD integrity_level) {
HANDLE token;
if (!::LogonUserW(username.c_str(), L".", password.c_str(),
LOGON32_LOGON_INTERACTIVE, LOGON32_PROVIDER_DEFAULT,
&token))
return WINC_ERROR_LOGON;
set_token(token);
LogonWithIntegrity::Init(integrity_level);
return WINC_OK;
}
ResultCode UserLogon::GrantAccess(HANDLE object, SE_OBJECT_TYPE object_type,
DWORD allowed_access) const {
Sid *sid;
ResultCode rc = GetGroupSid(&sid);
if (rc != WINC_OK)
return rc;
PACL old_dacl, new_dacl;
PSECURITY_DESCRIPTOR sd;
if (::GetSecurityInfo(object, object_type, DACL_SECURITY_INFORMATION,
NULL, NULL, &old_dacl, NULL, &sd) != ERROR_SUCCESS)
return WINC_ERROR_LOGON;
EXPLICIT_ACCESSW ea;
ea.grfAccessPermissions = allowed_access;
ea.grfAccessMode = GRANT_ACCESS;
ea.grfInheritance = 0;
ea.Trustee.pMultipleTrustee = NULL;
ea.Trustee.MultipleTrusteeOperation = NO_MULTIPLE_TRUSTEE;
ea.Trustee.TrusteeForm = TRUSTEE_IS_SID;
ea.Trustee.TrusteeType = TRUSTEE_IS_GROUP;
ea.Trustee.ptstrName = reinterpret_cast<LPWSTR>(sid->data());
if (::SetEntriesInAclW(1, &ea, old_dacl, &new_dacl) != ERROR_SUCCESS) {
::LocalFree(sd);
return WINC_ERROR_LOGON;
}
DWORD ret = ::SetSecurityInfo(object, object_type,
DACL_SECURITY_INFORMATION,
NULL, NULL, new_dacl, NULL);
::LocalFree(new_dacl);
::LocalFree(sd);
if (ret != ERROR_SUCCESS)
return WINC_ERROR_LOGON;
return LogonWithIntegrity::GrantAccess(object, object_type, allowed_access);
}
}
<commit_msg>bugfix<commit_after>// Copyright (c) 2015 Vijos Dev Team. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "core/logon.h"
#include <Windows.h>
#include <malloc.h>
#include <vector>
#include "core/sid.h"
using namespace std;
namespace winc {
ResultCode Logon::GetUserSid(Sid **out_sid) const {
if (!is_user_sid_cached_) {
ResultCode rc = InitUserSidCache();
if (rc != WINC_OK)
return rc;
}
*out_sid = &user_sid_cache_;
return WINC_OK;
}
ResultCode Logon::GetGroupSid(Sid **out_sid) const {
if (!is_group_sid_cached_) {
ResultCode rc = InitGroupSidCache();
if (rc != WINC_OK)
return rc;
}
*out_sid = &group_sid_cache_;
return WINC_OK;
}
ResultCode Logon::FilterToken(const SID_AND_ATTRIBUTES *sids,
DWORD sids_count,
HANDLE *out_token) const {
HANDLE new_token;
if (!::CreateRestrictedToken(token_.get(), DISABLE_MAX_PRIVILEGE,
0, NULL, 0, NULL, sids_count,
const_cast<SID_AND_ATTRIBUTES *>(sids),
&new_token))
return WINC_ERROR_LOGON;
*out_token = new_token;
return WINC_OK;
}
ResultCode Logon::InitUserSidCache() const {
DWORD size = sizeof(TOKEN_USER) + SECURITY_MAX_SID_SIZE;
TOKEN_USER *info = reinterpret_cast<TOKEN_USER *>(_alloca(size));
if (!::GetTokenInformation(token_.get(), TokenUser, info, size, &size))
return WINC_ERROR_LOGON;
user_sid_cache_.Init(info->User.Sid);
is_user_sid_cached_ = true;
return WINC_OK;
}
ResultCode Logon::InitGroupSidCache() const {
DWORD size;
if (!::GetTokenInformation(token_.get(), TokenGroups, NULL, 0, &size) &&
::GetLastError() != ERROR_INSUFFICIENT_BUFFER) {
return WINC_ERROR_LOGON;
}
vector<BYTE> buffer(size);
TOKEN_GROUPS *info = reinterpret_cast<TOKEN_GROUPS *>(buffer.data());
if (::GetTokenInformation(token_.get(), TokenGroups, info, size, &size)) {
for (unsigned int i = 0; i < info->GroupCount; ++i) {
if (info->Groups[i].Attributes & SE_GROUP_LOGON_ID) {
group_sid_cache_.Init(info->Groups[i].Sid);
is_group_sid_cached_ = true;
return WINC_OK;
}
}
}
return WINC_ERROR_LOGON;
}
ResultCode LogonWithIntegrity::FilterToken(const SID_AND_ATTRIBUTES *sids,
DWORD sids_count,
HANDLE *out_token) const {
HANDLE new_token;
ResultCode rc = Logon::FilterToken(sids, sids_count, &new_token);
if (rc != WINC_OK)
return rc;
// Set the integrity level of the new token
SID_IDENTIFIER_AUTHORITY authority = SECURITY_MANDATORY_LABEL_AUTHORITY;
Sid sid;
rc = sid.Init(&authority, integrity_level_);
if (rc != WINC_OK) {
::CloseHandle(new_token);
return rc;
}
TOKEN_MANDATORY_LABEL tml;
tml.Label.Sid = sid.data();
tml.Label.Attributes = SE_GROUP_INTEGRITY;
if (!::SetTokenInformation(new_token, TokenIntegrityLevel,
&tml, sizeof(tml) + sid.GetLength())) {
::CloseHandle(new_token);
return WINC_ERROR_LOGON;
}
*out_token = new_token;
return WINC_OK;
}
ResultCode LogonWithIntegrity::GrantAccess(HANDLE object,
SE_OBJECT_TYPE object_type,
DWORD allowed_access) const {
// Set the integrity level of the object
SID_IDENTIFIER_AUTHORITY authority = SECURITY_MANDATORY_LABEL_AUTHORITY;
Sid sid;
ResultCode rc = sid.Init(&authority, integrity_level_);
if (rc != WINC_OK)
return rc;
vector<BYTE> sacl_buffer(sizeof(ACL) +
FIELD_OFFSET(SYSTEM_MANDATORY_LABEL_ACE, SidStart) +
sid.GetLength());
ACL *acl = reinterpret_cast<ACL *>(sacl_buffer.data());
if (!::InitializeAcl(acl, static_cast<DWORD>(sacl_buffer.size()),
ACL_REVISION))
return WINC_ERROR_LOGON;
acl->AceCount = 1;
SYSTEM_MANDATORY_LABEL_ACE *ace =
reinterpret_cast<SYSTEM_MANDATORY_LABEL_ACE *>(
sacl_buffer.data() + sizeof(ACL));
ace->Header.AceType = SYSTEM_MANDATORY_LABEL_ACE_TYPE;
ace->Header.AceSize = static_cast<WORD>(
FIELD_OFFSET(SYSTEM_MANDATORY_LABEL_ACE, SidStart) + sid.GetLength());
ace->Mask = SYSTEM_MANDATORY_LABEL_NO_WRITE_UP;
if (!::CopySid(sid.GetLength(), &ace->SidStart, sid.data()))
return WINC_ERROR_LOGON;
DWORD ret = ::SetSecurityInfo(object, object_type,
LABEL_SECURITY_INFORMATION,
NULL, NULL, NULL,
reinterpret_cast<PACL>(sacl_buffer.data()));
if (ret != ERROR_SUCCESS)
return WINC_ERROR_LOGON;
return Logon::GrantAccess(object, object_type, allowed_access);
}
ResultCode CurrentLogon::Init(DWORD integrity_level) {
HANDLE token;
if (!::OpenProcessToken(::GetCurrentProcess(),
TOKEN_QUERY | TOKEN_DUPLICATE |
TOKEN_ADJUST_DEFAULT | TOKEN_ASSIGN_PRIMARY,
&token))
return WINC_ERROR_LOGON;
set_token(token);
LogonWithIntegrity::Init(integrity_level);
return WINC_OK;
}
ResultCode UserLogon::Init(const std::wstring &username,
const std::wstring &password,
DWORD integrity_level) {
HANDLE token;
if (!::LogonUserW(username.c_str(), L".", password.c_str(),
LOGON32_LOGON_INTERACTIVE, LOGON32_PROVIDER_DEFAULT,
&token))
return WINC_ERROR_LOGON;
set_token(token);
LogonWithIntegrity::Init(integrity_level);
return WINC_OK;
}
ResultCode UserLogon::GrantAccess(HANDLE object, SE_OBJECT_TYPE object_type,
DWORD allowed_access) const {
Sid *sid;
ResultCode rc = GetGroupSid(&sid);
if (rc != WINC_OK)
return rc;
PACL old_dacl, new_dacl;
PSECURITY_DESCRIPTOR sd;
if (::GetSecurityInfo(object, object_type, DACL_SECURITY_INFORMATION,
NULL, NULL, &old_dacl, NULL, &sd) != ERROR_SUCCESS)
return WINC_ERROR_LOGON;
EXPLICIT_ACCESSW ea;
ea.grfAccessPermissions = allowed_access;
ea.grfAccessMode = GRANT_ACCESS;
ea.grfInheritance = 0;
ea.Trustee.pMultipleTrustee = NULL;
ea.Trustee.MultipleTrusteeOperation = NO_MULTIPLE_TRUSTEE;
ea.Trustee.TrusteeForm = TRUSTEE_IS_SID;
ea.Trustee.TrusteeType = TRUSTEE_IS_GROUP;
ea.Trustee.ptstrName = reinterpret_cast<LPWSTR>(sid->data());
if (::SetEntriesInAclW(1, &ea, old_dacl, &new_dacl) != ERROR_SUCCESS) {
::LocalFree(sd);
return WINC_ERROR_LOGON;
}
DWORD ret = ::SetSecurityInfo(object, object_type,
DACL_SECURITY_INFORMATION,
NULL, NULL, new_dacl, NULL);
::LocalFree(new_dacl);
::LocalFree(sd);
if (ret != ERROR_SUCCESS)
return WINC_ERROR_LOGON;
return LogonWithIntegrity::GrantAccess(object, object_type, allowed_access);
}
}
<|endoftext|> |
<commit_before>/***************************************
** Tsunagari Tile Engine **
** music.cpp **
** Copyright 2011-2014 PariahSoft LLC **
***************************************/
// **********
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to
// deal in the Software without restriction, including without limitation the
// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
// sell copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
// IN THE SOFTWARE.
// **********
#include "client-conf.h"
#include "math.h"
#include "music.h"
Music::Music() : volume(100), paused(false), state(NOT_PLAYING)
{
}
Music::~Music() {}
bool Music::setIntro(const std::string& filename)
{
if (newIntro == filename)
return false;
switch (state) {
case NOT_PLAYING:
case PLAYING_INTRO:
case PLAYING_LOOP:
state = CHANGED_INTRO;
default: break;
}
newIntro = filename;
return true;
}
bool Music::setLoop(const std::string& filename)
{
if (newLoop == filename)
return false;
switch (state) {
case NOT_PLAYING:
case PLAYING_INTRO:
case PLAYING_LOOP:
state = CHANGED_LOOP;
default: break;
}
newLoop = filename;
return true;
}
int Music::getVolume()
{
return volume;
}
bool Music::setVolume(int level)
{
if (level == volume)
return false;
if (0 < level || level > 100) {
Log::info("Music", "volume can only be set between 0 and 100");
level = bound(level, 0, 100);
}
volume = conf.musicVolume = level;
return true;
}
bool Music::isPaused()
{
return paused;
}
bool Music::setPaused(bool p)
{
if (paused == p)
return false;
paused = p;
return true;
}
void Music::stop()
{
paused = false;
state = NOT_PLAYING;
}
void Music::tick() {}
void Music::playIntro()
{
curIntro = newIntro;
state = PLAYING_INTRO;
}
void Music::playLoop()
{
curLoop = newLoop;
state = PLAYING_LOOP;
}
<commit_msg>music: fix compiler warning<commit_after>/***************************************
** Tsunagari Tile Engine **
** music.cpp **
** Copyright 2011-2014 PariahSoft LLC **
***************************************/
// **********
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to
// deal in the Software without restriction, including without limitation the
// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
// sell copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
// IN THE SOFTWARE.
// **********
#include "client-conf.h"
#include "math.h"
#include "music.h"
Music::Music() : state(NOT_PLAYING), volume(100), paused(false)
{
}
Music::~Music() {}
bool Music::setIntro(const std::string& filename)
{
if (newIntro == filename)
return false;
switch (state) {
case NOT_PLAYING:
case PLAYING_INTRO:
case PLAYING_LOOP:
state = CHANGED_INTRO;
default: break;
}
newIntro = filename;
return true;
}
bool Music::setLoop(const std::string& filename)
{
if (newLoop == filename)
return false;
switch (state) {
case NOT_PLAYING:
case PLAYING_INTRO:
case PLAYING_LOOP:
state = CHANGED_LOOP;
default: break;
}
newLoop = filename;
return true;
}
int Music::getVolume()
{
return volume;
}
bool Music::setVolume(int level)
{
if (level == volume)
return false;
if (0 < level || level > 100) {
Log::info("Music", "volume can only be set between 0 and 100");
level = bound(level, 0, 100);
}
volume = conf.musicVolume = level;
return true;
}
bool Music::isPaused()
{
return paused;
}
bool Music::setPaused(bool p)
{
if (paused == p)
return false;
paused = p;
return true;
}
void Music::stop()
{
paused = false;
state = NOT_PLAYING;
}
void Music::tick() {}
void Music::playIntro()
{
curIntro = newIntro;
state = PLAYING_INTRO;
}
void Music::playLoop()
{
curLoop = newLoop;
state = PLAYING_LOOP;
}
<|endoftext|> |
<commit_before>/*********************************
** Tsunagari Tile Engine **
** music.cpp **
** Copyright 2011-2012 OmegaSDG **
*********************************/
#include "music.h"
#include "python.h"
Music::Music()
: volume(1.0),
paused(false),
state(NOT_PLAYING)
{
pythonSetGlobal("Music", this);
}
Music::~Music()
{
if (musicInst && musicInst->playing())
musicInst->stop();
}
std::string Music::getIntro()
{
return newIntro;
}
std::string Music::getLoop()
{
return newLoop;
}
void Music::setIntro(const std::string& filename)
{
Resourcer* rc = Resourcer::instance();
switch (state) {
case NOT_PLAYING:
case PLAYING_INTRO:
case PLAYING_LOOP:
if (newIntro != filename)
setState(CHANGED_INTRO);
default:
break;
}
if (newIntro != filename) {
newIntro = filename;
// Optimize XXX: Don't load until played.
introMusic = filename.size() ?
rc->getSong(filename) : SongRef();
}
}
void Music::setLoop(const std::string& filename)
{
Resourcer* rc = Resourcer::instance();
switch (state) {
case NOT_PLAYING:
case PLAYING_INTRO:
case PLAYING_LOOP:
if (newLoop != filename)
setState(CHANGED_LOOP);
default:
break;
}
if (newLoop != filename) {
newLoop = filename;
// Optimize XXX: Don't load until played.
loopMusic = filename.size() ?
rc->getSong(filename) : SongRef();
}
}
double Music::getVolume()
{
return volume;
}
void Music::setVolume(double level)
{
volume = level;
if (musicInst)
musicInst->changeVolume(level);
}
bool Music::isPaused()
{
return paused;
}
void Music::setPaused(bool p)
{
if (paused == p)
return;
paused = p;
if (musicInst) {
if (p)
musicInst->pause();
else
musicInst->play();
}
}
void Music::stop()
{
paused = false;
if (musicInst)
musicInst->stop();
state = NOT_PLAYING;
}
void Music::tick()
{
if (paused)
return;
switch (state) {
case NOT_PLAYING:
if (musicInst && musicInst->playing())
musicInst->stop();
break;
case PLAYING_INTRO:
if (!musicInst->playing()) {
if (newLoop.size() && loopMusic)
playLoop();
else
setState(NOT_PLAYING);
}
break;
case PLAYING_LOOP:
break;
case CHANGED_INTRO:
if (newIntro.size() && introMusic)
playIntro();
else if (newLoop.size() && newLoop != curLoop)
setState(CHANGED_LOOP);
else if (newLoop.size())
setState(PLAYING_LOOP);
else
setState(NOT_PLAYING);
break;
case CHANGED_LOOP:
if (newIntro.size() && loopMusic)
playIntro();
else if (newLoop.size() && loopMusic)
playLoop();
else
setState(NOT_PLAYING);
break;
}
}
void Music::playIntro()
{
if (musicInst && musicInst->playing())
musicInst->stop();
curIntro = newIntro;
introMusic->play(false);
introMusic->changeVolume(volume);
musicInst = introMusic;
setState(PLAYING_INTRO);
}
void Music::playLoop()
{
if (musicInst && musicInst->playing())
musicInst->stop();
curLoop = newLoop;
loopMusic->play(true);
loopMusic->changeVolume(volume);
musicInst = loopMusic;
setState(PLAYING_LOOP);
}
/*
static const char* stateStr(MUSIC_STATE state)
{
switch (state) {
case NOT_PLAYING:
return "NOT_PLAYING";
case PLAYING_INTRO:
return "PLAYING_INTRO";
case PLAYING_LOOP:
return "PLAYING_LOOP";
case CHANGED_INTRO:
return "CHANGED_INTRO";
case CHANGED_LOOP:
return "CHANGED_LOOP";
default:
return "";
}
}
*/
void Music::setState(MUSIC_STATE state)
{
// printf("State changed from %s to %s.\n", stateStr(this->state), stateStr(state));
this->state = state;
}
void exportMusic()
{
boost::python::class_<Music>("MusicManager", boost::python::no_init)
.add_property("intro", &Music::getIntro, &Music::setIntro)
.add_property("loop", &Music::getLoop, &Music::setLoop)
.add_property("volume", &Music::getVolume, &Music::setVolume)
.add_property("paused", &Music::isPaused, &Music::setPaused)
.def("stop", &Music::stop)
;
}
<commit_msg>minor clean of Music::set*<commit_after>/*********************************
** Tsunagari Tile Engine **
** music.cpp **
** Copyright 2011-2012 OmegaSDG **
*********************************/
#include "music.h"
#include "python.h"
Music::Music()
: volume(1.0),
paused(false),
state(NOT_PLAYING)
{
pythonSetGlobal("Music", this);
}
Music::~Music()
{
if (musicInst && musicInst->playing())
musicInst->stop();
}
std::string Music::getIntro()
{
return newIntro;
}
std::string Music::getLoop()
{
return newLoop;
}
void Music::setIntro(const std::string& filename)
{
if (newIntro == filename)
return;
switch (state) {
case NOT_PLAYING:
case PLAYING_INTRO:
case PLAYING_LOOP:
setState(CHANGED_INTRO);
default: break;
}
Resourcer* rc = Resourcer::instance();
newIntro = filename;
// Optimize XXX: Don't load until played.
introMusic = filename.size() ?
rc->getSong(filename) : SongRef();
}
void Music::setLoop(const std::string& filename)
{
if (newLoop == filename)
return;
switch (state) {
case NOT_PLAYING:
case PLAYING_INTRO:
case PLAYING_LOOP:
setState(CHANGED_LOOP);
default: break;
}
Resourcer* rc = Resourcer::instance();
newLoop = filename;
// Optimize XXX: Don't load until played.
loopMusic = filename.size() ?
rc->getSong(filename) : SongRef();
}
double Music::getVolume()
{
return volume;
}
void Music::setVolume(double level)
{
volume = level;
if (musicInst)
musicInst->changeVolume(level);
}
bool Music::isPaused()
{
return paused;
}
void Music::setPaused(bool p)
{
if (paused == p)
return;
paused = p;
if (musicInst) {
if (p)
musicInst->pause();
else
musicInst->play();
}
}
void Music::stop()
{
paused = false;
if (musicInst)
musicInst->stop();
state = NOT_PLAYING;
}
void Music::tick()
{
if (paused)
return;
switch (state) {
case NOT_PLAYING:
if (musicInst && musicInst->playing())
musicInst->stop();
break;
case PLAYING_INTRO:
if (!musicInst->playing()) {
if (newLoop.size() && loopMusic)
playLoop();
else
setState(NOT_PLAYING);
}
break;
case PLAYING_LOOP:
break;
case CHANGED_INTRO:
if (newIntro.size() && introMusic)
playIntro();
else if (newLoop.size() && newLoop != curLoop)
setState(CHANGED_LOOP);
else if (newLoop.size())
setState(PLAYING_LOOP);
else
setState(NOT_PLAYING);
break;
case CHANGED_LOOP:
if (newIntro.size() && loopMusic)
playIntro();
else if (newLoop.size() && loopMusic)
playLoop();
else
setState(NOT_PLAYING);
break;
}
}
void Music::playIntro()
{
if (musicInst && musicInst->playing())
musicInst->stop();
curIntro = newIntro;
introMusic->play(false);
introMusic->changeVolume(volume);
musicInst = introMusic;
setState(PLAYING_INTRO);
}
void Music::playLoop()
{
if (musicInst && musicInst->playing())
musicInst->stop();
curLoop = newLoop;
loopMusic->play(true);
loopMusic->changeVolume(volume);
musicInst = loopMusic;
setState(PLAYING_LOOP);
}
/*
static const char* stateStr(MUSIC_STATE state)
{
switch (state) {
case NOT_PLAYING:
return "NOT_PLAYING";
case PLAYING_INTRO:
return "PLAYING_INTRO";
case PLAYING_LOOP:
return "PLAYING_LOOP";
case CHANGED_INTRO:
return "CHANGED_INTRO";
case CHANGED_LOOP:
return "CHANGED_LOOP";
default:
return "";
}
}
*/
void Music::setState(MUSIC_STATE state)
{
// printf("State changed from %s to %s.\n", stateStr(this->state), stateStr(state));
this->state = state;
}
void exportMusic()
{
boost::python::class_<Music>("MusicManager", boost::python::no_init)
.add_property("intro", &Music::getIntro, &Music::setIntro)
.add_property("loop", &Music::getLoop, &Music::setLoop)
.add_property("volume", &Music::getVolume, &Music::setVolume)
.add_property("paused", &Music::isPaused, &Music::setPaused)
.def("stop", &Music::stop)
;
}
<|endoftext|> |
<commit_before>/* Copyright (c) 2010, Antonie Jovanoski
*
* All rights reserved.
*
* 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, see <http://www.gnu.org/licenses/>.
*
* Contact e-mail: Antonie Jovanoski <minimoog77_at_gmail.com>
*/
#include <QDateTime>
#include <QtAlgorithms>
#include <QCryptographicHash>
#include <QtDebug>
#include "oauth.h"
#define CONSUMER_KEY ""
#define CONSUMER_SECRET ""
/**
* Generates HMAC-SHA1 signature
* @param message for which to create signature
* @param key
*/
static QByteArray hmacSha1(const QByteArray& message, const QByteArray& key)
{
QByteArray normKey;
if (key.size() > 64) {
normKey = QCryptographicHash::hash(key, QCryptographicHash::Sha1);
} else {
normKey = key; // no need for zero padding ipad and opad are filled with zeros
}
unsigned char* K = (unsigned char *)normKey.constData();
unsigned char ipad[65];
unsigned char opad[65];
memset(ipad, 0, 65);
memset(opad, 0, 65);
memcpy(ipad, K, normKey.size());
memcpy(opad, K, normKey.size());
for (int i = 0; i < 64; ++i) {
ipad[i] ^= 0x36;
opad[i] ^= 0x5c;
}
QByteArray context;
context.append((const char *)ipad, 64);
context.append(message);
QByteArray sha1 = QCryptographicHash::hash(context, QCryptographicHash::Sha1);
context.clear();
context.append((const char *)opad, 64);
context.append(sha1);
sha1.clear();
sha1 = QCryptographicHash::hash(context, QCryptographicHash::Sha1);
return sha1;
}
/**
* Generates time stamp
* @return time stamp in epoch time
*/
static QByteArray generateTimeStamp()
{
//OAuth spec. 8 http://oauth.net/core/1.0/#nonce
QDateTime current = QDateTime::currentDateTime();
uint seconds = current.toTime_t();
return QString("%1").arg(seconds).toUtf8();
}
/**
* Generates random 16 length string
* @return random string
*/
static QByteArray generateNonce()
{
//OAuth spec. 8 http://oauth.net/core/1.0/#nonce
QByteArray chars("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789");
int max = chars.size();
int len = 16;
QByteArray nonce;
for(int i = 0; i < len; ++i){
nonce.append( chars[qrand() % max] );
}
return nonce;
}
/**
* Constructor
* @param parent parent QObject
*/
OAuth::OAuth(QObject *parent) : QObject(parent)
{
QDateTime current = QDateTime::currentDateTime();
qsrand(current.toTime_t());
}
/**
* Parses oauth_token and oauth_token_secret from response of the service provider
* and sets m_oauthToken and m_oauthTokenSecret accordingly
* @param response response from service provider
*/
void OAuth::parseTokens(const QByteArray& response)
{
//OAuth spec 5.3, 6.1.2, 6.3.2
//use QUrl for parsing
QByteArray parseQuery("http://parse.com?");
QUrl parseUrl = QUrl::fromEncoded(parseQuery + response);
m_oauthToken = parseUrl.encodedQueryItemValue("oauth_token");
m_oauthTokenSecret = parseUrl.encodedQueryItemValue("oauth_token_secret");
}
/**
* Sets oauth token
* @param token OAuth token
*/
void OAuth::setOAuthToken(const QByteArray& token)
{
m_oauthToken = token;
}
/**
* Sets OAauth token secret
* @param tokenSecret OAuth token secret
*/
void OAuth::setOAuthTokenSecret(const QByteArray& tokenSecret)
{
m_oauthTokenSecret = tokenSecret;
}
/**
* Gets oauth_token
* @return OAuth token
*/
QByteArray OAuth::oauthToken() const
{
return m_oauthToken;
}
/**
* Gets oauth_token_secret
* @return OAuth token secret
*/
QByteArray OAuth::oauthTokenSecret() const
{
return m_oauthTokenSecret;
}
/**
* Clears the oauth tokens
*/
void OAuth::clearTokens()
{
m_oauthToken.clear();
m_oauthTokenSecret.clear();
}
/**
* Generates HMAC-SHA1 signature
* @param signatureBase signature base
* @return HMAC-SHA1 signature
*/
QByteArray OAuth::generateSignatureHMACSHA1(const QByteArray& signatureBase)
{
//OAuth spec. 9.2 http://oauth.net/core/1.0/#anchor16
QByteArray key = QByteArray(CONSUMER_SECRET) + '&' + m_oauthTokenSecret;
QByteArray result = hmacSha1(signatureBase, key);
QByteArray resultBE64 = result.toBase64();
QByteArray resultPE = resultBE64.toPercentEncoding();
return resultPE;
}
/**
* Generates OAuth signature base
* @param url Url with encoded parameters
* @param method Http method
* @param timestamp timestamp
* @param nonce random string
* @return signature base
*/
QByteArray OAuth::generateSignatureBase(const QUrl& url, HttpMethod method, const QByteArray& timestamp, const QByteArray& nonce)
{
//OAuth spec. 9.1 http://oauth.net/core/1.0/#anchor14
//OAuth spec. 9.1.1
QList<QPair<QByteArray, QByteArray> > urlParameters = url.encodedQueryItems();
QList<QByteArray> normParameters;
QListIterator<QPair<QByteArray, QByteArray> > i(urlParameters);
while(i.hasNext()){
QPair<QByteArray, QByteArray> queryItem = i.next();
QByteArray normItem = queryItem.first + '=' + queryItem.second;
normParameters.append(normItem);
}
//consumer key
normParameters.append(QByteArray("oauth_consumer_key=") + QByteArray(CONSUMER_KEY));
//token
if(!m_oauthToken.isEmpty()){
normParameters.append(QByteArray("oauth_token=") + m_oauthToken);
}
//signature method, only HMAC_SHA1
normParameters.append(QByteArray("oauth_signature_method=HMAC-SHA1"));
//time stamp
normParameters.append(QByteArray("oauth_timestamp=") + timestamp);
//nonce
normParameters.append(QByteArray("oauth_nonce=") + nonce);
//version
normParameters.append(QByteArray("oauth_version=1.0"));
//OAuth spec. 9.1.1.1
qSort(normParameters);
//OAuth spec. 9.1.1.2
//QByteArray normString;
//QListIterator<QByteArray> j(normParameters);
//while(j.hasNext()){
// normString += j.next();
// normString += '&';
//}
//normString.chop(1);
QByteArray normString;
QListIterator<QByteArray> j(normParameters);
while (j.hasNext()) {
normString += j.next().toPercentEncoding();
normString += "%26";
}
normString.chop(3);
//OAuth spec. 9.1.2
QString urlScheme = url.scheme();
QString urlPath = url.path();
QString urlHost = url.host();
QByteArray normUrl = urlScheme.toUtf8() + "://" + urlHost.toUtf8() + urlPath.toUtf8();
QByteArray httpm;
switch (method)
{
case OAuth::GET:
httpm = "GET";
break;
case OAuth::POST:
httpm = "POST";
break;
case OAuth::DELETE:
httpm = "DELETE";
break;
case OAuth::PUT:
httpm = "PUT";
break;
}
//OAuth spec. 9.1.3
return httpm + '&' + normUrl.toPercentEncoding() + '&' + normString;
}
/**
* Generates Authorization Header
* @param url url with query items embedded
* @param method type of http method
* @remarks If HttpMethod is POST put query items in url (QUrl::addEncodedQueryItem)
*/
QByteArray OAuth::generateAuthorizationHeader( const QUrl& url, HttpMethod method )
{
if (m_oauthToken.isEmpty() && m_oauthTokenSecret.isEmpty())
qDebug() << "OAuth tokens are empty!";
QByteArray timeStamp = generateTimeStamp();
QByteArray nonce = generateNonce();
QByteArray sigBase = generateSignatureBase(url, method, timeStamp, nonce);
QByteArray signature = generateSignatureHMACSHA1(sigBase);
QByteArray header;
header += "OAuth ";
header += "oauth_consumer_key=\"" + QByteArray(CONSUMER_KEY) + "\",";
if(!m_oauthToken.isEmpty())
header += "oauth_token=\"" + m_oauthToken + "\",";
header += "oauth_signature_method=\"HMAC-SHA1\",";
header += "oauth_signature=\"" + signature + "\",";
header += "oauth_timestamp=\"" + timeStamp + "\",";
header += "oauth_nonce=\"" + nonce + "\",";
header += "oauth_version=\"1.0\"";
return header;
}
<commit_msg>Fixed issue 3. (suggestion by Tamás Demeter-Haludka)<commit_after>/* Copyright (c) 2010, Antonie Jovanoski
*
* All rights reserved.
*
* 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, see <http://www.gnu.org/licenses/>.
*
* Contact e-mail: Antonie Jovanoski <minimoog77_at_gmail.com>
*/
#include <QDateTime>
#include <QtAlgorithms>
#include <QCryptographicHash>
#include <QtDebug>
#include "oauth.h"
#ifndef CONSUMER_KEY
#define CONSUMER_KEY ""
#endif //CONSUMER_KEY
#ifndef CONSUMER_SECRET
#define CONSUMER_SECRET ""
#endif //CONSUMER_SECRET
/**
* Generates HMAC-SHA1 signature
* @param message for which to create signature
* @param key
*/
static QByteArray hmacSha1(const QByteArray& message, const QByteArray& key)
{
QByteArray normKey;
if (key.size() > 64) {
normKey = QCryptographicHash::hash(key, QCryptographicHash::Sha1);
} else {
normKey = key; // no need for zero padding ipad and opad are filled with zeros
}
unsigned char* K = (unsigned char *)normKey.constData();
unsigned char ipad[65];
unsigned char opad[65];
memset(ipad, 0, 65);
memset(opad, 0, 65);
memcpy(ipad, K, normKey.size());
memcpy(opad, K, normKey.size());
for (int i = 0; i < 64; ++i) {
ipad[i] ^= 0x36;
opad[i] ^= 0x5c;
}
QByteArray context;
context.append((const char *)ipad, 64);
context.append(message);
QByteArray sha1 = QCryptographicHash::hash(context, QCryptographicHash::Sha1);
context.clear();
context.append((const char *)opad, 64);
context.append(sha1);
sha1.clear();
sha1 = QCryptographicHash::hash(context, QCryptographicHash::Sha1);
return sha1;
}
/**
* Generates time stamp
* @return time stamp in epoch time
*/
static QByteArray generateTimeStamp()
{
//OAuth spec. 8 http://oauth.net/core/1.0/#nonce
QDateTime current = QDateTime::currentDateTime();
uint seconds = current.toTime_t();
return QString("%1").arg(seconds).toUtf8();
}
/**
* Generates random 16 length string
* @return random string
*/
static QByteArray generateNonce()
{
//OAuth spec. 8 http://oauth.net/core/1.0/#nonce
QByteArray chars("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789");
int max = chars.size();
int len = 16;
QByteArray nonce;
for(int i = 0; i < len; ++i){
nonce.append( chars[qrand() % max] );
}
return nonce;
}
/**
* Constructor
* @param parent parent QObject
*/
OAuth::OAuth(QObject *parent) : QObject(parent)
{
QDateTime current = QDateTime::currentDateTime();
qsrand(current.toTime_t());
}
/**
* Parses oauth_token and oauth_token_secret from response of the service provider
* and sets m_oauthToken and m_oauthTokenSecret accordingly
* @param response response from service provider
*/
void OAuth::parseTokens(const QByteArray& response)
{
//OAuth spec 5.3, 6.1.2, 6.3.2
//use QUrl for parsing
QByteArray parseQuery("http://parse.com?");
QUrl parseUrl = QUrl::fromEncoded(parseQuery + response);
m_oauthToken = parseUrl.encodedQueryItemValue("oauth_token");
m_oauthTokenSecret = parseUrl.encodedQueryItemValue("oauth_token_secret");
}
/**
* Sets oauth token
* @param token OAuth token
*/
void OAuth::setOAuthToken(const QByteArray& token)
{
m_oauthToken = token;
}
/**
* Sets OAauth token secret
* @param tokenSecret OAuth token secret
*/
void OAuth::setOAuthTokenSecret(const QByteArray& tokenSecret)
{
m_oauthTokenSecret = tokenSecret;
}
/**
* Gets oauth_token
* @return OAuth token
*/
QByteArray OAuth::oauthToken() const
{
return m_oauthToken;
}
/**
* Gets oauth_token_secret
* @return OAuth token secret
*/
QByteArray OAuth::oauthTokenSecret() const
{
return m_oauthTokenSecret;
}
/**
* Clears the oauth tokens
*/
void OAuth::clearTokens()
{
m_oauthToken.clear();
m_oauthTokenSecret.clear();
}
/**
* Generates HMAC-SHA1 signature
* @param signatureBase signature base
* @return HMAC-SHA1 signature
*/
QByteArray OAuth::generateSignatureHMACSHA1(const QByteArray& signatureBase)
{
//OAuth spec. 9.2 http://oauth.net/core/1.0/#anchor16
QByteArray key = QByteArray(CONSUMER_SECRET) + '&' + m_oauthTokenSecret;
QByteArray result = hmacSha1(signatureBase, key);
QByteArray resultBE64 = result.toBase64();
QByteArray resultPE = resultBE64.toPercentEncoding();
return resultPE;
}
/**
* Generates OAuth signature base
* @param url Url with encoded parameters
* @param method Http method
* @param timestamp timestamp
* @param nonce random string
* @return signature base
*/
QByteArray OAuth::generateSignatureBase(const QUrl& url, HttpMethod method, const QByteArray& timestamp, const QByteArray& nonce)
{
//OAuth spec. 9.1 http://oauth.net/core/1.0/#anchor14
//OAuth spec. 9.1.1
QList<QPair<QByteArray, QByteArray> > urlParameters = url.encodedQueryItems();
QList<QByteArray> normParameters;
QListIterator<QPair<QByteArray, QByteArray> > i(urlParameters);
while(i.hasNext()){
QPair<QByteArray, QByteArray> queryItem = i.next();
QByteArray normItem = queryItem.first + '=' + queryItem.second;
normParameters.append(normItem);
}
//consumer key
normParameters.append(QByteArray("oauth_consumer_key=") + QByteArray(CONSUMER_KEY));
//token
if(!m_oauthToken.isEmpty()){
normParameters.append(QByteArray("oauth_token=") + m_oauthToken);
}
//signature method, only HMAC_SHA1
normParameters.append(QByteArray("oauth_signature_method=HMAC-SHA1"));
//time stamp
normParameters.append(QByteArray("oauth_timestamp=") + timestamp);
//nonce
normParameters.append(QByteArray("oauth_nonce=") + nonce);
//version
normParameters.append(QByteArray("oauth_version=1.0"));
//OAuth spec. 9.1.1.1
qSort(normParameters);
//OAuth spec. 9.1.1.2
//QByteArray normString;
//QListIterator<QByteArray> j(normParameters);
//while(j.hasNext()){
// normString += j.next();
// normString += '&';
//}
//normString.chop(1);
QByteArray normString;
QListIterator<QByteArray> j(normParameters);
while (j.hasNext()) {
normString += j.next().toPercentEncoding();
normString += "%26";
}
normString.chop(3);
//OAuth spec. 9.1.2
QString urlScheme = url.scheme();
QString urlPath = url.path();
QString urlHost = url.host();
QByteArray normUrl = urlScheme.toUtf8() + "://" + urlHost.toUtf8() + urlPath.toUtf8();
QByteArray httpm;
switch (method)
{
case OAuth::GET:
httpm = "GET";
break;
case OAuth::POST:
httpm = "POST";
break;
case OAuth::DELETE:
httpm = "DELETE";
break;
case OAuth::PUT:
httpm = "PUT";
break;
}
//OAuth spec. 9.1.3
return httpm + '&' + normUrl.toPercentEncoding() + '&' + normString;
}
/**
* Generates Authorization Header
* @param url url with query items embedded
* @param method type of http method
* @remarks If HttpMethod is POST put query items in url (QUrl::addEncodedQueryItem)
*/
QByteArray OAuth::generateAuthorizationHeader( const QUrl& url, HttpMethod method )
{
if (m_oauthToken.isEmpty() && m_oauthTokenSecret.isEmpty())
qDebug() << "OAuth tokens are empty!";
QByteArray timeStamp = generateTimeStamp();
QByteArray nonce = generateNonce();
QByteArray sigBase = generateSignatureBase(url, method, timeStamp, nonce);
QByteArray signature = generateSignatureHMACSHA1(sigBase);
QByteArray header;
header += "OAuth ";
header += "oauth_consumer_key=\"" + QByteArray(CONSUMER_KEY) + "\",";
if(!m_oauthToken.isEmpty())
header += "oauth_token=\"" + m_oauthToken + "\",";
header += "oauth_signature_method=\"HMAC-SHA1\",";
header += "oauth_signature=\"" + signature + "\",";
header += "oauth_timestamp=\"" + timeStamp + "\",";
header += "oauth_nonce=\"" + nonce + "\",";
header += "oauth_version=\"1.0\"";
return header;
}
<|endoftext|> |
<commit_before>#include "ofApp.h"
#include <boost/python.hpp>
#if PY_VERSION_HEX >= 0x03000000
# define MODULE_INIT_FN(name) BOOST_PP_CAT(PyInit_, name)
# define PYTHON_BUILTINS "builtins"
#else
# define MODULE_INIT_FN(name) BOOST_PP_CAT(init, name)
# define PYTHON_BUILTINS "__builtin__"
#endif
using namespace boost::python;
void background(double x){
ofBackground( x * 255 );
}
BOOST_PYTHON_MODULE(core)
{
def( "background", &background );
}
object ns;
//--------------------------------------------------------------
void ofApp::setup(){
ofLog() << "Running setup()";
try {
Py_Initialize();
PySys_SetArgv( argc, argv );
ns = import( "__main__" ).attr( "__dict__" );
ns["__builtins__"] = import( PYTHON_BUILTINS );
PyImport_AppendInittab("core", &initcore);
exec( "from py.visions import load", ns );
exec( "vision = load('data/test.pn')", ns );
} catch( error_already_set ) {
PyErr_Print();
}
}
//--------------------------------------------------------------
void ofApp::update(){
exec( "vision.loop()", ns );
}
//--------------------------------------------------------------
void ofApp::draw(){
}
//--------------------------------------------------------------
void ofApp::keyPressed(int key){
}
//--------------------------------------------------------------
void ofApp::keyReleased(int key){
}
//--------------------------------------------------------------
void ofApp::mouseMoved(int x, int y){
}
//--------------------------------------------------------------
void ofApp::mouseDragged(int x, int y, int button){
}
//--------------------------------------------------------------
void ofApp::mousePressed(int x, int y, int button){
}
//--------------------------------------------------------------
void ofApp::mouseReleased(int x, int y, int button){
}
//--------------------------------------------------------------
void ofApp::mouseEntered(int x, int y){
}
//--------------------------------------------------------------
void ofApp::mouseExited(int x, int y){
}
//--------------------------------------------------------------
void ofApp::windowResized(int w, int h){
}
//--------------------------------------------------------------
void ofApp::gotMessage(ofMessage msg){
}
//--------------------------------------------------------------
void ofApp::dragEvent(ofDragInfo dragInfo){
}
<commit_msg>Use inline Hy code<commit_after>#include "ofApp.h"
#include <boost/python.hpp>
using namespace boost::python;
void background(double x){
ofBackground( x * 255 );
}
BOOST_PYTHON_MODULE(core)
{
def( "background", &background );
}
object ns;
//--------------------------------------------------------------
void ofApp::setup(){
ofLog() << "Running setup()";
try {
Py_Initialize();
PySys_SetArgv( argc, argv );
PyImport_AppendInittab( "core", &initcore );
ns = import( "__main__" ).attr( "__dict__" );
exec( "import hy", ns );
exec( "from py.hy_utils import eval_hy_code", ns );
exec( "dsl_ns = {}", ns );
exec( "dsl_history = []", ns );
// TODO move in a file (maybe)
exec( "eval_hy_code('(import [core [*]])', dsl_ns)", ns );
// TODO require macros from dsl.hy
// TODO take code from OSC
exec( "dsl_history.append('(background 0.2)')", ns );
} catch( error_already_set ) {
PyErr_Print();
}
}
//--------------------------------------------------------------
void ofApp::update(){
}
//--------------------------------------------------------------
void ofApp::draw(){
try {
// TODO check history
exec( "eval_hy_code(dsl_history[-1], dsl_ns)", ns );
} catch( error_already_set ) {
PyErr_Print();
}
}
//--------------------------------------------------------------
void ofApp::keyPressed(int key){
}
//--------------------------------------------------------------
void ofApp::keyReleased(int key){
}
//--------------------------------------------------------------
void ofApp::mouseMoved(int x, int y){
}
//--------------------------------------------------------------
void ofApp::mouseDragged(int x, int y, int button){
}
//--------------------------------------------------------------
void ofApp::mousePressed(int x, int y, int button){
}
//--------------------------------------------------------------
void ofApp::mouseReleased(int x, int y, int button){
}
//--------------------------------------------------------------
void ofApp::mouseEntered(int x, int y){
}
//--------------------------------------------------------------
void ofApp::mouseExited(int x, int y){
}
//--------------------------------------------------------------
void ofApp::windowResized(int w, int h){
}
//--------------------------------------------------------------
void ofApp::gotMessage(ofMessage msg){
}
//--------------------------------------------------------------
void ofApp::dragEvent(ofDragInfo dragInfo){
}
<|endoftext|> |
<commit_before>#include "troengame.h"
#include <osgDB/ReadFile>
#include <osgGA/TrackballManipulator>
#include <osgViewer/ViewerEventHandlers>
#include <chrono>
#include "sampleosgviewer.h"
#include "input/bikeinputstate.h"
#include "input/keyboardeventhandler.h"
#include "physics/physicsworld.h"
#include "physics/bike.h"
#include "updatebikepositioncallback.h"
#include "util/chronotimer.h"
using namespace troen;
using namespace std;
TroenGame::TroenGame(QThread* thread /*= NULL*/) :
m_gameThread(thread)
{
if (m_gameThread == NULL) {
m_gameThread = new QThread(this);
}
moveToThread(m_gameThread);
m_gameThread->start(QThread::HighestPriority);
//initialize();
}
TroenGame::~TroenGame()
{
}
bool TroenGame::initialize()
{
m_rootNode = new osg::Group;
// careful about the order of initialization
// TODO
// initialize sound, level and ... here
initializeModels();
composeSceneGraph();
initializeViews();
initializeViewer();
initializeInput();
initializeTimer();
initializePhysics();
return true;
}
bool TroenGame::initializeModels()
{
m_childNode = new osg::PositionAttitudeTransform();
m_childNode->addChild(osgDB::readNodeFile("data/models/cessna.osgt"));
return true;
}
bool TroenGame::composeSceneGraph()
{
m_rootNode->addChild(m_childNode);
return true;
}
bool TroenGame::initializeInput()
{
// TODO
// dw: clean this up, move it to the appropriate place
osg::ref_ptr<input::BikeInputState> bikeInputState = new input::BikeInputState();
osg::ref_ptr<physics::Bike> bike = new physics::Bike(bikeInputState);
m_childNode->setUpdateCallback(new UpdateBikePositionCallback(bike));
osg::ref_ptr<input::KeyboardEventHandler> keyboardHandler = new input::KeyboardEventHandler(bikeInputState);
m_gameView->addEventHandler(keyboardHandler);
return true;
}
bool TroenGame::initializeViews()
{
m_gameView = new osgViewer::View;
m_gameView->setCameraManipulator(new osgGA::TrackballManipulator);
m_gameView->setSceneData(m_rootNode);
m_gameView->setUpViewOnSingleScreen(0);
// TODO
// add camera to gameview
// (possibly multiple ones for multiple rendering passes)
return true;
}
bool TroenGame::initializeViewer()
{
m_sampleOSGViewer = new SampleOSGViewer();
m_sampleOSGViewer->addView(m_gameView);
// TODO
// add event handlers to the viewer here
return true;
}
bool TroenGame::initializeTimer()
{
m_timer = make_shared<util::ChronoTimer>(false, true);
return true;
}
bool TroenGame::initializePhysics()
{
physics::PhysicsWorld *world;
world = new physics::PhysicsWorld();
world->initialize();
delete world;
return true;
}
void TroenGame::startGameLoop()
{
// simplest version, use this if the below gameloop does not work
// or you still have timer issues
//while (!m_sampleOSGViewer->done())
//{
// m_sampleOSGViewer->frame();
//}
// game loop from here
// http://entropyinteractive.com/2011/02/game-engine-design-the-game-loop/
// INITIALIZATION
initialize();
m_timer->start();
// GAME LOOP VARIABLES
long double nextTime = m_timer->elapsed();
const long double minMillisecondsBetweenFrames = 10;
const long double maxMillisecondsBetweenFrames = 50;
int skippedFrames = 0;
int maxSkippedFrames = 4;
// GAME LOOP
while (!m_sampleOSGViewer->done())
{
long double currTime = m_timer->elapsed();
// are we significantly behind? if yes, "resync", force rendering
if ((currTime - nextTime) > maxMillisecondsBetweenFrames)
nextTime = currTime;
// is it time to render the next frame?
if (currTime >= nextTime)
{
//std::cout << "difference: " << currTime - nextTime << std::endl;
// assign the time for the next update
nextTime += minMillisecondsBetweenFrames;
// LOOP REALLY STARTS HERE:
//update();
// do we have extra time (to draw the frame) or have we rendered a frame recently?
if (currTime < nextTime || (skippedFrames > maxSkippedFrames))
{
//std::cout << "drawing" << std::endl;
m_sampleOSGViewer->frame();
skippedFrames = 0;
}
else
{
skippedFrames++;
}
}
else // WAIT
{
// calculate the time to sleep
long double sleepTime = (nextTime - currTime);
// sanity check
if (sleepTime > 0)
{
// sleep until nextTime
//std::cout << "sleep for: " << sleepTime << std::endl;
m_gameThread->msleep(sleepTime);
}
}
}
// SHUTDOWN
shutdown();
}
bool TroenGame::shutdown()
{
m_timer.reset();
m_sampleOSGViewer = NULL;
m_gameView = NULL;
m_childNode = NULL;
m_rootNode = NULL;
return true;
}<commit_msg>moved viewer from fullscreen to window<commit_after>#include "troengame.h"
#include <osgDB/ReadFile>
#include <osgGA/TrackballManipulator>
#include <osgViewer/ViewerEventHandlers>
#include <chrono>
#include "sampleosgviewer.h"
#include "input/bikeinputstate.h"
#include "input/keyboardeventhandler.h"
#include "physics/physicsworld.h"
#include "physics/bike.h"
#include "updatebikepositioncallback.h"
#include "util/chronotimer.h"
using namespace troen;
using namespace std;
TroenGame::TroenGame(QThread* thread /*= NULL*/) :
m_gameThread(thread)
{
if (m_gameThread == NULL) {
m_gameThread = new QThread(this);
}
moveToThread(m_gameThread);
m_gameThread->start(QThread::HighestPriority);
//initialize();
}
TroenGame::~TroenGame()
{
}
bool TroenGame::initialize()
{
m_rootNode = new osg::Group;
// careful about the order of initialization
// TODO
// initialize sound, level and ... here
std::cout << "initializing game ..." << std::endl;
std::cout << "models and scenegraph ..." << std::endl;
initializeModels();
composeSceneGraph();
std::cout << "views & viewer ..." << std::endl;
initializeViews();
initializeViewer();
std::cout << "input ..." << std::endl;
initializeInput();
std::cout << "timer ..." << std::endl;
initializeTimer();
std::cout << "physics ..." << std::endl;
initializePhysics();
std::cout << "successfully initialized !" << std::endl;
return true;
}
bool TroenGame::initializeModels()
{
m_childNode = new osg::PositionAttitudeTransform();
m_childNode->addChild(osgDB::readNodeFile("data/models/cessna.osgt"));
return true;
}
bool TroenGame::composeSceneGraph()
{
m_rootNode->addChild(m_childNode);
return true;
}
bool TroenGame::initializeInput()
{
// TODO
// dw: clean this up, move it to the appropriate place
osg::ref_ptr<input::BikeInputState> bikeInputState = new input::BikeInputState();
osg::ref_ptr<physics::Bike> bike = new physics::Bike(bikeInputState);
m_childNode->setUpdateCallback(new UpdateBikePositionCallback(bike));
osg::ref_ptr<input::KeyboardEventHandler> keyboardHandler = new input::KeyboardEventHandler(bikeInputState);
m_gameView->addEventHandler(keyboardHandler);
return true;
}
bool TroenGame::initializeViews()
{
m_gameView = new osgViewer::View;
m_gameView->setCameraManipulator(new osgGA::TrackballManipulator);
m_gameView->setSceneData(m_rootNode);
m_gameView->setUpViewInWindow(100, 100, 800, 640, 0);
// TODO
// add camera to gameview
// (possibly multiple ones for multiple rendering passes)
return true;
}
bool TroenGame::initializeViewer()
{
m_sampleOSGViewer = new SampleOSGViewer();
m_sampleOSGViewer->addView(m_gameView);
// TODO
// add event handlers to the viewer here
return true;
}
bool TroenGame::initializeTimer()
{
m_timer = make_shared<util::ChronoTimer>(false, true);
return true;
}
bool TroenGame::initializePhysics()
{
physics::PhysicsWorld *world;
world = new physics::PhysicsWorld();
world->initialize();
delete world;
return true;
}
void TroenGame::startGameLoop()
{
// simplest version, use this if the below gameloop does not work
// or you still have timer issues
//while (!m_sampleOSGViewer->done())
//{
// m_sampleOSGViewer->frame();
//}
// game loop from here
// http://entropyinteractive.com/2011/02/game-engine-design-the-game-loop/
// INITIALIZATION
initialize();
m_timer->start();
// GAME LOOP VARIABLES
long double nextTime = m_timer->elapsed();
const long double minMillisecondsBetweenFrames = 10;
const long double maxMillisecondsBetweenFrames = 50;
int skippedFrames = 0;
int maxSkippedFrames = 4;
// GAME LOOP
while (!m_sampleOSGViewer->done())
{
long double currTime = m_timer->elapsed();
// are we significantly behind? if yes, "resync", force rendering
if ((currTime - nextTime) > maxMillisecondsBetweenFrames)
nextTime = currTime;
// is it time to render the next frame?
if (currTime >= nextTime)
{
//std::cout << "difference: " << currTime - nextTime << std::endl;
// assign the time for the next update
nextTime += minMillisecondsBetweenFrames;
// LOOP REALLY STARTS HERE:
/* FROM GameProg Info session:
checkForUserInput()
runAI()
moveEnemies()
// (network / multiplayer)
resolveCollisisons() (Physics)
// (moveEnemies)
/**/
//update();
// do we have extra time (to draw the frame) or have we rendered a frame recently?
if (currTime < nextTime || (skippedFrames > maxSkippedFrames))
{
//std::cout << "drawing" << std::endl;
m_sampleOSGViewer->frame();
skippedFrames = 0;
}
else
{
skippedFrames++;
}
}
else // WAIT
{
// calculate the time to sleep
long double sleepTime = (nextTime - currTime);
// sanity check
if (sleepTime > 0)
{
// sleep until nextTime
//std::cout << "sleep for: " << sleepTime << std::endl;
m_gameThread->msleep(sleepTime);
}
}
}
// SHUTDOWN
shutdown();
}
bool TroenGame::shutdown()
{
m_timer.reset();
m_sampleOSGViewer = NULL;
m_gameView = NULL;
m_childNode = NULL;
m_rootNode = NULL;
return true;
}<|endoftext|> |
<commit_before>#include <test_helpers.hxx>
using namespace PGSTD;
using namespace pqxx;
namespace pqxx
{
template<> struct PQXX_PRIVATE string_traits<result::const_fielditerator>
{
static const char *name() { return "result::const_fielditerator"; }
static bool has_null() { return false; }
static bool is_null(result::const_fielditerator) { return false; }
static string to_string(result::const_fielditerator)
{ return "[const_fielditerator]"; }
};
template<>
struct PQXX_PRIVATE string_traits<result::const_reverse_fielditerator>
{
static const char *name() { return "result::const_reverse_fielditerator"; }
static bool has_null() { return false; }
static bool is_null(result::const_fielditerator) { return false; }
static string to_string(result::const_reverse_fielditerator)
{ return "[const_reverse_fielditerator]"; }
};
}
namespace
{
void test_result_slicing(transaction_base &t)
{
result r;
// Empty slice at beginning of tuple.
r = t.exec("SELECT 1");
result::tuple s = r[0].slice(0, 0);
PQXX_CHECK_EQUAL(s.size(), 0u, "Slicing produces wrong tuple size.");
PQXX_CHECK_EQUAL(s.begin(), s.end(), "Slice begin()/end() are broken.");
PQXX_CHECK_EQUAL(s.rbegin(), s.rend(), "Slice rbegin()/rend() are broken.");
PQXX_CHECK_THROWS(s.at(0), pqxx::range_error, "at() does not throw.");
PQXX_CHECK_THROWS(r[0].slice(0, 2), pqxx::range_error, "No range check.");
PQXX_CHECK_THROWS(r[0].slice(1, 0), pqxx::range_error, "Can reverse-slice.");
// Empty slice at end of tuple.
s = r[0].slice(1, 1);
PQXX_CHECK_EQUAL(s.size(), 0u, "size() is broken.");
PQXX_CHECK_EQUAL(s.begin(), s.end(), "begin()/end() are broken.");
PQXX_CHECK_EQUAL(s.rbegin(), s.rend(), "rbegin()/rend() are broken.");
PQXX_CHECK_THROWS(s.at(0), pqxx::range_error, "at() is inconsistent.");
// Slice that matches the entire tuple.
s = r[0].slice(0, 1);
PQXX_CHECK_EQUAL(s.size(), 1u, "size() breaks for non-empty slice.");
PQXX_CHECK_EQUAL(s.begin() + 1, s.end(), "Iteration is broken.");
PQXX_CHECK_EQUAL(s.rbegin() + 1, s.rend(), "Reverse iteration is broken.");
PQXX_CHECK_EQUAL(s.at(0).as<int>(), 1, "Accessing a slice is broken.");
PQXX_CHECK_EQUAL(s[0].as<int>(), 1, "operator[] is broken.");
PQXX_CHECK_THROWS(s.at(1).as<int>(), pqxx::range_error, "at() is off.");
// Meaningful slice at beginning of tuple.
r = t.exec("SELECT 1, 2, 3");
s = r[0].slice(0, 1);
PQXX_CHECK_THROWS(
s.at(1).as<int>(),
pqxx::range_error,
"at() does not enforce slice.");
// Meaningful slice that skips an initial column.
s = r[0].slice(1, 2);
PQXX_CHECK_EQUAL(s[0].as<int>(), 2, "Slicing offset is broken.");
PQXX_CHECK_EQUAL(s.begin()->as<int>(), 2, "Iteration uses wrong offset.");
PQXX_CHECK_EQUAL(s.begin() + 1, s.end(), "Iteration has wrong range.");
PQXX_CHECK_EQUAL(
s.rbegin() + 1,
s.rend(),
"Reverse iteration has wrong range.");
PQXX_CHECK_THROWS(
s.at(1).as<int>(),
pqxx::range_error,
"Offset slicing is broken.");
}
} // namespace
PQXX_REGISTER_TEST(test_result_slicing)
<commit_msg>Test column names in slices.<commit_after>#include <test_helpers.hxx>
using namespace PGSTD;
using namespace pqxx;
namespace pqxx
{
template<> struct PQXX_PRIVATE string_traits<result::const_fielditerator>
{
static const char *name() { return "result::const_fielditerator"; }
static bool has_null() { return false; }
static bool is_null(result::const_fielditerator) { return false; }
static string to_string(result::const_fielditerator)
{ return "[const_fielditerator]"; }
};
template<>
struct PQXX_PRIVATE string_traits<result::const_reverse_fielditerator>
{
static const char *name() { return "result::const_reverse_fielditerator"; }
static bool has_null() { return false; }
static bool is_null(result::const_fielditerator) { return false; }
static string to_string(result::const_reverse_fielditerator)
{ return "[const_reverse_fielditerator]"; }
};
}
namespace
{
void test_result_slicing(transaction_base &t)
{
result r;
// Empty slice at beginning of tuple.
r = t.exec("SELECT 1");
result::tuple s = r[0].slice(0, 0);
PQXX_CHECK_EQUAL(s.size(), 0u, "Slicing produces wrong tuple size.");
PQXX_CHECK_EQUAL(s.begin(), s.end(), "Slice begin()/end() are broken.");
PQXX_CHECK_EQUAL(s.rbegin(), s.rend(), "Slice rbegin()/rend() are broken.");
PQXX_CHECK_THROWS(s.at(0), pqxx::range_error, "at() does not throw.");
PQXX_CHECK_THROWS(r[0].slice(0, 2), pqxx::range_error, "No range check.");
PQXX_CHECK_THROWS(r[0].slice(1, 0), pqxx::range_error, "Can reverse-slice.");
// Empty slice at end of tuple.
s = r[0].slice(1, 1);
PQXX_CHECK_EQUAL(s.size(), 0u, "size() is broken.");
PQXX_CHECK_EQUAL(s.begin(), s.end(), "begin()/end() are broken.");
PQXX_CHECK_EQUAL(s.rbegin(), s.rend(), "rbegin()/rend() are broken.");
PQXX_CHECK_THROWS(s.at(0), pqxx::range_error, "at() is inconsistent.");
// Slice that matches the entire tuple.
s = r[0].slice(0, 1);
PQXX_CHECK_EQUAL(s.size(), 1u, "size() breaks for non-empty slice.");
PQXX_CHECK_EQUAL(s.begin() + 1, s.end(), "Iteration is broken.");
PQXX_CHECK_EQUAL(s.rbegin() + 1, s.rend(), "Reverse iteration is broken.");
PQXX_CHECK_EQUAL(s.at(0).as<int>(), 1, "Accessing a slice is broken.");
PQXX_CHECK_EQUAL(s[0].as<int>(), 1, "operator[] is broken.");
PQXX_CHECK_THROWS(s.at(1).as<int>(), pqxx::range_error, "at() is off.");
// Meaningful slice at beginning of tuple.
r = t.exec("SELECT 1, 2, 3");
s = r[0].slice(0, 1);
PQXX_CHECK_THROWS(
s.at(1).as<int>(),
pqxx::range_error,
"at() does not enforce slice.");
// Meaningful slice that skips an initial column.
s = r[0].slice(1, 2);
PQXX_CHECK_EQUAL(s[0].as<int>(), 2, "Slicing offset is broken.");
PQXX_CHECK_EQUAL(s.begin()->as<int>(), 2, "Iteration uses wrong offset.");
PQXX_CHECK_EQUAL(s.begin() + 1, s.end(), "Iteration has wrong range.");
PQXX_CHECK_EQUAL(
s.rbegin() + 1,
s.rend(),
"Reverse iteration has wrong range.");
PQXX_CHECK_THROWS(
s.at(1).as<int>(),
pqxx::range_error,
"Offset slicing is broken.");
// Column names in a slice.
r = t.exec("SELECT 1 AS one, 2 AS two, 3 AS three");
s = r[0].slice(1, 2);
PQXX_CHECK_EQUAL(s["two"].as<int>(), 2, "Column addressing breaks.");
PQXX_CHECK_THROWS(
s.column_number("one"),
argument_error,
"Can access column name before slice.");
PQXX_CHECK_THROWS(
s.column_number("three"),
argument_error,
"Can access column name after slice.");
PQXX_CHECK_EQUAL(
s.column_number("Two"),
0u,
"Column name is case sensitive.");
// Identical column names.
r = t.exec("SELECT 1 AS x, 2 AS x");
s = r[0].slice(1, 2);
PQXX_CHECK_EQUAL(s["x"].as<int>(), 2, "Identical column names break slice.");
}
} // namespace
PQXX_REGISTER_TEST(test_result_slicing)
<|endoftext|> |
<commit_before>#include "notepad.h"
#include "ui_notepad.h"
#include <QFileDialog>
#include <QFile>
#include <QMessageBox>
#include <QTextStream>
#include <QtPrintSupport>
#include <iostream>
Notepad::Notepad(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::Notepad)
{
// TODO, not sure where to organize instantiating methods
// Temporarily changing to a directory
working_dir = QDir("/Users/pybae/Documents");
file_list = working_dir.entryList();
QStringListIterator it(file_list);
while (it.hasNext()) {
std::cout << it.next().toStdString() << std::endl;
}
ui->setupUi(this);
}
Notepad::~Notepad()
{
delete ui;
}
// A helper method to save a file, given a fileName in the current working directory
void Notepad::saveFile(QString fileName)
{
if (!fileName.isEmpty()) {
QFile file(fileName);
if (!file.open(QIODevice::WriteOnly)) {
// error message
return;
} else {
QTextStream stream(&file);
stream << ui->mainTextEdit->toPlainText() << "\n";
stream.flush();
file.close();
}
}
else {
printf("File does not exist\n");
}
}
// Called when the "New" option is triggered by C-n or menu
void Notepad::on_actionNew_triggered()
{
QString newFileName = QFileDialog::getSaveFileName(this, tr("New File"), working_dir.absolutePath(),
tr("Text Files (*.txt);;C++ Files (*.cpp *.h)"));
saveFile(newFileName);
working_file_name = newFileName;
}
// Called when the "Open" option is triggered by C-o or menu
void Notepad::on_actionOpen_triggered()
{
QString fileName = QFileDialog::getOpenFileName(this, tr("Open File"), working_dir.absolutePath(),
tr("Text Files (*.txt);;C++ Files (*.cpp *.h)"));
if (!fileName.isEmpty()) {
QFile file(fileName);
working_file_name = file.fileName();
if (!file.open(QIODevice::ReadOnly)) {
QMessageBox::critical(this, tr("Error"), tr("Could not open file"));
return;
}
QTextStream in(&file);
ui->mainTextEdit->setText(in.readAll());
file.close();
}
}
// Called when the "Save" option is triggered by C-s or menu
void Notepad::on_actionSave_triggered()
{
saveFile(working_file_name);
}
// Called when the "Save As" option is triggered by C-S (Ctrl shift s) or menu
void Notepad::on_actionSaveAs_triggered()
{
QString fileName = QFileDialog::getSaveFileName(this, tr("Save File"), QString(),
tr("Text Files (*.txt);;C++ Files (*.cpp *.h)"));
saveFile(fileName);
}
// Called when the "Print" option is triggered by C-p or menu
void Notepad::on_actionPrint_triggered()
{
// QPrinter printer;
// QPrintDialog dialog(&printer, this);
// dialog.setWindowTitle(tr("Print Document"));
// if (dialog.exec() != QDialog::Accepted) {
// return;
// }
}
// Called when the "Exit" option is triggered by C-q or menu
void Notepad::on_actionExit_triggered()
{
// TODO need to check if there are any unsaved buffers
qApp->quit();
}
// Triggered when the mainTextEdit region has its text changed
// TODO figure out how frequently this method is called
void Notepad::on_mainTextEdit_textChanged()
{
// Save the current buffer
// Notepad::on_actionSave_triggered();
}
<commit_msg>Cleaned up code<commit_after>#include "notepad.h"
#include "ui_notepad.h"
#include <QFileDialog>
#include <QFile>
#include <QMessageBox>
#include <QTextStream>
#include <QtPrintSupport>
#include <iostream>
Notepad::Notepad(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::Notepad)
{
// TODO, not sure where to organize instantiating methods
// Temporarily changing to a directory
working_dir = QDir("/Users/pybae/Documents");
file_list = working_dir.entryList();
ui->setupUi(this);
}
Notepad::~Notepad()
{
delete ui;
}
// A helper method to save a file, given a fileName in the current working directory
void Notepad::saveFile(QString fileName)
{
if (!fileName.isEmpty()) {
QFile file(fileName);
if (!file.open(QIODevice::WriteOnly)) {
// error message
return;
} else {
QTextStream stream(&file);
stream << ui->mainTextEdit->toPlainText() << "\n";
stream.flush();
file.close();
}
}
else {
printf("File does not exist\n");
}
}
// Called when the "New" option is triggered by C-n or menu
void Notepad::on_actionNew_triggered()
{
QString newFileName = QFileDialog::getSaveFileName(this, tr("New File"), working_dir.absolutePath(),
tr("Text Files (*.txt);;C++ Files (*.cpp *.h)"));
saveFile(newFileName);
working_file_name = newFileName;
}
// Called when the "Open" option is triggered by C-o or menu
void Notepad::on_actionOpen_triggered()
{
QString fileName = QFileDialog::getOpenFileName(this, tr("Open File"), working_dir.absolutePath(),
tr("Text Files (*.txt);;C++ Files (*.cpp *.h)"));
if (!fileName.isEmpty()) {
QFile file(fileName);
working_file_name = file.fileName();
if (!file.open(QIODevice::ReadOnly)) {
QMessageBox::critical(this, tr("Error"), tr("Could not open file"));
return;
}
QTextStream in(&file);
ui->mainTextEdit->setText(in.readAll());
file.close();
}
}
// Called when the "Save" option is triggered by C-s or menu
void Notepad::on_actionSave_triggered()
{
saveFile(working_file_name);
}
// Called when the "Save As" option is triggered by C-S (Ctrl shift s) or menu
void Notepad::on_actionSaveAs_triggered()
{
QString fileName = QFileDialog::getSaveFileName(this, tr("Save File"), QString(),
tr("Text Files (*.txt);;C++ Files (*.cpp *.h)"));
saveFile(fileName);
}
// Called when the "Print" option is triggered by C-p or menu
void Notepad::on_actionPrint_triggered()
{
// QPrinter printer;
// QPrintDialog dialog(&printer, this);
// dialog.setWindowTitle(tr("Print Document"));
// if (dialog.exec() != QDialog::Accepted) {
// return;
// }
}
// Called when the "Exit" option is triggered by C-q or menu
void Notepad::on_actionExit_triggered()
{
// TODO need to check if there are any unsaved buffers
qApp->quit();
}
// Triggered when the mainTextEdit region has its text changed
// TODO figure out how frequently this method is called
void Notepad::on_mainTextEdit_textChanged()
{
// Save the current buffer
// Notepad::on_actionSave_triggered();
}
<|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 If.hxx
*
* Asynchronous NMRAnet interface.
*
* @author Balazs Racz
* @date 3 Dec 2013
*/
#ifndef _NMRANET_IF_HXX_
#define _NMRANET_IF_HXX_
/// @todo(balazs.racz) remove this dep
#include <string>
#include "nmranet/Node.hxx"
#include "nmranet/Defs.hxx"
#include "executor/Dispatcher.hxx"
#include "executor/Service.hxx"
#include "executor/Executor.hxx"
#include "utils/Buffer.hxx"
#include "utils/Queue.hxx"
#include "utils/Map.hxx"
namespace nmranet
{
class Node;
typedef string Payload;
/** Convenience function to render a 48-bit NMRAnet node ID into a new buffer.
*
* @param id is the 48-bit ID to render.
* @returns a new buffer (from the main pool) with 6 bytes of used space, a
* big-endian representation of the node ID.
*/
extern string node_id_to_buffer(NodeID id);
/** Converts a 6-byte-long buffer to a node ID.
*
* @param buf is a buffer that has to have exactly 6 bytes used, filled with a
* big-endian node id.
* @returns the node id (in host endian).
*/
extern NodeID buffer_to_node_id(const string& buf);
/** Formats a payload for response of error response messages such as OPtioanl
* Interaction Rejected or Terminate Due To Error. */
extern string error_to_buffer(uint16_t error_code, uint16_t mti);
/** A global class / variable for empty or not-yet-initialized payloads. */
extern string EMPTY_PAYLOAD;
/** This class is used in the dispatching of incoming or outgoing NMRAnet
* messages to the message handlers at the protocol-agnostic level (i.e. not
* CAN or TCP-specific).
*
* TODO(balazs.racz) There shall be one instance of this class that will be
* sent to all handlers that expressed interest in that MTI. When all those
* handlers are done, the instance should be freed. Currently the instance is
* copied by the dispatcher separately for each handler. */
struct NMRAnetMessage
{
NMRAnetMessage()
: src({0, 0}), dst({0, 0}), flagsSrc(0), flagsDst(0) {}
void reset(Defs::MTI mti, NodeID src, NodeHandle dst, const string &payload)
{
this->mti = mti;
this->src = {src, 0};
this->dst = dst;
this->payload = payload;
this->dstNode = nullptr;
this->flagsSrc = 0;
this->flagsDst = 0;
}
void reset(Defs::MTI mti, NodeID src, const string &payload)
{
this->mti = mti;
this->src = {src, 0};
this->dst = {0, 0};
this->payload = payload;
this->dstNode = nullptr;
this->flagsSrc = 0;
this->flagsDst = 0;
}
/// OpenLCB MTI of the incoming message.
Defs::MTI mti;
/// Source node.
NodeHandle src;
/// Destination node.
NodeHandle dst;
/// If the destination node is local, this value is non-NULL.
Node *dstNode;
/// Data content in the message body. Owned by the dispatcher.
/// @todo(balazs.racz) figure out a better container.
string payload;
unsigned flagsSrc : 4;
unsigned flagsDst : 4;
unsigned get_flags_src() {
return flagsSrc;
}
unsigned get_flags_dst() {
return flagsDst;
}
void set_flag_src(unsigned flags) {
flagsSrc |= flags;
}
void clear_flag_src(unsigned flags) {
flagsSrc &= ~flags;
}
/** Returns true if src flags has all the specified flags set. */
bool has_flag_src(unsigned flags) {
return ((flagsSrc & flags) == flags);
}
void set_flag_dst(unsigned flags) {
flagsDst |= flags;
}
void clear_flag_dst(unsigned flags) {
flagsDst &= ~flags;
}
/** Returns true if src flags has all the specified flags set. */
bool has_flag_dst(unsigned flags) {
return ((flagsDst & flags) == flags);
}
typedef uint32_t id_type;
id_type id() const
{
return static_cast<uint32_t>(mti);
}
enum DstFlags {
/** Specifies that the stack should wait for the local loopback
* processing before invoking the done notifiable. */
WAIT_FOR_LOCAL_LOOPBACK = 1,
// 2, 4, 8: free
};
enum SrcFlags {
// 1, 2, 4, 8: free
};
};
typedef FlowInterface<Buffer<NMRAnetMessage>> MessageHandler;
class If : public Service
{
public:
/** Constructs an NMRAnet interface.
* @param executor is the thread that will be used for all processing on
* this interface.
* @param local_nodes_count is the maximum number of virtual nodes that
* this interface will support. */
If(ExecutorBase *executor, int local_nodes_count);
/** Destructor */
virtual ~If()
{
}
/** @return Flow to send global messages to the NMRAnet bus. */
MessageHandler *global_message_write_flow()
{
HASSERT(globalWriteFlow_);
return globalWriteFlow_;
}
/** @return Flow to send addressed messages to the NMRAnet bus. */
MessageHandler *addressed_message_write_flow()
{
HASSERT(addressedWriteFlow_);
return addressedWriteFlow_;
}
/** Type of the dispatcher of incoming NMRAnet messages. */
typedef DispatchFlow<Buffer<NMRAnetMessage>, 4> MessageDispatchFlow;
/** @return Dispatcher of incoming NMRAnet messages. */
MessageDispatchFlow *dispatcher()
{
return &dispatcher_;
}
/** Transfers ownership of a module to the interface. It will be brought
* down in the destructor. The destruction order is guaranteed such that
* all supporting structures are still available when the flow is destryed,
* but incoming messages can not come in anymore.
*
* @todo(balazs.racz) revise whether this needs to be virtual. */
virtual void add_owned_flow(Executable *e) = 0;
/** Registers a new local node on this interface. This function must be
* called from the interface's executor.
*
* @param node is the node to register.
*/
void add_local_node(Node *node)
{
NodeID id = node->node_id();
HASSERT(localNodes_.find(id) == localNodes_.end());
localNodes_[id] = node;
}
/** Removes a local node from this interface. This function must be called
* from the interface's executor.
*
* @param node is the node to delete.
*/
void delete_local_node(Node *node)
{
HASSERT(0);
/*
auto it = localNodes_.find(node->node_id());
HASSERT(it != localNodes_.end());
localNodes_.erase(it);*/
}
/** Looks up a node ID in the local nodes' registry. This function must be
* called from the interface's executor.
*
* @param id is the 48-bit NMRAnet node ID to look up.
* @returns the node pointer or NULL if the node is not registered.
*/
Node *lookup_local_node(NodeID id)
{
auto it = localNodes_.find(id);
if (it == localNodes_.end())
{
return nullptr;
}
return it->second;
}
protected:
/// Allocator containing the global write flows.
MessageHandler *globalWriteFlow_;
/// Allocator containing the addressed write flows.
MessageHandler *addressedWriteFlow_;
private:
/// Flow responsible for routing incoming messages to handlers.
MessageDispatchFlow dispatcher_;
typedef Map<NodeID, Node *> VNodeMap;
/// Local virtual nodes registered on this interface.
VNodeMap localNodes_;
friend class VerifyNodeIdHandler;
DISALLOW_COPY_AND_ASSIGN(If);
};
typedef StateFlow<Buffer<NMRAnetMessage>, QList<4>> MessageStateFlowBase;
/** Base class for incoming message handler flows. */
class IncomingMessageStateFlow
: public MessageStateFlowBase
{
public:
IncomingMessageStateFlow(If *interface)
: MessageStateFlowBase(interface)
{
}
If *interface()
{
return static_cast<If *>(service());
}
/// Returns the NMRAnet message we received.
NMRAnetMessage *nmsg()
{
return message()->data();
}
};
} // namespace nmranet
#endif // _NMRANET_IF_HXX_
<commit_msg>Adds MTI priority capabilty to NMRAnetMessage.<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 If.hxx
*
* Asynchronous NMRAnet interface.
*
* @author Balazs Racz
* @date 3 Dec 2013
*/
#ifndef _NMRANET_IF_HXX_
#define _NMRANET_IF_HXX_
/// @todo(balazs.racz) remove this dep
#include <string>
#include "nmranet/Node.hxx"
#include "nmranet/Defs.hxx"
#include "executor/Dispatcher.hxx"
#include "executor/Service.hxx"
#include "executor/Executor.hxx"
#include "utils/Buffer.hxx"
#include "utils/Queue.hxx"
#include "utils/Map.hxx"
namespace nmranet
{
class Node;
typedef string Payload;
/** Convenience function to render a 48-bit NMRAnet node ID into a new buffer.
*
* @param id is the 48-bit ID to render.
* @returns a new buffer (from the main pool) with 6 bytes of used space, a
* big-endian representation of the node ID.
*/
extern string node_id_to_buffer(NodeID id);
/** Converts a 6-byte-long buffer to a node ID.
*
* @param buf is a buffer that has to have exactly 6 bytes used, filled with a
* big-endian node id.
* @returns the node id (in host endian).
*/
extern NodeID buffer_to_node_id(const string& buf);
/** Formats a payload for response of error response messages such as OPtioanl
* Interaction Rejected or Terminate Due To Error. */
extern string error_to_buffer(uint16_t error_code, uint16_t mti);
/** A global class / variable for empty or not-yet-initialized payloads. */
extern string EMPTY_PAYLOAD;
/** This class is used in the dispatching of incoming or outgoing NMRAnet
* messages to the message handlers at the protocol-agnostic level (i.e. not
* CAN or TCP-specific).
*
* TODO(balazs.racz) There shall be one instance of this class that will be
* sent to all handlers that expressed interest in that MTI. When all those
* handlers are done, the instance should be freed. Currently the instance is
* copied by the dispatcher separately for each handler. */
struct NMRAnetMessage
{
NMRAnetMessage()
: src({0, 0}), dst({0, 0}), flagsSrc(0), flagsDst(0) {}
void reset(Defs::MTI mti, NodeID src, NodeHandle dst, const string &payload)
{
this->mti = mti;
this->src = {src, 0};
this->dst = dst;
this->payload = payload;
this->dstNode = nullptr;
this->flagsSrc = 0;
this->flagsDst = 0;
}
void reset(Defs::MTI mti, NodeID src, const string &payload)
{
this->mti = mti;
this->src = {src, 0};
this->dst = {0, 0};
this->payload = payload;
this->dstNode = nullptr;
this->flagsSrc = 0;
this->flagsDst = 0;
}
/// OpenLCB MTI of the incoming message.
Defs::MTI mti;
/// Source node.
NodeHandle src;
/// Destination node.
NodeHandle dst;
/// If the destination node is local, this value is non-NULL.
Node *dstNode;
/// Data content in the message body. Owned by the dispatcher.
/// @todo(balazs.racz) figure out a better container.
string payload;
unsigned flagsSrc : 4;
unsigned flagsDst : 4;
unsigned get_flags_src() {
return flagsSrc;
}
unsigned get_flags_dst() {
return flagsDst;
}
void set_flag_src(unsigned flags) {
flagsSrc |= flags;
}
void clear_flag_src(unsigned flags) {
flagsSrc &= ~flags;
}
/** Returns true if src flags has all the specified flags set. */
bool has_flag_src(unsigned flags) {
return ((flagsSrc & flags) == flags);
}
void set_flag_dst(unsigned flags) {
flagsDst |= flags;
}
void clear_flag_dst(unsigned flags) {
flagsDst &= ~flags;
}
/** Returns true if src flags has all the specified flags set. */
bool has_flag_dst(unsigned flags) {
return ((flagsDst & flags) == flags);
}
typedef uint32_t id_type;
id_type id() const
{
return static_cast<uint32_t>(mti);
}
/** Returns the NMRAnet-defined priority band, in the range of 0..3. */
unsigned priority()
{
return (mti & Defs::MTI_PRIORITY_MASK) >> Defs::MTI_PRIORITY_SHIFT;
}
enum DstFlags {
/** Specifies that the stack should wait for the local loopback
* processing before invoking the done notifiable. */
WAIT_FOR_LOCAL_LOOPBACK = 1,
// 2, 4, 8: free
};
enum SrcFlags {
// 1, 2, 4, 8: free
};
};
typedef FlowInterface<Buffer<NMRAnetMessage>> MessageHandler;
class If : public Service
{
public:
/** Constructs an NMRAnet interface.
* @param executor is the thread that will be used for all processing on
* this interface.
* @param local_nodes_count is the maximum number of virtual nodes that
* this interface will support. */
If(ExecutorBase *executor, int local_nodes_count);
/** Destructor */
virtual ~If()
{
}
/** @return Flow to send global messages to the NMRAnet bus. */
MessageHandler *global_message_write_flow()
{
HASSERT(globalWriteFlow_);
return globalWriteFlow_;
}
/** @return Flow to send addressed messages to the NMRAnet bus. */
MessageHandler *addressed_message_write_flow()
{
HASSERT(addressedWriteFlow_);
return addressedWriteFlow_;
}
/** Type of the dispatcher of incoming NMRAnet messages. */
typedef DispatchFlow<Buffer<NMRAnetMessage>, 4> MessageDispatchFlow;
/** @return Dispatcher of incoming NMRAnet messages. */
MessageDispatchFlow *dispatcher()
{
return &dispatcher_;
}
/** Transfers ownership of a module to the interface. It will be brought
* down in the destructor. The destruction order is guaranteed such that
* all supporting structures are still available when the flow is destryed,
* but incoming messages can not come in anymore.
*
* @todo(balazs.racz) revise whether this needs to be virtual. */
virtual void add_owned_flow(Executable *e) = 0;
/** Registers a new local node on this interface. This function must be
* called from the interface's executor.
*
* @param node is the node to register.
*/
void add_local_node(Node *node)
{
NodeID id = node->node_id();
HASSERT(localNodes_.find(id) == localNodes_.end());
localNodes_[id] = node;
}
/** Removes a local node from this interface. This function must be called
* from the interface's executor.
*
* @param node is the node to delete.
*/
void delete_local_node(Node *node)
{
HASSERT(0);
/*
auto it = localNodes_.find(node->node_id());
HASSERT(it != localNodes_.end());
localNodes_.erase(it);*/
}
/** Looks up a node ID in the local nodes' registry. This function must be
* called from the interface's executor.
*
* @param id is the 48-bit NMRAnet node ID to look up.
* @returns the node pointer or NULL if the node is not registered.
*/
Node *lookup_local_node(NodeID id)
{
auto it = localNodes_.find(id);
if (it == localNodes_.end())
{
return nullptr;
}
return it->second;
}
protected:
/// Allocator containing the global write flows.
MessageHandler *globalWriteFlow_;
/// Allocator containing the addressed write flows.
MessageHandler *addressedWriteFlow_;
private:
/// Flow responsible for routing incoming messages to handlers.
MessageDispatchFlow dispatcher_;
typedef Map<NodeID, Node *> VNodeMap;
/// Local virtual nodes registered on this interface.
VNodeMap localNodes_;
friend class VerifyNodeIdHandler;
DISALLOW_COPY_AND_ASSIGN(If);
};
typedef StateFlow<Buffer<NMRAnetMessage>, QList<4>> MessageStateFlowBase;
/** Base class for incoming message handler flows. */
class IncomingMessageStateFlow
: public MessageStateFlowBase
{
public:
IncomingMessageStateFlow(If *interface)
: MessageStateFlowBase(interface)
{
}
If *interface()
{
return static_cast<If *>(service());
}
/// Returns the NMRAnet message we received.
NMRAnetMessage *nmsg()
{
return message()->data();
}
};
} // namespace nmranet
#endif // _NMRANET_IF_HXX_
<|endoftext|> |
<commit_before>//
// nthRoot.cpp
// Calculator
//
// Created by Gavin Scheele on 3/27/14.
// Copyright (c) 2014 Gavin Scheele. All rights reserved.
//
#include "nthRoot.h"
nthRoot::nthRoot(int root, int operand, int coefficient){
this->type = "nthRoot";
this->operand = operand;
this->root = root;
this->coefficient = 1;
int factors[50];
}
nthRoot::~nthRoot(){
}
int nthRoot::primeFactorization(int n) {
int k = 0;
while (n%2 == 0) {
factors[k] = 2;
k++;
n = n/2;
}
for (i = 3; i <= sqrt(n); i = i + 2) {
while (n%1 == 0) {
factors[k] = 2;
k++;
n = n/i;
}
}
if (n > 2) {
factors[k] = n;
}
return factors;
// added bonus: factors should be sorted already
}
Expression* nthRoot::simplify(){
int* factorsArray = primeFactorization(operand);
i = 0;
while (i <= factors.size()) {
j = i;
count = 0;
while (j <= factors.size() && factors[j + 1] == factors[j]) {
count++;
j++;
}
if (count >= root) {
coefficient *= (factors[i] ^ (count/root)); //how do I make count/root round down?
operand = operand / (factors[i] ^ (count - (count % root)))
}
i = j + 1;
}
Expression newRoot = nthRoot(root, operand, coefficient)
this.~nthRoot();
Expression* c = newroot;
return *c;
}
Expression* nthRoot::add(Expression* a){
asRoot = a.getRoot();
asOperand = a.getOperand();
asCoefficient = a.getCoefficient();
//make sure that in the canAdd method the operands and roots are the same!
newCoefficient = asCoefficient + coefficient;
nthRoot newNthRoot = new nthRoot(root, operand, newCoefficient);
Expression* c = newNthRoot;
return c;
}
Expression* nthRoot::subtract(Expression* a){
asRoot = a.getRoot();
asOperand = a.getOperand();
asCoefficient = a.getCoefficient();
//make sure that in the canSubtract method the operands and roots are the same!
newCoefficient = coefficient - asCoefficient;
nthRoot newNthRoot = new nthRoot(root, operand, newCoefficient);
Expression* c = newNthRoot;
return c;
}
Expression* nthRoot::multiply(Expression* a){
asOperand = a.getOperand();
asCoefficient = a.getCoefficient();
newCoefficient = asCoefficient * coefficient;
newOperand = operand * asOperand;
nthRoot newNthRoot = new nthRoot(root, newOperand, newCoefficient)
nthRoot simplifiedVersion = newNthRoot.simplify();
Expression* c = simplifiedVersion;
return c;
}
Expression* nthRoot::divide(Expression* a){
asRoot = a.getRoot();
asCoefficient = a.getCoefficient();
newCoefficient = coefficient / asCoefficient;
newRoot = root - asRoot;
nthRoot newNthRoot = new nthRoot(newRoot, operand, newCoefficient)
nthRoot simplifiedVersion = newNthRoot.simplify();
Expression* c = simplifiedVersion;
return c;
}
int getRoot() {
return root;
}
int getOperand() {
return operand;
}
int getCoefficient() {
return coefficient;
}
void setCoefficient(int n) {
this->coefficient = n;
}
void setOperand(int n) {
this->operand = n;
}
void setRoot(int n) {
this->root = n;
}
ostream& nthRoot::print(std::ostream& output) const{
output << this->coefficient << "*" << this->root << "rt:" << this->operand;
return output;
}
string nthRoot::toString(){
stringstream s;
s << coefficient << "*" << root << "rt:" << operand;
return s.str();
}
<commit_msg>hopefully divide semi-works<commit_after>//
// nthRoot.cpp
// Calculator
//
// Created by Gavin Scheele on 3/27/14.
// Copyright (c) 2014 Gavin Scheele. All rights reserved.
//
#include "nthRoot.h"
nthRoot::nthRoot(int root, int operand, int coefficient) {
this->type = "nthRoot";
this->operand = operand;
this->root = root;
this->coefficient = coefficient;
int factors[50];
}
nthRoot::~nthRoot() {
}
int nthRoot::primeFactorization(int n) {
int k = 0;
while (n%2 == 0) {
factors[k] = 2;
k++;
n = n/2;
}
for (i = 3; i <= sqrt(n); i = i + 2) {
while (n%1 == 0) {
factors[k] = 2;
k++;
n = n/i;
}
}
if (n > 2) {
factors[k] = n;
}
return factors;
// added bonus: factors should be sorted already
}
Expression* nthRoot::simplify(){
int* factorsArray = primeFactorization(operand);
i = 0;
while (i <= factors.size()) {
j = i;
count = 0;
while (j <= factors.size() && factors[j + 1] == factors[j]) {
count++;
j++;
}
if (count >= root) {
coefficient *= (factors[i] ^ (count/root)); //how do I make count/root round down?
operand = operand / (factors[i] ^ (count - (count % root)))
}
i = j + 1;
}
Expression newRoot = nthRoot(root, operand, coefficient)
this.~nthRoot();
Expression* c = newroot;
return *c;
}
Expression* nthRoot::add(Expression* a) {
asCoefficient = a.getCoefficient();
newCoefficient = asCoefficient + coefficient;
nthRoot newNthRoot = new nthRoot(root, operand, newCoefficient);
Expression* c = newNthRoot;
return c;
}
Expression* nthRoot::subtract(Expression* a) {
asCoefficient = a.getCoefficient();
newCoefficient = coefficient - asCoefficient;
nthRoot newNthRoot = new nthRoot(root, operand, newCoefficient);
Expression* c = newNthRoot;
return c;
}
Expression* nthRoot::multiply(Expression* a) {
asOperand = a.getOperand();
asCoefficient = a.getCoefficient();
newCoefficient = asCoefficient * coefficient;
newOperand = operand * asOperand;
nthRoot newNthRoot = new nthRoot(root, newOperand, newCoefficient)
nthRoot simplifiedVersion = newNthRoot.simplify();
Expression* c = simplifiedVersion;
return c;
}
Expression* nthRoot::divide(Expression* a) {
asOperand = a.getOperand();
asCoefficient = a.getCoefficient();
newCoefficient = coefficient / asCoefficient;
newOperand = operand / asOperand;
nthRoot newNthRoot = new nthRoot(root, newOperand, newCoefficient)
nthRoot simplifiedVersion = newNthRoot.simplify();
Expression* c = simplifiedVersion;
return c;
}
int getRoot() {
return root;
}
int getOperand() {
return operand;
}
int getCoefficient() {
return coefficient;
}
void setCoefficient(int n) {
this->coefficient = n;
}
void setOperand(int n) {
this->operand = n;
}
void setRoot(int n) {
this->root = n;
}
ostream& nthRoot::print(std::ostream& output) const {
output << this->coefficient << "*" << this->root << "rt:" << this->operand;
return output;
}
string nthRoot::toString() {
stringstream s;
s << coefficient << "*" << root << "rt:" << operand;
return s.str();
}
<|endoftext|> |
<commit_before>// Copyright 2014 Alessio Sclocco <a.sclocco@vu.nl>
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include <iostream>
#include <fstream>
#include <exception>
#include <string>
#include <utility>
#include <map>
#include <iomanip>
#include <ArgumentList.hpp>
#include <utils.hpp>
int main(int argc, char * argv[]) {
// DMs
unsigned int nrDMs = 0;
float firstDM = 0.0f;
float stepDM = 0.0f;
// Periods
unsigned int nrPeriods = 0;
unsigned int firstPeriod = 0;
unsigned int stepPeriod = 0;
// Sampling
unsigned int nrSamplesPerSecond = 0;
// I/O
std::string outFilename;
std::ifstream searchFile;
std::ofstream outFile;
// Data
bool exclusive = false;
bool * exclusionMapDM = 0;
bool * exclusionMapP = 0;
float percentile = 0;
std::multimap< float, std::pair< unsigned int, unsigned int > > snrList;
isa::utils::ArgumentList args(argc, argv);
try {
exclusive = args.getSwitch("-exclusive");
if ( exclusive ) {
nrDMs = args.getSwitchArgument< unsigned int >("-dms");
nrPeriods = args.getSwitchArgument< unsigned int >("-periods");
}
outFilename = args.getSwitchArgument< std::string >("-output");
firstDM = args.getSwitchArgument< float >("-dm_first");
stepDM = args.getSwitchArgument< float >("-dm_step");
firstPeriod = args.getSwitchArgument< unsigned int >("-period_first");
stepPeriod = args.getSwitchArgument< unsigned int >("-period_step");
nrSamplesPerSecond = args.getSwitchArgument< unsigned int >("-samples");
percentile = args.getSwitchArgument< float >("-percentile");
} catch ( isa::utils::EmptyCommandLine & err ) {
std::cerr << args.getName() << " [-exclusive] -output ... -dm_first ... -dm_step ... -period_first ... -period_step ... -samples ... -percentile ... input" << std::endl;
std::cerr << "\t -exclusive -dms ... -periods ..." << std::endl;
return 1;
} catch ( std::exception & err ) {
std::cerr << err.what() << std::endl;
return 1;
}
// Read the SNR data
try {
while ( true ) {
searchFile.open(args.getFirst< std::string >());
while ( ! searchFile.eof() ) {
std::string temp;
unsigned int splitPoint = 0;
unsigned int DM = 0;
unsigned int period = 0;
float snr = 0.0f;
std::getline(searchFile, temp);
if ( ! std::isdigit(temp[0]) ) {
continue;
}
splitPoint = temp.find(" ");
period = isa::utils::castToType< std::string, unsigned int >(temp.substr(0, splitPoint));
temp = temp.substr(splitPoint + 1);
splitPoint = temp.find(" ");
DM = isa::utils::castToType< std::string, unsigned int >(temp.substr(0, splitPoint));
temp = temp.substr(splitPoint + 1);
splitPoint = temp.find(" ");
snr = isa::utils::castToType< std::string, float >(temp);
snrList.insert(std::make_pair(snr, std::make_pair(DM, period)));
}
searchFile.close();
}
} catch ( isa::utils::EmptyCommandLine & err ) {
}
// Print the percentile
unsigned int lowerLimit = static_cast< unsigned int >((percentile * snrList.size()) / 100.0);
unsigned int counter = snrList.size() - 1;
if ( exclusive ) {
exclusionMapDM = new bool [nrDMs];
exclusionMapP = new bool [nrPeriods];
}
outFile.open(outFilename);
outFile << std::fixed;
outFile << "# DMIndex DM periodIndex period snr" << std::endl;
for ( std::multimap< float, std::pair< unsigned int, unsigned int> >::const_reverse_iterator item = snrList.crend(); counter >= lowerLimit; counter-- ) {
++item;
if ( exclusive && (exclusionMapDM[(*item).second.first] || exclusionMapP[(*item).second.second]) ) {
continue;
} else {
exclusionMapDM[(*item).second.first] = true;
exclusionMapP[(*item).second.second] = true;
}
outFile << std::setprecision(2);
outFile << (*item).second.first << " " << firstDM + ((*item).second.first * stepDM) << " ";
outFile << std::setprecision(6);
outFile << (*item).second.second << " " << (firstPeriod + ((*item).second.second * stepPeriod)) / static_cast< float >(nrSamplesPerSecond) << " ";
outFile << (*item).first << std::endl;
}
delete [] exclusionMapDM;
delete [] exclusionMapP;
outFile.close();
return 0;
}
<commit_msg>Fixing a bug.<commit_after>// Copyright 2014 Alessio Sclocco <a.sclocco@vu.nl>
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include <iostream>
#include <fstream>
#include <exception>
#include <string>
#include <utility>
#include <map>
#include <iomanip>
#include <ArgumentList.hpp>
#include <utils.hpp>
int main(int argc, char * argv[]) {
// DMs
unsigned int nrDMs = 0;
float firstDM = 0.0f;
float stepDM = 0.0f;
// Periods
unsigned int nrPeriods = 0;
unsigned int firstPeriod = 0;
unsigned int stepPeriod = 0;
// Sampling
unsigned int nrSamplesPerSecond = 0;
// I/O
std::string outFilename;
std::ifstream searchFile;
std::ofstream outFile;
// Data
bool exclusive = false;
bool * exclusionMapDM = 0;
bool * exclusionMapP = 0;
float percentile = 0;
std::multimap< float, std::pair< unsigned int, unsigned int > > snrList;
isa::utils::ArgumentList args(argc, argv);
try {
exclusive = args.getSwitch("-exclusive");
if ( exclusive ) {
nrDMs = args.getSwitchArgument< unsigned int >("-dms");
nrPeriods = args.getSwitchArgument< unsigned int >("-periods");
}
outFilename = args.getSwitchArgument< std::string >("-output");
firstDM = args.getSwitchArgument< float >("-dm_first");
stepDM = args.getSwitchArgument< float >("-dm_step");
firstPeriod = args.getSwitchArgument< unsigned int >("-period_first");
stepPeriod = args.getSwitchArgument< unsigned int >("-period_step");
nrSamplesPerSecond = args.getSwitchArgument< unsigned int >("-samples");
percentile = args.getSwitchArgument< float >("-percentile");
} catch ( isa::utils::EmptyCommandLine & err ) {
std::cerr << args.getName() << " [-exclusive] -output ... -dm_first ... -dm_step ... -period_first ... -period_step ... -samples ... -percentile ... input" << std::endl;
std::cerr << "\t -exclusive -dms ... -periods ..." << std::endl;
return 1;
} catch ( std::exception & err ) {
std::cerr << err.what() << std::endl;
return 1;
}
// Read the SNR data
try {
while ( true ) {
searchFile.open(args.getFirst< std::string >());
while ( ! searchFile.eof() ) {
std::string temp;
unsigned int splitPoint = 0;
unsigned int DM = 0;
unsigned int period = 0;
float snr = 0.0f;
std::getline(searchFile, temp);
if ( ! std::isdigit(temp[0]) ) {
continue;
}
splitPoint = temp.find(" ");
period = isa::utils::castToType< std::string, unsigned int >(temp.substr(0, splitPoint));
temp = temp.substr(splitPoint + 1);
splitPoint = temp.find(" ");
DM = isa::utils::castToType< std::string, unsigned int >(temp.substr(0, splitPoint));
temp = temp.substr(splitPoint + 1);
splitPoint = temp.find(" ");
snr = isa::utils::castToType< std::string, float >(temp);
snrList.insert(std::make_pair(snr, std::make_pair(DM, period)));
}
searchFile.close();
}
} catch ( isa::utils::EmptyCommandLine & err ) {
}
// Print the percentile
unsigned int lowerLimit = static_cast< unsigned int >((percentile * snrList.size()) / 100.0);
unsigned int counter = snrList.size() - 1;
if ( exclusive ) {
exclusionMapDM = new bool [nrDMs];
exclusionMapP = new bool [nrPeriods];
}
outFile.open(outFilename);
outFile << std::fixed;
outFile << "# DMIndex DM periodIndex period snr" << std::endl;
for ( std::multimap< float, std::pair< unsigned int, unsigned int> >::const_reverse_iterator item = snrList.crend(); counter >= lowerLimit; counter-- ) {
++item;
if ( exclusive && (exclusionMapDM[(*item).second.first] || exclusionMapP[(*item).second.second]) ) {
continue;
} else if ( exclusionMapDM[(*item).second.first] || exclusionMapP[(*item).second.second] ) {
exclusionMapDM[(*item).second.first] = true;
exclusionMapP[(*item).second.second] = true;
}
outFile << std::setprecision(2);
outFile << (*item).second.first << " " << firstDM + ((*item).second.first * stepDM) << " ";
outFile << std::setprecision(6);
outFile << (*item).second.second << " " << (firstPeriod + ((*item).second.second * stepPeriod)) / static_cast< float >(nrSamplesPerSecond) << " ";
outFile << (*item).first << std::endl;
}
delete [] exclusionMapDM;
delete [] exclusionMapP;
outFile.close();
return 0;
}
<|endoftext|> |
<commit_before>/*
* Copyright (C) 2015 Cloudius Systems, Ltd.
*/
/*
* This file is part of Scylla.
*
* Scylla is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Scylla 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 Scylla. If not, see <http://www.gnu.org/licenses/>.
*/
#pragma once
#include "bytes.hh"
#include "timestamp.hh"
#include "tombstone.hh"
#include "gc_clock.hh"
#include "utils/managed_bytes.hh"
#include "net/byteorder.hh"
#include <cstdint>
#include <iostream>
template<typename T>
static inline
void set_field(managed_bytes& v, unsigned offset, T val) {
reinterpret_cast<net::packed<T>*>(v.begin() + offset)->raw = net::hton(val);
}
template<typename T>
static inline
T get_field(const bytes_view& v, unsigned offset) {
return net::ntoh(*reinterpret_cast<const net::packed<T>*>(v.begin() + offset));
}
class atomic_cell_or_collection;
/*
* Represents atomic cell layout. Works on serialized form.
*
* Layout:
*
* <live> := <int8_t:flags><int64_t:timestamp>(<int32_t:expiry><int32_t:ttl>)?<value>
* <dead> := <int8_t: 0><int64_t:timestamp><int32_t:deletion_time>
*/
class atomic_cell_type final {
private:
static constexpr int8_t DEAD_FLAGS = 0;
static constexpr int8_t LIVE_FLAG = 0x01;
static constexpr int8_t EXPIRY_FLAG = 0x02; // When present, expiry field is present. Set only for live cells
static constexpr unsigned flags_size = 1;
static constexpr unsigned timestamp_offset = flags_size;
static constexpr unsigned timestamp_size = 8;
static constexpr unsigned expiry_offset = timestamp_offset + timestamp_size;
static constexpr unsigned expiry_size = 4;
static constexpr unsigned deletion_time_offset = timestamp_offset + timestamp_size;
static constexpr unsigned deletion_time_size = 4;
static constexpr unsigned ttl_offset = expiry_offset + expiry_size;
static constexpr unsigned ttl_size = 4;
private:
static bool is_live(const bytes_view& cell) {
return cell[0] != DEAD_FLAGS;
}
static bool is_live_and_has_ttl(const bytes_view& cell) {
return cell[0] & EXPIRY_FLAG;
}
static bool is_dead(const bytes_view& cell) {
return cell[0] == DEAD_FLAGS;
}
// Can be called on live and dead cells
static api::timestamp_type timestamp(const bytes_view& cell) {
return get_field<api::timestamp_type>(cell, timestamp_offset);
}
// Can be called on live cells only
static bytes_view value(bytes_view cell) {
auto expiry_field_size = bool(cell[0] & EXPIRY_FLAG) * (expiry_size + ttl_size);
auto value_offset = flags_size + timestamp_size + expiry_field_size;
cell.remove_prefix(value_offset);
return cell;
}
// Can be called only when is_dead() is true.
static gc_clock::time_point deletion_time(const bytes_view& cell) {
assert(is_dead(cell));
return gc_clock::time_point(gc_clock::duration(
get_field<int32_t>(cell, deletion_time_offset)));
}
// Can be called only when is_live_and_has_ttl() is true.
static gc_clock::time_point expiry(const bytes_view& cell) {
assert(is_live_and_has_ttl(cell));
auto expiry = get_field<int32_t>(cell, expiry_offset);
return gc_clock::time_point(gc_clock::duration(expiry));
}
// Can be called only when is_live_and_has_ttl() is true.
static gc_clock::duration ttl(const bytes_view& cell) {
assert(is_live_and_has_ttl(cell));
return gc_clock::duration(get_field<int32_t>(cell, ttl_offset));
}
static managed_bytes make_dead(api::timestamp_type timestamp, gc_clock::time_point deletion_time) {
managed_bytes b(managed_bytes::initialized_later(), flags_size + timestamp_size + deletion_time_size);
b[0] = DEAD_FLAGS;
set_field(b, timestamp_offset, timestamp);
set_field(b, deletion_time_offset, deletion_time.time_since_epoch().count());
return b;
}
static managed_bytes make_live(api::timestamp_type timestamp, bytes_view value) {
auto value_offset = flags_size + timestamp_size;
managed_bytes b(managed_bytes::initialized_later(), value_offset + value.size());
b[0] = LIVE_FLAG;
set_field(b, timestamp_offset, timestamp);
std::copy_n(value.begin(), value.size(), b.begin() + value_offset);
return b;
}
static managed_bytes make_live(api::timestamp_type timestamp, bytes_view value, gc_clock::time_point expiry, gc_clock::duration ttl) {
auto value_offset = flags_size + timestamp_size + expiry_size + ttl_size;
managed_bytes b(managed_bytes::initialized_later(), value_offset + value.size());
b[0] = EXPIRY_FLAG | LIVE_FLAG;
set_field(b, timestamp_offset, timestamp);
set_field(b, expiry_offset, expiry.time_since_epoch().count());
set_field(b, ttl_offset, ttl.count());
std::copy_n(value.begin(), value.size(), b.begin() + value_offset);
return b;
}
template<typename ByteContainer>
friend class atomic_cell_base;
friend class atomic_cell;
};
template<typename ByteContainer>
class atomic_cell_base {
protected:
ByteContainer _data;
protected:
atomic_cell_base(ByteContainer&& data) : _data(std::forward<ByteContainer>(data)) { }
atomic_cell_base(const ByteContainer& data) : _data(data) { }
public:
bool is_live() const {
return atomic_cell_type::is_live(_data);
}
bool is_live(tombstone t) const {
return is_live() && !is_covered_by(t);
}
bool is_live(tombstone t, gc_clock::time_point now) const {
return is_live() && !is_covered_by(t) && !has_expired(now);
}
bool is_live_and_has_ttl() const {
return atomic_cell_type::is_live_and_has_ttl(_data);
}
bool is_dead(gc_clock::time_point now) const {
return atomic_cell_type::is_dead(_data) || has_expired(now);
}
bool is_covered_by(tombstone t) const {
return timestamp() <= t.timestamp;
}
// Can be called on live and dead cells
api::timestamp_type timestamp() const {
return atomic_cell_type::timestamp(_data);
}
// Can be called on live cells only
bytes_view value() const {
return atomic_cell_type::value(_data);
}
// Can be called only when is_dead(gc_clock::time_point)
gc_clock::time_point deletion_time() const {
return !is_live() ? atomic_cell_type::deletion_time(_data) : expiry() - ttl();
}
// Can be called only when is_live_and_has_ttl()
gc_clock::time_point expiry() const {
return atomic_cell_type::expiry(_data);
}
// Can be called only when is_live_and_has_ttl()
gc_clock::duration ttl() const {
return atomic_cell_type::ttl(_data);
}
// Can be called on live and dead cells
bool has_expired(gc_clock::time_point now) const {
return is_live_and_has_ttl() && expiry() < now;
}
bytes_view serialize() const {
return _data;
}
};
class atomic_cell_view final : public atomic_cell_base<bytes_view> {
atomic_cell_view(bytes_view data) : atomic_cell_base(data) {}
public:
static atomic_cell_view from_bytes(bytes_view data) { return atomic_cell_view(data); }
friend class atomic_cell;
friend std::ostream& operator<<(std::ostream& os, const atomic_cell_view& acv);
};
class atomic_cell final : public atomic_cell_base<managed_bytes> {
atomic_cell(managed_bytes b) : atomic_cell_base(std::move(b)) {}
public:
atomic_cell(const atomic_cell&) = default;
atomic_cell(atomic_cell&&) = default;
atomic_cell& operator=(const atomic_cell&) = default;
atomic_cell& operator=(atomic_cell&&) = default;
static atomic_cell from_bytes(managed_bytes b) {
return atomic_cell(std::move(b));
}
atomic_cell(atomic_cell_view other) : atomic_cell_base(managed_bytes{other._data}) {}
operator atomic_cell_view() const {
return atomic_cell_view(_data);
}
static atomic_cell make_dead(api::timestamp_type timestamp, gc_clock::time_point deletion_time) {
return atomic_cell_type::make_dead(timestamp, deletion_time);
}
static atomic_cell make_live(api::timestamp_type timestamp, bytes_view value) {
return atomic_cell_type::make_live(timestamp, value);
}
static atomic_cell make_live(api::timestamp_type timestamp, bytes_view value,
gc_clock::time_point expiry, gc_clock::duration ttl)
{
return atomic_cell_type::make_live(timestamp, value, expiry, ttl);
}
static atomic_cell make_live(api::timestamp_type timestamp, bytes_view value, ttl_opt ttl) {
if (!ttl) {
return atomic_cell_type::make_live(timestamp, value);
} else {
return atomic_cell_type::make_live(timestamp, value, gc_clock::now() + *ttl, *ttl);
}
}
friend class atomic_cell_or_collection;
friend std::ostream& operator<<(std::ostream& os, const atomic_cell& ac);
};
class collection_mutation_view;
// Represents a mutation of a collection. Actual format is determined by collection type,
// and is:
// set: list of atomic_cell
// map: list of pair<atomic_cell, bytes> (for key/value)
// list: tbd, probably ugly
class collection_mutation {
public:
managed_bytes data;
collection_mutation() {}
collection_mutation(managed_bytes b) : data(std::move(b)) {}
collection_mutation(collection_mutation_view v);
operator collection_mutation_view() const;
};
class collection_mutation_view {
public:
bytes_view data;
bytes_view serialize() const { return data; }
static collection_mutation_view from_bytes(bytes_view v) { return { v }; }
};
inline
collection_mutation::collection_mutation(collection_mutation_view v)
: data(v.data) {
}
inline
collection_mutation::operator collection_mutation_view() const {
return { data };
}
namespace db {
template<typename T>
class serializer;
}
// A variant type that can hold either an atomic_cell, or a serialized collection.
// Which type is stored is determined by the schema.
class atomic_cell_or_collection final {
managed_bytes _data;
template<typename T>
friend class db::serializer;
private:
atomic_cell_or_collection(managed_bytes&& data) : _data(std::move(data)) {}
public:
atomic_cell_or_collection() = default;
atomic_cell_or_collection(atomic_cell ac) : _data(std::move(ac._data)) {}
static atomic_cell_or_collection from_atomic_cell(atomic_cell data) { return { std::move(data._data) }; }
atomic_cell_view as_atomic_cell() const { return atomic_cell_view::from_bytes(_data); }
atomic_cell_or_collection(collection_mutation cm) : _data(std::move(cm.data)) {}
explicit operator bool() const {
return !_data.empty();
}
static atomic_cell_or_collection from_collection_mutation(collection_mutation data) {
return std::move(data.data);
}
collection_mutation_view as_collection_mutation() const {
return collection_mutation_view{_data};
}
bytes_view serialize() const {
return _data;
}
bool operator==(const atomic_cell_or_collection& other) const {
return _data == other._data;
}
friend std::ostream& operator<<(std::ostream&, const atomic_cell_or_collection&);
};
class column_definition;
int compare_atomic_cell_for_merge(atomic_cell_view left, atomic_cell_view right);
void merge_column(const column_definition& def,
atomic_cell_or_collection& old,
const atomic_cell_or_collection& neww);
<commit_msg>atomic_cell_or_collection: linearize(), unlinearize()<commit_after>/*
* Copyright (C) 2015 Cloudius Systems, Ltd.
*/
/*
* This file is part of Scylla.
*
* Scylla is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Scylla 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 Scylla. If not, see <http://www.gnu.org/licenses/>.
*/
#pragma once
#include "bytes.hh"
#include "timestamp.hh"
#include "tombstone.hh"
#include "gc_clock.hh"
#include "utils/managed_bytes.hh"
#include "net/byteorder.hh"
#include <cstdint>
#include <iostream>
template<typename T>
static inline
void set_field(managed_bytes& v, unsigned offset, T val) {
reinterpret_cast<net::packed<T>*>(v.begin() + offset)->raw = net::hton(val);
}
template<typename T>
static inline
T get_field(const bytes_view& v, unsigned offset) {
return net::ntoh(*reinterpret_cast<const net::packed<T>*>(v.begin() + offset));
}
class atomic_cell_or_collection;
/*
* Represents atomic cell layout. Works on serialized form.
*
* Layout:
*
* <live> := <int8_t:flags><int64_t:timestamp>(<int32_t:expiry><int32_t:ttl>)?<value>
* <dead> := <int8_t: 0><int64_t:timestamp><int32_t:deletion_time>
*/
class atomic_cell_type final {
private:
static constexpr int8_t DEAD_FLAGS = 0;
static constexpr int8_t LIVE_FLAG = 0x01;
static constexpr int8_t EXPIRY_FLAG = 0x02; // When present, expiry field is present. Set only for live cells
static constexpr unsigned flags_size = 1;
static constexpr unsigned timestamp_offset = flags_size;
static constexpr unsigned timestamp_size = 8;
static constexpr unsigned expiry_offset = timestamp_offset + timestamp_size;
static constexpr unsigned expiry_size = 4;
static constexpr unsigned deletion_time_offset = timestamp_offset + timestamp_size;
static constexpr unsigned deletion_time_size = 4;
static constexpr unsigned ttl_offset = expiry_offset + expiry_size;
static constexpr unsigned ttl_size = 4;
private:
static bool is_live(const bytes_view& cell) {
return cell[0] != DEAD_FLAGS;
}
static bool is_live_and_has_ttl(const bytes_view& cell) {
return cell[0] & EXPIRY_FLAG;
}
static bool is_dead(const bytes_view& cell) {
return cell[0] == DEAD_FLAGS;
}
// Can be called on live and dead cells
static api::timestamp_type timestamp(const bytes_view& cell) {
return get_field<api::timestamp_type>(cell, timestamp_offset);
}
// Can be called on live cells only
static bytes_view value(bytes_view cell) {
auto expiry_field_size = bool(cell[0] & EXPIRY_FLAG) * (expiry_size + ttl_size);
auto value_offset = flags_size + timestamp_size + expiry_field_size;
cell.remove_prefix(value_offset);
return cell;
}
// Can be called only when is_dead() is true.
static gc_clock::time_point deletion_time(const bytes_view& cell) {
assert(is_dead(cell));
return gc_clock::time_point(gc_clock::duration(
get_field<int32_t>(cell, deletion_time_offset)));
}
// Can be called only when is_live_and_has_ttl() is true.
static gc_clock::time_point expiry(const bytes_view& cell) {
assert(is_live_and_has_ttl(cell));
auto expiry = get_field<int32_t>(cell, expiry_offset);
return gc_clock::time_point(gc_clock::duration(expiry));
}
// Can be called only when is_live_and_has_ttl() is true.
static gc_clock::duration ttl(const bytes_view& cell) {
assert(is_live_and_has_ttl(cell));
return gc_clock::duration(get_field<int32_t>(cell, ttl_offset));
}
static managed_bytes make_dead(api::timestamp_type timestamp, gc_clock::time_point deletion_time) {
managed_bytes b(managed_bytes::initialized_later(), flags_size + timestamp_size + deletion_time_size);
b[0] = DEAD_FLAGS;
set_field(b, timestamp_offset, timestamp);
set_field(b, deletion_time_offset, deletion_time.time_since_epoch().count());
return b;
}
static managed_bytes make_live(api::timestamp_type timestamp, bytes_view value) {
auto value_offset = flags_size + timestamp_size;
managed_bytes b(managed_bytes::initialized_later(), value_offset + value.size());
b[0] = LIVE_FLAG;
set_field(b, timestamp_offset, timestamp);
std::copy_n(value.begin(), value.size(), b.begin() + value_offset);
return b;
}
static managed_bytes make_live(api::timestamp_type timestamp, bytes_view value, gc_clock::time_point expiry, gc_clock::duration ttl) {
auto value_offset = flags_size + timestamp_size + expiry_size + ttl_size;
managed_bytes b(managed_bytes::initialized_later(), value_offset + value.size());
b[0] = EXPIRY_FLAG | LIVE_FLAG;
set_field(b, timestamp_offset, timestamp);
set_field(b, expiry_offset, expiry.time_since_epoch().count());
set_field(b, ttl_offset, ttl.count());
std::copy_n(value.begin(), value.size(), b.begin() + value_offset);
return b;
}
template<typename ByteContainer>
friend class atomic_cell_base;
friend class atomic_cell;
};
template<typename ByteContainer>
class atomic_cell_base {
protected:
ByteContainer _data;
protected:
atomic_cell_base(ByteContainer&& data) : _data(std::forward<ByteContainer>(data)) { }
atomic_cell_base(const ByteContainer& data) : _data(data) { }
public:
bool is_live() const {
return atomic_cell_type::is_live(_data);
}
bool is_live(tombstone t) const {
return is_live() && !is_covered_by(t);
}
bool is_live(tombstone t, gc_clock::time_point now) const {
return is_live() && !is_covered_by(t) && !has_expired(now);
}
bool is_live_and_has_ttl() const {
return atomic_cell_type::is_live_and_has_ttl(_data);
}
bool is_dead(gc_clock::time_point now) const {
return atomic_cell_type::is_dead(_data) || has_expired(now);
}
bool is_covered_by(tombstone t) const {
return timestamp() <= t.timestamp;
}
// Can be called on live and dead cells
api::timestamp_type timestamp() const {
return atomic_cell_type::timestamp(_data);
}
// Can be called on live cells only
bytes_view value() const {
return atomic_cell_type::value(_data);
}
// Can be called only when is_dead(gc_clock::time_point)
gc_clock::time_point deletion_time() const {
return !is_live() ? atomic_cell_type::deletion_time(_data) : expiry() - ttl();
}
// Can be called only when is_live_and_has_ttl()
gc_clock::time_point expiry() const {
return atomic_cell_type::expiry(_data);
}
// Can be called only when is_live_and_has_ttl()
gc_clock::duration ttl() const {
return atomic_cell_type::ttl(_data);
}
// Can be called on live and dead cells
bool has_expired(gc_clock::time_point now) const {
return is_live_and_has_ttl() && expiry() < now;
}
bytes_view serialize() const {
return _data;
}
};
class atomic_cell_view final : public atomic_cell_base<bytes_view> {
atomic_cell_view(bytes_view data) : atomic_cell_base(data) {}
public:
static atomic_cell_view from_bytes(bytes_view data) { return atomic_cell_view(data); }
friend class atomic_cell;
friend std::ostream& operator<<(std::ostream& os, const atomic_cell_view& acv);
};
class atomic_cell final : public atomic_cell_base<managed_bytes> {
atomic_cell(managed_bytes b) : atomic_cell_base(std::move(b)) {}
public:
atomic_cell(const atomic_cell&) = default;
atomic_cell(atomic_cell&&) = default;
atomic_cell& operator=(const atomic_cell&) = default;
atomic_cell& operator=(atomic_cell&&) = default;
static atomic_cell from_bytes(managed_bytes b) {
return atomic_cell(std::move(b));
}
atomic_cell(atomic_cell_view other) : atomic_cell_base(managed_bytes{other._data}) {}
operator atomic_cell_view() const {
return atomic_cell_view(_data);
}
static atomic_cell make_dead(api::timestamp_type timestamp, gc_clock::time_point deletion_time) {
return atomic_cell_type::make_dead(timestamp, deletion_time);
}
static atomic_cell make_live(api::timestamp_type timestamp, bytes_view value) {
return atomic_cell_type::make_live(timestamp, value);
}
static atomic_cell make_live(api::timestamp_type timestamp, bytes_view value,
gc_clock::time_point expiry, gc_clock::duration ttl)
{
return atomic_cell_type::make_live(timestamp, value, expiry, ttl);
}
static atomic_cell make_live(api::timestamp_type timestamp, bytes_view value, ttl_opt ttl) {
if (!ttl) {
return atomic_cell_type::make_live(timestamp, value);
} else {
return atomic_cell_type::make_live(timestamp, value, gc_clock::now() + *ttl, *ttl);
}
}
friend class atomic_cell_or_collection;
friend std::ostream& operator<<(std::ostream& os, const atomic_cell& ac);
};
class collection_mutation_view;
// Represents a mutation of a collection. Actual format is determined by collection type,
// and is:
// set: list of atomic_cell
// map: list of pair<atomic_cell, bytes> (for key/value)
// list: tbd, probably ugly
class collection_mutation {
public:
managed_bytes data;
collection_mutation() {}
collection_mutation(managed_bytes b) : data(std::move(b)) {}
collection_mutation(collection_mutation_view v);
operator collection_mutation_view() const;
};
class collection_mutation_view {
public:
bytes_view data;
bytes_view serialize() const { return data; }
static collection_mutation_view from_bytes(bytes_view v) { return { v }; }
};
inline
collection_mutation::collection_mutation(collection_mutation_view v)
: data(v.data) {
}
inline
collection_mutation::operator collection_mutation_view() const {
return { data };
}
namespace db {
template<typename T>
class serializer;
}
// A variant type that can hold either an atomic_cell, or a serialized collection.
// Which type is stored is determined by the schema.
class atomic_cell_or_collection final {
managed_bytes _data;
template<typename T>
friend class db::serializer;
private:
atomic_cell_or_collection(managed_bytes&& data) : _data(std::move(data)) {}
public:
atomic_cell_or_collection() = default;
atomic_cell_or_collection(atomic_cell ac) : _data(std::move(ac._data)) {}
static atomic_cell_or_collection from_atomic_cell(atomic_cell data) { return { std::move(data._data) }; }
atomic_cell_view as_atomic_cell() const { return atomic_cell_view::from_bytes(_data); }
atomic_cell_or_collection(collection_mutation cm) : _data(std::move(cm.data)) {}
explicit operator bool() const {
return !_data.empty();
}
static atomic_cell_or_collection from_collection_mutation(collection_mutation data) {
return std::move(data.data);
}
collection_mutation_view as_collection_mutation() const {
return collection_mutation_view{_data};
}
bytes_view serialize() const {
return _data;
}
bool operator==(const atomic_cell_or_collection& other) const {
return _data == other._data;
}
void linearize() {
_data.linearize();
}
void unlinearize() {
_data.scatter();
}
friend std::ostream& operator<<(std::ostream&, const atomic_cell_or_collection&);
};
class column_definition;
int compare_atomic_cell_for_merge(atomic_cell_view left, atomic_cell_view right);
void merge_column(const column_definition& def,
atomic_cell_or_collection& old,
const atomic_cell_or_collection& neww);
<|endoftext|> |
<commit_before>/*******************************************************************************
*
* MIT License
*
* Copyright (c) 2017 Advanced Micro Devices, Inc.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*
*******************************************************************************/
#include <miopen/rnn.hpp>
#include <miopen/env.hpp>
#include <miopen/util.hpp>
#include <miopen/float_equal.hpp>
#include <vector>
#include <numeric>
#include <miopengemm/gemm.hpp>
namespace miopen {
MIOPEN_DECLARE_ENV_VAR(MIOPEN_DEBUG_CONV_DIRECT)
struct AutoEnableProfiling
{
AutoEnableProfiling(Handle& x) : h(x)
{
prev_state = h.IsProfilingEnabled();
h.EnableProfiling();
}
~AutoEnableProfiling()
{
h.EnableProfiling(prev_state);
h.ResetKernelTime();
}
private:
Handle& h;
bool prev_state;
};
void RNNDescriptor::RNNForwardTraining(Handle& handle,
const int seqLen,
// const TensorDescriptor& xDesc,
ConstData_t x,
// const TensorDescriptor& hxDesc,
ConstData_t hx,
// const TensorDescriptor& cxDesc,
ConstData_t cx,
// const TensorDescriptor& wDesc,
ConstData_t w,
// const TensorDescriptor& yDesc,
Data_t y,
// const TensorDescriptor& hyDesc,
Data_t hy,
// const TensorDescriptor& cyDesc,
Data_t cy,
Data_t workSpace,
size_t workSpaceSize,
Data_t reserveSpace,
size_t reserveSpaceSize,
const std::vector<int> &in_n,
const int in_h,
const int hy_d,
const int hy_n,
const int hy_h,
const int out_h) const
{/*
if (x == nullptr || w == nullptr || y == nullptr)
{
MIOPEN_THROW(miopenStatusBadParm);
}
if (xDesc.GetSize() != yDesc.GetSize() || xDesc.GetSize() != wDesc.GetSize())
{
MIOPEN_THROW(miopenStatusBadParm);
}
if (xDesc.GetType() != yDesc.GetType() || xDesc.GetType() != wDesc.GetType())
{
MIOPEN_THROW(miopenStatusBadParm);
}
*/
// int in_n, in_c, in_h, in_w;
// std::tie(in_n, in_c, in_h, in_w) = tie4(xDesc.GetLengths());
// int out_h, out_w;
// std::tie(std::ignore, std::ignore, out_h, out_w) = tie4(yDesc.GetLengths());
/*
if (workSpace == nullptr ||
workSpaceSize < ForwardGetWorkSpaceSize(handle, wDesc, xDesc, yDesc) || reserveSpaceSize < ForwardGetReserveSpaceSize(handle, wDesc, xDesc, yDesc))
{
MIOPEN_THROW("Workspace is required");
}
*/
// miopenRNNMode_t mode;
// int seqLength;
// int layer;
// int bidir;
// int bias;
int batch_n = std::accumulate(in_n.begin(), in_n.end(), 0);
bool bidirection = (bidir != 0);
bool biased = (bias != 0);
int numlayer = layer;
int bacc, baccbi;
int bi = bidirection ? 2 : 1;
int wei_len = (bi * (in_h + hy_h + out_h) + (numlayer - 1) * bi * (bi + 1) * hy_h) * hy_h;
if (biased)
{
wei_len += (bi * 2 + (numlayer - 1) * bi * (bi + 1)) * hy_h + bi * out_h;
}
int wei_shift_bias =
((in_h + hy_h + out_h) * bi + (bi * hy_h + hy_h) * bi * (numlayer - 1)) * hy_h;
int in_stride = in_h;
int hy_stride = hy_h * bi;
int h_stride = hy_h * bi;
int out_stride = out_h;
int wei_stride = hy_h * bi;
if (mode == miopenRNNRELU || mode == miopenRNNTANH)
{
#if MIOPEN_USE_MIOPENGEMM
printf("rnn gpu \n");
cl_command_queue Q = (cl_command_queue)handle.GetStream();
for (int li = 0; li < numlayer; li++)
{
int hid_shift = li * batch_n * hy_h * bi;
int hx_shift = li * bi * in_n[0] * hy_h;
// from input
if (li == 0)
{
MIOpenGEMM::gemm0<float>(false,
false,
false,
batch_n,
hy_h * bi,
in_h,
1,
x,
0,
in_stride,
w,
0,
wei_stride,
1,
reserveSpace,
hid_shift,
hy_stride,
&Q,
0,
nullptr,
nullptr);
}
else
{
int wei_shift = bi * (in_h + hy_h) * hy_h + (li - 1) * bi * (bi * hy_h + hy_h) * hy_h;
int prelayer_shift = (li - 1) * batch_n * hy_h * bi;
MIOpenGEMM::gemm0<float>(false,
false,
false,
batch_n,
hy_h * bi,
hy_h * bi,
1,
workSpace,
prelayer_shift,
hy_stride,
w,
wei_shift,
wei_stride,
1,
reserveSpace,
hid_shift,
hy_stride,
&Q,
0,
nullptr,
nullptr);
}
// from hidden state
bacc = 0;
baccbi = batch_n;
for (int ti = 0; ti < seqLen; ti++)
{
baccbi -= in_n[seqLen - 1 - ti];
int wei_shift =
li == 0 ? (in_h * hy_h * bi)
: (bi * (in_h + hy_h) * hy_h + (li - 1) * bi * (bi * hy_h + hy_h) * hy_h +
bi * hy_h * hy_stride);
if (ti == 0)
{
MIOpenGEMM::gemm0<float>(false,
false,
false,
in_n[ti],
hy_h,
hy_h,
1,
hx,
hx_shift,
h_stride,
w,
wei_shift,
wei_stride,
1,
reserveSpace,
hid_shift + bacc * hy_stride,
hy_stride,
&Q,
0,
nullptr,
nullptr);
if (bidirection)
{
MIOpenGEMM::gemm0<float>(false,
false,
false,
in_n[seqLen - 1 - ti],
hy_h,
hy_h,
1,
hx,
hx_shift + hy_h,
h_stride,
w,
wei_shift + hy_h,
wei_stride,
1,
reserveSpace,
hid_shift + baccbi * hy_stride + hy_h,
hy_stride,
&Q,
0,
nullptr,
nullptr);
}
}
else
{
MIOpenGEMM::gemm0<float>(false,
false,
false,
in_n[ti],
hy_h,
hy_h,
1,
hy,
hx_shift,
h_stride,
w,
wei_shift,
wei_stride,
1,
reserveSpace,
hid_shift + bacc * hy_stride,
hy_stride,
&Q,
0,
nullptr,
nullptr);
if (bidirection)
{
MIOpenGEMM::gemm0<float>(false,
false,
false,
in_n[seqLen - 1 - ti],
hy_h,
hy_h,
1,
hy,
hx_shift + hy_h,
h_stride,
w,
wei_shift + hy_h,
wei_stride,
1,
reserveSpace,
hid_shift + baccbi * hy_stride + hy_h,
hy_stride,
&Q,
0,
nullptr,
nullptr);
}
}
int rsv_sz = batch_n * hy_d * hy_h;
std::vector<int> rsv_size(3, 1);
rsv_size.push_back(rsv_sz);
miopenTensorDescriptor_t rsvTensor;
miopenCreateTensorDescriptor(&rsvTensor);
SetTensor4d(rsvTensor, rsv_size);
miopenActivationDescriptor_t activDesc;
miopenCreateActivationDescriptor(&activDesc);
miopenActivationMode_t amode;
amode = (mode == miopenRNNRELU) ? miopenActivationRELU : miopenActivationLOGISTIC;
miopenSetActivationDescriptor(activDesc, amode, 1, 0, 1);
miopenActivationForward(handle,
activDesc,
1,
rsvTensor,
reserveSpace,
0,
rsvTensor,
workSpace);
bacc += in_n[ti];
}
}
int prelayer_shift = (numlayer - 1) * batch_n * hy_h * bi;
int wei_shift = bi * (in_h + hy_h) * hy_h + (numlayer - 1) * bi * (bi * hy_h + hy_h) * hy_h;
MIOpenGEMM::gemm0<float>(false,
false,
true,
batch_n,
out_h,
hy_h * bi,
1,
workSpace,
prelayer_shift,
hy_stride,
w,
wei_shift,
wei_stride,
1,
y,
0,
out_stride,
&Q,
0,
nullptr,
nullptr);
clFinish(Q);
#else
MIOPEN_THROW("GEMM is not supported");
#endif
}
else if (mode == miopenLSTM)
{
printf("lstm gpu \n");
}
else if (mode == miopenGRU)
{
printf("gru gpu \n");
}
};
void RNNDescriptor::RNNBackwardData(Handle& handle,
const int seqLen,
const TensorDescriptor& yDesc,
ConstData_t y,
const TensorDescriptor& dyDesc,
ConstData_t dy,
const TensorDescriptor& dhyDesc,
ConstData_t dhy,
const TensorDescriptor& dcyDesc,
ConstData_t dcy,
const TensorDescriptor& wDesc,
ConstData_t w,
const TensorDescriptor& hxDesc,
ConstData_t hx,
const TensorDescriptor& cxDesc,
ConstData_t cx,
const TensorDescriptor& dxDesc,
Data_t dx,
const TensorDescriptor& dhxDesc,
Data_t dhx,
const TensorDescriptor& dcxDesc,
Data_t dcx,
Data_t workSpace,
size_t workSpaceSize,
ConstData_t reserveSpace,
size_t reserveSpaceSize) const
{
/*
if (dx == nullptr || w == nullptr || dy == nullptr)
{
MIOPEN_THROW(miopenStatusBadParm);
}
if (dyDesc.GetSize() != dxDesc.GetSize() || dyDesc.GetSize() != wDesc.GetSize())
{
MIOPEN_THROW(miopenStatusBadParm);
}
if (dyDesc.GetType() != dxDesc.GetType() || dyDesc.GetType() != wDesc.GetType())
{
MIOPEN_THROW(miopenStatusBadParm);
}
*/
int in_n, in_c, in_h, in_w;
// std::tie(in_n, in_c, in_h, in_w) = tie4(xDesc.GetLengths());
int wei_n, wei_h, wei_w;
// std::tie(wei_n, std::ignore, wei_h, wei_w) = tie4(wDesc.GetLengths());
int out_h, out_w;
// std::tie(std::ignore, std::ignore, out_h, out_w) = tie4(yDesc.GetLengths());
};
void RNNDescriptor::RNNBackwardWeights(Handle& handle,
const int seqLen,
const TensorDescriptor& xDesc,
ConstData_t x,
const TensorDescriptor& hxDesc,
ConstData_t hx,
const TensorDescriptor& dyDesc,
ConstData_t dy,
ConstData_t workSpace,
size_t workSpaceSize,
const TensorDescriptor& dwDesc,
Data_t dw,
ConstData_t reserveSpace,
size_t reserveSpaceSize) const
{
int in_n, in_c, in_h, in_w;
// std::tie(in_n, in_c, in_h, in_w) = tie4(xDesc.GetLengths());
int wei_n, wei_h, wei_w;
// std::tie(wei_n, std::ignore, wei_h, wei_w) = tie4(wDesc.GetLengths());
int out_h, out_w;
// std::tie(std::ignore, std::ignore, out_h, out_w) = tie4(yDesc.GetLengths());
};
} // namespace miopen
<commit_msg>activ.<commit_after>/*******************************************************************************
*
* MIT License
*
* Copyright (c) 2017 Advanced Micro Devices, Inc.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*
*******************************************************************************/
#include "tensor_driver.hpp"
#include <miopen/rnn.hpp>
#include <miopen/env.hpp>
#include <miopen/util.hpp>
#include <miopen/float_equal.hpp>
#include <vector>
#include <numeric>
#include <miopengemm/gemm.hpp>
namespace miopen {
MIOPEN_DECLARE_ENV_VAR(MIOPEN_DEBUG_CONV_DIRECT)
struct AutoEnableProfiling
{
AutoEnableProfiling(Handle& x) : h(x)
{
prev_state = h.IsProfilingEnabled();
h.EnableProfiling();
}
~AutoEnableProfiling()
{
h.EnableProfiling(prev_state);
h.ResetKernelTime();
}
private:
Handle& h;
bool prev_state;
};
void RNNDescriptor::RNNForwardTraining(Handle& handle,
const int seqLen,
// const TensorDescriptor& xDesc,
ConstData_t x,
// const TensorDescriptor& hxDesc,
ConstData_t hx,
// const TensorDescriptor& cxDesc,
ConstData_t cx,
// const TensorDescriptor& wDesc,
ConstData_t w,
// const TensorDescriptor& yDesc,
Data_t y,
// const TensorDescriptor& hyDesc,
Data_t hy,
// const TensorDescriptor& cyDesc,
Data_t cy,
Data_t workSpace,
size_t workSpaceSize,
Data_t reserveSpace,
size_t reserveSpaceSize,
const std::vector<int> &in_n,
const int in_h,
const int hy_d,
const int hy_n,
const int hy_h,
const int out_h) const
{/*
if (x == nullptr || w == nullptr || y == nullptr)
{
MIOPEN_THROW(miopenStatusBadParm);
}
if (xDesc.GetSize() != yDesc.GetSize() || xDesc.GetSize() != wDesc.GetSize())
{
MIOPEN_THROW(miopenStatusBadParm);
}
if (xDesc.GetType() != yDesc.GetType() || xDesc.GetType() != wDesc.GetType())
{
MIOPEN_THROW(miopenStatusBadParm);
}
*/
// int in_n, in_c, in_h, in_w;
// std::tie(in_n, in_c, in_h, in_w) = tie4(xDesc.GetLengths());
// int out_h, out_w;
// std::tie(std::ignore, std::ignore, out_h, out_w) = tie4(yDesc.GetLengths());
/*
if (workSpace == nullptr ||
workSpaceSize < ForwardGetWorkSpaceSize(handle, wDesc, xDesc, yDesc) || reserveSpaceSize < ForwardGetReserveSpaceSize(handle, wDesc, xDesc, yDesc))
{
MIOPEN_THROW("Workspace is required");
}
*/
// miopenRNNMode_t mode;
// int seqLength;
// int layer;
// int bidir;
// int bias;
int batch_n = std::accumulate(in_n.begin(), in_n.end(), 0);
bool bidirection = (bidir != 0);
bool biased = (bias != 0);
int numlayer = layer;
int bacc, baccbi;
int bi = bidirection ? 2 : 1;
int wei_len = (bi * (in_h + hy_h + out_h) + (numlayer - 1) * bi * (bi + 1) * hy_h) * hy_h;
if (biased)
{
wei_len += (bi * 2 + (numlayer - 1) * bi * (bi + 1)) * hy_h + bi * out_h;
}
int wei_shift_bias =
((in_h + hy_h + out_h) * bi + (bi * hy_h + hy_h) * bi * (numlayer - 1)) * hy_h;
int in_stride = in_h;
int hy_stride = hy_h * bi;
int h_stride = hy_h * bi;
int out_stride = out_h;
int wei_stride = hy_h * bi;
if (mode == miopenRNNRELU || mode == miopenRNNTANH)
{
#if MIOPEN_USE_MIOPENGEMM
printf("rnn gpu \n");
cl_command_queue Q = (cl_command_queue)handle.GetStream();
for (int li = 0; li < numlayer; li++)
{
int hid_shift = li * batch_n * hy_h * bi;
int hx_shift = li * bi * in_n[0] * hy_h;
// from input
if (li == 0)
{
MIOpenGEMM::gemm0<float>(false,
false,
false,
batch_n,
hy_h * bi,
in_h,
1,
x,
0,
in_stride,
w,
0,
wei_stride,
1,
reserveSpace,
hid_shift,
hy_stride,
&Q,
0,
nullptr,
nullptr);
}
else
{
int wei_shift = bi * (in_h + hy_h) * hy_h + (li - 1) * bi * (bi * hy_h + hy_h) * hy_h;
int prelayer_shift = (li - 1) * batch_n * hy_h * bi;
MIOpenGEMM::gemm0<float>(false,
false,
false,
batch_n,
hy_h * bi,
hy_h * bi,
1,
workSpace,
prelayer_shift,
hy_stride,
w,
wei_shift,
wei_stride,
1,
reserveSpace,
hid_shift,
hy_stride,
&Q,
0,
nullptr,
nullptr);
}
// from hidden state
bacc = 0;
baccbi = batch_n;
for (int ti = 0; ti < seqLen; ti++)
{
baccbi -= in_n[seqLen - 1 - ti];
int wei_shift =
li == 0 ? (in_h * hy_h * bi)
: (bi * (in_h + hy_h) * hy_h + (li - 1) * bi * (bi * hy_h + hy_h) * hy_h +
bi * hy_h * hy_stride);
if (ti == 0)
{
MIOpenGEMM::gemm0<float>(false,
false,
false,
in_n[ti],
hy_h,
hy_h,
1,
hx,
hx_shift,
h_stride,
w,
wei_shift,
wei_stride,
1,
reserveSpace,
hid_shift + bacc * hy_stride,
hy_stride,
&Q,
0,
nullptr,
nullptr);
if (bidirection)
{
MIOpenGEMM::gemm0<float>(false,
false,
false,
in_n[seqLen - 1 - ti],
hy_h,
hy_h,
1,
hx,
hx_shift + hy_h,
h_stride,
w,
wei_shift + hy_h,
wei_stride,
1,
reserveSpace,
hid_shift + baccbi * hy_stride + hy_h,
hy_stride,
&Q,
0,
nullptr,
nullptr);
}
}
else
{
MIOpenGEMM::gemm0<float>(false,
false,
false,
in_n[ti],
hy_h,
hy_h,
1,
hy,
hx_shift,
h_stride,
w,
wei_shift,
wei_stride,
1,
reserveSpace,
hid_shift + bacc * hy_stride,
hy_stride,
&Q,
0,
nullptr,
nullptr);
if (bidirection)
{
MIOpenGEMM::gemm0<float>(false,
false,
false,
in_n[seqLen - 1 - ti],
hy_h,
hy_h,
1,
hy,
hx_shift + hy_h,
h_stride,
w,
wei_shift + hy_h,
wei_stride,
1,
reserveSpace,
hid_shift + baccbi * hy_stride + hy_h,
hy_stride,
&Q,
0,
nullptr,
nullptr);
}
}
int rsv_sz = batch_n * hy_d * hy_h;
std::vector<int> rsv_size(3, 1);
rsv_size.push_back(rsv_sz);
miopenTensorDescriptor_t rsvTensor;
miopenCreateTensorDescriptor(&rsvTensor);
SetTensor4d(rsvTensor, rsv_size);
miopenActivationDescriptor_t activDesc;
miopenCreateActivationDescriptor(&activDesc);
miopenActivationMode_t amode;
amode = (mode == miopenRNNRELU) ? miopenActivationRELU : miopenActivationLOGISTIC;
miopenSetActivationDescriptor(activDesc, amode, 1, 0, 1);
miopenActivationForward(handle,
activDesc,
1,
rsvTensor,
reserveSpace,
0,
rsvTensor,
workSpace);
bacc += in_n[ti];
}
}
int prelayer_shift = (numlayer - 1) * batch_n * hy_h * bi;
int wei_shift = bi * (in_h + hy_h) * hy_h + (numlayer - 1) * bi * (bi * hy_h + hy_h) * hy_h;
MIOpenGEMM::gemm0<float>(false,
false,
true,
batch_n,
out_h,
hy_h * bi,
1,
workSpace,
prelayer_shift,
hy_stride,
w,
wei_shift,
wei_stride,
1,
y,
0,
out_stride,
&Q,
0,
nullptr,
nullptr);
clFinish(Q);
#else
MIOPEN_THROW("GEMM is not supported");
#endif
}
else if (mode == miopenLSTM)
{
printf("lstm gpu \n");
}
else if (mode == miopenGRU)
{
printf("gru gpu \n");
}
};
void RNNDescriptor::RNNBackwardData(Handle& handle,
const int seqLen,
const TensorDescriptor& yDesc,
ConstData_t y,
const TensorDescriptor& dyDesc,
ConstData_t dy,
const TensorDescriptor& dhyDesc,
ConstData_t dhy,
const TensorDescriptor& dcyDesc,
ConstData_t dcy,
const TensorDescriptor& wDesc,
ConstData_t w,
const TensorDescriptor& hxDesc,
ConstData_t hx,
const TensorDescriptor& cxDesc,
ConstData_t cx,
const TensorDescriptor& dxDesc,
Data_t dx,
const TensorDescriptor& dhxDesc,
Data_t dhx,
const TensorDescriptor& dcxDesc,
Data_t dcx,
Data_t workSpace,
size_t workSpaceSize,
ConstData_t reserveSpace,
size_t reserveSpaceSize) const
{
/*
if (dx == nullptr || w == nullptr || dy == nullptr)
{
MIOPEN_THROW(miopenStatusBadParm);
}
if (dyDesc.GetSize() != dxDesc.GetSize() || dyDesc.GetSize() != wDesc.GetSize())
{
MIOPEN_THROW(miopenStatusBadParm);
}
if (dyDesc.GetType() != dxDesc.GetType() || dyDesc.GetType() != wDesc.GetType())
{
MIOPEN_THROW(miopenStatusBadParm);
}
*/
int in_n, in_c, in_h, in_w;
// std::tie(in_n, in_c, in_h, in_w) = tie4(xDesc.GetLengths());
int wei_n, wei_h, wei_w;
// std::tie(wei_n, std::ignore, wei_h, wei_w) = tie4(wDesc.GetLengths());
int out_h, out_w;
// std::tie(std::ignore, std::ignore, out_h, out_w) = tie4(yDesc.GetLengths());
};
void RNNDescriptor::RNNBackwardWeights(Handle& handle,
const int seqLen,
const TensorDescriptor& xDesc,
ConstData_t x,
const TensorDescriptor& hxDesc,
ConstData_t hx,
const TensorDescriptor& dyDesc,
ConstData_t dy,
ConstData_t workSpace,
size_t workSpaceSize,
const TensorDescriptor& dwDesc,
Data_t dw,
ConstData_t reserveSpace,
size_t reserveSpaceSize) const
{
int in_n, in_c, in_h, in_w;
// std::tie(in_n, in_c, in_h, in_w) = tie4(xDesc.GetLengths());
int wei_n, wei_h, wei_w;
// std::tie(wei_n, std::ignore, wei_h, wei_w) = tie4(wDesc.GetLengths());
int out_h, out_w;
// std::tie(std::ignore, std::ignore, out_h, out_w) = tie4(yDesc.GetLengths());
};
} // namespace miopen
<|endoftext|> |
<commit_before>/*********************************************************************/
/* Copyright (c) 2011 - 2012, The University of Texas at Austin. */
/* All rights reserved. */
/* */
/* Redistribution and use in source and binary forms, with or */
/* without modification, are permitted provided that the following */
/* conditions are met: */
/* */
/* 1. Redistributions of source code must retain the above */
/* copyright notice, this list of conditions and the following */
/* disclaimer. */
/* */
/* 2. Redistributions in binary form must reproduce the above */
/* copyright notice, this list of conditions and the following */
/* disclaimer in the documentation and/or other materials */
/* provided with the distribution. */
/* */
/* THIS SOFTWARE IS PROVIDED BY THE UNIVERSITY OF TEXAS AT */
/* AUSTIN ``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 UNIVERSITY OF TEXAS AT */
/* AUSTIN 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. */
/* */
/* The views and conclusions contained in the software and */
/* documentation are those of the authors and should not be */
/* interpreted as representing official policies, either expressed */
/* or implied, of The University of Texas at Austin. */
/*********************************************************************/
#include "Options.h"
Options::Options()
{
showWindowBorders_ = true;
showTestPattern_ = false;
enableMullionCompensation_ = true;
showZoomContext_ = true;
enableStreamingSynchronization_ = false;
showStreamingSegments_ = false;
showStreamingStatistics_ = false;
#if ENABLE_SKELETON_SUPPORT
showSkeletons_ = true;
#endif
}
bool Options::getShowWindowBorders()
{
return showWindowBorders_;
}
bool Options::getShowTestPattern()
{
return showTestPattern_;
}
bool Options::getEnableMullionCompensation()
{
return enableMullionCompensation_;
}
bool Options::getShowZoomContext()
{
return showZoomContext_;
}
bool Options::getEnableStreamingSynchronization()
{
return enableStreamingSynchronization_;
}
bool Options::getShowStreamingSegments()
{
return showStreamingSegments_;
}
bool Options::getShowStreamingStatistics()
{
return showStreamingStatistics_;
}
#if ENABLE_SKELETON_SUPPORT
bool Options::getShowSkeletons()
{
return showSkeletons_;
}
#endif
void Options::setShowWindowBorders(bool set)
{
showWindowBorders_ = set;
emit(updated());
}
void Options::setShowTestPattern(bool set)
{
showTestPattern_ = set;
emit(updated());
}
void Options::setEnableMullionCompensation(bool set)
{
enableMullionCompensation_ = set;
emit(updated());
}
void Options::setShowZoomContext(bool set)
{
showZoomContext_ = set;
emit(updated());
}
void Options::setEnableStreamingSynchronization(bool set)
{
enableStreamingSynchronization_ = set;
emit(updated());
}
void Options::setShowStreamingSegments(bool set)
{
showStreamingSegments_ = set;
emit(updated());
}
void Options::setShowStreamingStatistics(bool set)
{
showStreamingStatistics_ = set;
emit(updated());
}
#if ENABLE_SKELETON_SUPPORT
void Options::setShowSkeletons(bool set)
{
showSkeletons_ = set;
emit(updated());
}
#endif
<commit_msg>Set to reasonable default<commit_after>/*********************************************************************/
/* Copyright (c) 2011 - 2012, The University of Texas at Austin. */
/* All rights reserved. */
/* */
/* Redistribution and use in source and binary forms, with or */
/* without modification, are permitted provided that the following */
/* conditions are met: */
/* */
/* 1. Redistributions of source code must retain the above */
/* copyright notice, this list of conditions and the following */
/* disclaimer. */
/* */
/* 2. Redistributions in binary form must reproduce the above */
/* copyright notice, this list of conditions and the following */
/* disclaimer in the documentation and/or other materials */
/* provided with the distribution. */
/* */
/* THIS SOFTWARE IS PROVIDED BY THE UNIVERSITY OF TEXAS AT */
/* AUSTIN ``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 UNIVERSITY OF TEXAS AT */
/* AUSTIN 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. */
/* */
/* The views and conclusions contained in the software and */
/* documentation are those of the authors and should not be */
/* interpreted as representing official policies, either expressed */
/* or implied, of The University of Texas at Austin. */
/*********************************************************************/
#include "Options.h"
Options::Options()
{
showWindowBorders_ = false;
showTestPattern_ = false;
enableMullionCompensation_ = true;
showZoomContext_ = true;
enableStreamingSynchronization_ = false;
showStreamingSegments_ = false;
showStreamingStatistics_ = false;
#if ENABLE_SKELETON_SUPPORT
showSkeletons_ = true;
#endif
}
bool Options::getShowWindowBorders()
{
return showWindowBorders_;
}
bool Options::getShowTestPattern()
{
return showTestPattern_;
}
bool Options::getEnableMullionCompensation()
{
return enableMullionCompensation_;
}
bool Options::getShowZoomContext()
{
return showZoomContext_;
}
bool Options::getEnableStreamingSynchronization()
{
return enableStreamingSynchronization_;
}
bool Options::getShowStreamingSegments()
{
return showStreamingSegments_;
}
bool Options::getShowStreamingStatistics()
{
return showStreamingStatistics_;
}
#if ENABLE_SKELETON_SUPPORT
bool Options::getShowSkeletons()
{
return showSkeletons_;
}
#endif
void Options::setShowWindowBorders(bool set)
{
showWindowBorders_ = set;
emit(updated());
}
void Options::setShowTestPattern(bool set)
{
showTestPattern_ = set;
emit(updated());
}
void Options::setEnableMullionCompensation(bool set)
{
enableMullionCompensation_ = set;
emit(updated());
}
void Options::setShowZoomContext(bool set)
{
showZoomContext_ = set;
emit(updated());
}
void Options::setEnableStreamingSynchronization(bool set)
{
enableStreamingSynchronization_ = set;
emit(updated());
}
void Options::setShowStreamingSegments(bool set)
{
showStreamingSegments_ = set;
emit(updated());
}
void Options::setShowStreamingStatistics(bool set)
{
showStreamingStatistics_ = set;
emit(updated());
}
#if ENABLE_SKELETON_SUPPORT
void Options::setShowSkeletons(bool set)
{
showSkeletons_ = set;
emit(updated());
}
#endif
<|endoftext|> |
<commit_before>// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include <GLES2/gl2.h>
#include <GLES2/gl2ext.h>
#include "gpu/command_buffer/tests/gl_manager.h"
#include "gpu/command_buffer/tests/gl_test_utils.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.h"
#define SHADER(Src) #Src
namespace gpu {
class DepthTextureTest : public testing::Test {
protected:
static const GLsizei kResolution = 64;
virtual void SetUp() {
gl_.Initialize(gfx::Size(kResolution, kResolution));
}
virtual void TearDown() {
gl_.Destroy();
}
GLuint SetupUnitQuad(GLint position_location);
GLManager gl_;
};
GLuint DepthTextureTest::SetupUnitQuad(GLint position_location) {
GLuint vbo = 0;
glGenBuffers(1, &vbo);
glBindBuffer(GL_ARRAY_BUFFER, vbo);
static float vertices[] = {
1.0f, 1.0f, 1.0f,
-1.0f, 1.0f, 0.0f,
-1.0f, -1.0f, -1.0f,
1.0f, 1.0f, 1.0f,
-1.0f, -1.0f, -1.0f,
1.0f, -1.0f, 0.0f,
};
glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW);
glEnableVertexAttribArray(position_location);
glVertexAttribPointer(position_location, 3, GL_FLOAT, GL_FALSE, 0, 0);
return vbo;
}
namespace {
struct FormatType {
GLenum format;
GLenum type;
};
} // anonymous namespace
TEST_F(DepthTextureTest, RenderTo) {
if (!GLTestHelper::HasExtension("GL_CHROMIUM_depth_texture")) {
return;
}
bool have_depth_stencil = GLTestHelper::HasExtension(
"GL_OES_packed_depth_stencil");
static const char* v_shader_str = SHADER(
attribute vec4 v_position;
void main()
{
gl_Position = v_position;
}
);
static const char* f_shader_str = SHADER(
precision mediump float;
uniform sampler2D u_texture;
uniform vec2 u_resolution;
void main()
{
vec2 texcoord = gl_FragCoord.xy / u_resolution;
gl_FragColor = texture2D(u_texture, texcoord);
}
);
GLuint program = GLTestHelper::LoadProgram(v_shader_str, f_shader_str);
GLint position_loc = glGetAttribLocation(program, "v_position");
GLint resolution_loc = glGetUniformLocation(program, "u_resolution");
SetupUnitQuad(position_loc);
// Depth test needs to be on for the depth buffer to be updated.
glEnable(GL_DEPTH_TEST);
// create an fbo
GLuint fbo = 0;
glGenFramebuffers(1, &fbo);
glBindFramebuffer(GL_FRAMEBUFFER, fbo);
// create a depth texture.
GLuint color_texture = 0;
GLuint depth_texture = 0;
glGenTextures(1, &color_texture);
glBindTexture(GL_TEXTURE_2D, color_texture);
glTexImage2D(
GL_TEXTURE_2D, 0, GL_RGBA, kResolution, kResolution,
0, GL_RGBA, GL_UNSIGNED_BYTE, NULL);
glFramebufferTexture2D(
GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, color_texture, 0);
glGenTextures(1, &depth_texture);
glBindTexture(GL_TEXTURE_2D, depth_texture);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glFramebufferTexture2D(
GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_TEXTURE_2D, depth_texture, 0);
glUseProgram(program);
glUniform2f(resolution_loc, kResolution, kResolution);
static const FormatType format_types[] = {
{ GL_DEPTH_COMPONENT, GL_UNSIGNED_SHORT, },
{ GL_DEPTH_COMPONENT, GL_UNSIGNED_INT, },
{ GL_DEPTH_STENCIL_OES, GL_UNSIGNED_INT_24_8_OES, },
};
for (size_t ii = 0; ii < arraysize(format_types); ++ii) {
GLenum format = format_types[ii].format;
GLenum type = format_types[ii].type;
if (format == GL_DEPTH_STENCIL_OES && !have_depth_stencil) {
continue;
}
glBindTexture(GL_TEXTURE_2D, depth_texture);
glTexImage2D(
GL_TEXTURE_2D, 0, format, kResolution, kResolution,
0, format, type, NULL);
glBindFramebuffer(GL_FRAMEBUFFER, fbo);
EXPECT_TRUE(
glCheckFramebufferStatus(GL_FRAMEBUFFER) == GL_FRAMEBUFFER_COMPLETE);
GLTestHelper::CheckGLError("no errors", __LINE__);
glClearColor(1.0f, 1.0f, 1.0f, 1.0f);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
// Disconnect the texture so we'll render with the default texture.
glBindTexture(GL_TEXTURE_2D, 0);
// Render to the fbo.
glDrawArrays(GL_TRIANGLES, 0, 6);
// Render with the depth texture.
glBindFramebuffer(GL_FRAMEBUFFER, 0);
glBindTexture(GL_TEXTURE_2D, depth_texture);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glDrawArrays(GL_TRIANGLES, 0, 6);
uint8 actual_pixels[kResolution * kResolution * 4] = { 0, };
glReadPixels(
0, 0, kResolution, kResolution, GL_RGBA, GL_UNSIGNED_BYTE,
actual_pixels);
// Check that each pixel's RGB are the same and that it's value is less
// than the previous pixel in either direction. Basically verify we have a
// gradient.
for (GLint yy = 0; yy < kResolution; ++yy) {
for (GLint xx = 0; xx < kResolution; ++xx) {
const uint8* actual = &actual_pixels[(yy * kResolution + xx) * 4];
const uint8* left = actual - 4;
const uint8* down = actual - kResolution * 4;
EXPECT_EQ(actual[0], actual[1]);
EXPECT_EQ(actual[1], actual[2]);
if (xx > 0) {
EXPECT_GT(actual[0], left[0]);
}
if (yy > 0) {
EXPECT_GT(actual[0], down[0]);
}
}
}
// Check that bottom left corner is vastly different thatn top right.
EXPECT_GT(
actual_pixels[(kResolution * kResolution - 1) * 4] - actual_pixels[0],
0xC0);
GLTestHelper::CheckGLError("no errors", __LINE__);
}
}
} // namespace gpu
<commit_msg>Unreviewed pixel wrangling. Temporarily disable DepthTextureTest.RenderTo because it is failing on some gpu bots.<commit_after>// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include <GLES2/gl2.h>
#include <GLES2/gl2ext.h>
#include "gpu/command_buffer/tests/gl_manager.h"
#include "gpu/command_buffer/tests/gl_test_utils.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.h"
#define SHADER(Src) #Src
namespace gpu {
class DepthTextureTest : public testing::Test {
protected:
static const GLsizei kResolution = 64;
virtual void SetUp() {
gl_.Initialize(gfx::Size(kResolution, kResolution));
}
virtual void TearDown() {
gl_.Destroy();
}
GLuint SetupUnitQuad(GLint position_location);
GLManager gl_;
};
GLuint DepthTextureTest::SetupUnitQuad(GLint position_location) {
GLuint vbo = 0;
glGenBuffers(1, &vbo);
glBindBuffer(GL_ARRAY_BUFFER, vbo);
static float vertices[] = {
1.0f, 1.0f, 1.0f,
-1.0f, 1.0f, 0.0f,
-1.0f, -1.0f, -1.0f,
1.0f, 1.0f, 1.0f,
-1.0f, -1.0f, -1.0f,
1.0f, -1.0f, 0.0f,
};
glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW);
glEnableVertexAttribArray(position_location);
glVertexAttribPointer(position_location, 3, GL_FLOAT, GL_FALSE, 0, 0);
return vbo;
}
namespace {
struct FormatType {
GLenum format;
GLenum type;
};
} // anonymous namespace
// Temporarily marked disabled due to failure on gpu bots.
// https://code.google.com/p/chromium/issues/detail?id=135229
TEST_F(DepthTextureTest, DISABLED_RenderTo) {
if (!GLTestHelper::HasExtension("GL_CHROMIUM_depth_texture")) {
return;
}
bool have_depth_stencil = GLTestHelper::HasExtension(
"GL_OES_packed_depth_stencil");
static const char* v_shader_str = SHADER(
attribute vec4 v_position;
void main()
{
gl_Position = v_position;
}
);
static const char* f_shader_str = SHADER(
precision mediump float;
uniform sampler2D u_texture;
uniform vec2 u_resolution;
void main()
{
vec2 texcoord = gl_FragCoord.xy / u_resolution;
gl_FragColor = texture2D(u_texture, texcoord);
}
);
GLuint program = GLTestHelper::LoadProgram(v_shader_str, f_shader_str);
GLint position_loc = glGetAttribLocation(program, "v_position");
GLint resolution_loc = glGetUniformLocation(program, "u_resolution");
SetupUnitQuad(position_loc);
// Depth test needs to be on for the depth buffer to be updated.
glEnable(GL_DEPTH_TEST);
// create an fbo
GLuint fbo = 0;
glGenFramebuffers(1, &fbo);
glBindFramebuffer(GL_FRAMEBUFFER, fbo);
// create a depth texture.
GLuint color_texture = 0;
GLuint depth_texture = 0;
glGenTextures(1, &color_texture);
glBindTexture(GL_TEXTURE_2D, color_texture);
glTexImage2D(
GL_TEXTURE_2D, 0, GL_RGBA, kResolution, kResolution,
0, GL_RGBA, GL_UNSIGNED_BYTE, NULL);
glFramebufferTexture2D(
GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, color_texture, 0);
glGenTextures(1, &depth_texture);
glBindTexture(GL_TEXTURE_2D, depth_texture);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glFramebufferTexture2D(
GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_TEXTURE_2D, depth_texture, 0);
glUseProgram(program);
glUniform2f(resolution_loc, kResolution, kResolution);
static const FormatType format_types[] = {
{ GL_DEPTH_COMPONENT, GL_UNSIGNED_SHORT, },
{ GL_DEPTH_COMPONENT, GL_UNSIGNED_INT, },
{ GL_DEPTH_STENCIL_OES, GL_UNSIGNED_INT_24_8_OES, },
};
for (size_t ii = 0; ii < arraysize(format_types); ++ii) {
GLenum format = format_types[ii].format;
GLenum type = format_types[ii].type;
if (format == GL_DEPTH_STENCIL_OES && !have_depth_stencil) {
continue;
}
glBindTexture(GL_TEXTURE_2D, depth_texture);
glTexImage2D(
GL_TEXTURE_2D, 0, format, kResolution, kResolution,
0, format, type, NULL);
glBindFramebuffer(GL_FRAMEBUFFER, fbo);
EXPECT_TRUE(
glCheckFramebufferStatus(GL_FRAMEBUFFER) == GL_FRAMEBUFFER_COMPLETE);
GLTestHelper::CheckGLError("no errors", __LINE__);
glClearColor(1.0f, 1.0f, 1.0f, 1.0f);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
// Disconnect the texture so we'll render with the default texture.
glBindTexture(GL_TEXTURE_2D, 0);
// Render to the fbo.
glDrawArrays(GL_TRIANGLES, 0, 6);
// Render with the depth texture.
glBindFramebuffer(GL_FRAMEBUFFER, 0);
glBindTexture(GL_TEXTURE_2D, depth_texture);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glDrawArrays(GL_TRIANGLES, 0, 6);
uint8 actual_pixels[kResolution * kResolution * 4] = { 0, };
glReadPixels(
0, 0, kResolution, kResolution, GL_RGBA, GL_UNSIGNED_BYTE,
actual_pixels);
// Check that each pixel's RGB are the same and that it's value is less
// than the previous pixel in either direction. Basically verify we have a
// gradient.
for (GLint yy = 0; yy < kResolution; ++yy) {
for (GLint xx = 0; xx < kResolution; ++xx) {
const uint8* actual = &actual_pixels[(yy * kResolution + xx) * 4];
const uint8* left = actual - 4;
const uint8* down = actual - kResolution * 4;
EXPECT_EQ(actual[0], actual[1]);
EXPECT_EQ(actual[1], actual[2]);
if (xx > 0) {
EXPECT_GT(actual[0], left[0]);
}
if (yy > 0) {
EXPECT_GT(actual[0], down[0]);
}
}
}
// Check that bottom left corner is vastly different thatn top right.
EXPECT_GT(
actual_pixels[(kResolution * kResolution - 1) * 4] - actual_pixels[0],
0xC0);
GLTestHelper::CheckGLError("no errors", __LINE__);
}
}
} // namespace gpu
<|endoftext|> |
<commit_before>/***************************************************************************
* Copyright (C) 2005-2007 by the FIFE Team *
* fife-public@lists.sourceforge.net *
* This file is part of FIFE. *
* *
* FIFE is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation; either version 2 of the License, or *
* (at your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU General Public License for more details. *
* *
* You should have received a copy of the GNU General Public License *
* along with this program; if not, write to the *
* Free Software Foundation, Inc., *
* 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA *
***************************************************************************/
// Standard C++ library includes
#include <string>
// 3rd party library includes
#include <boost/lexical_cast.hpp>
// FIFE includes
// These includes are split up in two parts, separated by one empty line
// First block: files included from the FIFE root src directory
// Second block: files included from the same folder
#include "util/debugutils.h"
#include "util/exception.h"
#include "util/time/timemanager.h"
#include "animation.h"
#include "image.h"
#include "util/rect.h"
namespace FIFE {
Animation::Animation():
m_action_frame(-1),
m_animation_endtime(-1),
m_direction(0) {
}
Animation::~Animation() {
std::cout << ">>> in Animation destructor\n";
std::vector<FrameInfo>::const_iterator i(m_frames.begin());
while (i != m_frames.end()) {
i->img->decRef();
i++;
}
}
void Animation::addFrame(Image* image, unsigned int duration) {
image->addRef();
FrameInfo info;
info.index = m_frames.size();
info.duration = duration;
info.img = image;
m_frames.push_back(info);
std::map<unsigned int, FrameInfo>::const_iterator i(m_framemap.end());
if (i == m_framemap.begin()) {
m_framemap[0] = info;
m_animation_endtime = duration;
} else {
--i;
unsigned int frametime = i->first + i->second.duration;
m_framemap[frametime] = info;
m_animation_endtime = frametime + duration;
}
}
int Animation::getFrameIndex(unsigned int timestamp) {
int val = -1;
if ((static_cast<int>(timestamp) < m_animation_endtime) && (m_animation_endtime > 0)) {
std::map<unsigned int, FrameInfo>::const_iterator i(m_framemap.lower_bound(timestamp));
val = i->second.index;
}
return val;
}
bool Animation::isValidIndex(int index) {
int size = m_frames.size();
if ((size == 0) || (index > (size - 1))) {
return false;
}
return true;
}
Image* Animation::getFrame(int index) {
if (isValidIndex(index)) {
return m_frames[index].img;
} else {
return NULL;
}
}
Image* Animation::getFrameByTimestamp(unsigned int timestamp) {
int index = getFrameIndex(timestamp);
if( index > 0 ) {
return getFrame(index);
}
return 0;
}
int Animation::getFrameDuration(int index) {
if (isValidIndex(index)) {
return m_frames[index].duration;
} else {
return -1;
}
}
unsigned int Animation::getNumFrames() const {
return m_frames.size();
}
void Animation::setDirection(unsigned int direction) {
m_direction = direction % 360;
}
}
/* vim: set noexpandtab: set shiftwidth=2: set tabstop=2: */
<commit_msg>Sorry last commit obscured the problem instead of _really_ fixing it. isValidIndex had the bug and is now fixed properly.<commit_after>/***************************************************************************
* Copyright (C) 2005-2007 by the FIFE Team *
* fife-public@lists.sourceforge.net *
* This file is part of FIFE. *
* *
* FIFE is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation; either version 2 of the License, or *
* (at your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU General Public License for more details. *
* *
* You should have received a copy of the GNU General Public License *
* along with this program; if not, write to the *
* Free Software Foundation, Inc., *
* 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA *
***************************************************************************/
// Standard C++ library includes
#include <string>
// 3rd party library includes
#include <boost/lexical_cast.hpp>
// FIFE includes
// These includes are split up in two parts, separated by one empty line
// First block: files included from the FIFE root src directory
// Second block: files included from the same folder
#include "util/debugutils.h"
#include "util/exception.h"
#include "util/time/timemanager.h"
#include "animation.h"
#include "image.h"
#include "util/rect.h"
namespace FIFE {
Animation::Animation():
m_action_frame(-1),
m_animation_endtime(-1),
m_direction(0) {
}
Animation::~Animation() {
std::cout << ">>> in Animation destructor\n";
std::vector<FrameInfo>::const_iterator i(m_frames.begin());
while (i != m_frames.end()) {
i->img->decRef();
i++;
}
}
void Animation::addFrame(Image* image, unsigned int duration) {
image->addRef();
FrameInfo info;
info.index = m_frames.size();
info.duration = duration;
info.img = image;
m_frames.push_back(info);
std::map<unsigned int, FrameInfo>::const_iterator i(m_framemap.end());
if (i == m_framemap.begin()) {
m_framemap[0] = info;
m_animation_endtime = duration;
} else {
--i;
unsigned int frametime = i->first + i->second.duration;
m_framemap[frametime] = info;
m_animation_endtime = frametime + duration;
}
}
int Animation::getFrameIndex(unsigned int timestamp) {
int val = -1;
if ((static_cast<int>(timestamp) < m_animation_endtime) && (m_animation_endtime > 0)) {
std::map<unsigned int, FrameInfo>::const_iterator i(m_framemap.lower_bound(timestamp));
val = i->second.index;
}
return val;
}
bool Animation::isValidIndex(int index) {
int size = m_frames.size();
if ((size == 0) || (index > (size - 1)) || (index < 0)) {
return false;
}
return true;
}
Image* Animation::getFrame(int index) {
if (isValidIndex(index)) {
return m_frames[index].img;
} else {
return NULL;
}
}
Image* Animation::getFrameByTimestamp(unsigned int timestamp) {
return getFrame(getFrameIndex(timestamp));
}
int Animation::getFrameDuration(int index) {
if (isValidIndex(index)) {
return m_frames[index].duration;
} else {
return -1;
}
}
unsigned int Animation::getNumFrames() const {
return m_frames.size();
}
void Animation::setDirection(unsigned int direction) {
m_direction = direction % 360;
}
}
/* vim: set noexpandtab: set shiftwidth=2: set tabstop=2: */
<|endoftext|> |
<commit_before>/*
* Copyright (c) 2015, Intel Corporation
*
* 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 Intel Corporation nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS 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 LOG OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef PROFILE_HPP_INCLUDE
#define PROFILE_HPP_INCLUDE
#include <stdint.h>
#include <string>
#include <list>
#include <forward_list>
#include <fstream>
#include <mpi.h>
#include "geopm_time.h"
#include "geopm_message.h"
#include "SharedMemory.hpp"
#include "LockingHashTable.hpp"
namespace geopm
{
/// Encapsulates the state and provides the interface for
/// computational application profiling.
///
/// The C++ implementation of the computational application side
/// interface to the GEOPM profiler. The class methods support
/// the C interface defined for use with the geopm_prof_c
/// structure and are named accordingly. The geopm_prof_c
/// structure is an opaque reference to the geopm::Profile class.
class Profile
{
public:
Profile(const std::string prof_name, size_t table_size, const std::string shm_key_base, MPI_Comm comm);
virtual ~Profile();
uint64_t region(const std::string region_name, long policy_hint);
void enter(uint64_t region_id);
void exit(uint64_t region_id);
void progress(uint64_t region_id, double fraction);
void outer_sync(void);
void sample(uint64_t region_id);
void enable(const std::string feature_name);
void disable(const std::string feature_name);
void print(const std::string file_name, int depth);
protected:
void name_set(const std::string file_name);
void report(void);
void shutdown(void);
void init_cpu_list(void);
std::string m_prof_name;
uint64_t m_curr_region_id;
int m_num_enter;
int m_num_progress;
double m_progress;
void *m_table_buffer;
SharedMemoryUser *m_ctl_shmem;
struct geopm_ctl_message_s *m_ctl_msg;
SharedMemoryUser *m_table_shmem;
LockingHashTable<struct geopm_prof_message_s> *m_table;
std::list<int> m_cpu_list;
MPI_Comm m_shm_comm;
int m_rank;
int m_shm_rank;
};
class ProfileRankSampler
{
public:
ProfileRankSampler(const std::string shm_key, size_t table_size);
virtual ~ProfileRankSampler();
void rank_sample(std::vector<std::pair<uint64_t, struct geopm_prof_message_s> >::iterator content_begin, size_t &length);
size_t capacity(void);
void report(std::ofstream &file_desc);
bool name_fill(void);
protected:
SharedMemory m_table_shmem;
LockingHashTable<struct geopm_prof_message_s> m_table;
std::map<uint64_t, struct geopm_sample_message_s> m_agg_stats;
struct geopm_prof_message_s m_region_entry;
std::string m_prof_name;
std::string m_report_name;
std::set<std::string> m_name_set;
bool m_is_name_finished;
};
class ProfileSampler
{
public:
ProfileSampler(const std::string shm_key_base, size_t table_size, MPI_Comm comm);
virtual ~ProfileSampler(void);
size_t capacity(void);
void sample(std::vector<std::pair<uint64_t, struct geopm_prof_message_s> > &content, size_t &length);
bool do_shutdown(void);
void report(void);
void initialize(void);
protected:
void name_set(std::string &file_name, std::string &prof_name, std::set<std::string> &key_name);
void print(const std::string file_name, const std::set<std::string> &key_name);
SharedMemory m_ctl_shmem;
struct geopm_ctl_message_s *m_ctl_msg;
std::forward_list<ProfileRankSampler *> m_rank_sampler;
MPI_Comm m_comm;
size_t m_table_size;
};
}
#endif
<commit_msg>Added doxygen comments to the Profile class.<commit_after>/*
* Copyright (c) 2015, Intel Corporation
*
* 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 Intel Corporation nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS 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 LOG OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef PROFILE_HPP_INCLUDE
#define PROFILE_HPP_INCLUDE
#include <stdint.h>
#include <string>
#include <list>
#include <forward_list>
#include <fstream>
#include <mpi.h>
#include "geopm_time.h"
#include "geopm_message.h"
#include "SharedMemory.hpp"
#include "LockingHashTable.hpp"
namespace geopm
{
/// @brief Encapsulates the state and provides the interface for
/// computational application profiling.
///
/// The C++ implementation of the computational application side
/// interface to the GEOPM profiler. The class methods support
/// the C interface defined for use with the geopm_prof_c
/// structure and are named accordingly. The geopm_prof_c
/// structure is an opaque reference to the geopm::Profile class.
class Profile
{
public:
/// @brief Profile constructor.
///
/// The Profile object is used by the application to
/// instrument regions of code and post profile
/// information to a shared memory region to be read by
/// the Controller process.
///
/// @param [in] prof_name Name associated with the
/// profile. This name will be printed in the
/// header of the report.
///
/// @param [in] table_size Size in bytes of shared memory
/// region that will be used for posting updates.
/// The Controller is responsible for creating the
/// shared memory region that the Profile object
/// attaches to. The Controller is the consumer of
/// the posted data that the Profile produces.
///
/// @param [in] shm_key_base String that is the base for
/// the POSIX shared memory keys that have been
/// created by the Controller. There is one key
/// created for each MPI rank in the communicator
/// provided (comm), and each key is constructed by
/// appending an underscore followed by a string
/// representation of the integer MPI rank.
///
/// @param [in] comm The application's MPI communicator.
/// Each rank of this communicator will report to a
/// separate shared memory region. One controller
/// on each compute node will consume the output
/// from each rank running on the compute node.
Profile(const std::string prof_name, size_t table_size, const std::string shm_key_base, MPI_Comm comm);
/// @brief Profile destructor, virtual.
virtual ~Profile();
/// @brief Register a region of code to be profiled.
///
/// The statistics gathered for each region are aggregated
/// in the final report, and the power policy will be
/// determined distinctly for each region. The
/// registration of a region is idempotent, and the first
/// call will have more overhead than subsequent
/// attempts to re-register the same region.
///
/// @param [in] region_name Unique name that identifies
/// the region being profiled. This name will
/// be printed next to the region statistics
/// in the report.
///
/// @param [in] policy_hint Value from the
/// #geopm_policy_hint_e structure which is
/// used to derive a starting policy before
/// the application has been profiled.
uint64_t region(const std::string region_name, long policy_hint);
void enter(uint64_t region_id);
void exit(uint64_t region_id);
void progress(uint64_t region_id, double fraction);
void outer_sync(void);
void sample(uint64_t region_id);
void enable(const std::string feature_name);
void disable(const std::string feature_name);
void print(const std::string file_name, int depth);
protected:
void name_set(const std::string file_name);
void report(void);
void shutdown(void);
void init_cpu_list(void);
std::string m_prof_name;
uint64_t m_curr_region_id;
int m_num_enter;
int m_num_progress;
double m_progress;
void *m_table_buffer;
SharedMemoryUser *m_ctl_shmem;
struct geopm_ctl_message_s *m_ctl_msg;
SharedMemoryUser *m_table_shmem;
LockingHashTable<struct geopm_prof_message_s> *m_table;
std::list<int> m_cpu_list;
MPI_Comm m_shm_comm;
int m_rank;
int m_shm_rank;
};
class ProfileRankSampler
{
public:
ProfileRankSampler(const std::string shm_key, size_t table_size);
virtual ~ProfileRankSampler();
void rank_sample(std::vector<std::pair<uint64_t, struct geopm_prof_message_s> >::iterator content_begin, size_t &length);
size_t capacity(void);
void report(std::ofstream &file_desc);
bool name_fill(void);
protected:
SharedMemory m_table_shmem;
LockingHashTable<struct geopm_prof_message_s> m_table;
std::map<uint64_t, struct geopm_sample_message_s> m_agg_stats;
struct geopm_prof_message_s m_region_entry;
std::string m_prof_name;
std::string m_report_name;
std::set<std::string> m_name_set;
bool m_is_name_finished;
};
class ProfileSampler
{
public:
ProfileSampler(const std::string shm_key_base, size_t table_size, MPI_Comm comm);
virtual ~ProfileSampler(void);
size_t capacity(void);
void sample(std::vector<std::pair<uint64_t, struct geopm_prof_message_s> > &content, size_t &length);
bool do_shutdown(void);
void report(void);
void initialize(void);
protected:
void name_set(std::string &file_name, std::string &prof_name, std::set<std::string> &key_name);
void print(const std::string file_name, const std::set<std::string> &key_name);
SharedMemory m_ctl_shmem;
struct geopm_ctl_message_s *m_ctl_msg;
std::forward_list<ProfileRankSampler *> m_rank_sampler;
MPI_Comm m_comm;
size_t m_table_size;
};
}
#endif
<|endoftext|> |
<commit_before>// Program.cpp
#include "stdafx.h"
#include "Program.h"
#include "PythonStuff.h"
#include "tinyxml/tinyxml.h"
#include "ProgramCanvas.h"
#include "NCCode.h"
#include "interface/MarkedObject.h"
#include "interface/PropertyString.h"
#include "interface/Tool.h"
#include "Profile.h"
#include "Pocket.h"
#include "ZigZag.h"
#include "Adaptive.h"
#include "Op.h"
bool COperations::CanAdd(HeeksObj* object)
{
return object->GetType() == ProfileType || object->GetType() == PocketType || object->GetType() == ZigZagType || object->GetType() == AdaptiveType;
}
void COperations::WriteXML(TiXmlNode *root)
{
TiXmlElement * element;
element = new TiXmlElement( "Operations" );
root->LinkEndChild( element );
WriteBaseXML(element);
}
//static
HeeksObj* COperations::ReadFromXMLElement(TiXmlElement* pElem)
{
COperations* new_object = new COperations;
new_object->ReadBaseXML(pElem);
return new_object;
}
static COperations* object_for_tools = NULL;
class SetAllActive: public Tool{
// Tool's virtual functions
const wxChar* GetTitle(){return _("Set All Operations Active");}
void Run()
{
for(HeeksObj* object = object_for_tools->GetFirstChild(); object; object = object_for_tools->GetNextChild())
{
if(COp::IsAnOperation(object->GetType()))
{
((COp*)object)->m_active = true;
heeksCAD->WasModified(object);
}
}
}
wxString BitmapPath(){ return _T("setactive");}
};
static SetAllActive set_all_active;
class SetAllInactive: public Tool{
// Tool's virtual functions
const wxChar* GetTitle(){return _("Set All Operations Inactive");}
void Run()
{
for(HeeksObj* object = object_for_tools->GetFirstChild(); object; object = object_for_tools->GetNextChild())
{
if(COp::IsAnOperation(object->GetType()))
{
((COp*)object)->m_active = false;
heeksCAD->WasModified(object);
}
}
}
wxString BitmapPath(){ return _T("setinactive");}
};
static SetAllInactive set_all_inactive;
void COperations::GetTools(std::list<Tool*>* t_list, const wxPoint* p)
{
object_for_tools = this;
t_list->push_back(&set_all_active);
t_list->push_back(&set_all_inactive);
ObjList::GetTools(t_list, p);
}
CProgram::CProgram():m_machine(_T("nc.iso")), m_output_file(_T("test.tap")), m_nc_code(NULL), m_operations(NULL), m_script_edited(false)
{
}
HeeksObj *CProgram::MakeACopy(void)const
{
return new CProgram(*this);
}
void CProgram::CopyFrom(const HeeksObj* object)
{
operator=(*((CProgram*)object));
}
static void on_set_machine(const wxChar* value, HeeksObj* object){((CProgram*)object)->m_machine = value;}
static void on_set_output_file(const wxChar* value, HeeksObj* object){((CProgram*)object)->m_output_file = value;}
void CProgram::GetProperties(std::list<Property *> *list)
{
list->push_back(new PropertyString(_("machine"), m_machine, this, on_set_machine));
list->push_back(new PropertyString(_("output file"), m_output_file, this, on_set_output_file));
HeeksObj::GetProperties(list);
}
bool CProgram::CanAdd(HeeksObj* object)
{
return object->GetType() == NCCodeType || object->GetType() == OperationsType;
}
bool CProgram::CanAddTo(HeeksObj* owner)
{
return owner->GetType() == DocumentType;
}
void CProgram::SetClickMarkPoint(MarkedObject* marked_object, const double* ray_start, const double* ray_direction)
{
if(marked_object->m_map.size() > 0)
{
MarkedObject* sub_marked_object = marked_object->m_map.begin()->second;
if(sub_marked_object)
{
HeeksObj* object = sub_marked_object->m_map.begin()->first;
if(object && object->GetType() == NCCodeType)
{
((CNCCode*)object)->SetClickMarkPoint(sub_marked_object, ray_start, ray_direction);
}
}
}
}
void CProgram::WriteXML(TiXmlNode *root)
{
TiXmlElement * element;
element = new TiXmlElement( "Program" );
root->LinkEndChild( element );
element->SetAttribute("machine", Ttc(m_machine.c_str()));
element->SetAttribute("output_file", Ttc(m_output_file.c_str()));
element->SetAttribute("program", Ttc(theApp.m_program_canvas->m_textCtrl->GetValue()));
WriteBaseXML(element);
}
bool CProgram::Add(HeeksObj* object, HeeksObj* prev_object)
{
if(object->GetType() == NCCodeType)m_nc_code = (CNCCode*)object;
if(object->GetType() == OperationsType)m_operations = (COperations*)object;
return ObjList::Add(object, prev_object);
}
void CProgram::Remove(HeeksObj* object)
{
// these shouldn't happen, though
if(object == m_nc_code)m_nc_code = NULL;
else if(object == m_operations)m_operations = NULL;
ObjList::Remove(object);
}
// static member function
HeeksObj* CProgram::ReadFromXMLElement(TiXmlElement* pElem)
{
CProgram* new_object = new CProgram;
// get the attributes
for(TiXmlAttribute* a = pElem->FirstAttribute(); a; a = a->Next())
{
std::string name(a->Name());
if(name == "machine"){new_object->m_machine.assign(Ctt(a->Value()));}
else if(name == "output_file"){new_object->m_output_file.assign(Ctt(a->Value()));}
else if(name == "program"){theApp.m_program_canvas->m_textCtrl->SetValue(Ctt(a->Value()));}
}
new_object->ReadBaseXML(pElem);
theApp.m_program = new_object;
return new_object;
}
void CProgram::RewritePythonProgram()
{
theApp.m_program_canvas->m_textCtrl->Clear();
CZigZag::number_for_stl_file = 1;
CAdaptive::number_for_stl_file = 1;
bool profile_op_exists = false;
bool pocket_op_exists = false;
bool zigzag_op_exists = false;
bool adaptive_op_exists = false;
for(HeeksObj* object = m_operations->GetFirstChild(); object; object = m_operations->GetNextChild())
{
if(object->GetType() == ProfileType)
{
if(((CProfile*)object)->m_active)profile_op_exists = true;
}
else if(object->GetType() == PocketType)
{
if(((CPocket*)object)->m_active)pocket_op_exists = true;
}
else if(object->GetType() == ZigZagType)
{
if(((CZigZag*)object)->m_active)zigzag_op_exists = true;
}
else if(object->GetType() == AdaptiveType)
{
if(((CAdaptive*)object)->m_active)adaptive_op_exists = true;
}
}
// add standard stuff at the top
// kurve related things
if(profile_op_exists)
{
theApp.m_program_canvas->m_textCtrl->AppendText(_T("import kurve\n"));
theApp.m_program_canvas->m_textCtrl->AppendText(_T("import kurve_funcs\n"));
}
// area related things
if(pocket_op_exists)
{
theApp.m_program_canvas->m_textCtrl->AppendText(_T("import area\n"));
theApp.m_program_canvas->m_textCtrl->AppendText(_T("import area_funcs\n"));
}
// pycam stuff
if(zigzag_op_exists)
{
theApp.m_program_canvas->m_textCtrl->AppendText(_T("import sys\n"));
theApp.m_program_canvas->m_textCtrl->AppendText(_T("sys.path.insert(0,'PyCam/trunk')\n"));
theApp.m_program_canvas->m_textCtrl->AppendText(_T("\n"));
theApp.m_program_canvas->m_textCtrl->AppendText(_T("from pycam.Geometry import *\n"));
theApp.m_program_canvas->m_textCtrl->AppendText(_T("from pycam.Cutters.SphericalCutter import *\n"));
theApp.m_program_canvas->m_textCtrl->AppendText(_T("from pycam.Cutters.CylindricalCutter import *\n"));
theApp.m_program_canvas->m_textCtrl->AppendText(_T("from pycam.Cutters.ToroidalCutter import *\n"));
theApp.m_program_canvas->m_textCtrl->AppendText(_T("from pycam.Importers.STLImporter import ImportModel\n"));
theApp.m_program_canvas->m_textCtrl->AppendText(_T("from pycam.PathGenerators.DropCutter import DropCutter\n"));
theApp.m_program_canvas->m_textCtrl->AppendText(_T("from PyCamToHeeks import HeeksCNCExporter\n"));
theApp.m_program_canvas->m_textCtrl->AppendText(_T("\n"));
}
// actp
if(adaptive_op_exists)
{
theApp.m_program_canvas->m_textCtrl->AppendText(_T("import actp_funcs\n"));
theApp.m_program_canvas->m_textCtrl->AppendText(_T("import actp\n"));
theApp.m_program_canvas->m_textCtrl->AppendText(_T("\n"));
}
// machine general stuff
theApp.m_program_canvas->m_textCtrl->AppendText(_T("from nc.nc import *\n"));
// specific machine
theApp.m_program_canvas->m_textCtrl->AppendText(_T("import ") + m_machine + _T("\n"));
theApp.m_program_canvas->m_textCtrl->AppendText(_T("\n"));
// output file
theApp.m_program_canvas->m_textCtrl->AppendText(_T("output('") + m_output_file + _T("')\n"));
// begin program
theApp.m_program_canvas->m_textCtrl->AppendText(_T("program_begin(123, 'Test program')\n"));
theApp.m_program_canvas->m_textCtrl->AppendText(_T("absolute()\n"));
theApp.m_program_canvas->m_textCtrl->AppendText(_T("metric()\n"));
theApp.m_program_canvas->m_textCtrl->AppendText(_T("set_plane(0)\n"));
theApp.m_program_canvas->m_textCtrl->AppendText(_T("\n"));
// write the operations
for(HeeksObj* object = m_operations->GetFirstChild(); object; object = m_operations->GetNextChild())
{
switch(object->GetType())
{
case ProfileType:
if(((CProfile*)object)->m_active)((CProfile*)object)->AppendTextToProgram();
break;
case PocketType:
if(((CPocket*)object)->m_active)((CPocket*)object)->AppendTextToProgram();
break;
case ZigZagType:
if(((CZigZag*)object)->m_active)((CZigZag*)object)->AppendTextToProgram();
break;
case AdaptiveType:
if(((CAdaptive*)object)->m_active)((CAdaptive*)object)->AppendTextToProgram();
break;
}
}
}
ProgramUserType CProgram::GetUserType()
{
if(m_nc_code->m_user_edited)return ProgramUserTypeNC;
if(m_script_edited)return ProgramUserTypeScript;
if(m_operations->GetFirstChild())return ProgramUserTypeTree;
return ProgramUserTypeUnkown;
}
void CProgram::UpdateFromUserType()
{
#if 0
switch(GetUserType())
{
case ProgramUserTypeUnkown:
case tree:
Enable "Operations" icon in tree
editing the tree, recreates the python script
Read only "Program" window
pressing "Post-process" creates the NC code ( and backplots it )
Read only "Output" window
Disable all buttons on "Output" window
}
#endif
}
<commit_msg>fixed "Remember machine" http://code.google.com/p/heekscnc/issues/detail?id=72<commit_after>// Program.cpp
#include "stdafx.h"
#include "Program.h"
#include "PythonStuff.h"
#include "tinyxml/tinyxml.h"
#include "ProgramCanvas.h"
#include "NCCode.h"
#include "interface/MarkedObject.h"
#include "interface/PropertyString.h"
#include "interface/Tool.h"
#include "Profile.h"
#include "Pocket.h"
#include "ZigZag.h"
#include "Adaptive.h"
#include "Op.h"
#include "CNCConfig.h"
bool COperations::CanAdd(HeeksObj* object)
{
return object->GetType() == ProfileType || object->GetType() == PocketType || object->GetType() == ZigZagType || object->GetType() == AdaptiveType;
}
void COperations::WriteXML(TiXmlNode *root)
{
TiXmlElement * element;
element = new TiXmlElement( "Operations" );
root->LinkEndChild( element );
WriteBaseXML(element);
}
//static
HeeksObj* COperations::ReadFromXMLElement(TiXmlElement* pElem)
{
COperations* new_object = new COperations;
new_object->ReadBaseXML(pElem);
return new_object;
}
static COperations* object_for_tools = NULL;
class SetAllActive: public Tool{
// Tool's virtual functions
const wxChar* GetTitle(){return _("Set All Operations Active");}
void Run()
{
for(HeeksObj* object = object_for_tools->GetFirstChild(); object; object = object_for_tools->GetNextChild())
{
if(COp::IsAnOperation(object->GetType()))
{
((COp*)object)->m_active = true;
heeksCAD->WasModified(object);
}
}
}
wxString BitmapPath(){ return _T("setactive");}
};
static SetAllActive set_all_active;
class SetAllInactive: public Tool{
// Tool's virtual functions
const wxChar* GetTitle(){return _("Set All Operations Inactive");}
void Run()
{
for(HeeksObj* object = object_for_tools->GetFirstChild(); object; object = object_for_tools->GetNextChild())
{
if(COp::IsAnOperation(object->GetType()))
{
((COp*)object)->m_active = false;
heeksCAD->WasModified(object);
}
}
}
wxString BitmapPath(){ return _T("setinactive");}
};
static SetAllInactive set_all_inactive;
void COperations::GetTools(std::list<Tool*>* t_list, const wxPoint* p)
{
object_for_tools = this;
t_list->push_back(&set_all_active);
t_list->push_back(&set_all_inactive);
ObjList::GetTools(t_list, p);
}
CProgram::CProgram():m_nc_code(NULL), m_operations(NULL), m_script_edited(false)
{
CNCConfig config;
config.Read(_T("ProgramMachine"), &m_machine, _T("nc.iso"));
config.Read(_T("ProgramOutputFile"), &m_output_file, _T("test.tap"));
}
HeeksObj *CProgram::MakeACopy(void)const
{
return new CProgram(*this);
}
void CProgram::CopyFrom(const HeeksObj* object)
{
operator=(*((CProgram*)object));
}
static void on_set_machine(const wxChar* value, HeeksObj* object)
{
((CProgram*)object)->m_machine = value;
CNCConfig config;
config.Write(_T("ProgramMachine"), ((CProgram*)object)->m_machine);
}
static void on_set_output_file(const wxChar* value, HeeksObj* object)
{
((CProgram*)object)->m_output_file = value;
CNCConfig config;
config.Write(_T("ProgramOutputFile"), ((CProgram*)object)->m_output_file);
}
void CProgram::GetProperties(std::list<Property *> *list)
{
list->push_back(new PropertyString(_("machine"), m_machine, this, on_set_machine));
list->push_back(new PropertyString(_("output file"), m_output_file, this, on_set_output_file));
HeeksObj::GetProperties(list);
}
bool CProgram::CanAdd(HeeksObj* object)
{
return object->GetType() == NCCodeType || object->GetType() == OperationsType;
}
bool CProgram::CanAddTo(HeeksObj* owner)
{
return owner->GetType() == DocumentType;
}
void CProgram::SetClickMarkPoint(MarkedObject* marked_object, const double* ray_start, const double* ray_direction)
{
if(marked_object->m_map.size() > 0)
{
MarkedObject* sub_marked_object = marked_object->m_map.begin()->second;
if(sub_marked_object)
{
HeeksObj* object = sub_marked_object->m_map.begin()->first;
if(object && object->GetType() == NCCodeType)
{
((CNCCode*)object)->SetClickMarkPoint(sub_marked_object, ray_start, ray_direction);
}
}
}
}
void CProgram::WriteXML(TiXmlNode *root)
{
TiXmlElement * element;
element = new TiXmlElement( "Program" );
root->LinkEndChild( element );
element->SetAttribute("machine", Ttc(m_machine.c_str()));
element->SetAttribute("output_file", Ttc(m_output_file.c_str()));
element->SetAttribute("program", Ttc(theApp.m_program_canvas->m_textCtrl->GetValue()));
WriteBaseXML(element);
}
bool CProgram::Add(HeeksObj* object, HeeksObj* prev_object)
{
if(object->GetType() == NCCodeType)m_nc_code = (CNCCode*)object;
if(object->GetType() == OperationsType)m_operations = (COperations*)object;
return ObjList::Add(object, prev_object);
}
void CProgram::Remove(HeeksObj* object)
{
// these shouldn't happen, though
if(object == m_nc_code)m_nc_code = NULL;
else if(object == m_operations)m_operations = NULL;
ObjList::Remove(object);
}
// static member function
HeeksObj* CProgram::ReadFromXMLElement(TiXmlElement* pElem)
{
CProgram* new_object = new CProgram;
// get the attributes
for(TiXmlAttribute* a = pElem->FirstAttribute(); a; a = a->Next())
{
std::string name(a->Name());
if(name == "machine"){new_object->m_machine.assign(Ctt(a->Value()));}
else if(name == "output_file"){new_object->m_output_file.assign(Ctt(a->Value()));}
else if(name == "program"){theApp.m_program_canvas->m_textCtrl->SetValue(Ctt(a->Value()));}
}
new_object->ReadBaseXML(pElem);
theApp.m_program = new_object;
return new_object;
}
void CProgram::RewritePythonProgram()
{
theApp.m_program_canvas->m_textCtrl->Clear();
CZigZag::number_for_stl_file = 1;
CAdaptive::number_for_stl_file = 1;
bool profile_op_exists = false;
bool pocket_op_exists = false;
bool zigzag_op_exists = false;
bool adaptive_op_exists = false;
for(HeeksObj* object = m_operations->GetFirstChild(); object; object = m_operations->GetNextChild())
{
if(object->GetType() == ProfileType)
{
if(((CProfile*)object)->m_active)profile_op_exists = true;
}
else if(object->GetType() == PocketType)
{
if(((CPocket*)object)->m_active)pocket_op_exists = true;
}
else if(object->GetType() == ZigZagType)
{
if(((CZigZag*)object)->m_active)zigzag_op_exists = true;
}
else if(object->GetType() == AdaptiveType)
{
if(((CAdaptive*)object)->m_active)adaptive_op_exists = true;
}
}
// add standard stuff at the top
// kurve related things
if(profile_op_exists)
{
theApp.m_program_canvas->m_textCtrl->AppendText(_T("import kurve\n"));
theApp.m_program_canvas->m_textCtrl->AppendText(_T("import kurve_funcs\n"));
}
// area related things
if(pocket_op_exists)
{
theApp.m_program_canvas->m_textCtrl->AppendText(_T("import area\n"));
theApp.m_program_canvas->m_textCtrl->AppendText(_T("import area_funcs\n"));
}
// pycam stuff
if(zigzag_op_exists)
{
theApp.m_program_canvas->m_textCtrl->AppendText(_T("import sys\n"));
theApp.m_program_canvas->m_textCtrl->AppendText(_T("sys.path.insert(0,'PyCam/trunk')\n"));
theApp.m_program_canvas->m_textCtrl->AppendText(_T("\n"));
theApp.m_program_canvas->m_textCtrl->AppendText(_T("from pycam.Geometry import *\n"));
theApp.m_program_canvas->m_textCtrl->AppendText(_T("from pycam.Cutters.SphericalCutter import *\n"));
theApp.m_program_canvas->m_textCtrl->AppendText(_T("from pycam.Cutters.CylindricalCutter import *\n"));
theApp.m_program_canvas->m_textCtrl->AppendText(_T("from pycam.Cutters.ToroidalCutter import *\n"));
theApp.m_program_canvas->m_textCtrl->AppendText(_T("from pycam.Importers.STLImporter import ImportModel\n"));
theApp.m_program_canvas->m_textCtrl->AppendText(_T("from pycam.PathGenerators.DropCutter import DropCutter\n"));
theApp.m_program_canvas->m_textCtrl->AppendText(_T("from PyCamToHeeks import HeeksCNCExporter\n"));
theApp.m_program_canvas->m_textCtrl->AppendText(_T("\n"));
}
// actp
if(adaptive_op_exists)
{
theApp.m_program_canvas->m_textCtrl->AppendText(_T("import actp_funcs\n"));
theApp.m_program_canvas->m_textCtrl->AppendText(_T("import actp\n"));
theApp.m_program_canvas->m_textCtrl->AppendText(_T("\n"));
}
// machine general stuff
theApp.m_program_canvas->m_textCtrl->AppendText(_T("from nc.nc import *\n"));
// specific machine
theApp.m_program_canvas->m_textCtrl->AppendText(_T("import ") + m_machine + _T("\n"));
theApp.m_program_canvas->m_textCtrl->AppendText(_T("\n"));
// output file
theApp.m_program_canvas->m_textCtrl->AppendText(_T("output('") + m_output_file + _T("')\n"));
// begin program
theApp.m_program_canvas->m_textCtrl->AppendText(_T("program_begin(123, 'Test program')\n"));
theApp.m_program_canvas->m_textCtrl->AppendText(_T("absolute()\n"));
theApp.m_program_canvas->m_textCtrl->AppendText(_T("metric()\n"));
theApp.m_program_canvas->m_textCtrl->AppendText(_T("set_plane(0)\n"));
theApp.m_program_canvas->m_textCtrl->AppendText(_T("\n"));
// write the operations
for(HeeksObj* object = m_operations->GetFirstChild(); object; object = m_operations->GetNextChild())
{
switch(object->GetType())
{
case ProfileType:
if(((CProfile*)object)->m_active)((CProfile*)object)->AppendTextToProgram();
break;
case PocketType:
if(((CPocket*)object)->m_active)((CPocket*)object)->AppendTextToProgram();
break;
case ZigZagType:
if(((CZigZag*)object)->m_active)((CZigZag*)object)->AppendTextToProgram();
break;
case AdaptiveType:
if(((CAdaptive*)object)->m_active)((CAdaptive*)object)->AppendTextToProgram();
break;
}
}
}
ProgramUserType CProgram::GetUserType()
{
if(m_nc_code->m_user_edited)return ProgramUserTypeNC;
if(m_script_edited)return ProgramUserTypeScript;
if(m_operations->GetFirstChild())return ProgramUserTypeTree;
return ProgramUserTypeUnkown;
}
void CProgram::UpdateFromUserType()
{
#if 0
switch(GetUserType())
{
case ProgramUserTypeUnkown:
case tree:
Enable "Operations" icon in tree
editing the tree, recreates the python script
Read only "Program" window
pressing "Post-process" creates the NC code ( and backplots it )
Read only "Output" window
Disable all buttons on "Output" window
}
#endif
}
<|endoftext|> |
<commit_before>/*=========================================================================
Program: Visualization Library
Module: PtS2PtSF.cc
Language: C++
Date: $Date$
Version: $Revision$
This file is part of the Visualization Library. No part of this file
or its contents may be copied, reproduced or altered in any way
without the express written consent of the authors.
Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen 1993, 1994
=========================================================================*/
#include "PtS2PtSF.hh"
#include "PolyData.hh"
vlPointSetToPointSetFilter::vlPointSetToPointSetFilter()
{
// prevents dangling reference to PointSet
this->PointSet = new vlPolyData;
}
vlPointSetToPointSetFilter::~vlPointSetToPointSetFilter()
{
delete this->PointSet;
}
vlDataSet* vlPointSetToPointSetFilter::MakeObject()
{
// vlPointSetToPointSetFilter *o = new vlPointSetToPointSetFilter();
vlPointSetToPointSetFilter *o;
o->PointSet = this->PointSet;
o->SetPoints(this->GetPoints());
return o;
}
void vlPointSetToPointSetFilter::Modified()
{
this->vlPointSet::Modified();
this->vlPointSetFilter::_Modified();
}
unsigned long int vlPointSetToPointSetFilter::GetMTime()
{
unsigned long dtime = this->vlPointSet::GetMTime();
unsigned long ftime = this->vlPointSetFilter::_GetMTime();
return (dtime > ftime ? dtime : ftime);
}
void vlPointSetToPointSetFilter::Update()
{
this->UpdateFilter();
}
void vlPointSetToPointSetFilter::Initialize()
{
if ( this->Input != NULL )
{
vlDataSet *ds=this->Input->MakeObject();
delete this->PointSet;
// copies input geometry to internal data set
this->PointSet = ds;
}
else
{
return;
}
}
void vlPointSetToPointSetFilter::ComputeBounds()
{
if ( this->Points != NULL )
{
this->Points->ComputeBounds();
float *bounds=this->Points->GetBounds();
for (int i=0; i < 6; i++) this->Bounds[i] = bounds[i];
}
};
void vlPointSetToPointSetFilter::PrintSelf(ostream& os, vlIndent indent)
{
vlPointSet::PrintSelf(os,indent);
vlPointSetFilter::_PrintSelf(os,indent);
if ( this->PointSet )
{
os << indent << "PointSet: (" << this->PointSet << ")\n";
os << indent << "PointSet type: " << this->PointSet->GetClassName() <<"\n";
}
else
{
os << indent << "PointSet: (none)\n";
}
}
<commit_msg>ENH: Fixed bug.<commit_after>/*=========================================================================
Program: Visualization Library
Module: PtS2PtSF.cc
Language: C++
Date: 11/6/94
Version: 1.8
This file is part of the Visualization Library. No part of this file
or its contents may be copied, reproduced or altered in any way
without the express written consent of the authors.
Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen 1993, 1994
=========================================================================*/
#include "PtS2PtSF.hh"
#include "PolyData.hh"
vlPointSetToPointSetFilter::vlPointSetToPointSetFilter()
{
// prevents dangling reference to PointSet
this->PointSet = new vlPolyData;
}
vlPointSetToPointSetFilter::~vlPointSetToPointSetFilter()
{
delete this->PointSet;
}
vlDataSet* vlPointSetToPointSetFilter::MakeObject()
{
// vlPointSetToPointSetFilter *o = new vlPointSetToPointSetFilter();
vlPointSetToPointSetFilter *o;
o->PointSet = this->PointSet;
o->SetPoints(this->GetPoints());
return o;
}
void vlPointSetToPointSetFilter::Modified()
{
this->vlPointSet::Modified();
this->vlPointSetFilter::_Modified();
}
unsigned long int vlPointSetToPointSetFilter::GetMTime()
{
unsigned long dtime = this->vlPointSet::GetMTime();
unsigned long ftime = this->vlPointSetFilter::_GetMTime();
return (dtime > ftime ? dtime : ftime);
}
void vlPointSetToPointSetFilter::Update()
{
this->UpdateFilter();
}
void vlPointSetToPointSetFilter::Initialize()
{
if ( this->Input != NULL )
{
vlDataSet *ds=this->Input->MakeObject();
delete this->PointSet;
// copies input geometry to internal data set
this->PointSet = ds;
}
else
{
return;
}
}
void vlPointSetToPointSetFilter::ComputeBounds()
{
if ( this->Points != NULL )
{
this->Points->ComputeBounds();
float *bounds=this->Points->GetBounds();
for (int i=0; i < 6; i++) this->Bounds[i] = bounds[i];
}
};
void vlPointSetToPointSetFilter::PrintSelf(ostream& os, vlIndent indent)
{
vlPointSet::PrintSelf(os,indent);
vlPointSetFilter::_PrintSelf(os,indent);
if ( this->PointSet )
{
os << indent << "PointSet: (" << this->PointSet << ")\n";
os << indent << "PointSet type: " << this->PointSet->GetClassName() <<"\n";
}
else
{
os << indent << "PointSet: (none)\n";
}
}
<|endoftext|> |
<commit_before>#include <vector>
#include "player.h"
#include "pieces.h"
#include "coord.h"
#include <locale>
using namespace std;
Player::Player(GameBoard* gb, int colour): gb(gb), colour(colour) {}
bool Player::wouldPutInCheck(Coord stc, Coord endc, bool opponent, bool isKing) {
#ifdef DEBUG
cout << "WPIC::Running would put in CHECK" << endl;
#endif
int colourConsidering = colour;
if (opponent == true) {
colourConsidering = 1 - colour;
}
map<int, map<int, Pieces*> > tempBoard;
if ((stc.getX() == endc.getX()) && (stc.getY() == endc.getY())) {
tempBoard = gb->makeTempBoard();
} else {
tempBoard = gb->makeTempBoard(stc, endc);
}
//Find location of the king and store it in a Coord
int kingx;
int kingy;
for(int x = 0; x <= 7; x++) {
for(int y = 0; y <= 7; y++) {
if((tempBoard[x][y] != NULL) &&
(tempBoard[x][y]->getColour() == colourConsidering) &&
(tempBoard[x][y]->getPiece() == 'K' || tempBoard[x][y]->getPiece() == 'k')) {
kingx = x;
kingy = y;
}
}
}
#ifdef DEBUG
cout << "WPIC::got this king's coords, it is at: " << kingx << " " << kingy << endl;
#endif
Coord kc;
if(isKing) {
kc = Coord(kingx, kingy);
}
else {
kc = endc;
}
//Find if there are people attacking the king (The Knight will need to be addressed seperately)
bool inCheck = false;
for (int x = -1; x <= 1 && inCheck == false; x++) {
for (int y = -1; y <= 1 && inCheck == false; y++) {
if((x != 0) || (y != 0)) {
//Going across all 8 possible directions
int mag = 1;
bool continueForward = true;
while(continueForward) {
int movex = kc.getX() + x*mag;
int movey = kc.getY() + y*mag;
Coord temp = Coord(movex, movey);
#ifdef DEBUG
cout << "WPIC::Checking x and y for temp position: " << temp.getX() << " " << temp.getY() << endl;
#endif
if(!temp.inBounds() ||
((tempBoard[movex][movey] != NULL) && (tempBoard[movex][movey]->getColour() == colourConsidering))) {
continueForward = false;
} else if(tempBoard[movex][movey] == NULL) {
mag++;
} else {
char p = tempBoard[movex][movey]->getPiece();
if((y == 0) || (x == 0)) { //Horizontal or vertical attack
if((p == 'Q') || (p == 'R') || (p == 'q') || (p == 'r')) {
inCheck = true;
} else if(mag == 1) {
if((p == 'K') || (p == 'k')) inCheck = true;
}
} else { //Diagonal Attack
if((p == 'Q') || (p == 'B') || (p == 'q') || (p == 'b')) {
inCheck = true;
} else if(mag == 1) {
if((p == 'K') ||(p == 'k')) {
inCheck = true;
} else if ((colourConsidering == 0) && (y == 1) && (p == 'p')) {
inCheck = true;
} else if ((colourConsidering == 1) && (y == -1) && (p == 'P')) {
inCheck = true;
}
}
}
continueForward = false;
}
}
}
}
}
//Special Check for Horses
for (int x = -2; x <= 2 && inCheck == false; x++) {
for (int y = -2; y <= 2 && inCheck == false; y++) {
if((x != 0) && (y != 0) && (x != y) && (x != -y)) {
Coord temp = Coord(kc.getX() + x, kc.getY() + y);
#ifdef DEBUG
cout << "Horse Coords check: " << temp.getX() << " " << temp.getY() << endl;
#endif
if(temp.inBounds() && tempBoard[temp.getX()][temp.getY()] != NULL) {
char a = tempBoard[kc.getX()][kc.getY()]->getPiece(); //gb->getPiece(kc)->getPiece();
char b = tempBoard[temp.getX()][temp.getY()]->getPiece(); //gb->getPiece(temp)->getPiece();
if((isupper(a) && b == 'n') || (!(isupper(a)) && b == 'N')) {
inCheck = true;
}
}
}
}
}
#ifdef DEBUG
cout << "WPIC:: Returning: " << inCheck << endl;
#endif
return inCheck;
}
bool Player::isMyPiece(Pieces* p) {
if(p == NULL) {
#ifdef DEBUG
cerr << "There does not exist a piece at this location" << endl;
#endif
return false;
}
else {
return (colour == p->getColour());
}
}
<commit_msg>Updating coding style<commit_after>#include <vector>
#include "player.h"
#include "pieces.h"
#include "coord.h"
#include <locale>
using namespace std;
Player::Player(GameBoard* gb, int colour) : gb(gb), colour(colour) {}
bool Player::wouldPutInCheck(Coord stc, Coord endc, bool opponent, bool isKing)
{
#ifdef DEBUG
cout << "WPIC::Running would put in CHECK" << endl;
#endif
int colourConsidering = colour;
if (opponent == true) colourConsidering = 1 - colour;
map<int, map<int, Pieces*> > tempBoard;
if ((stc.getX() == endc.getX()) && (stc.getY() == endc.getY()))
tempBoard = gb->makeTempBoard();
else tempBoard = gb->makeTempBoard(stc, endc);
//Find location of the king and store it in a Coord
int kingx, kingy;
for (int x = 0; x <= 7; x++)
for (int y = 0; y <= 7; y++)
if ((tempBoard[x][y] != NULL) &&
(tempBoard[x][y]->getColour() == colourConsidering) &&
(tempBoard[x][y]->getPiece() == 'K' || tempBoard[x][y]->getPiece() == 'k'))
{
kingx = x;
kingy = y;
}
#ifdef DEBUG
cout << "WPIC::got this king's coords, it is at: " << kingx << " " << kingy << endl;
#endif
Coord kc;
if (isKing) kc = Coord(kingx, kingy);
else kc = endc;
//Find if there are people attacking the king (The Knight will need to be addressed seperately)
bool inCheck = false;
for (int x = -1; x <= 1 && inCheck == false; x++)
for (int y = -1; y <= 1 && inCheck == false; y++)
if ((x != 0) || (y != 0))
{
//Going across all 8 possible directions
int mag = 1;
bool continueForward = true;
while (continueForward)
{
int movex = kc.getX() + x*mag;
int movey = kc.getY() + y*mag;
Coord temp = Coord(movex, movey);
#ifdef DEBUG
cout << "WPIC::Checking x and y for temp position: " << temp.getX() << " " << temp.getY() << endl;
#endif
if (!temp.inBounds() ||
((tempBoard[movex][movey] != NULL) &&
(tempBoard[movex][movey]->getColour() == colourConsidering)))
continueForward = false;
else if (tempBoard[movex][movey] == NULL) mag++;
else
{
char p = tempBoard[movex][movey]->getPiece();
//Horizontal or vertical attack
if ((y == 0) || (x == 0))
{
if ((p == 'Q') || (p == 'R') || (p == 'q') || (p == 'r'))
inCheck = true;
else if (mag == 1)
if ((p == 'K') || (p == 'k'))
inCheck = true;
}
//Diagonal Attack
else
{
if ((p == 'Q') || (p == 'B') || (p == 'q') || (p == 'b'))
inCheck = true;
else if (mag == 1)
{
if ((p == 'K') || (p == 'k'))
inCheck = true;
else if ((colourConsidering == 0) && (y == 1) && (p == 'p'))
inCheck = true;
else if ((colourConsidering == 1) && (y == -1) && (p == 'P'))
inCheck = true;
}
}
continueForward = false;
}
}
}
//Special Check for Horses
for (int x = -2; x <= 2 && inCheck == false; x++)
for (int y = -2; y <= 2 && inCheck == false; y++)
if ((x != 0) && (y != 0) && (x != y) && (x != -y))
{
Coord temp = Coord(kc.getX() + x, kc.getY() + y);
#ifdef DEBUG
cout << "Horse Coords check: " << temp.getX() << " " << temp.getY() << endl;
#endif
if (temp.inBounds() && tempBoard[temp.getX()][temp.getY()] != NULL)
{
char a = tempBoard[kc.getX()][kc.getY()]->getPiece();
char b = tempBoard[temp.getX()][temp.getY()]->getPiece();
if ((isupper(a) && b == 'n') || (!(isupper(a)) && b == 'N')) inCheck = true;
}
}
#ifdef DEBUG
cout << "WPIC:: Returning: " << inCheck << endl;
#endif
return inCheck;
}
bool Player::isMyPiece(Pieces* p)
{
if (p == NULL)
{
#ifdef DEBUG
cerr << "There does not exist a piece at this location" << endl;
#endif
return false;
}
else return (colour == p->getColour());
}
<|endoftext|> |
<commit_before>/*
* StringImage.cpp
*
* Created on: January 27, 2011
* Author: Craig Rasmussen
*/
#include "StringImage.hpp"
#include <src/include/pv_common.h> // for PI
#include <src/utils/pv_random.h>
namespace PV {
StringImage::StringImage(const char * name, HyPerCol * hc) :
Image(name, hc)
{
this->type = type;
const PVLayerLoc * loc = getLayerLoc();
// set default params
// set reference position of bars
this->prefPosition = (loc->nx + 2*loc->nb) / 2.0;
this->position = this->prefPosition;
this->lastPosition = this->prefPosition;
// set bars orientation to default values
this->orientation = left;
this->lastOrientation = orientation;
// check for explicit parameters in params.stdp
//
PVParams * params = hc->parameters();
pMove = params->value(name, "pMove", 0.0);
pJit = params->value(name, "pJitter", 0.0);
pBackground = (.5/1000.) * 50; // dt==.5 ms, freq=50 Hz
// set parameters that controls writing of new images
writeImages = params->value(name, "writeImages", 0.0);
initPattern();
// make sure initialization is finished
updateState(0.0, 0.0);
}
StringImage::~StringImage()
{
// CER-new
//fclose(fp);
}
int StringImage::tag()
{
if (orientation == left) return position;
else return 10*position;
}
/**
* Initialize pattern with background noise
*/
int StringImage::initPattern()
{
for (int kex = 0; kex < getNumExtended(); kex++) {
data[kex] = (pv_random_prob() < pBackground) ? 1.0 : 0.0;
}
return 0;
}
/**
* update the image buffers
*/
int StringImage::updateState(float time, float dt)
{
// for now alphabet is {i1,i2,f1,f2} (two phases)
// initialize pattern to background
//
initPattern();
const PVLayerLoc * loc = getLayerLoc();
int x = this->position;
int y = (loc->ny + 2*loc->nb) / 2;
int sy = strideYExtended(loc);
if (pv_random_prob() < pMove) { // move pattern with probability pMove
orientation = (orientation == right) ? left : right;
if (orientation == right) x += 2;
if (pv_random_prob() < 0.5) x += 1; // pick phase with even probability
data[x + y*sy] = 1;
}
else if (pv_random_prob() < pJit) {
if (orientation == right) x += 2;
if (pv_random_prob() < 0.5) x += 1; // pick phase with even probability
data[x + y*sy] = 1;
}
return 0;
}
} // namespace PV
<commit_msg>Changed to inherit from Retina. Added jitter effect.<commit_after>/*
* StringImage.cpp
*
* Created on: January 27, 2011
* Author: Craig Rasmussen
*/
#include "StringImage.hpp"
#include <src/include/pv_common.h> // for PI
#include <src/utils/pv_random.h>
namespace PV {
StringImage::StringImage(const char * name, HyPerCol * hc) : Retina(name, hc)
{
this->type = type;
const PVLayerLoc * loc = getLayerLoc();
// set default params
// set reference position of bars
this->position = (loc->nx + 2*loc->nb) / 2.0;
this->jitter = 0;
// set string orientation to default values
this->orientation = left;
this->lastOrientation = orientation;
// check for explicit parameters in params.stdp
//
PVParams * params = hc->parameters();
pMove = params->value(name, "pMove", 0.0);
pJit = params->value(name, "pJitter", 0.0);
// set parameters that controls writing of new images
writeImages = params->value(name, "writeImages", 0.0);
initPattern();
// make sure initialization is finished
updateState(0.0, 0.0);
}
StringImage::~StringImage()
{
}
int StringImage::tag()
{
if (orientation == left) return position;
else return 10*position;
}
/**
* Initialize pattern with background noise
*/
int StringImage::initPattern()
{
pvdata_t * data = getChannel(CHANNEL_EXC);
for (int kex = 0; kex < getNumExtended(); kex++) {
data[kex] = 0.0;
}
return 0;
}
/**
* Set Phi[CHANNEL_EXC] based on string input and then call parent recvSynapticInput
*/
int StringImage::recvSynapticInput(HyPerConn * conn, PVLayerCube * cube, int neighbor)
{
// for now alphabet is {i1,i2,f1,f2} (two phases)
pvdata_t * data = getChannel(CHANNEL_EXC);
const PVLayerLoc * loc = getLayerLoc();
int x = this->position;
int y = (loc->ny + 2*loc->nb) / 2;
int sy = strideYExtended(loc);
if (pv_random_prob() < pMove) { // move pattern with probability pMove
orientation = (orientation == right) ? left : right;
}
else if (pv_random_prob() < pJit) {
jitter = (pv_random_prob() < 0.5) ? 0 : 1; // pick phase with equal probability
}
if (orientation == right) x += 2;
x += jitter;
data[x + y*sy] = 1;
return 0;
}
/**
* Call recvSynapticInput to set Phi[CHANNEL_EXC] and then let Retina class
*/
int StringImage::updateState(float time, float dt)
{
int status = recvSynapticInput(NULL, NULL, 0);
status |= Retina::updateState(time, dt);
return status;
}
} // namespace PV
<|endoftext|> |
<commit_before>#include "RThread.h"
#include "REventLoop.h"
#include "RForwardList.h"
class RThreadPrivate
{
public:
static void
run(void *arg);
};
// FIXME: Thread list not guarded by mutex now !
static RForwardList<RThread *> sThreads;
void
RThreadPrivate::run(void *arg)
{
RThread *thread = static_cast<RThread *>(arg);
if(thread)
{
thread->started.emit();
thread->run();
thread->finished.emit();
}
}
RThread::RThread(TaskHandle_t handle)
// So that RObject won't create another RThread lead infinite looping
: RObject(this)
, mStackSize(128)
, mHandle(handle)
, mIsOwnded(false)
{
}
RThread::RThread()
: RObject(this)
, mStackSize(128)
, mHandle(NULL)
, mIsOwnded(false)
{
sThreads.pushFront(this);
}
RThread::~RThread()
{
terminate();
// Clear this thread pointer in thread list
sThreads.remove(this);
}
void
RThread::exit(int returnCode)
{
REventLoop::instance(this)->exit(returnCode);
}
bool
RThread::isFinished() const
{
if(!mHandle)
{
return true;
}
return (eDeleted == eTaskGetState(mHandle));
}
bool
RThread::isRunning() const
{
if(!mHandle)
{
return false;
}
return (eDeleted != eTaskGetState(mHandle));
}
RThread::Priority
RThread::priority() const
{
if(!mHandle)
{
return IdlePriority;
}
return static_cast<RThread::Priority>(uxTaskPriorityGet(mHandle));
}
void
RThread::setPriority(RThread::Priority priority)
{
if(!mHandle)
{
return;
}
vTaskPrioritySet(mHandle, static_cast<UBaseType_t>(priority));
}
void
RThread::setStackSize(size_t stackSize)
{
mStackSize = stackSize;
}
size_t
RThread::stackSize() const
{
return mStackSize;
}
bool
RThread::wait(unsigned long time)
{
/// FIXME: Ugly way to wait for thread finished.
/* Block for 100ms each time */
const TickType_t ticksPerBlock = 100 / portTICK_PERIOD_MS;
if(currentThreadId() == mHandle)
{
// You can't wait yourself in the samethread!
return false;
}
while(true)
{
if(isFinished())
{
return true;
}
if(time < std::numeric_limits<unsigned long>::max())
{
if(time <= 100)
{
// Timeout!
return false;
}
else
{
time -= 100;
}
}
vTaskDelay(ticksPerBlock);
}
}
void
RThread::quit()
{
this->exit(0);
}
void
RThread::start(RThread::Priority priority)
{
/* Create the task, storing the handle. */
TaskHandle_t handle = NULL;
if(isRunning())
{
return;
}
terminate();
UBaseType_t targetPriority = IdlePriority;
if(InheritPriority == priority)
{
targetPriority = uxTaskPriorityGet(currentThreadId());
}
auto ret = xTaskCreate(
RThreadPrivate::run, /* Function that implements the task. */
"", /* Text name for the task. */
(stackSize() + 1) % sizeof(uint16_t), /* Stack size in words, not bytes. */
static_cast<void *>(this), /* Parameter passed into the task. */
targetPriority, /* Priority at which the task is created. */
&handle); /* Used to pass out the created task's handle. */
if(ret == pdPASS)
{
mIsOwnded = true;
mHandle = handle;
}
}
void
RThread::terminate()
{
if(mIsOwnded && mHandle)
{
// Ensure no tasks and interrupts will be trigger during thread event loop
// destruction.
taskENTER_CRITICAL();
REventLoop::_destroy(this);
vTaskDelete(mHandle);
taskEXIT_CRITICAL();
terminated.emit();
}
mHandle = NULL;
}
RThread *
RThread::currentThread()
{
TaskHandle_t handle = currentThreadId();
for(auto it = sThreads.begin(); it != sThreads.end(); ++it)
{
if(handle == (*it)->mHandle)
{
return *it;
}
}
// FIXME: Here generated an orphan RThread object!
return new RThread(handle);
}
TaskHandle_t
RThread::currentThreadId()
{
return xTaskGetCurrentTaskHandle();
}
void
RThread::yieldCurrentThread()
{
taskYIELD();
}
int
RThread::exec()
{
REventLoop *loop = REventLoop::instance(this);
return loop->exec();
}
void
RThread::run()
{
exec();
}
void
RThread::msleep(unsigned long msecs)
{
unsigned long blockTime = std::numeric_limits<unsigned long>::max() / 1000;
while(msecs > 0)
{
if(msecs <= std::numeric_limits<unsigned long>::max())
{
usleep(msecs);
return;
}
usleep(std::numeric_limits<unsigned long>::max());
msecs -= blockTime;
}
}
void
RThread::sleep(unsigned long secs)
{
unsigned long blockTime = std::numeric_limits<unsigned long>::max() /
1000000l;
while(secs > 0)
{
if(secs <= std::numeric_limits<unsigned long>::max())
{
usleep(secs);
return;
}
usleep(std::numeric_limits<unsigned long>::max());
secs -= blockTime;
}
}
void
RThread::usleep(unsigned long usecs)
{
unsigned long ticks = usecs / (1000 * portTICK_PERIOD_MS);
while(ticks > 0)
{
if(ticks <= static_cast<decltype(usecs)>(portMAX_DELAY))
{
vTaskDelay(static_cast<decltype(portMAX_DELAY)>(ticks));
return;
}
vTaskDelay(portMAX_DELAY);
ticks -= static_cast<decltype(usecs)>(portMAX_DELAY);
}
}
<commit_msg>RThread: Use spin locker to protected resources from tasks<commit_after>#include "RThread.h"
#include "REventLoop.h"
#include "RForwardList.h"
#include "RSpinLocker.h"
class RThreadPrivate
{
public:
static void
run(void *arg);
};
// FIXME: Thread list not guarded by mutex now !
static RForwardList<RThread *> sThreads;
void
RThreadPrivate::run(void *arg)
{
RThread *thread = static_cast<RThread *>(arg);
if(thread)
{
thread->started.emit();
thread->run();
thread->finished.emit();
}
}
RThread::RThread(TaskHandle_t handle)
// So that RObject won't create another RThread lead infinite looping
: RObject(this)
, mStackSize(128)
, mHandle(handle)
, mIsOwnded(false)
{
}
RThread::RThread()
: RObject(this)
, mStackSize(128)
, mHandle(NULL)
, mIsOwnded(false)
{
R_MAKE_SPINLOCKER();
sThreads.pushFront(this);
}
RThread::~RThread()
{
terminate();
R_MAKE_SPINLOCKER();
// Clear this thread pointer in thread list
sThreads.remove(this);
}
void
RThread::exit(int returnCode)
{
REventLoop::instance(this)->exit(returnCode);
}
bool
RThread::isFinished() const
{
if(!mHandle)
{
return true;
}
return (eDeleted == eTaskGetState(mHandle));
}
bool
RThread::isRunning() const
{
if(!mHandle)
{
return false;
}
return (eDeleted != eTaskGetState(mHandle));
}
RThread::Priority
RThread::priority() const
{
if(!mHandle)
{
return IdlePriority;
}
return static_cast<RThread::Priority>(uxTaskPriorityGet(mHandle));
}
void
RThread::setPriority(RThread::Priority priority)
{
if(!mHandle)
{
return;
}
vTaskPrioritySet(mHandle, static_cast<UBaseType_t>(priority));
}
void
RThread::setStackSize(size_t stackSize)
{
mStackSize = stackSize;
}
size_t
RThread::stackSize() const
{
return mStackSize;
}
bool
RThread::wait(unsigned long time)
{
/// FIXME: Ugly way to wait for thread finished.
/* Block for 100ms each time */
const TickType_t ticksPerBlock = 100 / portTICK_PERIOD_MS;
if(currentThreadId() == mHandle)
{
// You can't wait yourself in the samethread!
return false;
}
while(true)
{
if(isFinished())
{
return true;
}
if(time < std::numeric_limits<unsigned long>::max())
{
if(time <= 100)
{
// Timeout!
return false;
}
else
{
time -= 100;
}
}
vTaskDelay(ticksPerBlock);
}
}
void
RThread::quit()
{
this->exit(0);
}
void
RThread::start(RThread::Priority priority)
{
/* Create the task, storing the handle. */
TaskHandle_t handle = NULL;
if(isRunning())
{
return;
}
terminate();
UBaseType_t targetPriority = IdlePriority;
if(InheritPriority == priority)
{
targetPriority = uxTaskPriorityGet(currentThreadId());
}
auto ret = xTaskCreate(
RThreadPrivate::run, /* Function that implements the task. */
"", /* Text name for the task. */
(stackSize() + 1) % sizeof(uint16_t), /* Stack size in words, not bytes. */
static_cast<void *>(this), /* Parameter passed into the task. */
targetPriority, /* Priority at which the task is created. */
&handle); /* Used to pass out the created task's handle. */
if(ret == pdPASS)
{
mIsOwnded = true;
mHandle = handle;
}
}
void
RThread::terminate()
{
if(mIsOwnded && mHandle)
{
// Ensure no tasks and interrupts will be trigger during thread event loop
// destruction.
{
R_MAKE_SPINLOCKER();
REventLoop::_destroy(this);
vTaskDelete(mHandle);
}
terminated.emit();
}
mHandle = NULL;
}
RThread *
RThread::currentThread()
{
TaskHandle_t handle = currentThreadId();
for(auto it = sThreads.begin(); it != sThreads.end(); ++it)
{
if(handle == (*it)->mHandle)
{
return *it;
}
}
// FIXME: Here generated an orphan RThread object!
return new RThread(handle);
}
TaskHandle_t
RThread::currentThreadId()
{
return xTaskGetCurrentTaskHandle();
}
void
RThread::yieldCurrentThread()
{
taskYIELD();
}
int
RThread::exec()
{
REventLoop *loop = REventLoop::instance(this);
return loop->exec();
}
void
RThread::run()
{
exec();
}
void
RThread::msleep(unsigned long msecs)
{
unsigned long blockTime = std::numeric_limits<unsigned long>::max() / 1000;
while(msecs > 0)
{
if(msecs <= std::numeric_limits<unsigned long>::max())
{
usleep(msecs);
return;
}
usleep(std::numeric_limits<unsigned long>::max());
msecs -= blockTime;
}
}
void
RThread::sleep(unsigned long secs)
{
unsigned long blockTime = std::numeric_limits<unsigned long>::max() /
1000000l;
while(secs > 0)
{
if(secs <= std::numeric_limits<unsigned long>::max())
{
usleep(secs);
return;
}
usleep(std::numeric_limits<unsigned long>::max());
secs -= blockTime;
}
}
void
RThread::usleep(unsigned long usecs)
{
unsigned long ticks = usecs / (1000 * portTICK_PERIOD_MS);
while(ticks > 0)
{
if(ticks <= static_cast<decltype(usecs)>(portMAX_DELAY))
{
vTaskDelay(static_cast<decltype(portMAX_DELAY)>(ticks));
return;
}
vTaskDelay(portMAX_DELAY);
ticks -= static_cast<decltype(usecs)>(portMAX_DELAY);
}
}
<|endoftext|> |
<commit_before>/*//////////////////////////////////////////////////////////////////
//// SKIRT -- an advanced radiative transfer code ////
//// © Astronomical Observatory, Ghent University ////
///////////////////////////////////////////////////////////////// */
#include <cmath>
#include "DustMix.hpp"
#include "FatalError.hpp"
#include "FilePaths.hpp"
#include "Log.hpp"
#include "NR.hpp"
#include "Random.hpp"
#include "SPHDustDistribution.hpp"
#include "SPHGasParticleGrid.hpp"
#include "TextInFile.hpp"
#include "Units.hpp"
using namespace std;
//////////////////////////////////////////////////////////////////////
SPHDustDistribution::SPHDustDistribution()
: _fdust(0), _Tmax(0), _mix(0), _grid(0), _negativeMasses(false)
{
}
////////////////////////////////////////////////////////////////////
SPHDustDistribution::~SPHDustDistribution()
{
delete _grid;
}
//////////////////////////////////////////////////////////////////////
void SPHDustDistribution::setupSelfBefore()
{
// verify appropriate setup
DustDistribution::setupSelfBefore();
if (_fdust <= 0.0) throw FATALERROR("The dust fraction should be positive");
if (!_mix) throw FATALERROR("Dust mix was not set");
// get conversion factors for units
const double pc = Units::pc();
const double Msun = Units::Msun();
// load the SPH gas particles
TextInFile infile(this, _filename, "SPH gas particles");
int Nignored = 0;
double Mtot = 0;
double Mmetal = 0;
double x, y, z, h, M, Z, T;
while (infile.readRow(1, x, y, z, h, M, Z, T))
{
// ignore particle if the temperature is higher than the maximum (assuming both T and Tmax are valid)
if (T > 0 && _Tmax > 0 && T > _Tmax)
{
Nignored++;
}
else
{
// add a particle
_pv.push_back(SPHGasParticle(Vec(x, y,z)*pc, h*pc, M*Msun, Z));
Mtot += M;
Mmetal += M * Z;
// remember whether there are any negative masses
if (M<0) _negativeMasses = true;
}
}
find<Log>()->info(" Number of high-temperature particles ignored: " + QString::number(Nignored));
find<Log>()->info(" Number of SPH gas particles containing dust: " + QString::number(_pv.size()));
find<Log>()->info(" Total gas mass: " + QString::number(Mtot) + " Msun");
find<Log>()->info(" Total metal mass: " + QString::number(Mmetal) + " Msun");
// construct a 3D-grid over the particle space, and create a list of particles that overlap each grid cell
const int GRIDSIZE = 20;
QString size = QString::number(GRIDSIZE);
find<Log>()->info("Constructing intermediate " + size + "x" + size + "x" + size + " grid for particles...");
_grid = new SPHGasParticleGrid(_pv, GRIDSIZE);
find<Log>()->info(" Smallest number of particles per cell: " + QString::number(_grid->minParticlesPerCell()));
find<Log>()->info(" Largest number of particles per cell: " + QString::number(_grid->maxParticlesPerCell()));
find<Log>()->info(" Average number of particles per cell: "
+ QString::number(_grid->totalParticles() / double(GRIDSIZE*GRIDSIZE*GRIDSIZE),'f',1));
// construct a vector with the normalized cumulative particle densities
NR::cdf(_cumrhov, _pv.size(), [this](int i){return _pv[i].metalMass();} );
}
//////////////////////////////////////////////////////////////////////
void SPHDustDistribution::setFilename(QString value)
{
_filename = value;
}
//////////////////////////////////////////////////////////////////////
QString SPHDustDistribution::filename() const
{
return _filename;
}
//////////////////////////////////////////////////////////////////////
void SPHDustDistribution::setDustFraction(double value)
{
_fdust = value;
}
//////////////////////////////////////////////////////////////////////
double SPHDustDistribution::dustFraction() const
{
return _fdust;
}
//////////////////////////////////////////////////////////////////////
void SPHDustDistribution::setMaximumTemperature(double value)
{
_Tmax = value;
}
//////////////////////////////////////////////////////////////////////
double SPHDustDistribution::maximumTemperature() const
{
return _Tmax;
}
//////////////////////////////////////////////////////////////////////
void SPHDustDistribution::setDustMix(DustMix *value)
{
if (_mix) delete _mix;
_mix = value;
if (_mix) _mix->setParent(this);
}
//////////////////////////////////////////////////////////////////////
DustMix *SPHDustDistribution::dustMix() const
{
return _mix;
}
//////////////////////////////////////////////////////////////////////
int SPHDustDistribution::dimension() const
{
return 3;
}
//////////////////////////////////////////////////////////////////////
int SPHDustDistribution::Ncomp() const
{
return 1;
}
//////////////////////////////////////////////////////////////////////
DustMix* SPHDustDistribution::mix(int h) const
{
if (h!=0) throw FATALERROR("Wrong value for h (" + QString::number(h) + ")");
return _mix;
}
//////////////////////////////////////////////////////////////////////
double SPHDustDistribution::density(int h, Position bfr) const
{
if (h!=0) throw FATALERROR("Wrong value for h (" + QString::number(h) + ")");
return density(bfr);
}
//////////////////////////////////////////////////////////////////////
double SPHDustDistribution::density(Position bfr) const
{
const vector<const SPHGasParticle*>& particles = _grid->particlesFor(bfr);
double sum = 0.0;
int n = particles.size();
for (int i=0; i<n; i++)
sum += particles[i]->metalDensity(bfr); // sum contains the total density in metals
sum *= _fdust; // sum now contains the total density in metals locked up in dust grains
return max(sum,0.); // guard against negative dust masses
}
//////////////////////////////////////////////////////////////////////
Position SPHDustDistribution::generatePosition() const
{
Random* random = find<Random>();
int i = NR::locate_clip(_cumrhov, random->uniform());
double x = random->gauss();
double y = random->gauss();
double z = random->gauss();
return Position( _pv[i].center() + Vec(x,y,z) * (_pv[i].radius() / 2.42 / M_SQRT2) );
}
//////////////////////////////////////////////////////////////////////
double SPHDustDistribution::massInBox(int h, const Box& box) const
{
if (h!=0) throw FATALERROR("Wrong value for h (" + QString::number(h) + ")");
return massInBox(box);
}
//////////////////////////////////////////////////////////////////////
double SPHDustDistribution::massInBox(const Box& box) const
{
const vector<const SPHGasParticle*>& particles = _grid->particlesFor(box);
double sum = 0.0;
int n = particles.size();
for (int i=0; i<n; i++)
sum += particles[i]->metalMassInBox(box); // total mass in metals
sum *= _fdust; // total mass in metals locked up in dust grains
return max(sum,0.); // guard against negative dust masses
}
//////////////////////////////////////////////////////////////////////
double SPHDustDistribution::mass(int h) const
{
if (h!=0) throw FATALERROR("Wrong value for h (" + QString::number(h) + ")");
return mass();
}
//////////////////////////////////////////////////////////////////////
double SPHDustDistribution::mass() const
{
double sum = 0.0;
int n = _pv.size();
for (int i=0; i<n; i++)
sum += _pv[i].metalMass(); // sum contains the total mass in metals
sum *= _fdust; // sum now contains the total mass in metals locked up in dust grains
return max(sum,0.); // guard against negative dust masses
}
//////////////////////////////////////////////////////////////////////
double SPHDustDistribution::SigmaX() const
{
const int NSAMPLES = 10000;
double sum = 0;
double xmin = _grid->xmin();
double xmax = _grid->xmax();
for (int k = 0; k < NSAMPLES; k++)
{
sum += density(Position(xmin + k*(xmax-xmin)/NSAMPLES, 0, 0));
}
return (sum/NSAMPLES)*(xmax-xmin);
}
//////////////////////////////////////////////////////////////////////
double SPHDustDistribution::SigmaY() const
{
const int NSAMPLES = 10000;
double sum = 0;
double ymin = _grid->ymin();
double ymax = _grid->ymax();
for (int k = 0; k < NSAMPLES; k++)
{
sum += density(Position(0, ymin + k*(ymax-ymin)/NSAMPLES, 0));
}
return (sum/NSAMPLES)*(ymax-ymin);
}
//////////////////////////////////////////////////////////////////////
double SPHDustDistribution::SigmaZ() const
{
const int NSAMPLES = 10000;
double sum = 0;
double zmin = _grid->zmin();
double zmax = _grid->zmax();
for (int k = 0; k < NSAMPLES; k++)
{
sum += density(Position(0, 0, zmin + k*(zmax-zmin)/NSAMPLES));
}
return (sum/NSAMPLES)*(zmax-zmin);
}
//////////////////////////////////////////////////////////////////////
int SPHDustDistribution::numParticles() const
{
return _pv.size();
}
//////////////////////////////////////////////////////////////////////
Vec SPHDustDistribution::particleCenter(int index) const
{
int n = _pv.size();
if (index<0 || index>=n) throw FATALERROR("Particle index out of range: " + QString::number(index));
return _pv[index].center();
}
//////////////////////////////////////////////////////////////////////
QList<SimulationItem*> SPHDustDistribution::interfaceCandidates(const type_info& interfaceTypeInfo)
{
if (interfaceTypeInfo == typeid(DustMassInBoxInterface) && _negativeMasses)
return QList<SimulationItem*>();
return DustDistribution::interfaceCandidates(interfaceTypeInfo);
}
//////////////////////////////////////////////////////////////////////
<commit_msg>suppress all dust if total cold and/or metallic gas mass is negative<commit_after>/*//////////////////////////////////////////////////////////////////
//// SKIRT -- an advanced radiative transfer code ////
//// © Astronomical Observatory, Ghent University ////
///////////////////////////////////////////////////////////////// */
#include <cmath>
#include "DustMix.hpp"
#include "FatalError.hpp"
#include "FilePaths.hpp"
#include "Log.hpp"
#include "NR.hpp"
#include "Random.hpp"
#include "SPHDustDistribution.hpp"
#include "SPHGasParticleGrid.hpp"
#include "TextInFile.hpp"
#include "Units.hpp"
using namespace std;
//////////////////////////////////////////////////////////////////////
SPHDustDistribution::SPHDustDistribution()
: _fdust(0), _Tmax(0), _mix(0), _grid(0), _negativeMasses(false)
{
}
////////////////////////////////////////////////////////////////////
SPHDustDistribution::~SPHDustDistribution()
{
delete _grid;
}
//////////////////////////////////////////////////////////////////////
void SPHDustDistribution::setupSelfBefore()
{
// verify appropriate setup
DustDistribution::setupSelfBefore();
if (_fdust <= 0.0) throw FATALERROR("The dust fraction should be positive");
if (!_mix) throw FATALERROR("Dust mix was not set");
// get conversion factors for units
const double pc = Units::pc();
const double Msun = Units::Msun();
// load the SPH gas particles
TextInFile infile(this, _filename, "SPH gas particles");
int Nignored = 0;
double Mtot = 0;
double Mmetal = 0;
double x, y, z, h, M, Z, T;
while (infile.readRow(1, x, y, z, h, M, Z, T))
{
// ignore particle if the temperature is higher than the maximum (assuming both T and Tmax are valid)
if (T > 0 && _Tmax > 0 && T > _Tmax)
{
Nignored++;
}
else
{
// add a particle
_pv.push_back(SPHGasParticle(Vec(x, y,z)*pc, h*pc, M*Msun, Z));
Mtot += M;
Mmetal += M * Z;
// remember whether there are any negative masses
if (M<0) _negativeMasses = true;
}
}
// if the total cold and/or metallic gas mass is negative, suppress the complete dust distribution
if (Mtot<0 || Mmetal<0)
{
find<Log>()->warning(" Total cold and/or metallic gas mass is negative; suppressing all dust");
_pv.clear();
Mtot = 0;
Mmetal = 0;
}
// show some statistics
find<Log>()->info(" Number of high-temperature particles ignored: " + QString::number(Nignored));
find<Log>()->info(" Number of SPH gas particles containing dust: " + QString::number(_pv.size()));
find<Log>()->info(" Total gas mass: " + QString::number(Mtot) + " Msun");
find<Log>()->info(" Total metal mass: " + QString::number(Mmetal) + " Msun");
// construct a 3D-grid over the particle space, and create a list of particles that overlap each grid cell
const int GRIDSIZE = 20;
QString size = QString::number(GRIDSIZE);
find<Log>()->info("Constructing intermediate " + size + "x" + size + "x" + size + " grid for particles...");
_grid = new SPHGasParticleGrid(_pv, GRIDSIZE);
find<Log>()->info(" Smallest number of particles per cell: " + QString::number(_grid->minParticlesPerCell()));
find<Log>()->info(" Largest number of particles per cell: " + QString::number(_grid->maxParticlesPerCell()));
find<Log>()->info(" Average number of particles per cell: "
+ QString::number(_grid->totalParticles() / double(GRIDSIZE*GRIDSIZE*GRIDSIZE),'f',1));
// construct a vector with the normalized cumulative particle densities
NR::cdf(_cumrhov, _pv.size(), [this](int i){return _pv[i].metalMass();} );
}
//////////////////////////////////////////////////////////////////////
void SPHDustDistribution::setFilename(QString value)
{
_filename = value;
}
//////////////////////////////////////////////////////////////////////
QString SPHDustDistribution::filename() const
{
return _filename;
}
//////////////////////////////////////////////////////////////////////
void SPHDustDistribution::setDustFraction(double value)
{
_fdust = value;
}
//////////////////////////////////////////////////////////////////////
double SPHDustDistribution::dustFraction() const
{
return _fdust;
}
//////////////////////////////////////////////////////////////////////
void SPHDustDistribution::setMaximumTemperature(double value)
{
_Tmax = value;
}
//////////////////////////////////////////////////////////////////////
double SPHDustDistribution::maximumTemperature() const
{
return _Tmax;
}
//////////////////////////////////////////////////////////////////////
void SPHDustDistribution::setDustMix(DustMix *value)
{
if (_mix) delete _mix;
_mix = value;
if (_mix) _mix->setParent(this);
}
//////////////////////////////////////////////////////////////////////
DustMix *SPHDustDistribution::dustMix() const
{
return _mix;
}
//////////////////////////////////////////////////////////////////////
int SPHDustDistribution::dimension() const
{
return 3;
}
//////////////////////////////////////////////////////////////////////
int SPHDustDistribution::Ncomp() const
{
return 1;
}
//////////////////////////////////////////////////////////////////////
DustMix* SPHDustDistribution::mix(int h) const
{
if (h!=0) throw FATALERROR("Wrong value for h (" + QString::number(h) + ")");
return _mix;
}
//////////////////////////////////////////////////////////////////////
double SPHDustDistribution::density(int h, Position bfr) const
{
if (h!=0) throw FATALERROR("Wrong value for h (" + QString::number(h) + ")");
return density(bfr);
}
//////////////////////////////////////////////////////////////////////
double SPHDustDistribution::density(Position bfr) const
{
const vector<const SPHGasParticle*>& particles = _grid->particlesFor(bfr);
double sum = 0.0;
int n = particles.size();
for (int i=0; i<n; i++)
sum += particles[i]->metalDensity(bfr); // sum contains the total density in metals
sum *= _fdust; // sum now contains the total density in metals locked up in dust grains
return max(sum,0.); // guard against negative dust masses
}
//////////////////////////////////////////////////////////////////////
Position SPHDustDistribution::generatePosition() const
{
Random* random = find<Random>();
int i = NR::locate_clip(_cumrhov, random->uniform());
double x = random->gauss();
double y = random->gauss();
double z = random->gauss();
return Position( _pv[i].center() + Vec(x,y,z) * (_pv[i].radius() / 2.42 / M_SQRT2) );
}
//////////////////////////////////////////////////////////////////////
double SPHDustDistribution::massInBox(int h, const Box& box) const
{
if (h!=0) throw FATALERROR("Wrong value for h (" + QString::number(h) + ")");
return massInBox(box);
}
//////////////////////////////////////////////////////////////////////
double SPHDustDistribution::massInBox(const Box& box) const
{
const vector<const SPHGasParticle*>& particles = _grid->particlesFor(box);
double sum = 0.0;
int n = particles.size();
for (int i=0; i<n; i++)
sum += particles[i]->metalMassInBox(box); // total mass in metals
sum *= _fdust; // total mass in metals locked up in dust grains
return max(sum,0.); // guard against negative dust masses
}
//////////////////////////////////////////////////////////////////////
double SPHDustDistribution::mass(int h) const
{
if (h!=0) throw FATALERROR("Wrong value for h (" + QString::number(h) + ")");
return mass();
}
//////////////////////////////////////////////////////////////////////
double SPHDustDistribution::mass() const
{
double sum = 0.0;
int n = _pv.size();
for (int i=0; i<n; i++)
sum += _pv[i].metalMass(); // sum contains the total mass in metals
sum *= _fdust; // sum now contains the total mass in metals locked up in dust grains
return max(sum,0.); // guard against negative dust masses
}
//////////////////////////////////////////////////////////////////////
double SPHDustDistribution::SigmaX() const
{
const int NSAMPLES = 10000;
double sum = 0;
double xmin = _grid->xmin();
double xmax = _grid->xmax();
for (int k = 0; k < NSAMPLES; k++)
{
sum += density(Position(xmin + k*(xmax-xmin)/NSAMPLES, 0, 0));
}
return (sum/NSAMPLES)*(xmax-xmin);
}
//////////////////////////////////////////////////////////////////////
double SPHDustDistribution::SigmaY() const
{
const int NSAMPLES = 10000;
double sum = 0;
double ymin = _grid->ymin();
double ymax = _grid->ymax();
for (int k = 0; k < NSAMPLES; k++)
{
sum += density(Position(0, ymin + k*(ymax-ymin)/NSAMPLES, 0));
}
return (sum/NSAMPLES)*(ymax-ymin);
}
//////////////////////////////////////////////////////////////////////
double SPHDustDistribution::SigmaZ() const
{
const int NSAMPLES = 10000;
double sum = 0;
double zmin = _grid->zmin();
double zmax = _grid->zmax();
for (int k = 0; k < NSAMPLES; k++)
{
sum += density(Position(0, 0, zmin + k*(zmax-zmin)/NSAMPLES));
}
return (sum/NSAMPLES)*(zmax-zmin);
}
//////////////////////////////////////////////////////////////////////
int SPHDustDistribution::numParticles() const
{
return _pv.size();
}
//////////////////////////////////////////////////////////////////////
Vec SPHDustDistribution::particleCenter(int index) const
{
int n = _pv.size();
if (index<0 || index>=n) throw FATALERROR("Particle index out of range: " + QString::number(index));
return _pv[index].center();
}
//////////////////////////////////////////////////////////////////////
QList<SimulationItem*> SPHDustDistribution::interfaceCandidates(const type_info& interfaceTypeInfo)
{
if (interfaceTypeInfo == typeid(DustMassInBoxInterface) && _negativeMasses)
return QList<SimulationItem*>();
return DustDistribution::interfaceCandidates(interfaceTypeInfo);
}
//////////////////////////////////////////////////////////////////////
<|endoftext|> |
<commit_before>//
// OpenFlight loader for OpenSceneGraph
//
// Copyright (C) 2005-2006 Brede Johansen
//
#include <stdexcept>
#include <osg/Notify>
#include <osg/ProxyNode>
#include <osgDB/FileNameUtils>
#include <osgDB/FileUtils>
#include <osgDB/Registry>
#include <osgDB/ReadFile>
#include <osgDB/ReentrantMutex>
#include <osgUtil/Optimizer>
#include "Registry.h"
#include "Document.h"
#include "RecordInputStream.h"
#define SERIALIZER() OpenThreads::ScopedLock<osgDB::ReentrantMutex> lock(_serializerMutex)
using namespace flt;
using namespace osg;
using namespace osgDB;
class ReadExternalsVisitor : public osg::NodeVisitor
{
osg::ref_ptr<ReaderWriter::Options> _options;
public:
ReadExternalsVisitor(ReaderWriter::Options* options) :
osg::NodeVisitor(osg::NodeVisitor::TRAVERSE_ALL_CHILDREN),
_options(options)
{
}
virtual ~ReadExternalsVisitor() {}
virtual void apply(ProxyNode& node)
{
// Transfer ownership of pools.
_options->setUserData( node.getUserData() );
node.setUserData(NULL);
for (unsigned int pos=0; pos<node.getNumFileNames(); pos++)
{
std::string filename = node.getFileName(pos);
// read external
osg::Node* external = osgDB::readNodeFile(filename,_options.get());
if (external)
node.addChild(external);
}
}
};
class FLTReaderWriter : public ReaderWriter
{
public:
virtual const char* className() const { return "FLT Reader/Writer"; }
virtual bool acceptsExtension(const std::string& extension) const
{
return equalCaseInsensitive(extension,"flt");
}
virtual ReadResult readObject(const std::string& file, const Options* options) const
{
return readNode(file, options);
}
virtual ReadResult readNode(const std::string& file, const Options* options) const
{
SERIALIZER();
std::string ext = osgDB::getLowerCaseFileExtension(file);
if (!acceptsExtension(ext)) return ReadResult::FILE_NOT_HANDLED;
std::string fileName = osgDB::findDataFile(file, options);
if (fileName.empty()) return ReadResult::FILE_NOT_FOUND;
// in local cache?
{
osg::Node* node = flt::Registry::instance()->getFromLocalCache(fileName);
if (node)
return ReadResult(node, ReaderWriter::ReadResult::FILE_LOADED_FROM_CACHE);
}
// setting up the database path so that internally referenced file are searched for on relative paths.
osg::ref_ptr<Options> local_opt = options ? static_cast<Options*>(options->clone(osg::CopyOp::SHALLOW_COPY)) : new Options;
local_opt->setDatabasePath(osgDB::getFilePath(fileName));
ReadResult rr;
// read file
{
std::ifstream istream;
istream.imbue(std::locale::classic());
istream.open(fileName.c_str(), std::ios::in | std::ios::binary);
if (istream)
{
rr = readNode(istream,local_opt.get());
}
}
static int nestedExternalsLevel = 0;
if (rr.success())
{
// add to local cache.
flt::Registry::instance()->addToLocalCache(fileName,rr.getNode());
// read externals.
if (rr.getNode())
{
nestedExternalsLevel++;
ReadExternalsVisitor visitor(local_opt.get());
rr.getNode()->accept(visitor);
nestedExternalsLevel--;
}
}
// clear local cache.
if (nestedExternalsLevel==0)
flt::Registry::instance()->clearLocalCache();
return rr;
}
virtual ReadResult readObject(std::istream& fin, const Options* options) const
{
return readNode(fin, options);
}
virtual ReadResult readNode(std::istream& fin, const Options* options) const
{
Document document;
document.setOptions(options);
// option string and parent pools
if (options)
{
const char readerMsg[] = "flt reader option: ";
document.setPreserveFace((options->getOptionString().find("preserveFace")!=std::string::npos));
osg::notify(osg::DEBUG_INFO) << readerMsg << "preserveFace=" << document.getPreserveFace() << std::endl;
document.setDefaultDOFAnimationState((options->getOptionString().find("dofAnimation")!=std::string::npos));
osg::notify(osg::DEBUG_INFO) << readerMsg << "dofAnimation=" << document.getDefaultDOFAnimationState() << std::endl;
document.setUseTextureAlphaForTransparancyBinning(options->getOptionString().find("noTextureAlphaForTransparancyBinning")==std::string::npos);
osg::notify(osg::DEBUG_INFO) << readerMsg << "noTextureAlphaForTransparancyBinning=" << document.getUseTextureAlphaForTransparancyBinning() << std::endl;
document.setDoUnitsConversion((options->getOptionString().find("noUnitsConversion")==std::string::npos)); // default to true, unless noUnitsConversion is specified.
osg::notify(osg::DEBUG_INFO) << readerMsg << "noUnitsConversion=" << document.getDoUnitsConversion() << std::endl;
if (document.getDoUnitsConversion())
{
if (options->getOptionString().find("convertToFeet")!=std::string::npos)
document.setDesiredUnits(FEET);
else if (options->getOptionString().find("convertToInches")!=std::string::npos)
document.setDesiredUnits(INCHES);
else if (options->getOptionString().find("convertToMeters")!=std::string::npos)
document.setDesiredUnits(METERS);
else if (options->getOptionString().find("convertToKilometers")!=std::string::npos)
document.setDesiredUnits(KILOMETERS);
else if (options->getOptionString().find("convertToNauticalMiles")!=std::string::npos)
document.setDesiredUnits(NAUTICAL_MILES);
}
const ParentPools* pools = dynamic_cast<const ParentPools*>( options->getUserData() );
if (pools)
{
// This file is an external reference. The individual pools will
// be non-NULL if the parent is overriding the ext ref model's pools.
if (pools->getColorPool())
document.setColorPool( pools->getColorPool(), true );
if (pools->getTexturePool())
document.setTexturePool( pools->getTexturePool(), true );
if (pools->getMaterialPool())
document.setMaterialPool( pools->getMaterialPool(), true );
if (pools->getLPAppearancePool())
document.setLightPointAppearancePool( pools->getLPAppearancePool(), true );
if (pools->getShaderPool())
document.setShaderPool( pools->getShaderPool(), true );
}
}
{
// read records
flt::RecordInputStream recordStream(fin.rdbuf());
while (recordStream.good() && !document.done())
{
recordStream.readRecord(document);
}
}
if (!document.getHeaderNode())
return ReadResult::ERROR_IN_READING_FILE;
if (!document.getPreserveFace())
{
osgUtil::Optimizer optimizer;
optimizer.optimize(document.getHeaderNode(), osgUtil::Optimizer::SHARE_DUPLICATE_STATE | osgUtil::Optimizer::MERGE_GEOMETRY | osgUtil::Optimizer::MERGE_GEODES);
}
return document.getHeaderNode();
}
virtual WriteResult writeObject(const Object& object,const std::string& fileName, const osgDB::ReaderWriter::Options* options) const
{
const Node* node = dynamic_cast<const Node*>(&object);
if (node) return writeNode( *node, fileName, options );
return WriteResult::FILE_NOT_HANDLED;
}
virtual WriteResult writeNode(const Node& node,const std::string& fileName, const osgDB::ReaderWriter::Options* options) const
{
std::string ext = getFileExtension(fileName);
if (!acceptsExtension(ext)) return WriteResult::FILE_NOT_HANDLED;
// code for setting up the database path so that internally referenced file are searched for on relative paths.
osg::ref_ptr<Options> local_opt = options ? static_cast<Options*>(options->clone(osg::CopyOp::SHALLOW_COPY)) : new Options;
if(local_opt->getDatabasePathList().empty())
local_opt->setDatabasePath(osgDB::getFilePath(fileName));
std::ofstream fout(fileName.c_str(), std::ios::out | std::ios::binary);
WriteResult result = writeNode(node, fout, local_opt.get());
fout.close();
return result;
}
virtual WriteResult writeObject(const Object& object,std::ostream& fout, const osgDB::ReaderWriter::Options* options) const
{
const Node* node = dynamic_cast<const Node*>(&object);
if (node) return writeNode( *node, fout, options );
return WriteResult::FILE_NOT_HANDLED;
}
virtual WriteResult writeNode(const Node& /*node*/,std::ostream& /*fout*/, const osgDB::ReaderWriter::Options* /*options*/) const
{
return WriteResult::FILE_NOT_HANDLED;
}
protected:
mutable osgDB::ReentrantMutex _serializerMutex;
};
// now register with Registry to instantiate the above
// reader/writer.
RegisterReaderWriterProxy<FLTReaderWriter> g_FLTReaderWriterProxy;
<commit_msg>Added TESSELATE_GEOMETRY to Optimizer pass to fix z fighting issues.<commit_after>//
// OpenFlight loader for OpenSceneGraph
//
// Copyright (C) 2005-2006 Brede Johansen
//
#include <stdexcept>
#include <osg/Notify>
#include <osg/ProxyNode>
#include <osgDB/FileNameUtils>
#include <osgDB/FileUtils>
#include <osgDB/Registry>
#include <osgDB/ReadFile>
#include <osgDB/ReentrantMutex>
#include <osgUtil/Optimizer>
#include "Registry.h"
#include "Document.h"
#include "RecordInputStream.h"
#define SERIALIZER() OpenThreads::ScopedLock<osgDB::ReentrantMutex> lock(_serializerMutex)
using namespace flt;
using namespace osg;
using namespace osgDB;
class ReadExternalsVisitor : public osg::NodeVisitor
{
osg::ref_ptr<ReaderWriter::Options> _options;
public:
ReadExternalsVisitor(ReaderWriter::Options* options) :
osg::NodeVisitor(osg::NodeVisitor::TRAVERSE_ALL_CHILDREN),
_options(options)
{
}
virtual ~ReadExternalsVisitor() {}
virtual void apply(ProxyNode& node)
{
// Transfer ownership of pools.
_options->setUserData( node.getUserData() );
node.setUserData(NULL);
for (unsigned int pos=0; pos<node.getNumFileNames(); pos++)
{
std::string filename = node.getFileName(pos);
// read external
osg::Node* external = osgDB::readNodeFile(filename,_options.get());
if (external)
node.addChild(external);
}
}
};
class FLTReaderWriter : public ReaderWriter
{
public:
virtual const char* className() const { return "FLT Reader/Writer"; }
virtual bool acceptsExtension(const std::string& extension) const
{
return equalCaseInsensitive(extension,"flt");
}
virtual ReadResult readObject(const std::string& file, const Options* options) const
{
return readNode(file, options);
}
virtual ReadResult readNode(const std::string& file, const Options* options) const
{
SERIALIZER();
std::string ext = osgDB::getLowerCaseFileExtension(file);
if (!acceptsExtension(ext)) return ReadResult::FILE_NOT_HANDLED;
std::string fileName = osgDB::findDataFile(file, options);
if (fileName.empty()) return ReadResult::FILE_NOT_FOUND;
// in local cache?
{
osg::Node* node = flt::Registry::instance()->getFromLocalCache(fileName);
if (node)
return ReadResult(node, ReaderWriter::ReadResult::FILE_LOADED_FROM_CACHE);
}
// setting up the database path so that internally referenced file are searched for on relative paths.
osg::ref_ptr<Options> local_opt = options ? static_cast<Options*>(options->clone(osg::CopyOp::SHALLOW_COPY)) : new Options;
local_opt->setDatabasePath(osgDB::getFilePath(fileName));
ReadResult rr;
// read file
{
std::ifstream istream;
istream.imbue(std::locale::classic());
istream.open(fileName.c_str(), std::ios::in | std::ios::binary);
if (istream)
{
rr = readNode(istream,local_opt.get());
}
}
static int nestedExternalsLevel = 0;
if (rr.success())
{
// add to local cache.
flt::Registry::instance()->addToLocalCache(fileName,rr.getNode());
// read externals.
if (rr.getNode())
{
nestedExternalsLevel++;
ReadExternalsVisitor visitor(local_opt.get());
rr.getNode()->accept(visitor);
nestedExternalsLevel--;
}
}
// clear local cache.
if (nestedExternalsLevel==0)
flt::Registry::instance()->clearLocalCache();
return rr;
}
virtual ReadResult readObject(std::istream& fin, const Options* options) const
{
return readNode(fin, options);
}
virtual ReadResult readNode(std::istream& fin, const Options* options) const
{
Document document;
document.setOptions(options);
// option string and parent pools
if (options)
{
const char readerMsg[] = "flt reader option: ";
document.setPreserveFace((options->getOptionString().find("preserveFace")!=std::string::npos));
osg::notify(osg::DEBUG_INFO) << readerMsg << "preserveFace=" << document.getPreserveFace() << std::endl;
document.setDefaultDOFAnimationState((options->getOptionString().find("dofAnimation")!=std::string::npos));
osg::notify(osg::DEBUG_INFO) << readerMsg << "dofAnimation=" << document.getDefaultDOFAnimationState() << std::endl;
document.setUseTextureAlphaForTransparancyBinning(options->getOptionString().find("noTextureAlphaForTransparancyBinning")==std::string::npos);
osg::notify(osg::DEBUG_INFO) << readerMsg << "noTextureAlphaForTransparancyBinning=" << document.getUseTextureAlphaForTransparancyBinning() << std::endl;
document.setDoUnitsConversion((options->getOptionString().find("noUnitsConversion")==std::string::npos)); // default to true, unless noUnitsConversion is specified.
osg::notify(osg::DEBUG_INFO) << readerMsg << "noUnitsConversion=" << document.getDoUnitsConversion() << std::endl;
if (document.getDoUnitsConversion())
{
if (options->getOptionString().find("convertToFeet")!=std::string::npos)
document.setDesiredUnits(FEET);
else if (options->getOptionString().find("convertToInches")!=std::string::npos)
document.setDesiredUnits(INCHES);
else if (options->getOptionString().find("convertToMeters")!=std::string::npos)
document.setDesiredUnits(METERS);
else if (options->getOptionString().find("convertToKilometers")!=std::string::npos)
document.setDesiredUnits(KILOMETERS);
else if (options->getOptionString().find("convertToNauticalMiles")!=std::string::npos)
document.setDesiredUnits(NAUTICAL_MILES);
}
const ParentPools* pools = dynamic_cast<const ParentPools*>( options->getUserData() );
if (pools)
{
// This file is an external reference. The individual pools will
// be non-NULL if the parent is overriding the ext ref model's pools.
if (pools->getColorPool())
document.setColorPool( pools->getColorPool(), true );
if (pools->getTexturePool())
document.setTexturePool( pools->getTexturePool(), true );
if (pools->getMaterialPool())
document.setMaterialPool( pools->getMaterialPool(), true );
if (pools->getLPAppearancePool())
document.setLightPointAppearancePool( pools->getLPAppearancePool(), true );
if (pools->getShaderPool())
document.setShaderPool( pools->getShaderPool(), true );
}
}
{
// read records
flt::RecordInputStream recordStream(fin.rdbuf());
while (recordStream.good() && !document.done())
{
recordStream.readRecord(document);
}
}
if (!document.getHeaderNode())
return ReadResult::ERROR_IN_READING_FILE;
if (!document.getPreserveFace())
{
osgUtil::Optimizer optimizer;
optimizer.optimize(document.getHeaderNode(), osgUtil::Optimizer::SHARE_DUPLICATE_STATE | osgUtil::Optimizer::MERGE_GEOMETRY | osgUtil::Optimizer::MERGE_GEODES | osgUtil::Optimizer::TESSELATE_GEOMETRY );
}
return document.getHeaderNode();
}
virtual WriteResult writeObject(const Object& object,const std::string& fileName, const osgDB::ReaderWriter::Options* options) const
{
const Node* node = dynamic_cast<const Node*>(&object);
if (node) return writeNode( *node, fileName, options );
return WriteResult::FILE_NOT_HANDLED;
}
virtual WriteResult writeNode(const Node& node,const std::string& fileName, const osgDB::ReaderWriter::Options* options) const
{
std::string ext = getFileExtension(fileName);
if (!acceptsExtension(ext)) return WriteResult::FILE_NOT_HANDLED;
// code for setting up the database path so that internally referenced file are searched for on relative paths.
osg::ref_ptr<Options> local_opt = options ? static_cast<Options*>(options->clone(osg::CopyOp::SHALLOW_COPY)) : new Options;
if(local_opt->getDatabasePathList().empty())
local_opt->setDatabasePath(osgDB::getFilePath(fileName));
std::ofstream fout(fileName.c_str(), std::ios::out | std::ios::binary);
WriteResult result = writeNode(node, fout, local_opt.get());
fout.close();
return result;
}
virtual WriteResult writeObject(const Object& object,std::ostream& fout, const osgDB::ReaderWriter::Options* options) const
{
const Node* node = dynamic_cast<const Node*>(&object);
if (node) return writeNode( *node, fout, options );
return WriteResult::FILE_NOT_HANDLED;
}
virtual WriteResult writeNode(const Node& /*node*/,std::ostream& /*fout*/, const osgDB::ReaderWriter::Options* /*options*/) const
{
return WriteResult::FILE_NOT_HANDLED;
}
protected:
mutable osgDB::ReentrantMutex _serializerMutex;
};
// now register with Registry to instantiate the above
// reader/writer.
RegisterReaderWriterProxy<FLTReaderWriter> g_FLTReaderWriterProxy;
<|endoftext|> |
<commit_before>/* The MIT License (MIT)
Copyright (c) 2016 Sumwunn @ github.com
Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal 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 "stdafx.h"
#include <cstdlib>
#include <cerrno>
#include <string>
#include <iostream>
using namespace std;
#include "rapidjson/document.h"
#include "rapidjson/writer.h"
#include "rapidjson/stringbuffer.h"
#include "rapidjson/filereadstream.h"
using namespace rapidjson;
#include "curl_easy.h"
#include "curl_header.h"
#include "curl_pair.h"
#include "curl_exception.h"
using curl::curl_easy;
using curl::curl_header;
using curl::curl_pair;
using curl::curl_easy_exception;
// Has to be after curl or terrible compile error.
#include <windows.h>
#include <ShlObj.h>
#include "PlayerStatsAPI_FO4.h"
// Defined functions.
// C++
DWORD WINAPI GameSenseDataSender(LPVOID lpParam);
void PostJson(StringBuffer& Buffer, char* Address); // JSSSSSSOOOOOONNNNNNNNNNNN.
// Data we need across multiple functions here.
#define corePropsJsonBufferSize MAX_PATH
#define SSGS_ServerAddressBufferSize 64
char SSGS_corePropsJsonPath[MAX_PATH]; // SteelSeries Engine 3 ProgramData path.
char SSGS_corePropsJsonBuffer[corePropsJsonBufferSize]; // SteelSeries Engine 3 coreProps.json buffer.
char SSGS_ServerAddress[SSGS_ServerAddressBufferSize]; // SteelSeries Engine 3 GameSense server address.
char SSGS_ServerAddress_GameEvent[SSGS_ServerAddressBufferSize]; // Current game data gets sent here.
// INI Settings.
int bEnabled = TRUE;
int iUpdateInterval = 250;
int bConsoleLoggingEnabled = FALSE;
FILE *pConsole = NULL;
// Handles.
HANDLE GameSenseDataSender_hThread = NULL;
int Setup() {
//////// Setup Part 1 - INI ////////
// Setup INI.
PWSTR INIPathPTR = NULL;
TCHAR INIPath[MAX_PATH];
// Get paths.
SHGetKnownFolderPath(FOLDERID_Documents, NULL, NULL, &INIPathPTR);
_tcscpy_s(INIPath, MAX_PATH, INIPathPTR);
_tcscat_s(INIPath, MAX_PATH, L"\\My Games\\Fallout4\\SSGSPlugin_Fallout4.ini");
bEnabled = GetPrivateProfileInt(L"General", L"bEnabled", TRUE, INIPath);
iUpdateInterval = GetPrivateProfileInt(L"General", L"iUpdateInterval", 250, INIPath);
bConsoleLoggingEnabled = GetPrivateProfileInt(L"General", L"bConsoleLoggingEnabled", FALSE, INIPath);
// Am I enabled?
if (bEnabled == FALSE) {
// NOPE.
return 0;
}
// Enable logging via console.
if (bConsoleLoggingEnabled) {
AllocConsole();
SetConsoleTitle(L"SteelSeries GameSense Plugin Logging");
freopen_s(&pConsole, "CONOUT$", "r+", stdout);
}
//////// Setup Part 2 - Addresses ////////
// Get path to SteelSeries Engine 3's coreProps.json and grab the address from it.
GetEnvironmentVariableA("PROGRAMDATA", SSGS_corePropsJsonPath, MAX_PATH);
strcat_s(SSGS_corePropsJsonPath, MAX_PATH, "\\SteelSeries\\SteelSeries Engine 3\\coreProps.json");
// Grab address.
FILE* fp;
if (fopen_s(&fp, SSGS_corePropsJsonPath, "rb") != 0) {
// No coreProps.json?!
if (bConsoleLoggingEnabled) {
cout << "coreProps.json not found. Make sure GameSense is enabled." << endl;
}
return 0;
}
// Parse json.
FileReadStream is(fp, SSGS_corePropsJsonBuffer, corePropsJsonBufferSize);
Document d;
d.ParseStream(is);
strcpy_s(SSGS_ServerAddress, SSGS_ServerAddressBufferSize, d["address"].GetString());
fclose(fp);
// Setup multiple addresses.
// Game event.
strcpy_s(SSGS_ServerAddress_GameEvent, SSGS_ServerAddressBufferSize, SSGS_ServerAddress);
strcat_s(SSGS_ServerAddress_GameEvent, SSGS_ServerAddressBufferSize, "/game_event");
//////// Setup Part 3 - Hooks & Threads ////////
int Result = InstallHook();
if (Result == -1) {
if (bConsoleLoggingEnabled) {
cout << "Incorrect process detected." << endl;
return 0;
}
}
else if (Result == -2) {
if (bConsoleLoggingEnabled) {
cout << "Unsupported version detected." << endl;
return 0;
}
}
// Setup threads.
GameSenseDataSender_hThread = CreateThread(NULL, NULL, GameSenseDataSender, NULL, NULL, NULL);
return 0;
}
// Keeps SteelSeries Engine 3 GameSense server updated with game data.
DWORD WINAPI GameSenseDataSender(LPVOID lpParam) {
// Data.
const char* GameDataJson = "{\"game\":\"FALLOUT4\",\"event\":\"HEALTH\",\"data\":{\"value\":0}}";
const char* GameData2Json = "{\"game\":\"FALLOUT4\",\"event\":\"STAMINA\",\"data\":{\"value\":0}}";
const char* GameData3Json = "{\"game\":\"FALLOUT4\",\"event\":\"RADS\",\"data\":{\"value\":0}}";
const char* GameData4Json = "{\"game\":\"FALLOUT4\",\"event\":\"WEIGHT\",\"data\":{\"value\":0}}";
// Parsed JSON.
Document GameJsonParsed;
Document GameJson2Parsed;
Document GameJson3Parsed;
Document GameJson4Parsed;
// Processed JSON ready be posted.
StringBuffer Buffer;
// Current value.
int CurrentValue;
// Parse.
GameJsonParsed.Parse(GameDataJson);
GameJson2Parsed.Parse(GameData2Json);
GameJson3Parsed.Parse(GameData3Json);
GameJson4Parsed.Parse(GameData4Json);
// Infinite loop.
for (;;) {
Sleep(iUpdateInterval);
//////////////// -HEALTH- ////////////////
// In GameSense Interface: 0 = Dead, 100 = Good.
// Get current Health value and send it to GameSense server.
CurrentValue = PlayerStatsGetValue(1);
// If current value is negative, set to ZERO.
Value& STR = GameJsonParsed["data"]["value"]; // Points to HEALTH->Data->Value.
STR.SetInt(CurrentValue); // Set current Health.
// Stringify the DOM.
Writer<StringBuffer> writer(Buffer);
GameJsonParsed.Accept(writer);
// Post.
PostJson(Buffer, SSGS_ServerAddress_GameEvent);
// Cleanup.
Buffer.Clear();
//////////////// -STAMINA- ////////////////
// In GameSense Interface: 0 = None, 100 = Full.
// Get current Stamina value and send it to GameSense server.
CurrentValue = PlayerStatsGetValue(2);
// Get JSON ready.
Value& STR2 = GameJson2Parsed["data"]["value"]; // Points to STAMINA->Data->Value.
STR2.SetInt(CurrentValue); // Set current Stamina.
// Stringify the DOM.
Writer<StringBuffer> writer2(Buffer);
GameJson2Parsed.Accept(writer2);
// Post.
PostJson(Buffer, SSGS_ServerAddress_GameEvent);
// Cleanup.
Buffer.Clear();
//////////////// -RADS- ////////////////
// In GameSense Interface: 0 = No RADS, 100 = Max RADS.
// Get current RADS value and send it to GameSense server.
CurrentValue = PlayerStatsGetValue(3);
// Get JSON ready.
Value& STR3 = GameJson3Parsed["data"]["value"]; // Points to RADS->Data->Value.
STR3.SetInt(CurrentValue); // Set current RADS.
// Stringify the DOM.
Writer<StringBuffer> writer3(Buffer);
GameJson3Parsed.Accept(writer3);
// Post.
PostJson(Buffer, SSGS_ServerAddress_GameEvent);
// Cleanup.
Buffer.Clear();
//////////////// -WEIGHT- ////////////////
// In GameSense Interface: 0 = Over encumbered, 100+ = Plenty left.
// Get current WEIGHT difference and send it to GameSense server.
CurrentValue = PlayerStatsGetValue(4);
// Get JSON ready.
Value& STR4 = GameJson4Parsed["data"]["value"]; // Points to WEIGHT->Data->Value.
STR4.SetInt(CurrentValue); // Set current WEIGHT.
// Stringify the DOM.
Writer<StringBuffer> writer4(Buffer);
GameJson4Parsed.Accept(writer4);
// Post.
PostJson(Buffer, SSGS_ServerAddress_GameEvent);
// Cleanup.
Buffer.Clear();
}
return 0;
}
void PostJson(StringBuffer& Buffer, char* Address) {
curl_easy easy;
curl_header header;
header.add("Content-Type: application/json");
easy.add(curl_pair<CURLoption, curl_header>(CURLOPT_HTTPHEADER, header));
easy.add(curl_pair<CURLoption, string>(CURLOPT_URL, Address));
easy.add(curl_pair<CURLoption, string>(CURLOPT_POSTFIELDS, Buffer.GetString()));
try {
easy.perform();
}
catch (curl_easy_exception error) {
error.print_traceback();
}
return;
}<commit_msg>Fixed return typo.<commit_after>/* The MIT License (MIT)
Copyright (c) 2016 Sumwunn @ github.com
Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal 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 "stdafx.h"
#include <cstdlib>
#include <cerrno>
#include <string>
#include <iostream>
using namespace std;
#include "rapidjson/document.h"
#include "rapidjson/writer.h"
#include "rapidjson/stringbuffer.h"
#include "rapidjson/filereadstream.h"
using namespace rapidjson;
#include "curl_easy.h"
#include "curl_header.h"
#include "curl_pair.h"
#include "curl_exception.h"
using curl::curl_easy;
using curl::curl_header;
using curl::curl_pair;
using curl::curl_easy_exception;
// Has to be after curl or terrible compile error.
#include <windows.h>
#include <ShlObj.h>
#include "PlayerStatsAPI_FO4.h"
// Defined functions.
// C++
DWORD WINAPI GameSenseDataSender(LPVOID lpParam);
void PostJson(StringBuffer& Buffer, char* Address); // JSSSSSSOOOOOONNNNNNNNNNNN.
// Data we need across multiple functions here.
#define corePropsJsonBufferSize MAX_PATH
#define SSGS_ServerAddressBufferSize 64
char SSGS_corePropsJsonPath[MAX_PATH]; // SteelSeries Engine 3 ProgramData path.
char SSGS_corePropsJsonBuffer[corePropsJsonBufferSize]; // SteelSeries Engine 3 coreProps.json buffer.
char SSGS_ServerAddress[SSGS_ServerAddressBufferSize]; // SteelSeries Engine 3 GameSense server address.
char SSGS_ServerAddress_GameEvent[SSGS_ServerAddressBufferSize]; // Current game data gets sent here.
// INI Settings.
int bEnabled = TRUE;
int iUpdateInterval = 250;
int bConsoleLoggingEnabled = FALSE;
FILE *pConsole = NULL;
// Handles.
HANDLE GameSenseDataSender_hThread = NULL;
int Setup() {
//////// Setup Part 1 - INI ////////
// Setup INI.
PWSTR INIPathPTR = NULL;
TCHAR INIPath[MAX_PATH];
// Get paths.
SHGetKnownFolderPath(FOLDERID_Documents, NULL, NULL, &INIPathPTR);
_tcscpy_s(INIPath, MAX_PATH, INIPathPTR);
_tcscat_s(INIPath, MAX_PATH, L"\\My Games\\Fallout4\\SSGSPlugin_Fallout4.ini");
bEnabled = GetPrivateProfileInt(L"General", L"bEnabled", TRUE, INIPath);
iUpdateInterval = GetPrivateProfileInt(L"General", L"iUpdateInterval", 250, INIPath);
bConsoleLoggingEnabled = GetPrivateProfileInt(L"General", L"bConsoleLoggingEnabled", FALSE, INIPath);
// Am I enabled?
if (bEnabled == FALSE) {
// NOPE.
return 0;
}
// Enable logging via console.
if (bConsoleLoggingEnabled) {
AllocConsole();
SetConsoleTitle(L"SteelSeries GameSense Plugin Logging");
freopen_s(&pConsole, "CONOUT$", "r+", stdout);
}
//////// Setup Part 2 - Addresses ////////
// Get path to SteelSeries Engine 3's coreProps.json and grab the address from it.
GetEnvironmentVariableA("PROGRAMDATA", SSGS_corePropsJsonPath, MAX_PATH);
strcat_s(SSGS_corePropsJsonPath, MAX_PATH, "\\SteelSeries\\SteelSeries Engine 3\\coreProps.json");
// Grab address.
FILE* fp;
if (fopen_s(&fp, SSGS_corePropsJsonPath, "rb") != 0) {
// No coreProps.json?!
if (bConsoleLoggingEnabled) {
cout << "coreProps.json not found. Make sure GameSense is enabled." << endl;
}
return 0;
}
// Parse json.
FileReadStream is(fp, SSGS_corePropsJsonBuffer, corePropsJsonBufferSize);
Document d;
d.ParseStream(is);
strcpy_s(SSGS_ServerAddress, SSGS_ServerAddressBufferSize, d["address"].GetString());
fclose(fp);
// Setup multiple addresses.
// Game event.
strcpy_s(SSGS_ServerAddress_GameEvent, SSGS_ServerAddressBufferSize, SSGS_ServerAddress);
strcat_s(SSGS_ServerAddress_GameEvent, SSGS_ServerAddressBufferSize, "/game_event");
//////// Setup Part 3 - Hooks & Threads ////////
int Result = InstallHook();
if (Result == -1) {
if (bConsoleLoggingEnabled) {
cout << "Incorrect process detected." << endl;
}
return 0;
}
else if (Result == -2) {
if (bConsoleLoggingEnabled) {
cout << "Unsupported version detected." << endl;
}
return 0;
}
// Setup threads.
GameSenseDataSender_hThread = CreateThread(NULL, NULL, GameSenseDataSender, NULL, NULL, NULL);
return 0;
}
// Keeps SteelSeries Engine 3 GameSense server updated with game data.
DWORD WINAPI GameSenseDataSender(LPVOID lpParam) {
// Data.
const char* GameDataJson = "{\"game\":\"FALLOUT4\",\"event\":\"HEALTH\",\"data\":{\"value\":0}}";
const char* GameData2Json = "{\"game\":\"FALLOUT4\",\"event\":\"STAMINA\",\"data\":{\"value\":0}}";
const char* GameData3Json = "{\"game\":\"FALLOUT4\",\"event\":\"RADS\",\"data\":{\"value\":0}}";
const char* GameData4Json = "{\"game\":\"FALLOUT4\",\"event\":\"WEIGHT\",\"data\":{\"value\":0}}";
// Parsed JSON.
Document GameJsonParsed;
Document GameJson2Parsed;
Document GameJson3Parsed;
Document GameJson4Parsed;
// Processed JSON ready be posted.
StringBuffer Buffer;
// Current value.
int CurrentValue;
// Parse.
GameJsonParsed.Parse(GameDataJson);
GameJson2Parsed.Parse(GameData2Json);
GameJson3Parsed.Parse(GameData3Json);
GameJson4Parsed.Parse(GameData4Json);
// Infinite loop.
for (;;) {
Sleep(iUpdateInterval);
//////////////// -HEALTH- ////////////////
// In GameSense Interface: 0 = Dead, 100 = Good.
// Get current Health value and send it to GameSense server.
CurrentValue = PlayerStatsGetValue(1);
// If current value is negative, set to ZERO.
Value& STR = GameJsonParsed["data"]["value"]; // Points to HEALTH->Data->Value.
STR.SetInt(CurrentValue); // Set current Health.
// Stringify the DOM.
Writer<StringBuffer> writer(Buffer);
GameJsonParsed.Accept(writer);
// Post.
PostJson(Buffer, SSGS_ServerAddress_GameEvent);
// Cleanup.
Buffer.Clear();
//////////////// -STAMINA- ////////////////
// In GameSense Interface: 0 = None, 100 = Full.
// Get current Stamina value and send it to GameSense server.
CurrentValue = PlayerStatsGetValue(2);
// Get JSON ready.
Value& STR2 = GameJson2Parsed["data"]["value"]; // Points to STAMINA->Data->Value.
STR2.SetInt(CurrentValue); // Set current Stamina.
// Stringify the DOM.
Writer<StringBuffer> writer2(Buffer);
GameJson2Parsed.Accept(writer2);
// Post.
PostJson(Buffer, SSGS_ServerAddress_GameEvent);
// Cleanup.
Buffer.Clear();
//////////////// -RADS- ////////////////
// In GameSense Interface: 0 = No RADS, 100 = Max RADS.
// Get current RADS value and send it to GameSense server.
CurrentValue = PlayerStatsGetValue(3);
// Get JSON ready.
Value& STR3 = GameJson3Parsed["data"]["value"]; // Points to RADS->Data->Value.
STR3.SetInt(CurrentValue); // Set current RADS.
// Stringify the DOM.
Writer<StringBuffer> writer3(Buffer);
GameJson3Parsed.Accept(writer3);
// Post.
PostJson(Buffer, SSGS_ServerAddress_GameEvent);
// Cleanup.
Buffer.Clear();
//////////////// -WEIGHT- ////////////////
// In GameSense Interface: 0 = Over encumbered, 100+ = Plenty left.
// Get current WEIGHT difference and send it to GameSense server.
CurrentValue = PlayerStatsGetValue(4);
// Get JSON ready.
Value& STR4 = GameJson4Parsed["data"]["value"]; // Points to WEIGHT->Data->Value.
STR4.SetInt(CurrentValue); // Set current WEIGHT.
// Stringify the DOM.
Writer<StringBuffer> writer4(Buffer);
GameJson4Parsed.Accept(writer4);
// Post.
PostJson(Buffer, SSGS_ServerAddress_GameEvent);
// Cleanup.
Buffer.Clear();
}
return 0;
}
void PostJson(StringBuffer& Buffer, char* Address) {
curl_easy easy;
curl_header header;
header.add("Content-Type: application/json");
easy.add(curl_pair<CURLoption, curl_header>(CURLOPT_HTTPHEADER, header));
easy.add(curl_pair<CURLoption, string>(CURLOPT_URL, Address));
easy.add(curl_pair<CURLoption, string>(CURLOPT_POSTFIELDS, Buffer.GetString()));
try {
easy.perform();
}
catch (curl_easy_exception error) {
error.print_traceback();
}
return;
}<|endoftext|> |
<commit_before>/*****************************************************************************
* Media Library
*****************************************************************************
* Copyright (C) 2022 Hugo Beauzée-Luyssen, Videolabs, VideoLAN
*
* 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.
*****************************************************************************/
#ifdef HAVE_CONFIG_H
# include "config.h"
#endif
#include "Service.h"
#include "Subscription.h"
#include "parser/Task.h"
namespace medialibrary
{
const std::string Service::Table::Name = "Service";
const std::string Service::Table::PrimaryKeyColumn = "id_service";
int64_t Service::*const Service::Table::PrimaryKey = &Service::m_id;
Service::Service( MediaLibraryPtr ml, sqlite::Row& row )
: m_ml( ml )
, m_id( row.extract<decltype(m_id)>() )
, m_autoDownload( row.extract<decltype(m_autoDownload)>() )
, m_newMediaNotif( row.extract<decltype(m_newMediaNotif)>() )
, m_maxCacheSize( row.extract<decltype(m_maxCacheSize)>() )
, m_nbSubscriptions( row.extract<decltype(m_nbSubscriptions)>() )
, m_nbUnplayedMedia( row.extract<decltype(m_nbUnplayedMedia)>() )
{
assert( row.hasRemainingColumns() == false );
}
Service::Service( MediaLibraryPtr ml, Type type )
: m_ml( ml )
, m_id( static_cast<std::underlying_type_t<Type>>( type ) )
, m_autoDownload( true )
, m_newMediaNotif( true )
, m_maxCacheSize( -1 )
, m_nbSubscriptions( 0 )
, m_nbUnplayedMedia( 0 )
{
}
Service::Type Service::type() const
{
return static_cast<Type>( m_id );
}
bool Service::addSubscription( std::string mrl )
{
auto t = parser::Task::create( m_ml, std::move( mrl ), type() );
if ( t == nullptr )
return false;
++m_nbSubscriptions;
auto parser = m_ml->getParser();
if ( parser == nullptr )
return false;
parser->parse( std::move( t ) );
return true;
}
Query<ISubscription> Service::subscriptions( const QueryParameters* params ) const
{
return Subscription::fromService( m_ml, type(), params );
}
bool Service::isAutoDownloadEnabled() const
{
return m_autoDownload;
}
bool Service::setAutoDownloadEnabled( bool enabled )
{
if ( m_autoDownload == enabled )
return true;
const std::string req = "UPDATE " + Table::Name +
" SET auto_download = ? WHERE id_service = ?";
if ( sqlite::Tools::executeUpdate( m_ml->getConn(), req, enabled, m_id ) == false )
return false;
m_autoDownload = enabled;
return true;
}
bool Service::isNewMediaNotificationEnabled() const
{
return m_newMediaNotif;
}
bool Service::setNewMediaNotificationEnabled( bool enabled )
{
if ( m_newMediaNotif == enabled )
return true;
const std::string req = "UPDATE " + Table::Name +
" SET notify = ? WHERE id_service = ?";
if ( sqlite::Tools::executeUpdate( m_ml->getConn(), req, enabled, m_id ) == false )
return false;
m_newMediaNotif = enabled;
return true;
}
int64_t Service::maxCachedSize() const
{
return m_maxCacheSize;
}
bool Service::setMaxCachedSize( int64_t maxSize )
{
if ( maxSize < 0 )
maxSize = -1;
if ( m_maxCacheSize == maxSize )
return true;
const std::string req = "UPDATE " + Table::Name +
" SET max_cached_size = ? WHERE id_service = ?";
if ( sqlite::Tools::executeUpdate( m_ml->getConn(), req, maxSize, m_id ) == false )
return false;
m_maxCacheSize = maxSize;
return true;
}
uint32_t Service::nbSubscriptions() const
{
return m_nbSubscriptions;
}
uint32_t Service::nbUnplayedMedia() const
{
return m_nbUnplayedMedia;
}
std::string Service::schema( const std::string& name, uint32_t dbModel )
{
UNUSED_IN_RELEASE( name );
UNUSED_IN_RELEASE( dbModel );
assert( dbModel >= 37 );
assert( name == Table::Name );
return "CREATE TABLE " + Table::Name +
"("
+ Table::PrimaryKeyColumn + " UNSIGNED INTEGER PRIMARY KEY,"
"auto_download BOOLEAN NOT NULL DEFAULT 1,"
"notify BOOLEAN NOT NULL DEFAULT 1,"
"max_cached_size INTEGER NOT NULL DEFAULT -1,"
"nb_subscriptions INTEGER NOT NULL DEFAULT 0,"
"unplayed_media INTEGER NOT NULL DEFAULT 0"
")";
}
void Service::createTable( sqlite::Connection* dbConn )
{
sqlite::Tools::executeRequest( dbConn,
schema( Table::Name, Settings::DbModelVersion ) );
}
void Service::createTriggers( sqlite::Connection* dbConn )
{
sqlite::Tools::executeRequest( dbConn,
trigger( Triggers::IncrementNbSubscriptions, Settings::DbModelVersion ) );
sqlite::Tools::executeRequest( dbConn,
trigger( Triggers::DecrementNbSubscriptions, Settings::DbModelVersion ) );
sqlite::Tools::executeRequest( dbConn,
trigger( Triggers::UpdateUnplayedMedia, Settings::DbModelVersion ) );
sqlite::Tools::executeRequest( dbConn,
trigger( Triggers::DecrementUnplayedMediaOnSubRemoval, Settings::DbModelVersion ) );
}
bool Service::checkDbModel( MediaLibraryPtr ml )
{
OPEN_READ_CONTEXT( ctx, ml->getConn() );
auto checkTrigger = []( Triggers t ) {
return sqlite::Tools::checkTriggerStatement(
trigger( t, Settings::DbModelVersion ),
triggerName( t, Settings::DbModelVersion ) );
};
return sqlite::Tools::checkTableSchema(
schema( Table::Name, Settings::DbModelVersion ), Table::Name ) &&
checkTrigger( Triggers::IncrementNbSubscriptions ) &&
checkTrigger( Triggers::DecrementNbSubscriptions ) &&
checkTrigger( Triggers::UpdateUnplayedMedia ) &&
checkTrigger( Triggers::DecrementUnplayedMediaOnSubRemoval );
}
std::string Service::trigger( Triggers t, uint32_t dbModel )
{
UNUSED_IN_RELEASE( dbModel );
assert( dbModel >= 37 );
switch ( t )
{
case Triggers::IncrementNbSubscriptions:
return "CREATE TRIGGER " + triggerName( t, dbModel ) +
" AFTER INSERT ON " + Subscription::Table::Name +
" BEGIN"
" UPDATE " + Table::Name +
" SET nb_subscriptions = nb_subscriptions + 1"
" WHERE " + Table::PrimaryKeyColumn + " = new.service_id;"
" END";
case Triggers::DecrementNbSubscriptions:
return "CREATE TRIGGER " + triggerName( t, dbModel ) +
" AFTER DELETE ON " + Subscription::Table::Name +
" BEGIN"
" UPDATE " + Table::Name +
" SET nb_subscriptions = nb_subscriptions - 1"
" WHERE " + Table::PrimaryKeyColumn + " = old.service_id;"
" END";
case Triggers::UpdateUnplayedMedia:
return "CREATE TRIGGER " + triggerName( t, dbModel ) +
" AFTER UPDATE OF unplayed_media ON " + Subscription::Table::Name +
" WHEN old.unplayed_media != new.unplayed_media"
" BEGIN"
" UPDATE " + Table::Name +
" SET unplayed_media = unplayed_media + "
"(new.unplayed_media - old.unplayed_media)"
" WHERE " + Table::PrimaryKeyColumn + " = new.service_id;"
" END";
case Triggers::DecrementUnplayedMediaOnSubRemoval:
return "CREATE TRIGGER " + triggerName( t, dbModel ) +
" AFTER DELETE ON " + Subscription::Table::Name +
" WHEN old.unplayed_media > 0"
" BEGIN"
" UPDATE " + Table::Name +
" SET unplayed_media = unplayed_media - old.unplayed_media"
" WHERE " + Table::PrimaryKeyColumn + " = old.service_id;"
" END";
default:
assert( !"Invalid trigger provided" );
}
return "<invalid trigger>";
}
std::string Service::triggerName( Triggers t, uint32_t dbModel )
{
UNUSED_IN_RELEASE( dbModel );
assert( dbModel >= 37 );
switch ( t )
{
case Triggers::IncrementNbSubscriptions:
return "service_increment_nb_subs";
case Triggers::DecrementNbSubscriptions:
return "service_decrement_nb_subs";
case Triggers::UpdateUnplayedMedia:
return "service_update_unplayed_media";
case Triggers::DecrementUnplayedMediaOnSubRemoval:
return "service_decrement_unplayed_media_sub_removal";
default:
assert( !"Invalid trigger provided" );
}
return "<invalid trigger>";
}
std::shared_ptr<Service> Service::create( MediaLibraryPtr ml, Type type )
{
auto self = std::make_shared<Service>( ml, type );
const std::string req = "INSERT INTO " + Table::Name + " ("
+ Table::PrimaryKeyColumn + ") VALUES(?)";
if ( insert( ml, self, req, type ) == false )
return nullptr;
return self;
}
std::shared_ptr<Service> Service::fetch( MediaLibraryPtr ml, Type type )
{
auto s = DatabaseHelpers<Service>::fetch( ml,
static_cast<std::underlying_type_t<IService::Type>>( type ) );
if ( s == nullptr )
s = create( ml, type );
return s;
}
}
<commit_msg>Service: Unsign `unplayed_media` in the model<commit_after>/*****************************************************************************
* Media Library
*****************************************************************************
* Copyright (C) 2022 Hugo Beauzée-Luyssen, Videolabs, VideoLAN
*
* 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.
*****************************************************************************/
#ifdef HAVE_CONFIG_H
# include "config.h"
#endif
#include "Service.h"
#include "Subscription.h"
#include "parser/Task.h"
namespace medialibrary
{
const std::string Service::Table::Name = "Service";
const std::string Service::Table::PrimaryKeyColumn = "id_service";
int64_t Service::*const Service::Table::PrimaryKey = &Service::m_id;
Service::Service( MediaLibraryPtr ml, sqlite::Row& row )
: m_ml( ml )
, m_id( row.extract<decltype(m_id)>() )
, m_autoDownload( row.extract<decltype(m_autoDownload)>() )
, m_newMediaNotif( row.extract<decltype(m_newMediaNotif)>() )
, m_maxCacheSize( row.extract<decltype(m_maxCacheSize)>() )
, m_nbSubscriptions( row.extract<decltype(m_nbSubscriptions)>() )
, m_nbUnplayedMedia( row.extract<decltype(m_nbUnplayedMedia)>() )
{
assert( row.hasRemainingColumns() == false );
}
Service::Service( MediaLibraryPtr ml, Type type )
: m_ml( ml )
, m_id( static_cast<std::underlying_type_t<Type>>( type ) )
, m_autoDownload( true )
, m_newMediaNotif( true )
, m_maxCacheSize( -1 )
, m_nbSubscriptions( 0 )
, m_nbUnplayedMedia( 0 )
{
}
Service::Type Service::type() const
{
return static_cast<Type>( m_id );
}
bool Service::addSubscription( std::string mrl )
{
auto t = parser::Task::create( m_ml, std::move( mrl ), type() );
if ( t == nullptr )
return false;
++m_nbSubscriptions;
auto parser = m_ml->getParser();
if ( parser == nullptr )
return false;
parser->parse( std::move( t ) );
return true;
}
Query<ISubscription> Service::subscriptions( const QueryParameters* params ) const
{
return Subscription::fromService( m_ml, type(), params );
}
bool Service::isAutoDownloadEnabled() const
{
return m_autoDownload;
}
bool Service::setAutoDownloadEnabled( bool enabled )
{
if ( m_autoDownload == enabled )
return true;
const std::string req = "UPDATE " + Table::Name +
" SET auto_download = ? WHERE id_service = ?";
if ( sqlite::Tools::executeUpdate( m_ml->getConn(), req, enabled, m_id ) == false )
return false;
m_autoDownload = enabled;
return true;
}
bool Service::isNewMediaNotificationEnabled() const
{
return m_newMediaNotif;
}
bool Service::setNewMediaNotificationEnabled( bool enabled )
{
if ( m_newMediaNotif == enabled )
return true;
const std::string req = "UPDATE " + Table::Name +
" SET notify = ? WHERE id_service = ?";
if ( sqlite::Tools::executeUpdate( m_ml->getConn(), req, enabled, m_id ) == false )
return false;
m_newMediaNotif = enabled;
return true;
}
int64_t Service::maxCachedSize() const
{
return m_maxCacheSize;
}
bool Service::setMaxCachedSize( int64_t maxSize )
{
if ( maxSize < 0 )
maxSize = -1;
if ( m_maxCacheSize == maxSize )
return true;
const std::string req = "UPDATE " + Table::Name +
" SET max_cached_size = ? WHERE id_service = ?";
if ( sqlite::Tools::executeUpdate( m_ml->getConn(), req, maxSize, m_id ) == false )
return false;
m_maxCacheSize = maxSize;
return true;
}
uint32_t Service::nbSubscriptions() const
{
return m_nbSubscriptions;
}
uint32_t Service::nbUnplayedMedia() const
{
return m_nbUnplayedMedia;
}
std::string Service::schema( const std::string& name, uint32_t dbModel )
{
UNUSED_IN_RELEASE( name );
UNUSED_IN_RELEASE( dbModel );
assert( dbModel >= 37 );
assert( name == Table::Name );
return "CREATE TABLE " + Table::Name +
"("
+ Table::PrimaryKeyColumn + " UNSIGNED INTEGER PRIMARY KEY,"
"auto_download BOOLEAN NOT NULL DEFAULT 1,"
"notify BOOLEAN NOT NULL DEFAULT 1,"
"max_cached_size INTEGER NOT NULL DEFAULT -1,"
"nb_subscriptions INTEGER NOT NULL DEFAULT 0,"
"unplayed_media UNSIGNED INTEGER NOT NULL DEFAULT 0"
")";
}
void Service::createTable( sqlite::Connection* dbConn )
{
sqlite::Tools::executeRequest( dbConn,
schema( Table::Name, Settings::DbModelVersion ) );
}
void Service::createTriggers( sqlite::Connection* dbConn )
{
sqlite::Tools::executeRequest( dbConn,
trigger( Triggers::IncrementNbSubscriptions, Settings::DbModelVersion ) );
sqlite::Tools::executeRequest( dbConn,
trigger( Triggers::DecrementNbSubscriptions, Settings::DbModelVersion ) );
sqlite::Tools::executeRequest( dbConn,
trigger( Triggers::UpdateUnplayedMedia, Settings::DbModelVersion ) );
sqlite::Tools::executeRequest( dbConn,
trigger( Triggers::DecrementUnplayedMediaOnSubRemoval, Settings::DbModelVersion ) );
}
bool Service::checkDbModel( MediaLibraryPtr ml )
{
OPEN_READ_CONTEXT( ctx, ml->getConn() );
auto checkTrigger = []( Triggers t ) {
return sqlite::Tools::checkTriggerStatement(
trigger( t, Settings::DbModelVersion ),
triggerName( t, Settings::DbModelVersion ) );
};
return sqlite::Tools::checkTableSchema(
schema( Table::Name, Settings::DbModelVersion ), Table::Name ) &&
checkTrigger( Triggers::IncrementNbSubscriptions ) &&
checkTrigger( Triggers::DecrementNbSubscriptions ) &&
checkTrigger( Triggers::UpdateUnplayedMedia ) &&
checkTrigger( Triggers::DecrementUnplayedMediaOnSubRemoval );
}
std::string Service::trigger( Triggers t, uint32_t dbModel )
{
UNUSED_IN_RELEASE( dbModel );
assert( dbModel >= 37 );
switch ( t )
{
case Triggers::IncrementNbSubscriptions:
return "CREATE TRIGGER " + triggerName( t, dbModel ) +
" AFTER INSERT ON " + Subscription::Table::Name +
" BEGIN"
" UPDATE " + Table::Name +
" SET nb_subscriptions = nb_subscriptions + 1"
" WHERE " + Table::PrimaryKeyColumn + " = new.service_id;"
" END";
case Triggers::DecrementNbSubscriptions:
return "CREATE TRIGGER " + triggerName( t, dbModel ) +
" AFTER DELETE ON " + Subscription::Table::Name +
" BEGIN"
" UPDATE " + Table::Name +
" SET nb_subscriptions = nb_subscriptions - 1"
" WHERE " + Table::PrimaryKeyColumn + " = old.service_id;"
" END";
case Triggers::UpdateUnplayedMedia:
return "CREATE TRIGGER " + triggerName( t, dbModel ) +
" AFTER UPDATE OF unplayed_media ON " + Subscription::Table::Name +
" WHEN old.unplayed_media != new.unplayed_media"
" BEGIN"
" UPDATE " + Table::Name +
" SET unplayed_media = unplayed_media + "
"(new.unplayed_media - old.unplayed_media)"
" WHERE " + Table::PrimaryKeyColumn + " = new.service_id;"
" END";
case Triggers::DecrementUnplayedMediaOnSubRemoval:
return "CREATE TRIGGER " + triggerName( t, dbModel ) +
" AFTER DELETE ON " + Subscription::Table::Name +
" WHEN old.unplayed_media > 0"
" BEGIN"
" UPDATE " + Table::Name +
" SET unplayed_media = unplayed_media - old.unplayed_media"
" WHERE " + Table::PrimaryKeyColumn + " = old.service_id;"
" END";
default:
assert( !"Invalid trigger provided" );
}
return "<invalid trigger>";
}
std::string Service::triggerName( Triggers t, uint32_t dbModel )
{
UNUSED_IN_RELEASE( dbModel );
assert( dbModel >= 37 );
switch ( t )
{
case Triggers::IncrementNbSubscriptions:
return "service_increment_nb_subs";
case Triggers::DecrementNbSubscriptions:
return "service_decrement_nb_subs";
case Triggers::UpdateUnplayedMedia:
return "service_update_unplayed_media";
case Triggers::DecrementUnplayedMediaOnSubRemoval:
return "service_decrement_unplayed_media_sub_removal";
default:
assert( !"Invalid trigger provided" );
}
return "<invalid trigger>";
}
std::shared_ptr<Service> Service::create( MediaLibraryPtr ml, Type type )
{
auto self = std::make_shared<Service>( ml, type );
const std::string req = "INSERT INTO " + Table::Name + " ("
+ Table::PrimaryKeyColumn + ") VALUES(?)";
if ( insert( ml, self, req, type ) == false )
return nullptr;
return self;
}
std::shared_ptr<Service> Service::fetch( MediaLibraryPtr ml, Type type )
{
auto s = DatabaseHelpers<Service>::fetch( ml,
static_cast<std::underlying_type_t<IService::Type>>( type ) );
if ( s == nullptr )
s = create( ml, type );
return s;
}
}
<|endoftext|> |
<commit_before>/*
Copyright (c) 2012 Daniele Bartolini, Simone Boscaratto
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 "Terrain.h"
#include "MeshChunk.h"
#include "Device.h"
#include "Renderer.h"
#include "MathUtils.h"
#include <GL/glew.h>
#include "Log.h"
#include <cstdio>
#include "Vec2.h"
#include "Interpolation.h"
#include "BMPImageLoader.h"
#include <cmath>
namespace Crown
{
Terrain::Terrain() :
mHeights(NULL),
mVertices(NULL),
mNormals(NULL),
mTexCoords(NULL),
mIndices(NULL),
mMinHeight(-10.0f),
mMaxHeight(10.0f)
{
}
Terrain::~Terrain()
{
if (mHeights != NULL)
{
delete[] mHeights;
}
delete[] mVertices;
delete[] mNormals;
delete[] mTexCoords;
delete[] mIndices;
}
void Terrain::CreateTerrain(uint xSize, uint zSize, uint tilePerMeter, float initialHeight)
{
assert(xSize > 0);
assert(zSize > 0);
assert(tilePerMeter > 0);
mSizeX = xSize;
mSizeZ = zSize;
mTilePerMeter = tilePerMeter;
float tileStep = +(float)mSizeX / ((float)mSizeX * (float)mTilePerMeter); // Tile step is the same for both x and z ;)
mTilesInSizeX = ((float)mSizeX / tileStep);
mTilesInSizeZ = ((float)mSizeZ / tileStep);
mVerticesInSizeX = mTilesInSizeX + 1;
mVerticesInSizeZ = mTilesInSizeZ + 1;
printf("Vertices in size x/z: %d %d\n", mVerticesInSizeX, mVerticesInSizeZ);
uint heightsCount = mVerticesInSizeX * mVerticesInSizeZ;
mHeights = new float[heightsCount];
// Init heights
for (uint i = 0; i < heightsCount; i++)
{
mHeights[i] = initialHeight;
}
// Construct drawing data
mVertices = new Vec3[heightsCount]; // There are as many vertices as heights
mVertexCount = heightsCount;
mNormals = new Vec3[heightsCount]; // Same as vertices
mNormalCount = heightsCount;
mTexCoords = new Vec2[heightsCount]; // Same as vertices
mTexCoordCount = heightsCount;
mIndices = new ushort[mTilesInSizeX * mTilesInSizeZ * 6]; //
mIndexCount = mTilesInSizeX * mTilesInSizeZ * 6;
// Populate vertex list (generate a grid lying on the xz-plane and facing upwards)
float xStart = -(float)mSizeX * 0.5f;
float zStart = +(float)mSizeZ * 0.5f;
mOffsetX = xStart;
mOffsetZ = zStart;
uint vIndex = 0; // Just because I'm lazy
float xCurrent; // Keeps track of current x position
float zCurrent = zStart; // Keeps track of current z position
for (uint z = 0; z < mVerticesInSizeZ; z++)
{
xCurrent = xStart;
for (uint x = 0; x < mVerticesInSizeX; x++)
{
mVertices[vIndex].x = xCurrent;
mVertices[vIndex].y = mHeights[vIndex];
mVertices[vIndex].z = zCurrent;
mNormals[vIndex].x = 0.0f;
mNormals[vIndex].y = 1.0f;
mNormals[vIndex].z = 0.0f;
mTexCoords[vIndex].x = (float)x;
mTexCoords[vIndex].y = (float)z;
vIndex++;
xCurrent += tileStep;
}
zCurrent -= tileStep;
}
// Populate index list
uint iIndex = 0;
for (uint z = 0; z < mTilesInSizeZ; z++)
{
for (uint x = 0; x < mTilesInSizeX; x++)
{
uint firstRow = z * mVerticesInSizeX + x;
uint secondRow = (z + 1) * mVerticesInSizeX + x;
mIndices[iIndex + 0] = firstRow;
mIndices[iIndex + 1] = secondRow + 1;
mIndices[iIndex + 2] = secondRow;
mIndices[iIndex + 3] = firstRow;
mIndices[iIndex + 4] = firstRow + 1;
mIndices[iIndex + 5] = secondRow + 1;
iIndex += 6;
}
}
}
void Terrain::UpdateVertexBuffer(bool recomputeNormals)
{
uint vIndex = 0;
for (uint z = 0; z < mVerticesInSizeZ; z++)
{
for (uint x = 0; x < mVerticesInSizeX; x++)
{
mVertices[vIndex].y = mHeights[vIndex];
vIndex++;
}
}
if (recomputeNormals)
{
for (uint i = 0; i < mIndexCount; i += 3)
{
Vec3 normal;
Vec3 v1;
Vec3 v2;
v1 = mVertices[mIndices[i + 0]] - mVertices[mIndices[i + 1]];
v2 = mVertices[mIndices[i + 2]] - mVertices[mIndices[i + 1]];
normal = v2.Cross(v1).Normalize();
mNormals[mIndices[i + 0]] = normal;
mNormals[mIndices[i + 1]] = normal;
mNormals[mIndices[i + 2]] = normal;
}
}
}
float Terrain::GetHeightAt(uint x, uint z) const
{
if (x > mVerticesInSizeX) return 0.0f;
if (z > mVerticesInSizeZ) return 0.0f;
return mHeights[z * mVerticesInSizeX + x];
}
float Terrain::GetHeightAt(const Vec3& xyz) const
{
uint x, z;
WorldToHeight(xyz, x, z);
return GetHeightAt(x, z);
}
void Terrain::SetHeightAt(uint x, uint z, float height)
{
if (x >= mVerticesInSizeX) return;
if (z >= mVerticesInSizeZ) return;
mHeights[z * mVerticesInSizeX + x] += height;
mHeights[z * mVerticesInSizeX + x] = Math::ClampToRange(mMinHeight, mMaxHeight, mHeights[z * mVerticesInSizeX + x]);
}
void Terrain::SetHeightAt(const Vec3& xyz, float height)
{
uint x, z;
WorldToHeight(xyz, x, z);
SetHeightAt(x + 0, z + 0, height);
}
void Terrain::WorldToHeight(const Vec3& xyz, uint& x, uint& z) const
{
Vec3 offsetted = xyz + Vec3(-mOffsetX, 0.0f, mOffsetZ);
offsetted.z = (float)mSizeZ - offsetted.z;
x = (uint)offsetted.x;
z = (uint)offsetted.z;
}
bool Terrain::TraceRay(const Ray& ray, Triangle& result, Triangle& tri2, real& dist)
{
bool hit = false;
real minDist = 9999999.0f;
for (uint i = 0; i < mIndexCount; i += 3)
{
Triangle tri;
tri.v1 = mVertices[mIndices[i + 0]];
tri.v2 = mVertices[mIndices[i + 1]];
tri.v3 = mVertices[mIndices[i + 2]];
real ret;
Vec3 intersectionPoint;
if (Intersection::TestRayTriangle(ray, tri, ret, intersectionPoint))
{
if (ret < minDist)
{
minDist = ret;
result = tri;
}
hit = true;
}
}
dist = minDist;
return hit;
}
uint Terrain::SnapToGrid(const Vec3& vertex)
{
float minDist = 9999999.0f;
uint indexToSnapped;
// Find the snapped point to input vertex
for (int i = 0; i < mVertexCount; i++)
{
Vec3 tmp = mVertices[i];
Vec3 vertex2 = vertex;
tmp.y = vertex2.y = 0.0f;
if (tmp.GetDistanceTo(vertex2) < minDist)
{
indexToSnapped = i;
minDist = tmp.GetDistanceTo(vertex2);
}
}
return indexToSnapped;
}
void Terrain::SaveAsBmp(const char* name)
{
Image image;
uchar* buffer = new uchar[mVertexCount * 3];
float scale = 255.0f / (mMaxHeight - mMinHeight);
uint j = 0;
for (uint i = 0; i < mVertexCount; i++)
{
buffer[j + 0] = (mHeights[i] + (-mMinHeight)) * scale;
buffer[j + 1] = (mHeights[i] + (-mMinHeight)) * scale;
buffer[j + 2] = (mHeights[i] + (-mMinHeight)) * scale;
j += 3;
}
image.CreateImage(PF_RGB_8, mVerticesInSizeX, mVerticesInSizeZ, buffer);
BMPImageLoader bmpLoader;
bmpLoader.SaveFile(&image, name);
}
void Terrain::Render()
{
Renderer* renderer = GetDevice()->GetRenderer();
glBindBuffer(GL_ARRAY_BUFFER, 0);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
glEnableClientState(GL_VERTEX_ARRAY);
glEnableClientState(GL_NORMAL_ARRAY);
glEnableClientState(GL_TEXTURE_COORD_ARRAY);
glVertexPointer(3, GL_FLOAT, 0, mVertices);
glNormalPointer(GL_FLOAT, 0, mNormals);
glTexCoordPointer(2, GL_FLOAT, 0, mTexCoords);
glDrawElements(GL_TRIANGLES, mTilesInSizeX * mTilesInSizeZ * 6, GL_UNSIGNED_SHORT, mIndices);
glDisableClientState(GL_VERTEX_ARRAY);
glDisableClientState(GL_NORMAL_ARRAY);
glDisableClientState(GL_TEXTURE_COORD_ARRAY);
}
float Terrain::GaussDist(float x, float y, float sigma)
{
float gauss = 1.0f / Math::TWO_PI * (sigma * sigma);
float e = 2.71828183f;
float exponent = ((x * x) + (y * y)) / (2.0f * (sigma * sigma));
return gauss * pow(e, -exponent);
}
void Terrain::BuildBrush(uint width, uint height, float smooth)
{
assert(width < MAX_BRUSH_SIZE);
assert(height < MAX_BRUSH_SIZE);
mBrushWidth = width;
mBrushHeight = height;
float xStart = -(float)width * 0.5f;
float yStart = -(float)height * 0.5f;
float xCurrent = xStart;
for (uint i = 0; i <= width; i++)
{
float yCurrent = yStart;
for (uint j = 0; j <= height; j++)
{
mBrush[j * MAX_BRUSH_SIZE + i] = GaussDist(xCurrent, yCurrent, smooth);
yCurrent += 1.0f;
}
xCurrent += 1.0f;
}
}
void Terrain::PlotCircle(int xx, int yy, int radius, int i)
{
for (int i = 0; i < 256 * 256; i++)
{
mBrush[i] = 0;
}
int x, y;
mBrushWidth = radius * 2;
mBrushHeight = radius * 2;
for (y = -radius; y <= radius; y++)
for (x = -radius; x <= radius; x++)
if ((x * x) + (y * y) <= (radius * radius))
{
float rDist = 1.0 - Math::Sqrt(x * x + y * y) / radius;
if (i == 0)
{
mBrush[(y + yy) * MAX_BRUSH_SIZE + (x + xx)] = Interpolation::Linear(0.0f, 1.0f, rDist);
}
else if (i == 1)
{
mBrush[(y + yy) * MAX_BRUSH_SIZE + (x + xx)] = Interpolation::Cosine(0.0f, 1.0f, rDist);
}
else if (i == 2)
{
mBrush[(y + yy) * MAX_BRUSH_SIZE + (x + xx)] = Interpolation::Cubic(0.0f, 1.0f, rDist);
}
}
}
void Terrain::ApplyBrush(uint x, uint z, float scale)
{
uint offsetX = mBrushWidth / 2;
uint offsetY = mBrushHeight / 2;
for (uint i = 0; i < mBrushWidth; i++)
{
for (uint j = 0; j < mBrushHeight; j++)
{
SetHeightAt((x - offsetX) + i, (z - offsetY) + j, scale * mBrush[j * MAX_BRUSH_SIZE + i]);
}
}
}
void Terrain::ApplyBrush(const Vec3& xyz, float scale)
{
uint x, z;
WorldToHeight(xyz, x, z);
ApplyBrush(x, z, scale);
}
} // namespace Crown
<commit_msg>Update Terrain<commit_after>/*
Copyright (c) 2012 Daniele Bartolini, Simone Boscaratto
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 "Terrain.h"
#include "MeshChunk.h"
#include "Device.h"
#include "Renderer.h"
#include "MathUtils.h"
#include <GL/glew.h>
#include "Log.h"
#include <cstdio>
#include "Vec2.h"
#include "Interpolation.h"
#include "BMPImageLoader.h"
#include <cmath>
namespace Crown
{
Terrain::Terrain() :
mHeights(NULL),
mVertices(NULL),
mNormals(NULL),
mTexCoords(NULL),
mIndices(NULL),
mMinHeight(-10.0f),
mMaxHeight(10.0f)
{
}
Terrain::~Terrain()
{
if (mHeights != NULL)
{
delete[] mHeights;
}
delete[] mVertices;
delete[] mNormals;
delete[] mTexCoords;
delete[] mIndices;
}
void Terrain::CreateTerrain(uint xSize, uint zSize, uint tilePerMeter, float initialHeight)
{
assert(xSize > 0);
assert(zSize > 0);
assert(tilePerMeter > 0);
mSizeX = xSize;
mSizeZ = zSize;
mTilePerMeter = tilePerMeter;
float tileStep = +(float)mSizeX / ((float)mSizeX * (float)mTilePerMeter); // Tile step is the same for both x and z ;)
mTilesInSizeX = ((float)mSizeX / tileStep);
mTilesInSizeZ = ((float)mSizeZ / tileStep);
mVerticesInSizeX = mTilesInSizeX + 1;
mVerticesInSizeZ = mTilesInSizeZ + 1;
printf("Vertices in size x/z: %d %d\n", mVerticesInSizeX, mVerticesInSizeZ);
uint heightsCount = mVerticesInSizeX * mVerticesInSizeZ;
mHeights = new float[heightsCount];
// Init heights
for (uint i = 0; i < heightsCount; i++)
{
mHeights[i] = initialHeight;
}
// Construct drawing data
mVertices = new Vec3[heightsCount]; // There are as many vertices as heights
mVertexCount = heightsCount;
mNormals = new Vec3[heightsCount]; // Same as vertices
mNormalCount = heightsCount;
mTexCoords = new Vec2[heightsCount]; // Same as vertices
mTexCoordCount = heightsCount;
mIndices = new ushort[mTilesInSizeX * mTilesInSizeZ * 6]; //
mIndexCount = mTilesInSizeX * mTilesInSizeZ * 6;
// Populate vertex list (generate a grid lying on the xz-plane and facing upwards)
float xStart = -(float)mSizeX * 0.5f;
float zStart = +(float)mSizeZ * 0.5f;
mOffsetX = xStart;
mOffsetZ = zStart;
uint vIndex = 0; // Just because I'm lazy
float xCurrent; // Keeps track of current x position
float zCurrent = zStart; // Keeps track of current z position
for (uint z = 0; z < mVerticesInSizeZ; z++)
{
xCurrent = xStart;
for (uint x = 0; x < mVerticesInSizeX; x++)
{
mVertices[vIndex].x = xCurrent;
mVertices[vIndex].y = mHeights[vIndex];
mVertices[vIndex].z = zCurrent;
mNormals[vIndex].x = 0.0f;
mNormals[vIndex].y = 1.0f;
mNormals[vIndex].z = 0.0f;
mTexCoords[vIndex].x = (float)x;
mTexCoords[vIndex].y = (float)z;
vIndex++;
xCurrent += tileStep;
}
zCurrent -= tileStep;
}
// Populate index list
uint iIndex = 0;
for (uint z = 0; z < mTilesInSizeZ; z++)
{
for (uint x = 0; x < mTilesInSizeX; x++)
{
uint firstRow = z * mVerticesInSizeX + x;
uint secondRow = (z + 1) * mVerticesInSizeX + x;
mIndices[iIndex + 0] = firstRow;
mIndices[iIndex + 1] = secondRow + 1;
mIndices[iIndex + 2] = secondRow;
mIndices[iIndex + 3] = firstRow;
mIndices[iIndex + 4] = firstRow + 1;
mIndices[iIndex + 5] = secondRow + 1;
iIndex += 6;
}
}
}
void Terrain::UpdateVertexBuffer(bool recomputeNormals)
{
uint vIndex = 0;
for (uint z = 0; z < mVerticesInSizeZ; z++)
{
for (uint x = 0; x < mVerticesInSizeX; x++)
{
mVertices[vIndex].y = mHeights[vIndex];
vIndex++;
}
}
if (recomputeNormals)
{
for (uint i = 0; i < mIndexCount; i += 3)
{
Vec3 normal;
Vec3 v1;
Vec3 v2;
v1 = mVertices[mIndices[i + 0]] - mVertices[mIndices[i + 1]];
v2 = mVertices[mIndices[i + 2]] - mVertices[mIndices[i + 1]];
normal = v2.cross(v1).normalize();
mNormals[mIndices[i + 0]] = normal;
mNormals[mIndices[i + 1]] = normal;
mNormals[mIndices[i + 2]] = normal;
}
}
}
float Terrain::GetHeightAt(uint x, uint z) const
{
if (x > mVerticesInSizeX) return 0.0f;
if (z > mVerticesInSizeZ) return 0.0f;
return mHeights[z * mVerticesInSizeX + x];
}
float Terrain::GetHeightAt(const Vec3& xyz) const
{
uint x, z;
WorldToHeight(xyz, x, z);
return GetHeightAt(x, z);
}
void Terrain::SetHeightAt(uint x, uint z, float height)
{
if (x >= mVerticesInSizeX) return;
if (z >= mVerticesInSizeZ) return;
mHeights[z * mVerticesInSizeX + x] += height;
mHeights[z * mVerticesInSizeX + x] = math::clamp_to_range(mMinHeight, mMaxHeight, mHeights[z * mVerticesInSizeX + x]);
}
void Terrain::SetHeightAt(const Vec3& xyz, float height)
{
uint x, z;
WorldToHeight(xyz, x, z);
SetHeightAt(x + 0, z + 0, height);
}
void Terrain::WorldToHeight(const Vec3& xyz, uint& x, uint& z) const
{
Vec3 offsetted = xyz + Vec3(-mOffsetX, 0.0f, mOffsetZ);
offsetted.z = (float)mSizeZ - offsetted.z;
x = (uint)offsetted.x;
z = (uint)offsetted.z;
}
bool Terrain::TraceRay(const Ray& ray, Triangle& result, Triangle& tri2, real& dist)
{
bool hit = false;
real minDist = 9999999.0f;
for (uint i = 0; i < mIndexCount; i += 3)
{
Triangle tri;
tri.v1 = mVertices[mIndices[i + 0]];
tri.v2 = mVertices[mIndices[i + 1]];
tri.v3 = mVertices[mIndices[i + 2]];
real ret;
Vec3 intersectionPoint;
if (Intersection::TestRayTriangle(ray, tri, ret, intersectionPoint))
{
if (ret < minDist)
{
minDist = ret;
result = tri;
}
hit = true;
}
}
dist = minDist;
return hit;
}
uint Terrain::SnapToGrid(const Vec3& vertex)
{
float minDist = 9999999.0f;
uint indexToSnapped;
// Find the snapped point to input vertex
for (int i = 0; i < mVertexCount; i++)
{
Vec3 tmp = mVertices[i];
Vec3 vertex2 = vertex;
tmp.y = vertex2.y = 0.0f;
if (tmp.get_distance_to(vertex2) < minDist)
{
indexToSnapped = i;
minDist = tmp.get_distance_to(vertex2);
}
}
return indexToSnapped;
}
void Terrain::SaveAsBmp(const char* name)
{
Image image;
uchar* buffer = new uchar[mVertexCount * 3];
float scale = 255.0f / (mMaxHeight - mMinHeight);
uint j = 0;
for (uint i = 0; i < mVertexCount; i++)
{
buffer[j + 0] = (mHeights[i] + (-mMinHeight)) * scale;
buffer[j + 1] = (mHeights[i] + (-mMinHeight)) * scale;
buffer[j + 2] = (mHeights[i] + (-mMinHeight)) * scale;
j += 3;
}
image.CreateImage(PF_RGB_8, mVerticesInSizeX, mVerticesInSizeZ, buffer);
BMPImageLoader bmpLoader;
bmpLoader.SaveFile(&image, name);
}
void Terrain::Render()
{
Renderer* renderer = GetDevice()->GetRenderer();
glBindBuffer(GL_ARRAY_BUFFER, 0);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
glEnableClientState(GL_VERTEX_ARRAY);
glEnableClientState(GL_NORMAL_ARRAY);
glEnableClientState(GL_TEXTURE_COORD_ARRAY);
glVertexPointer(3, GL_FLOAT, 0, mVertices);
glNormalPointer(GL_FLOAT, 0, mNormals);
glTexCoordPointer(2, GL_FLOAT, 0, mTexCoords);
glDrawElements(GL_TRIANGLES, mTilesInSizeX * mTilesInSizeZ * 6, GL_UNSIGNED_SHORT, mIndices);
glDisableClientState(GL_VERTEX_ARRAY);
glDisableClientState(GL_NORMAL_ARRAY);
glDisableClientState(GL_TEXTURE_COORD_ARRAY);
}
float Terrain::GaussDist(float x, float y, float sigma)
{
float gauss = 1.0f / math::TWO_PI * (sigma * sigma);
float e = 2.71828183f;
float exponent = ((x * x) + (y * y)) / (2.0f * (sigma * sigma));
return gauss * pow(e, -exponent);
}
void Terrain::BuildBrush(uint width, uint height, float smooth)
{
assert(width < MAX_BRUSH_SIZE);
assert(height < MAX_BRUSH_SIZE);
mBrushWidth = width;
mBrushHeight = height;
float xStart = -(float)width * 0.5f;
float yStart = -(float)height * 0.5f;
float xCurrent = xStart;
for (uint i = 0; i <= width; i++)
{
float yCurrent = yStart;
for (uint j = 0; j <= height; j++)
{
mBrush[j * MAX_BRUSH_SIZE + i] = GaussDist(xCurrent, yCurrent, smooth);
yCurrent += 1.0f;
}
xCurrent += 1.0f;
}
}
void Terrain::PlotCircle(int xx, int yy, int radius, int i)
{
for (int i = 0; i < 256 * 256; i++)
{
mBrush[i] = 0;
}
int x, y;
mBrushWidth = radius * 2;
mBrushHeight = radius * 2;
for (y = -radius; y <= radius; y++)
for (x = -radius; x <= radius; x++)
if ((x * x) + (y * y) <= (radius * radius))
{
float rDist = 1.0 - math::sqrt(x * x + y * y) / radius;
if (i == 0)
{
mBrush[(y + yy) * MAX_BRUSH_SIZE + (x + xx)] = Interpolation::linear(0.0f, 1.0f, rDist);
}
else if (i == 1)
{
mBrush[(y + yy) * MAX_BRUSH_SIZE + (x + xx)] = Interpolation::cosine(0.0f, 1.0f, rDist);
}
else if (i == 2)
{
mBrush[(y + yy) * MAX_BRUSH_SIZE + (x + xx)] = Interpolation::cubic(0.0f, 1.0f, rDist);
}
}
}
void Terrain::ApplyBrush(uint x, uint z, float scale)
{
uint offsetX = mBrushWidth / 2;
uint offsetY = mBrushHeight / 2;
for (uint i = 0; i < mBrushWidth; i++)
{
for (uint j = 0; j < mBrushHeight; j++)
{
SetHeightAt((x - offsetX) + i, (z - offsetY) + j, scale * mBrush[j * MAX_BRUSH_SIZE + i]);
}
}
}
void Terrain::ApplyBrush(const Vec3& xyz, float scale)
{
uint x, z;
WorldToHeight(xyz, x, z);
ApplyBrush(x, z, scale);
}
} // namespace Crown
<|endoftext|> |
<commit_before>/* vim:expandtab:shiftwidth=2:tabstop=2:smarttab:
*
* Data Differential YATL (i.e. libtest) library
*
* Copyright (C) 2012 Data Differential, http://datadifferential.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.
*
* * The names of its contributors may not 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 "libtest/yatlcon.h"
#include <libtest/common.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netdb.h>
namespace libtest {
bool lookup(const char* host)
{
bool success= false;
assert(host and host[0]);
if (host and host[0])
{
struct addrinfo *addrinfo= NULL;
struct addrinfo hints;
memset(&hints, 0, sizeof(hints));
hints.ai_socktype= SOCK_STREAM;
hints.ai_protocol= IPPROTO_TCP;
int limit= 5;
while (--limit and success == false)
{
if (addrinfo)
{
freeaddrinfo(addrinfo);
addrinfo= NULL;
}
int ret;
if ((ret= getaddrinfo(host, "echo", &hints, &addrinfo)) == 0)
{
success= true;
break;
}
switch (ret)
{
case EAI_AGAIN:
continue;
case EAI_NONAME:
default:
break;
}
break;
}
if (addrinfo)
{
freeaddrinfo(addrinfo);
}
}
return success;
}
bool check_dns()
{
if (lookup("exist.gearman.info") == false)
{
return false;
}
if (lookup("does_not_exist.gearman.info")) // This should fail, if it passes,...
{
fatal_assert("Your service provider sucks and is providing bogus DNS. You might be in an airport.");
}
return true;
}
} // namespace libtest
<commit_msg>Stop running DNS tests under valgrind.<commit_after>/* vim:expandtab:shiftwidth=2:tabstop=2:smarttab:
*
* Data Differential YATL (i.e. libtest) library
*
* Copyright (C) 2012 Data Differential, http://datadifferential.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.
*
* * The names of its contributors may not 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 "libtest/yatlcon.h"
#include <libtest/common.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netdb.h>
namespace libtest {
bool lookup(const char* host)
{
bool success= false;
assert(host and host[0]);
if (host and host[0])
{
struct addrinfo *addrinfo= NULL;
struct addrinfo hints;
memset(&hints, 0, sizeof(hints));
hints.ai_socktype= SOCK_STREAM;
hints.ai_protocol= IPPROTO_TCP;
int limit= 5;
while (--limit and success == false)
{
if (addrinfo)
{
freeaddrinfo(addrinfo);
addrinfo= NULL;
}
int ret;
if ((ret= getaddrinfo(host, "echo", &hints, &addrinfo)) == 0)
{
success= true;
break;
}
switch (ret)
{
case EAI_AGAIN:
continue;
case EAI_NONAME:
default:
break;
}
break;
}
if (addrinfo)
{
freeaddrinfo(addrinfo);
}
}
return success;
}
bool check_dns()
{
if (valgrind_is_caller())
{
return false;
}
if (lookup("exist.gearman.info") == false)
{
return false;
}
if (lookup("does_not_exist.gearman.info")) // This should fail, if it passes,...
{
fatal_assert("Your service provider sucks and is providing bogus DNS. You might be in an airport.");
}
return true;
}
} // namespace libtest
<|endoftext|> |
<commit_before>/* vim:expandtab:shiftwidth=2:tabstop=2:smarttab:
*
* Data Differential YATL (i.e. libtest) library
*
* Copyright (C) 2012 Data Differential, http://datadifferential.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.
*
* * The names of its contributors may not 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 <config.h>
#include <libtest/common.h>
#include <cstdlib>
#include <unistd.h>
namespace libtest {
bool has_libmemcached(void)
{
if (HAVE_LIBMEMCACHED)
{
return true;
}
return false;
}
bool has_libdrizzle(void)
{
if (HAVE_LIBDRIZZLE)
{
return true;
}
return false;
}
bool has_postgres_support(void)
{
char *getenv_ptr;
if (bool((getenv_ptr= getenv("POSTGES_IS_RUNNING_AND_SETUP"))))
{
(void)(getenv_ptr);
if (HAVE_LIBPQ)
{
return true;
}
}
return false;
}
bool has_gearmand()
{
if (HAVE_GEARMAND_BINARY)
{
std::stringstream arg_buffer;
char *getenv_ptr;
if (bool((getenv_ptr= getenv("PWD"))) and
((strcmp(GEARMAND_BINARY, "./gearmand/gearmand") == 0) or (strcmp(GEARMAND_BINARY, "gearmand/gearmand") == 0)))
{
arg_buffer << getenv_ptr;
arg_buffer << "/";
}
arg_buffer << GEARMAND_BINARY;
if (access(arg_buffer.str().c_str(), X_OK) == 0)
{
return true;
}
}
return false;
}
bool has_drizzled()
{
#if defined(HAVE_DRIZZLED_BINARY) && HAVE_DRIZZLED_BINARY
if (HAVE_DRIZZLED_BINARY)
{
if (access(DRIZZLED_BINARY, X_OK) == 0)
{
return true;
}
}
#endif
return false;
}
bool has_mysqld()
{
#if defined(HAVE_MYSQLD_BUILD) && HAVE_MYSQLD_BUILD
if (HAVE_MYSQLD_BUILD)
{
if (access(MYSQLD_BINARY, X_OK) == 0)
{
return true;
}
}
#endif
return false;
}
bool has_memcached()
{
if (HAVE_MEMCACHED_BINARY)
{
std::stringstream arg_buffer;
char *getenv_ptr;
if (bool((getenv_ptr= getenv("PWD"))) and strcmp(MEMCACHED_BINARY, "memcached/memcached") == 0)
{
arg_buffer << getenv_ptr;
arg_buffer << "/";
}
arg_buffer << MEMCACHED_BINARY;
if (access(arg_buffer.str().c_str(), X_OK) == 0)
{
return true;
}
}
return false;
}
bool has_memcached_sasl()
{
#if defined(HAVE_MEMCACHED_SASL_BINARY) && HAVE_MEMCACHED_SASL_BINARY
if (HAVE_MEMCACHED_SASL_BINARY)
{
if (access(MEMCACHED_SASL_BINARY, X_OK) == 0)
{
return true;
}
}
#endif
return false;
}
} // namespace libtest
<commit_msg>Fix for libtest<commit_after>/* vim:expandtab:shiftwidth=2:tabstop=2:smarttab:
*
* Data Differential YATL (i.e. libtest) library
*
* Copyright (C) 2012 Data Differential, http://datadifferential.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.
*
* * The names of its contributors may not 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 <config.h>
#include <libtest/common.h>
#include <cstdlib>
#include <unistd.h>
namespace libtest {
bool has_libmemcached(void)
{
if (HAVE_LIBMEMCACHED)
{
return true;
}
return false;
}
bool has_libdrizzle(void)
{
if (HAVE_LIBDRIZZLE)
{
return true;
}
return false;
}
bool has_postgres_support(void)
{
char *getenv_ptr;
if (bool((getenv_ptr= getenv("POSTGES_IS_RUNNING_AND_SETUP"))))
{
(void)(getenv_ptr);
if (HAVE_LIBPQ)
{
return true;
}
}
return false;
}
bool has_gearmand()
{
if (HAVE_GEARMAND_BINARY)
{
#if defined(HAVE_GEARMAND_BINARY) && HAVE_GEARMAND_BINARY
std::stringstream arg_buffer;
char *getenv_ptr;
if (bool((getenv_ptr= getenv("PWD"))) and
((strcmp(GEARMAND_BINARY, "./gearmand/gearmand") == 0) or (strcmp(GEARMAND_BINARY, "gearmand/gearmand") == 0)))
{
arg_buffer << getenv_ptr;
arg_buffer << "/";
}
arg_buffer << GEARMAND_BINARY;
if (access(arg_buffer.str().c_str(), X_OK) == 0)
{
return true;
}
#endif
}
return false;
}
bool has_drizzled()
{
#if defined(HAVE_DRIZZLED_BINARY) && HAVE_DRIZZLED_BINARY
if (HAVE_DRIZZLED_BINARY)
{
if (access(DRIZZLED_BINARY, X_OK) == 0)
{
return true;
}
}
#endif
return false;
}
bool has_mysqld()
{
#if defined(HAVE_MYSQLD_BUILD) && HAVE_MYSQLD_BUILD
if (HAVE_MYSQLD_BUILD)
{
if (access(MYSQLD_BINARY, X_OK) == 0)
{
return true;
}
}
#endif
return false;
}
bool has_memcached()
{
if (HAVE_MEMCACHED_BINARY)
{
std::stringstream arg_buffer;
char *getenv_ptr;
if (bool((getenv_ptr= getenv("PWD"))) and strcmp(MEMCACHED_BINARY, "memcached/memcached") == 0)
{
arg_buffer << getenv_ptr;
arg_buffer << "/";
}
arg_buffer << MEMCACHED_BINARY;
if (access(arg_buffer.str().c_str(), X_OK) == 0)
{
return true;
}
}
return false;
}
bool has_memcached_sasl()
{
#if defined(HAVE_MEMCACHED_SASL_BINARY) && HAVE_MEMCACHED_SASL_BINARY
if (HAVE_MEMCACHED_SASL_BINARY)
{
if (access(MEMCACHED_SASL_BINARY, X_OK) == 0)
{
return true;
}
}
#endif
return false;
}
} // namespace libtest
<|endoftext|> |
<commit_before>// This file is distributed under the BSD License.
// See "license.txt" for details.
// Copyright 2009-2011, Jonathan Turner (jonathan@emptycrate.com)
// and Jason Turner (jason@emptycrate.com)
// http://www.chaiscript.com
#include <boost/preprocessor.hpp>
#ifndef BOOST_PP_IS_ITERATING
#ifndef CHAISCRIPT_PROXY_CONSTRUCTORS_HPP_
#define CHAISCRIPT_PROXY_CONSTRUCTORS_HPP_
#define BOOST_PP_ITERATION_LIMITS ( 0, 10 )
#define BOOST_PP_FILENAME_1 <chaiscript/dispatchkit/proxy_constructors.hpp>
#include BOOST_PP_ITERATE()
# endif
namespace chaiscript
{
/// \brief Generates a constructor function for use with ChaiScript
///
/// \tparam T The signature of the constructor to generate. In the form of: ClassType (ParamType1, ParamType2, ...)
///
/// Example:
/// \code
/// chaiscript::ChaiScript chai;
/// // Create a new function that creates a MyClass object using the (int, float) constructor
/// // and call that function "MyClass" so that it appears as a normal constructor to the user.
/// chai.add(constructor<MyClass (int, float)>(), "MyClass");
/// \endcode
template<typename T>
Proxy_Function constructor()
{
T *f = 0;
return (dispatch::detail::build_constructor_(f));
}
}
#else
# define n BOOST_PP_ITERATION()
namespace chaiscript
{
namespace dispatch
{
namespace detail
{
/**
* A constructor function, used for creating a new object
* of a given type with a given set of params
*/
template<typename Class BOOST_PP_COMMA_IF(n) BOOST_PP_ENUM_PARAMS(n, typename Param) >
std::shared_ptr<Class> constructor_( BOOST_PP_ENUM_BINARY_PARAMS(n, Param, p) )
{
return std::shared_ptr<Class>(new Class( BOOST_PP_ENUM_PARAMS(n, p) ));
}
/**
* Helper function for build a constructor function
* example:
* dispatchengine.register_function(build_constructor<MyClass, int, const std::string&>, "MyClass");
* \todo See if it is possible to make this not be a variadic function
*/
template<typename Class BOOST_PP_COMMA_IF(n) BOOST_PP_ENUM_PARAMS(n, typename Param) >
Proxy_Function build_constructor_(Class (*)(BOOST_PP_ENUM_PARAMS(n, Param)))
{
typedef std::shared_ptr<Class> (sig)(BOOST_PP_ENUM_PARAMS(n, Param));
return Proxy_Function(new Proxy_Function_Impl<sig>(std::function<sig>(&(constructor_<Class BOOST_PP_COMMA_IF(n) BOOST_PP_ENUM_PARAMS(n, Param)>))));
}
}
}
}
#undef n
#endif
<commit_msg>One more file no longer using boost_pp<commit_after>// This file is distributed under the BSD License.
// See "license.txt" for details.
// Copyright 2009-2011, Jonathan Turner (jonathan@emptycrate.com)
// and Jason Turner (jason@emptycrate.com)
// http://www.chaiscript.com
#ifndef CHAISCRIPT_PROXY_CONSTRUCTORS_HPP_
#define CHAISCRIPT_PROXY_CONSTRUCTORS_HPP_
namespace chaiscript
{
namespace dispatch
{
namespace detail
{
/**
* A constructor function, used for creating a new object
* of a given type with a given set of params
*/
template<typename Class, typename ... Params>
std::shared_ptr<Class> constructor_(Params ... params)
{
return std::shared_ptr<Class>(new Class(params...));
}
template<typename Class, typename ... Params >
Proxy_Function build_constructor_(Class (*)(Params...))
{
typedef std::shared_ptr<Class> (sig)(Params...);
return Proxy_Function(new Proxy_Function_Impl<sig>(std::function<sig>(&(constructor_<Class, Params...>))));
}
}
}
/// \brief Generates a constructor function for use with ChaiScript
///
/// \tparam T The signature of the constructor to generate. In the form of: ClassType (ParamType1, ParamType2, ...)
///
/// Example:
/// \code
/// chaiscript::ChaiScript chai;
/// // Create a new function that creates a MyClass object using the (int, float) constructor
/// // and call that function "MyClass" so that it appears as a normal constructor to the user.
/// chai.add(constructor<MyClass (int, float)>(), "MyClass");
/// \endcode
template<typename T>
Proxy_Function constructor()
{
T *f = 0;
return (dispatch::detail::build_constructor_(f));
}
}
#endif
<|endoftext|> |
<commit_before>#include "itkCommandLineArgumentParser.h"
#include "CommandLineArgumentHelper.h"
#include "itkImageFileReader.h"
#include "itkSmoothingRecursiveGaussianImageFilter2.h"
#include "itkImageFileWriter.h"
//-------------------------------------------------------------------------------------
/** run: A macro to call a function. */
#define run( function, type, dim ) \
if ( componentType == #type && Dimension == dim ) \
{ \
typedef itk::Image< type, dim > OutputImageType; \
function< OutputImageType >( inputFileName, outputFileName, sigma, order ); \
supported = true; \
}
//-------------------------------------------------------------------------------------
/** Declare GaussianImageFilter. */
template< class OutputImageType >
void GaussianImageFilter(
const std::string & inputFileName,
const std::string & outputFileName,
const std::vector<float> & sigma,
const std::vector<unsigned int> & order );
/** Declare PrintHelp. */
void PrintHelp( void );
//-------------------------------------------------------------------------------------
int main( int argc, char ** argv )
{
/** Check arguments for help. */
if ( argc < 3 || argc > 15 )
{
PrintHelp();
return 1;
}
/** Create a command line argument parser. */
itk::CommandLineArgumentParser::Pointer parser = itk::CommandLineArgumentParser::New();
parser->SetCommandLineArguments( argc, argv );
/** Get arguments. */
std::string inputFileName = "";
bool retin = parser->GetCommandLineArgument( "-in", inputFileName );
std::vector<float> sigma;
sigma.push_back(1.0); // default 1.0 for each resolution
bool retstd = parser->GetCommandLineArgument( "-std", sigma );
std::vector<unsigned int> order;
bool retord = parser->GetCommandLineArgument( "-ord", order );
std::string outputFileName = inputFileName.substr( 0, inputFileName.rfind( "." ) );
outputFileName += "BLURRED.mhd";
bool retout = parser->GetCommandLineArgument( "-out", outputFileName );
std::string componentType = "";
bool retpt = parser->GetCommandLineArgument( "-pt", componentType );
/** Check if the required arguments are given. */
if ( !retin )
{
std::cerr << "ERROR: You should specify \"-in\"." << std::endl;
return 1;
}
/** Check options. */
for ( unsigned int i = 0; i < order.size(); ++i )
{
if ( order[ i ] > 2 )
{
std::cerr << "ERROR: The order should not be higher than 2." << std::endl;
std::cerr << "Only zeroth, first and second order derivatives are supported." << std::endl;
return 1;
}
}
/** Determine image properties. */
std::string ComponentTypeIn = "short";
std::string PixelType; //we don't use this
unsigned int Dimension = 3;
unsigned int NumberOfComponents = 1;
std::vector<unsigned int> imagesize( Dimension, 0 );
int retgip = GetImageProperties(
inputFileName,
PixelType,
ComponentTypeIn,
Dimension,
NumberOfComponents,
imagesize );
if ( retgip != 0 )
{
return 1;
}
/** The default output is equal to the input, but can be overridden by
* specifying -pt in the command line.
*/
if ( !retpt ) componentType = ComponentTypeIn;
/** Check for vector images. */
if ( NumberOfComponents > 1 )
{
std::cerr << "ERROR: The NumberOfComponents is larger than 1!" << std::endl;
std::cerr << "Cannot make vector of vector images." << std::endl;
return 1;
}
/** Get rid of the possible "_" in ComponentType. */
ReplaceUnderscoreWithSpace( ComponentTypeIn );
/** Check order. */
if ( order.size() != Dimension )
{
std::cerr << "ERROR: the # of orders should be equal to the image dimension!" << std::endl;
return 1;
}
/** Check sigma. */
if ( sigma.size() != 1 && sigma.size() != Dimension )
{
std::cerr << "ERROR: the # of sigmas should be equal to 1 or the image dimension!" << std::endl;
return 1;
}
/** Run the program. */
bool supported = false;
try
{
run( GaussianImageFilter, char, 2 );
run( GaussianImageFilter, unsigned char, 2 );
run( GaussianImageFilter, short, 2 );
run( GaussianImageFilter, unsigned short, 2 );
run( GaussianImageFilter, int, 2 );
run( GaussianImageFilter, unsigned int, 2 );
run( GaussianImageFilter, long, 2 );
run( GaussianImageFilter, unsigned long, 2 );
run( GaussianImageFilter, float, 2 );
run( GaussianImageFilter, double, 2 );
run( GaussianImageFilter, char, 3 );
run( GaussianImageFilter, unsigned char, 3 );
run( GaussianImageFilter, short, 3 );
run( GaussianImageFilter, unsigned short, 3 );
run( GaussianImageFilter, int, 3 );
run( GaussianImageFilter, unsigned int, 3 );
run( GaussianImageFilter, long, 3 );
run( GaussianImageFilter, unsigned long, 3 );
run( GaussianImageFilter, float, 3 );
run( GaussianImageFilter, double, 3 );
}
catch( itk::ExceptionObject &e )
{
std::cerr << "Caught ITK exception: " << e << std::endl;
return 1;
}
if ( !supported )
{
std::cerr << "ERROR: this combination of pixeltype and dimension is not supported!" << std::endl;
std::cerr <<
"pixel (component) type = " << ComponentTypeIn <<
" ; dimension = " << Dimension
<< std::endl;
return 1;
}
/** End program. */
return 0;
} // end main
/**
* ******************* GaussianImageFilter *******************
*/
template< class OutputImageType >
void GaussianImageFilter( const std::string & inputFileName,
const std::string & outputFileName,
const std::vector<float> & sigma,
const std::vector<unsigned int> & order )
{
/** Typedef's. */
const unsigned int Dimension = OutputImageType::ImageDimension;
typedef float InputPixelType;
typedef itk::Image< InputPixelType, Dimension > InputImageType;
typedef itk::ImageFileReader< InputImageType > ReaderType;
typedef itk::SmoothingRecursiveGaussianImageFilter2<
InputImageType, OutputImageType > FilterType;
typedef typename FilterType::OrderType OrderType;
typedef typename FilterType::SigmaType SigmaType;
typedef itk::ImageFileWriter< OutputImageType > WriterType;
/** Read in the input image. */
typename ReaderType::Pointer reader = ReaderType::New();
reader->SetFileName( inputFileName );
/** Setup the order and sigma. */
OrderType orderFA;
SigmaType sigmaFA;
sigmaFA.Fill( sigma[ 0 ] );
for ( unsigned int i = 0; i < Dimension; ++i )
{
orderFA[ i ] = order[ i ];
if ( sigma.size() == Dimension ) sigmaFA[ i ] = sigma[ i ];
}
/** Setup the smoothing filter. */
typename FilterType::Pointer filter = FilterType::New();
filter->SetNormalizeAcrossScale( false );
filter->SetInput( reader->GetOutput() );
filter->SetSigma( sigmaFA );
filter->SetOrder( orderFA );
/** Write image. */
typename WriterType::Pointer writer = WriterType::New();
writer->SetFileName( outputFileName );
writer->SetInput( filter->GetOutput() );
writer->Update();
} // end GaussianImageFilter()
/**
* ******************* PrintHelp *******************
*/
void PrintHelp()
{
std::cout << "Usage:" << std::endl << "pxgaussianimagefilter" << std::endl;
std::cout << " -in inputFilename" << std::endl;
std::cout << " [-out] outputFilename, default in + BLURRED.mhd" << std::endl;
std::cout << " [-std] sigma, for each dimension, default 1.0" << std::endl;
std::cout << " [-ord] order, for each dimension, default zero\n";
std::cout << " 0: zero order = blurring\n";
std::cout << " 1: first order = gradient\n";
std::cout << " 2: second order derivative" << std::endl;
std::cout << " [-pt] output pixel type, default equal to input" << std::endl;
std::cout << "Supported: 2D, 3D, (unsigned) char, (unsigned) short, (unsigned) int, (unsigned) long, float, double." << std::endl;
} // end PrintHelp()
<commit_msg>MS:<commit_after>#include "itkCommandLineArgumentParser.h"
#include "CommandLineArgumentHelper.h"
#include "itkImageFileReader.h"
#include "itkSmoothingRecursiveGaussianImageFilter2.h"
#include "itkImageToVectorImageFilter.h"
#include "itkGradientToMagnitudeImageFilter.h"
#include "itkImageFileWriter.h"
//-------------------------------------------------------------------------------------
/** run: A macro to call a function. */
#define run( function, type, dim ) \
if ( componentType == #type && Dimension == dim ) \
{ \
typedef itk::Image< type, dim > OutputImageType; \
if ( retmag == false ) \
{ \
function< OutputImageType >( inputFileName, outputFileName, sigma, order ); \
} \
else \
{ \
function##Magnitude< OutputImageType >( inputFileName, outputFileName, sigma, order ); \
} \
supported = true; \
}
//-------------------------------------------------------------------------------------
/** Declare GaussianImageFilter. */
template< class OutputImageType >
void GaussianImageFilter(
const std::string & inputFileName,
const std::string & outputFileName,
const std::vector<float> & sigma,
const std::vector<unsigned int> & order );
/** Declare GaussianImageFilter. */
template< class OutputImageType >
void GaussianImageFilterMagnitude(
const std::string & inputFileName,
const std::string & outputFileName,
const std::vector<float> & sigma,
const std::vector<unsigned int> & order );
/** Declare PrintHelp. */
void PrintHelp( void );
//-------------------------------------------------------------------------------------
int main( int argc, char ** argv )
{
/** Check arguments for help. */
if ( argc < 3 || argc > 15 )
{
PrintHelp();
return 1;
}
/** Create a command line argument parser. */
itk::CommandLineArgumentParser::Pointer parser = itk::CommandLineArgumentParser::New();
parser->SetCommandLineArguments( argc, argv );
/** Get arguments. */
std::string inputFileName = "";
bool retin = parser->GetCommandLineArgument( "-in", inputFileName );
std::vector<float> sigma;
sigma.push_back(1.0); // default 1.0 for each resolution
bool retstd = parser->GetCommandLineArgument( "-std", sigma );
std::vector<unsigned int> order;
bool retord = parser->GetCommandLineArgument( "-ord", order );
std::string outputFileName = inputFileName.substr( 0, inputFileName.rfind( "." ) );
outputFileName += "BLURRED.mhd";
bool retout = parser->GetCommandLineArgument( "-out", outputFileName );
bool retmag = parser->ArgumentExists( "-mag" );
std::string componentType = "";
bool retpt = parser->GetCommandLineArgument( "-pt", componentType );
/** Check if the required arguments are given. */
if ( !retin )
{
std::cerr << "ERROR: You should specify \"-in\"." << std::endl;
return 1;
}
/** Check options. */
for ( unsigned int i = 0; i < order.size(); ++i )
{
if ( order[ i ] > 2 )
{
std::cerr << "ERROR: The order should not be higher than 2." << std::endl;
std::cerr << "Only zeroth, first and second order derivatives are supported." << std::endl;
return 1;
}
}
/** Determine image properties. */
std::string ComponentTypeIn = "short";
std::string PixelType; //we don't use this
unsigned int Dimension = 3;
unsigned int NumberOfComponents = 1;
std::vector<unsigned int> imagesize( Dimension, 0 );
int retgip = GetImageProperties(
inputFileName,
PixelType,
ComponentTypeIn,
Dimension,
NumberOfComponents,
imagesize );
if ( retgip != 0 )
{
return 1;
}
/** The default output is equal to the input, but can be overridden by
* specifying -pt in the command line.
*/
if ( !retpt ) componentType = ComponentTypeIn;
/** Check for vector images. */
if ( NumberOfComponents > 1 )
{
std::cerr << "ERROR: The NumberOfComponents is larger than 1!" << std::endl;
std::cerr << "Cannot make vector of vector images." << std::endl;
return 1;
}
/** Get rid of the possible "_" in ComponentType. */
ReplaceUnderscoreWithSpace( ComponentTypeIn );
/** Check order. */
if ( order.size() != Dimension )
{
std::cerr << "ERROR: the # of orders should be equal to the image dimension!" << std::endl;
return 1;
}
/** Check sigma. */
if ( sigma.size() != 1 && sigma.size() != Dimension )
{
std::cerr << "ERROR: the # of sigmas should be equal to 1 or the image dimension!" << std::endl;
return 1;
}
/** Run the program. */
bool supported = false;
try
{
run( GaussianImageFilter, char, 2 );
run( GaussianImageFilter, unsigned char, 2 );
run( GaussianImageFilter, short, 2 );
run( GaussianImageFilter, unsigned short, 2 );
run( GaussianImageFilter, int, 2 );
run( GaussianImageFilter, unsigned int, 2 );
run( GaussianImageFilter, long, 2 );
run( GaussianImageFilter, unsigned long, 2 );
run( GaussianImageFilter, float, 2 );
run( GaussianImageFilter, double, 2 );
run( GaussianImageFilter, char, 3 );
run( GaussianImageFilter, unsigned char, 3 );
run( GaussianImageFilter, short, 3 );
run( GaussianImageFilter, unsigned short, 3 );
run( GaussianImageFilter, int, 3 );
run( GaussianImageFilter, unsigned int, 3 );
run( GaussianImageFilter, long, 3 );
run( GaussianImageFilter, unsigned long, 3 );
run( GaussianImageFilter, float, 3 );
run( GaussianImageFilter, double, 3 );
}
catch( itk::ExceptionObject &e )
{
std::cerr << "Caught ITK exception: " << e << std::endl;
return 1;
}
if ( !supported )
{
std::cerr << "ERROR: this combination of pixeltype and dimension is not supported!" << std::endl;
std::cerr <<
"pixel (component) type = " << ComponentTypeIn <<
" ; dimension = " << Dimension
<< std::endl;
return 1;
}
/** End program. */
return 0;
} // end main
/**
* ******************* GaussianImageFilter *******************
*/
template< class OutputImageType >
void GaussianImageFilter(
const std::string & inputFileName,
const std::string & outputFileName,
const std::vector<float> & sigma,
const std::vector<unsigned int> & order )
{
/** Typedef's. */
const unsigned int Dimension = OutputImageType::ImageDimension;
typedef float InputPixelType;
typedef itk::Image< InputPixelType, Dimension > InputImageType;
typedef itk::ImageFileReader< InputImageType > ReaderType;
typedef itk::SmoothingRecursiveGaussianImageFilter2<
InputImageType, OutputImageType > FilterType;
typedef typename FilterType::OrderType OrderType;
typedef typename FilterType::SigmaType SigmaType;
typedef itk::ImageFileWriter< OutputImageType > WriterType;
/** Read in the input image. */
typename ReaderType::Pointer reader = ReaderType::New();
reader->SetFileName( inputFileName );
/** Setup the order and sigma. */
OrderType orderFA;
SigmaType sigmaFA;
sigmaFA.Fill( sigma[ 0 ] );
for ( unsigned int i = 0; i < Dimension; ++i )
{
orderFA[ i ] = order[ i ];
if ( sigma.size() == Dimension ) sigmaFA[ i ] = sigma[ i ];
}
/** Setup the smoothing filter. */
typename FilterType::Pointer filter = FilterType::New();
filter->SetNormalizeAcrossScale( false );
filter->SetInput( reader->GetOutput() );
filter->SetSigma( sigmaFA );
filter->SetOrder( orderFA );
/** Write image. */
typename WriterType::Pointer writer = WriterType::New();
writer->SetFileName( outputFileName );
writer->SetInput( filter->GetOutput() );
writer->Update();
} // end GaussianImageFilter()
/**
* ******************* GaussianImageFilterMagnitude *******************
*/
template< class OutputImageType >
void GaussianImageFilterMagnitude(
const std::string & inputFileName,
const std::string & outputFileName,
const std::vector<float> & sigma,
const std::vector<unsigned int> & order )
{
/** Typedef's. */
const unsigned int Dimension = OutputImageType::ImageDimension;
typedef float InputPixelType;
typedef itk::Image< InputPixelType, Dimension > InputImageType;
typedef itk::ImageFileReader< InputImageType > ReaderType;
typedef itk::SmoothingRecursiveGaussianImageFilter2<
InputImageType, InputImageType > SmoothingFilterType;
typedef typename SmoothingFilterType::Pointer SmoothingFilterPointer;
typedef typename SmoothingFilterType::OrderType OrderType;
typedef typename SmoothingFilterType::SigmaType SigmaType;
typedef itk::ImageToVectorImageFilter<
InputImageType > ImageToVectorImageFilterType;
typedef typename ImageToVectorImageFilterType
::OutputImageType VectorImageType;
typedef itk::GradientToMagnitudeImageFilter<
VectorImageType, OutputImageType > MagnitudeFilterType;
typedef itk::ImageFileWriter< OutputImageType > WriterType;
/** Read in the input image. */
typename ReaderType::Pointer reader = ReaderType::New();
reader->SetFileName( inputFileName );
/** Setup the order and sigma. */
OrderType orderFA;
SigmaType sigmaFA;
sigmaFA.Fill( sigma[ 0 ] );
for ( unsigned int i = 0; i < Dimension; ++i )
{
orderFA[ i ] = order[ i ];
if ( sigma.size() == Dimension ) sigmaFA[ i ] = sigma[ i ];
}
/** Setup filters. */
typename ImageToVectorImageFilterType::Pointer imageToVectorImageFilter
= ImageToVectorImageFilterType::New();
typename MagnitudeFilterType::Pointer magnitudeFilter = MagnitudeFilterType::New();
/** Setup and run the smoothing filters. */
std::vector< SmoothingFilterPointer > filter( Dimension );
for ( unsigned int i = 0; i < Dimension; ++i )
{
filter[ i ] = SmoothingFilterType::New();
filter[ i ]->SetNormalizeAcrossScale( false );
filter[ i ]->SetInput( reader->GetOutput() );
SigmaType sigma2; sigma2.Fill( 0.0 ); sigma2[ i ] = sigmaFA[ i ];
OrderType order2; order2.Fill( 0.0 ); order2[ i ] = orderFA[ i ];
filter[ i ]->SetSigma( sigma2 );
filter[ i ]->SetOrder( order2 );
filter[ i ]->Update();
/** Setup composition filter. */
imageToVectorImageFilter->SetNthInput( i, filter[ i ]->GetOutput() );
}
/** Compose vector image and compute magnitude. */
magnitudeFilter->SetInput( imageToVectorImageFilter->GetOutput() );
magnitudeFilter->Update();
/** Write image. */
typename WriterType::Pointer writer = WriterType::New();
writer->SetFileName( outputFileName );
writer->SetInput( magnitudeFilter->GetOutput() );
writer->Update();
} // end GaussianImageFilterMagnitude()
/**
* ******************* PrintHelp *******************
*/
void PrintHelp()
{
std::cout << "Usage:" << std::endl << "pxgaussianimagefilter" << std::endl;
std::cout << " -in inputFilename" << std::endl;
std::cout << " [-out] outputFilename, default in + BLURRED.mhd" << std::endl;
std::cout << " [-std] sigma, for each dimension, default 1.0" << std::endl;
std::cout << " [-ord] order, for each dimension, default zero\n";
std::cout << " 0: zero order = blurring\n";
std::cout << " 1: first order = gradient\n";
std::cout << " 2: second order derivative" << std::endl;
std::cout << " [-mag] compute the magnitude of the separate blurrings, default false" << std::endl;
std::cout << " [-pt] output pixel type, default equal to input" << std::endl;
std::cout << "Supported: 2D, 3D, (unsigned) char, (unsigned) short, (unsigned) int, (unsigned) long, float, double." << std::endl;
} // end PrintHelp()
<|endoftext|> |
<commit_before>// SETUP
// GET, SET, ADD, REPLACE, DELETE, CAS, FLUSH_ALL, INCR, DECR, APPEND, PREPEND, STATS
// TODO find way to interact with postgres / peloton?
SET
insert into test (k, d) values ('$key', '$value') on conflict (k) do update set d = excluded.d;
GET
select d from test where k = '$key';<commit_msg>WIP prepared statements<commit_after>// SETUP
// GET, SET, ADD, REPLACE, DELETE, CAS, FLUSH_ALL, INCR, DECR, APPEND, PREPEND, STATS
// TODO find way to interact with postgres / peloton?
// prepared statements
// execute only once
int setup() {
CREATE TABLE test ( k VARCHAR(40) PRIMARY KEY, d VARCHAR(400) );
DEALLOCATE SET;
PREPARE SET (text, text) AS
INSERT INTO test (k, d) VALUES ($1, $2) ON CONFLICT (k) DO UPDATE SET d = excluded.d;
DEALLOCATE GET;
PREPARE GET (text) AS
SELECT d FROM TEST WHERE k = $1;
}
int get(std::string &key, std::string &value) {
EXECUTE SET (,)
}
int get(std::string &key, std::string &value) {
EXECUTE SET (,)
}<|endoftext|> |
<commit_before>#include <iostream>
#include "prefs.h"
#include "XPLMUtilities.h"
#include "viewer_window.h"
#include <boost/property_tree/ptree.hpp>
#include <boost/property_tree/json_parser.hpp>
#include <boost/foreach.hpp>
bool loadPrefs(const boost::filesystem::path & path) {
//open file, and deserialize
std::ifstream f(path.string());
if(f.fail()) {
std::cerr << "Couldn't open properties file: " << path.string() << std::endl;
return false;
}
boost::property_tree::ptree prefs;
read_json(f, prefs);
BOOST_FOREACH(boost::property_tree::ptree::value_type & window_detail_val, prefs.get_child("windows")) {
showViewerWindow(window_detail_val.second);
}
return true;
}
bool savePrefs(const boost::filesystem::path & path) {
boost::property_tree::ptree prefs;
boost::property_tree::ptree windows = getViewerWindowsDetails();
prefs.put("author", "Lee C. Baker");
prefs.put("compile_date", __DATE__ " " __TIME__);
prefs.add_child("windows", windows);
//serialize and save to file
std::ofstream f(path.string());
if(f.fail()) {
return false;
}
try {
write_json(f, prefs);
} catch(boost::property_tree::json_parser_error & e) {
const std::string message = std::string("DRT: Error writing preferences file at ") + path.string() + std::string("\n");
XPLMDebugString(message.c_str());
return false;
}
return false == f.fail();
}<commit_msg>Make preference write error message more descriptive.<commit_after>#include <iostream>
#include "prefs.h"
#include "XPLMUtilities.h"
#include "viewer_window.h"
#include <boost/property_tree/ptree.hpp>
#include <boost/property_tree/json_parser.hpp>
#include <boost/foreach.hpp>
bool loadPrefs(const boost::filesystem::path & path) {
//open file, and deserialize
std::ifstream f(path.string());
if(f.fail()) {
std::cerr << "Couldn't open properties file: " << path.string() << std::endl;
return false;
}
boost::property_tree::ptree prefs;
read_json(f, prefs);
BOOST_FOREACH(boost::property_tree::ptree::value_type & window_detail_val, prefs.get_child("windows")) {
showViewerWindow(window_detail_val.second);
}
return true;
}
bool savePrefs(const boost::filesystem::path & path) {
boost::property_tree::ptree prefs;
boost::property_tree::ptree windows = getViewerWindowsDetails();
prefs.put("author", "Lee C. Baker");
prefs.put("compile_date", __DATE__ " " __TIME__);
prefs.add_child("windows", windows);
//serialize and save to file
std::ofstream f(path.string());
if(f.fail()) {
return false;
}
try {
write_json(f, prefs);
} catch(boost::property_tree::json_parser_error & e) {
const std::string message = std::string("DRT: Error writing preferences file at ") + path.string() + std::string("\n");
XPLMDebugString(message.c_str());
XPLMDebugString(("DRT: " + e.filename() + ":" + std::to_string(e.line())).c_str());
XPLMDebugString(("DRT: " + e.message()).c_str());
return false;
}
return false == f.fail();
}<|endoftext|> |
<commit_before>/*
* =====================================================================================
*
* Filename: 3.cpp
*
* Description: Solution to the third problem of the `evens' section.
*
* Version: 1.0
* Created: 28.01.2015 6,00,07
* Revision: none
* Compiler: gcc
*
* Author: Radoslav Georgiev (sid), rgeorgiev583@gmail.com
* Company: Faculty of Mathematics and Informatics at Sofia University
*
* =====================================================================================
*/
#include <iostream>
using namespace std;
const int MAX_SIZE = 1000;
const char diff = 'a' - 'A';
bool isWordChar(char c)
{
return c == '(' || c == ')' || c == '-' || c >= 'A' && c <= 'Z' || c >= 'a' && c <= 'z';
}
const char* skipWhitespaceReverse(const char* s)
{
while (*s == ' ')
s--;
return s;
}
const char* goToEnd(const char* s)
{
while (*s)
s++;
return s;
}
char toUpper(char c)
{
return c >= 'a' && c <= 'z' ? c - diff : c;
}
char toLower(char c)
{
return c >= 'A' && c <= 'Z' ? c + diff : c;
}
void swap(char* a, char* b)
{
char x = *a;
*a = *b;
*b = x;
}
// Ако изречението е невалидно, връщаме NULL
char* reverseSentence(const char* s)
{
if (!s)
return NULL;
const char* end = goToEnd(s);
end--;
if (end < s || *end != '!' && *end != '.' && *end != '?')
return NULL;
end--;
const char* beg = end;
bool is_first = true;
while (beg >= s)
{
while (beg >= s && isWordChar(*beg))
beg--;
if (beg == end)
return NULL;
beg++;
if (beg < s)
{
char first[2];
strncat(first, beg, 1);
*first = toLower(*first);
strcat(rev, first);
strncat(rev, beg + 1, end - beg);
}
else
{
strncat(rev, beg, end - beg + 1);
end = beg - 1;
if (*end != ' ')
return NULL;
end--;
if (end < s)
return NULL;
if (*end == ',' || *end == ':' || *end == ';')
strncat(rev, end, 1);
strncat(rev, end + 1, 1);
}
}
*rev = toUpper(*rev);
char *p = rev, *lp = NULL;
int b = 0;
while (p)
{
if (*p == '(')
{
b++;
if (lp && b == 0)
{
swap(p, lp);
lp = NULL;
}
}
else if (*p == ')')
{
b--;
if (b == -1)
lp = p;
}
p++;
}
cout << rev << endl;
return 0;
}
<commit_msg>rewrote reverse function signature: now passing reversed string buffer as parameter<commit_after>/*
* =====================================================================================
*
* Filename: 3.cpp
*
* Description: Solution to the third problem of the `evens' section.
*
* Version: 1.0
* Created: 28.01.2015 6,00,07
* Revision: none
* Compiler: gcc
*
* Author: Radoslav Georgiev (sid), rgeorgiev583@gmail.com
* Company: Faculty of Mathematics and Informatics at Sofia University
*
* =====================================================================================
*/
#include <iostream>
using namespace std;
const int MAX_SIZE = 1000;
const char diff = 'a' - 'A';
bool isWordChar(char c)
{
return c == '(' || c == ')' || c == '-' || c >= 'A' && c <= 'Z' || c >= 'a' && c <= 'z';
}
const char* skipWhitespaceReverse(const char* s)
{
while (*s == ' ')
s--;
return s;
}
const char* goToEnd(const char* s)
{
while (*s)
s++;
return s;
}
char toUpper(char c)
{
return c >= 'a' && c <= 'z' ? c - diff : c;
}
char toLower(char c)
{
return c >= 'A' && c <= 'Z' ? c + diff : c;
}
void swap(char* a, char* b)
{
char x = *a;
*a = *b;
*b = x;
}
// Ако изречението е невалидно, връщаме NULL
char* reverseSentence(char* rev, const char* s)
{
if (!s)
return NULL;
const char* end = goToEnd(s);
end--;
if (end < s || *end != '!' && *end != '.' && *end != '?')
return NULL;
end--;
const char* beg = end;
bool is_first = true;
while (beg >= s)
{
while (beg >= s && isWordChar(*beg))
beg--;
if (beg == end)
return NULL;
beg++;
if (beg < s)
{
char first[2];
strncat(first, beg, 1);
*first = toLower(*first);
strcat(rev, first);
strncat(rev, beg + 1, end - beg);
}
else
{
strncat(rev, beg, end - beg + 1);
end = beg - 1;
if (*end != ' ')
return NULL;
end--;
if (end < s)
return NULL;
if (*end == ',' || *end == ':' || *end == ';')
strncat(rev, end, 1);
strncat(rev, end + 1, 1);
}
}
*rev = toUpper(*rev);
char *p = rev, *lp = NULL;
int b = 0;
while (p)
{
if (*p == '(')
{
b++;
if (lp && b == 0)
{
swap(p, lp);
lp = NULL;
}
}
else if (*p == ')')
{
b--;
if (b == -1)
lp = p;
}
p++;
}
cout << rev << endl;
return 0;
}
<|endoftext|> |
<commit_before>#include <string>
#include <sstream>
#include "benchmark.h"
#ifdef HAVE_HACL
extern "C" {
#include <Hacl_Ed25519.h>
}
#endif
#ifdef HAVE_OPENSSL
#include <openssl/evp.h>
#endif
#define SIGNATURE_LENGTH 64
class DSABenchmark: public Benchmark
{
protected:
typedef __attribute__((aligned(32))) uint8_t X25519_KEY[32];
X25519_KEY shared_secret, our_secret, our_public, their_secret, their_public;
size_t msg_len;
uint8_t *signature, *msg;
public:
static std::string column_headers() { return "\"Algorithm\",\"Size [b]\"" + Benchmark::column_headers() + ",\"Avg Cycles/Byte\""; }
DSABenchmark(size_t msg_len, std::string const & prefix) :
Benchmark(prefix),
msg_len(msg_len)
{
signature = new uint8_t[SIGNATURE_LENGTH];
msg = new uint8_t[msg_len];
}
virtual ~DSABenchmark()
{
delete[](msg);
delete[](signature);
}
virtual void bench_setup(const BenchmarkSettings & s)
{
Benchmark::bench_setup(s);
randomize(our_secret, 32);
randomize(their_secret, 32);
randomize(msg, msg_len);
}
virtual void report(std::ostream & rs, const BenchmarkSettings & s) const
{
rs << "\"" << name.c_str() << "\"" << "," << msg_len;
Benchmark::report(rs, s);
rs << "," << (ctotal/(double)msg_len)/(double)s.samples << "\n";
}
};
#ifdef HAVE_HACL
class HaclSign: public DSABenchmark
{
public:
HaclSign(size_t msg_len) : DSABenchmark(msg_len, "HaCl (sign)") {}
virtual void bench_func()
{ Hacl_Ed25519_sign(signature, our_secret, msg, msg_len); }
virtual ~HaclSign() {}
};
#define EXPANDED_KEYS_SIZE 96
class HaclSignExpanded: public DSABenchmark
{
protected:
uint8_t expanded_keys[EXPANDED_KEYS_SIZE];
public:
HaclSignExpanded(size_t msg_len) : DSABenchmark(msg_len, "HaCl (expanded)") {}
virtual void bench_setup(const BenchmarkSettings & s)
{
DSABenchmark::bench_setup(s);
Hacl_Ed25519_expand_keys(expanded_keys, our_secret);
}
virtual void bench_func()
{ Hacl_Ed25519_sign_expanded(signature, expanded_keys, msg, msg_len); }
virtual ~HaclSignExpanded() {}
};
class HaclVerify: public DSABenchmark
{
public:
HaclVerify(size_t msg_len) : DSABenchmark(msg_len, "HaCl (verify)") {}
virtual void bench_setup(const BenchmarkSettings & s)
{
DSABenchmark::bench_setup(s);
Hacl_Ed25519_secret_to_public(our_public, our_secret);
Hacl_Ed25519_sign(signature, our_secret, msg, msg_len);
}
virtual void bench_func()
{
#ifdef _DEBUG
if (!
#endif
Hacl_Ed25519_verify(our_public, msg, msg_len, signature)
#ifdef _DEBUG
) throw std::logic_error("Signature verification failed")
#endif
;
}
virtual ~HaclVerify() {}
};
#endif
#ifdef HAVE_OPENSSL
class OpenSSLSign: public DSABenchmark
{
protected:
size_t sig_len = SIGNATURE_LENGTH;
EVP_MD_CTX *mdctx;
EVP_PKEY *ours = NULL;
public:
OpenSSLSign(size_t msg_len) : DSABenchmark(msg_len, "OpenSSL (sign)") {}
virtual void bench_setup(const BenchmarkSettings & s)
{
DSABenchmark::bench_setup(s);
ours = EVP_PKEY_new();
EVP_PKEY_CTX *pkctx = EVP_PKEY_CTX_new_id(EVP_PKEY_ED25519, NULL);
EVP_PKEY_keygen_init(pkctx);
EVP_PKEY_keygen(pkctx, &ours);
EVP_PKEY_CTX_free(pkctx);
mdctx = EVP_MD_CTX_new();
}
virtual void bench_func()
{
#ifdef _DEBUG
if (EVP_DigestSignInit(mdctx, NULL, NULL, NULL, ours) <= 0)
throw std::logic_error("OpenSSL EVP_DigestSignInit failed");
if (EVP_DigestSign(mdctx, signature, &sig_len, msg, msg_len) <= 0)
throw std::logic_error("OpenSSL EVP_DigestSign failed");
#else
EVP_DigestSignInit(mdctx, NULL, NULL, NULL, ours);
EVP_DigestSign(mdctx, signature, &sig_len, msg, msg_len);
#endif
}
virtual void bench_cleanup(const BenchmarkSettings & s)
{
EVP_MD_CTX_free(mdctx);
EVP_PKEY_free(ours);
DSABenchmark::bench_cleanup(s);
}
virtual ~OpenSSLSign() {}
};
class OpenSSLVerify: public DSABenchmark
{
protected:
size_t sig_len = SIGNATURE_LENGTH;
EVP_MD_CTX *mdctx;
EVP_PKEY *ours = NULL;
public:
OpenSSLVerify(size_t msg_len) : DSABenchmark(msg_len, "OpenSSL (verify)") {}
virtual void bench_setup(const BenchmarkSettings & s)
{
DSABenchmark::bench_setup(s);
ours = EVP_PKEY_new();
EVP_PKEY_CTX *pkctx = EVP_PKEY_CTX_new_id(EVP_PKEY_ED25519, NULL);
EVP_PKEY_keygen_init(pkctx);
EVP_PKEY_keygen(pkctx, &ours);
EVP_PKEY_CTX_free(pkctx);
mdctx = EVP_MD_CTX_new();
if (EVP_DigestSignInit(mdctx, NULL, NULL, NULL, ours) <= 0)
throw std::logic_error("OpenSSL EVP_DigestSignInit failed");
if (EVP_DigestSign(mdctx, signature, &sig_len, msg, msg_len) <= 0)
throw std::logic_error("OpenSSL EVP_DigestSign failed");
}
virtual void bench_func()
{
#ifdef _DEBUG
if (EVP_DigestVerifyInit(mdctx, NULL, NULL, NULL, ours) <= 0)
throw std::logic_error("OpenSSL EVP_DigestVerifyInit failed");
if (EVP_DigestVerify(mdctx, signature, sig_len, msg, msg_len) <= 0)
throw std::logic_error("OpenSSL EVP_DigestVerify failed");
#else
EVP_DigestVerifyInit(mdctx, NULL, NULL, NULL, ours);
EVP_DigestVerify(mdctx, signature, sig_len, msg, msg_len);
#endif
}
virtual void bench_cleanup(const BenchmarkSettings & s)
{
EVP_MD_CTX_free(mdctx);
EVP_PKEY_free(ours);
DSABenchmark::bench_cleanup(s);
}
virtual ~OpenSSLVerify() {}
};
#endif
void bench_ed25519(const BenchmarkSettings & s)
{
size_t data_sizes[] = { 1024, 2048, 4096, 8192, 16384, 32768, 65536 };
for (size_t ds: data_sizes)
{
std::string data_filename = "bench_ed25519_" + std::to_string(ds) + ".csv";
std::list<Benchmark*> todo = {
#ifdef HAVE_HACL
new HaclSign(ds),
new HaclSignExpanded(ds),
new HaclVerify(ds),
#endif
#ifdef HAVE_OPENSSL
new OpenSSLSign(ds),
new OpenSSLVerify(ds),
#endif
};
Benchmark::run_batch(s, DSABenchmark::column_headers(), data_filename, todo);
Benchmark::plot_spec_t plot_spec_cycles =
{ std::make_pair(data_filename, "using 'Avg':xticlabels(strcol('Algorithm')) with boxes title columnheader"),
std::make_pair("", "using 0:'Avg':xticlabels(strcol('Algorithm')):(sprintf(\"%0.0f\", column('Avg'))) with labels font \"Courier,8\" offset char 0,.5") };
Benchmark::make_plot(s,
"svg",
"Ed25519 performance (message size=" + std::to_string(ds) + " bytes)",
"",
"Avg. performance [CPU cycles/operation]",
plot_spec_cycles,
"bench_ed25519_" + std::to_string(ds) + "_cycles.svg",
"");
Benchmark::plot_spec_t plot_spec_bytes =
{ std::make_pair(data_filename, "using 'Avg Cycles/Byte':xticlabels(strcol('Algorithm')) with boxes title columnheader"),
std::make_pair("", "using 0:'Avg Cycles/Byte':xticlabels(strcol('Algorithm')):(sprintf(\"%0.0f\", column('Avg Cycles/Byte'))) with labels font \"Courier,8\" offset char 0,.5") };
Benchmark::make_plot(s,
"svg",
"Ed25519 performance (message size=" + std::to_string(ds) + " bytes)",
"",
"Avg. performance [CPU cycles/byte]",
plot_spec_bytes,
"bench_ed25519_" + std::to_string(ds) + "_bytes.svg",
"");
Benchmark::plot_spec_t plot_spec_candlesticks =
{ std::make_pair(data_filename, "using 0:'Q25':'Min':'Max':'Q75':xticlabels(strcol('Algorithm')) with candlesticks whiskerbars .25") };
Benchmark::make_plot(s,
"svg",
"Ed25519 performance (message size=" + std::to_string(ds) + " bytes)",
"",
"Avg. performance [CPU cycles/operation]",
plot_spec_candlesticks,
"bench_ed25519_" + std::to_string(ds) + "_candlesticks.svg",
"set boxwidth 0.25\nset xrange[-.5:4.5]\nset style fill empty\n");
}
}<commit_msg>Wired new Ed25519 into benchmarks<commit_after>#include <string>
#include <sstream>
#include "benchmark.h"
#ifdef HAVE_HACL
extern "C" {
#include <Hacl_Ed25519.h>
}
#endif
#ifdef HAVE_OPENSSL
#include <openssl/evp.h>
#endif
#define SIGNATURE_LENGTH 64
class DSABenchmark: public Benchmark
{
protected:
typedef __attribute__((aligned(32))) uint8_t X25519_KEY[32];
X25519_KEY shared_secret, our_secret, our_public, their_secret, their_public;
size_t msg_len;
uint8_t *signature, *msg;
public:
static std::string column_headers() { return "\"Algorithm\",\"Size [b]\"" + Benchmark::column_headers() + ",\"Avg Cycles/Byte\""; }
DSABenchmark(size_t msg_len, std::string const & prefix) :
Benchmark(prefix),
msg_len(msg_len)
{
signature = new uint8_t[SIGNATURE_LENGTH];
msg = new uint8_t[msg_len];
}
virtual ~DSABenchmark()
{
delete[](msg);
delete[](signature);
}
virtual void bench_setup(const BenchmarkSettings & s)
{
Benchmark::bench_setup(s);
randomize(our_secret, 32);
randomize(their_secret, 32);
randomize(msg, msg_len);
}
virtual void report(std::ostream & rs, const BenchmarkSettings & s) const
{
rs << "\"" << name.c_str() << "\"" << "," << msg_len;
Benchmark::report(rs, s);
rs << "," << (ctotal/(double)msg_len)/(double)s.samples << "\n";
}
};
#ifdef HAVE_HACL
class HaclSign: public DSABenchmark
{
public:
HaclSign(size_t msg_len) : DSABenchmark(msg_len, "HaCl (sign)") {}
virtual void bench_func()
{ Hacl_Ed25519_sign(signature, our_secret, msg_len, msg); }
virtual ~HaclSign() {}
};
#define EXPANDED_KEYS_SIZE 96
class HaclSignExpanded: public DSABenchmark
{
protected:
uint8_t expanded_keys[EXPANDED_KEYS_SIZE];
public:
HaclSignExpanded(size_t msg_len) : DSABenchmark(msg_len, "HaCl (expanded)") {}
virtual void bench_setup(const BenchmarkSettings & s)
{
DSABenchmark::bench_setup(s);
Hacl_Ed25519_expand_keys(expanded_keys, our_secret);
}
virtual void bench_func()
{ Hacl_Ed25519_sign_expanded(signature, expanded_keys, msg_len, msg); }
virtual ~HaclSignExpanded() {}
};
class HaclVerify: public DSABenchmark
{
public:
HaclVerify(size_t msg_len) : DSABenchmark(msg_len, "HaCl (verify)") {}
virtual void bench_setup(const BenchmarkSettings & s)
{
DSABenchmark::bench_setup(s);
Hacl_Ed25519_secret_to_public(our_public, our_secret);
Hacl_Ed25519_sign(signature, our_secret, msg_len, msg);
}
virtual void bench_func()
{
#ifdef _DEBUG
if (!
#endif
Hacl_Ed25519_verify(our_public, msg_len, msg, signature)
#ifdef _DEBUG
) throw std::logic_error("Signature verification failed")
#endif
;
}
virtual ~HaclVerify() {}
};
#endif
#ifdef HAVE_OPENSSL
class OpenSSLSign: public DSABenchmark
{
protected:
size_t sig_len = SIGNATURE_LENGTH;
EVP_MD_CTX *mdctx;
EVP_PKEY *ours = NULL;
public:
OpenSSLSign(size_t msg_len) : DSABenchmark(msg_len, "OpenSSL (sign)") {}
virtual void bench_setup(const BenchmarkSettings & s)
{
DSABenchmark::bench_setup(s);
ours = EVP_PKEY_new();
EVP_PKEY_CTX *pkctx = EVP_PKEY_CTX_new_id(EVP_PKEY_ED25519, NULL);
EVP_PKEY_keygen_init(pkctx);
EVP_PKEY_keygen(pkctx, &ours);
EVP_PKEY_CTX_free(pkctx);
mdctx = EVP_MD_CTX_new();
}
virtual void bench_func()
{
#ifdef _DEBUG
if (EVP_DigestSignInit(mdctx, NULL, NULL, NULL, ours) <= 0)
throw std::logic_error("OpenSSL EVP_DigestSignInit failed");
if (EVP_DigestSign(mdctx, signature, &sig_len, msg, msg_len) <= 0)
throw std::logic_error("OpenSSL EVP_DigestSign failed");
#else
EVP_DigestSignInit(mdctx, NULL, NULL, NULL, ours);
EVP_DigestSign(mdctx, signature, &sig_len, msg, msg_len);
#endif
}
virtual void bench_cleanup(const BenchmarkSettings & s)
{
EVP_MD_CTX_free(mdctx);
EVP_PKEY_free(ours);
DSABenchmark::bench_cleanup(s);
}
virtual ~OpenSSLSign() {}
};
class OpenSSLVerify: public DSABenchmark
{
protected:
size_t sig_len = SIGNATURE_LENGTH;
EVP_MD_CTX *mdctx;
EVP_PKEY *ours = NULL;
public:
OpenSSLVerify(size_t msg_len) : DSABenchmark(msg_len, "OpenSSL (verify)") {}
virtual void bench_setup(const BenchmarkSettings & s)
{
DSABenchmark::bench_setup(s);
ours = EVP_PKEY_new();
EVP_PKEY_CTX *pkctx = EVP_PKEY_CTX_new_id(EVP_PKEY_ED25519, NULL);
EVP_PKEY_keygen_init(pkctx);
EVP_PKEY_keygen(pkctx, &ours);
EVP_PKEY_CTX_free(pkctx);
mdctx = EVP_MD_CTX_new();
if (EVP_DigestSignInit(mdctx, NULL, NULL, NULL, ours) <= 0)
throw std::logic_error("OpenSSL EVP_DigestSignInit failed");
if (EVP_DigestSign(mdctx, signature, &sig_len, msg, msg_len) <= 0)
throw std::logic_error("OpenSSL EVP_DigestSign failed");
}
virtual void bench_func()
{
#ifdef _DEBUG
if (EVP_DigestVerifyInit(mdctx, NULL, NULL, NULL, ours) <= 0)
throw std::logic_error("OpenSSL EVP_DigestVerifyInit failed");
if (EVP_DigestVerify(mdctx, signature, sig_len, msg, msg_len) <= 0)
throw std::logic_error("OpenSSL EVP_DigestVerify failed");
#else
EVP_DigestVerifyInit(mdctx, NULL, NULL, NULL, ours);
EVP_DigestVerify(mdctx, signature, sig_len, msg, msg_len);
#endif
}
virtual void bench_cleanup(const BenchmarkSettings & s)
{
EVP_MD_CTX_free(mdctx);
EVP_PKEY_free(ours);
DSABenchmark::bench_cleanup(s);
}
virtual ~OpenSSLVerify() {}
};
#endif
void bench_ed25519(const BenchmarkSettings & s)
{
size_t data_sizes[] = { 1024, 2048, 4096, 8192, 16384, 32768, 65536 };
for (size_t ds: data_sizes)
{
std::string data_filename = "bench_ed25519_" + std::to_string(ds) + ".csv";
std::list<Benchmark*> todo = {
#ifdef HAVE_HACL
new HaclSign(ds),
new HaclSignExpanded(ds),
new HaclVerify(ds),
#endif
#ifdef HAVE_OPENSSL
new OpenSSLSign(ds),
new OpenSSLVerify(ds),
#endif
};
Benchmark::run_batch(s, DSABenchmark::column_headers(), data_filename, todo);
Benchmark::plot_spec_t plot_spec_cycles =
{ std::make_pair(data_filename, "using 'Avg':xticlabels(strcol('Algorithm')) with boxes title columnheader"),
std::make_pair("", "using 0:'Avg':xticlabels(strcol('Algorithm')):(sprintf(\"%0.0f\", column('Avg'))) with labels font \"Courier,8\" offset char 0,.5") };
Benchmark::make_plot(s,
"svg",
"Ed25519 performance (message size=" + std::to_string(ds) + " bytes)",
"",
"Avg. performance [CPU cycles/operation]",
plot_spec_cycles,
"bench_ed25519_" + std::to_string(ds) + "_cycles.svg",
"");
Benchmark::plot_spec_t plot_spec_bytes =
{ std::make_pair(data_filename, "using 'Avg Cycles/Byte':xticlabels(strcol('Algorithm')) with boxes title columnheader"),
std::make_pair("", "using 0:'Avg Cycles/Byte':xticlabels(strcol('Algorithm')):(sprintf(\"%0.0f\", column('Avg Cycles/Byte'))) with labels font \"Courier,8\" offset char 0,.5") };
Benchmark::make_plot(s,
"svg",
"Ed25519 performance (message size=" + std::to_string(ds) + " bytes)",
"",
"Avg. performance [CPU cycles/byte]",
plot_spec_bytes,
"bench_ed25519_" + std::to_string(ds) + "_bytes.svg",
"");
Benchmark::plot_spec_t plot_spec_candlesticks =
{ std::make_pair(data_filename, "using 0:'Q25':'Min':'Max':'Q75':xticlabels(strcol('Algorithm')) with candlesticks whiskerbars .25") };
Benchmark::make_plot(s,
"svg",
"Ed25519 performance (message size=" + std::to_string(ds) + " bytes)",
"",
"Avg. performance [CPU cycles/operation]",
plot_spec_candlesticks,
"bench_ed25519_" + std::to_string(ds) + "_candlesticks.svg",
"set boxwidth 0.25\nset xrange[-.5:4.5]\nset style fill empty\n");
}
}<|endoftext|> |
<commit_before>////////////////////////////////////////////////////////////////////////////////
//
// Copyright 2006 - 2015, Paul Beckingham, Federico Hernandez.
//
// 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.
//
// http://www.opensource.org/licenses/mit-license.php
//
////////////////////////////////////////////////////////////////////////////////
#include <cmake.h>
#include <iostream>
#include <iomanip>
#include <fstream>
#include <sstream>
#include <sys/types.h>
#include <inttypes.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <stdlib.h>
#include <pwd.h>
#include <time.h>
#include <Context.h>
#include <Date.h>
#include <Duration.h>
#include <Lexer.h>
#include <ISO8601.h>
#include <text.h>
#include <util.h>
#include <i18n.h>
#include <main.h>
// Global context for use by all.
extern Context context;
////////////////////////////////////////////////////////////////////////////////
// Scans all tasks, and for any recurring tasks, determines whether any new
// child tasks need to be generated to fill gaps.
void handleRecurrence ()
{
// Recurrence can be disabled.
// Note: This is currently a workaround for TD-44, TW-1520.
if (! context.config.getBoolean ("recurrence"))
return;
auto tasks = context.tdb2.pending.get_tasks ();
Date now;
// Look at all tasks and find any recurring ones.
for (auto& t : tasks)
{
if (t.getStatus () == Task::recurring)
{
// Generate a list of due dates for this recurring task, regardless of
// the mask.
std::vector <Date> due;
if (!generateDueDates (t, due))
{
// Determine the end date.
t.setStatus (Task::deleted);
context.tdb2.modify (t);
context.footnote (onExpiration (t));
continue;
}
// Get the mask from the parent task.
std::string mask = t.get ("mask");
// Iterate over the due dates, and check each against the mask.
bool changed = false;
unsigned int i = 0;
for (auto& d : due)
{
if (mask.length () <= i)
{
changed = true;
Task rec (t); // Clone the parent.
rec.setStatus (Task::pending); // Change the status.
rec.id = context.tdb2.next_id (); // New ID.
rec.set ("uuid", uuid ()); // New UUID.
rec.set ("parent", t.get ("uuid")); // Remember mom.
rec.setAsNow ("entry"); // New entry date.
char dueDate[16];
sprintf (dueDate, "%u", (unsigned int) d.toEpoch ());
rec.set ("due", dueDate); // Store generated due date.
if (t.has ("wait"))
{
Date old_wait (t.get_date ("wait"));
Date old_due (t.get_date ("due"));
Date due (d);
sprintf (dueDate, "%u", (unsigned int) (due + (old_wait - old_due)).toEpoch ());
rec.set ("wait", dueDate);
rec.setStatus (Task::waiting);
mask += 'W';
}
else
{
mask += '-';
rec.setStatus (Task::pending);
}
char indexMask[12];
sprintf (indexMask, "%u", (unsigned int) i);
rec.set ("imask", indexMask); // Store index into mask.
rec.remove ("mask"); // Remove the mask of the parent.
// Add the new task to the DB.
context.tdb2.add (rec);
}
++i;
}
// Only modify the parent if necessary.
if (changed)
{
t.set ("mask", mask);
context.tdb2.modify (t);
}
}
// Non-recurring tasks expire too.
else
{
if (t.has ("until") &&
Date (t.get_date ("until")) < now)
{
t.setStatus (Task::deleted);
context.tdb2.modify(t);
context.footnote (onExpiration (t));
}
}
}
}
////////////////////////////////////////////////////////////////////////////////
// Determine a start date (due), an optional end date (until), and an increment
// period (recur). Then generate a set of corresponding dates.
//
// Returns false if the parent recurring task is depleted.
bool generateDueDates (Task& parent, std::vector <Date>& allDue)
{
// Determine due date, recur period and until date.
Date due (parent.get_date ("due"));
if (due == 0)
{
return false;
}
std::string recur = parent.get ("recur");
bool specificEnd = false;
Date until;
if (parent.get ("until") != "")
{
until = Date (parent.get ("until"));
specificEnd = true;
}
int recurrence_limit = context.config.getInteger ("recurrence.limit");
int recurrence_counter = 0;
Date now;
for (Date i = due; ; i = getNextRecurrence (i, recur))
{
allDue.push_back (i);
if (specificEnd && i > until)
{
// If i > until, it means there are no more tasks to generate, and if the
// parent mask contains all + or X, then there never will be another task
// to generate, and this parent task may be safely reaped.
std::string mask = parent.get ("mask");
if (mask.length () == allDue.size () &&
mask.find ('-') == std::string::npos)
return false;
return true;
}
if (i > now)
++recurrence_counter;
if (recurrence_counter >= recurrence_limit)
return true;
}
return true;
}
////////////////////////////////////////////////////////////////////////////////
Date getNextRecurrence (Date& current, std::string& period)
{
int m = current.month ();
int d = current.day ();
int y = current.year ();
// Some periods are difficult, because they can be vague.
if (period == "monthly" ||
period == "P1M")
{
if (++m > 12)
{
m -= 12;
++y;
}
while (! Date::valid (m, d, y))
--d;
return Date (m, d, y);
}
else if (period == "weekdays")
{
int dow = current.dayOfWeek ();
int days;
if (dow == 5) days = 3;
else if (dow == 6) days = 2;
else days = 1;
return current + (days * 86400);
}
else if (Lexer::isDigit (period[0]) &&
period[period.length () - 1] == 'm')
{
int increment = strtol (period.substr (0, period.length () - 1).c_str (), NULL, 10);
m += increment;
while (m > 12)
{
m -= 12;
++y;
}
while (! Date::valid (m, d, y))
--d;
return Date (m, d, y);
}
else if (period[0] == 'P' &&
Lexer::isAllDigits (period.substr (1, period.length () - 2)) &&
period[period.length () - 1] == 'M')
{
int increment = strtol (period.substr (0, period.length () - 1).c_str (), NULL, 10);
m += increment;
while (m > 12)
{
m -= 12;
++y;
}
while (! Date::valid (m, d, y))
--d;
return Date (m, d, y);
}
else if (period == "quarterly" ||
period == "P3M")
{
m += 3;
if (m > 12)
{
m -= 12;
++y;
}
while (! Date::valid (m, d, y))
--d;
return Date (m, d, y);
}
else if (Lexer::isDigit (period[0]) && period[period.length () - 1] == 'q')
{
int increment = strtol (period.substr (0, period.length () - 1).c_str (), NULL, 10);
m += 3 * increment;
while (m > 12)
{
m -= 12;
++y;
}
while (! Date::valid (m, d, y))
--d;
return Date (m, d, y);
}
else if (period == "semiannual" ||
period == "P6M")
{
m += 6;
if (m > 12)
{
m -= 12;
++y;
}
while (! Date::valid (m, d, y))
--d;
return Date (m, d, y);
}
else if (period == "bimonthly" ||
period == "P2M")
{
m += 2;
if (m > 12)
{
m -= 12;
++y;
}
while (! Date::valid (m, d, y))
--d;
return Date (m, d, y);
}
else if (period == "biannual" ||
period == "biyearly" ||
period == "P2Y")
{
y += 2;
return Date (m, d, y);
}
else if (period == "annual" ||
period == "yearly" ||
period == "P1Y")
{
y += 1;
// If the due data just happens to be 2/29 in a leap year, then simply
// incrementing y is going to create an invalid date.
if (m == 2 && d == 29)
d = 28;
return Date (m, d, y);
}
// If the period is an 'easy' one, add it to current, and we're done.
// If it throws an error, the duration was not recognized.
int secs = 0;
std::string::size_type idx = 0;
Duration du;
if (du.parse (period, idx))
{
secs = du;
}
else
{
idx = 0;
ISO8601p p;
if (p.parse (period, idx))
{
secs = p;
}
else
throw std::string (format (STRING_TASK_VALID_RECUR, period));
}
return current + secs;
}
////////////////////////////////////////////////////////////////////////////////
// When the status of a recurring child task changes, the parent task must
// update it's mask.
void updateRecurrenceMask (Task& task)
{
std::string uuid = task.get ("parent");
Task parent;
if (uuid != "" &&
context.tdb2.get (uuid, parent))
{
unsigned int index = strtol (task.get ("imask").c_str (), NULL, 10);
std::string mask = parent.get ("mask");
if (mask.length () > index)
{
mask[index] = (task.getStatus () == Task::pending) ? '-'
: (task.getStatus () == Task::completed) ? '+'
: (task.getStatus () == Task::deleted) ? 'X'
: (task.getStatus () == Task::waiting) ? 'W'
: '?';
}
else
{
std::string mask;
for (unsigned int i = 0; i < index; ++i)
mask += "?";
mask += (task.getStatus () == Task::pending) ? '-'
: (task.getStatus () == Task::completed) ? '+'
: (task.getStatus () == Task::deleted) ? 'X'
: (task.getStatus () == Task::waiting) ? 'W'
: '?';
}
parent.set ("mask", mask);
context.tdb2.modify (parent);
}
}
////////////////////////////////////////////////////////////////////////////////
// Returns a Boolean indicator as to whether a nag message was generated, so
// that commands can control the number of nag messages displayed (ie one is
// enough).
//
// Otherwise generates a nag message, if one is defined, if there are tasks of
// higher urgency.
bool nag (Task& task)
{
// Special tag overrides nagging.
if (task.hasTag ("nonag"))
return false;
std::string nagMessage = context.config.get ("nag");
if (nagMessage != "")
{
// Scan all pending, non-recurring tasks.
auto pending = context.tdb2.pending.get_tasks ();
for (auto& t : pending)
{
if ((t.getStatus () == Task::pending ||
t.getStatus () == Task::waiting) &&
t.urgency () > task.urgency ())
{
context.footnote (nagMessage);
return true;
}
}
}
return false;
}
////////////////////////////////////////////////////////////////////////////////
<commit_msg>Recurrence: Duration replaced by ISO8601p<commit_after>////////////////////////////////////////////////////////////////////////////////
//
// Copyright 2006 - 2015, Paul Beckingham, Federico Hernandez.
//
// 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.
//
// http://www.opensource.org/licenses/mit-license.php
//
////////////////////////////////////////////////////////////////////////////////
#include <cmake.h>
#include <iostream>
#include <iomanip>
#include <fstream>
#include <sstream>
#include <sys/types.h>
#include <inttypes.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <stdlib.h>
#include <pwd.h>
#include <time.h>
#include <Context.h>
#include <Date.h>
#include <ISO8601.h>
#include <Lexer.h>
#include <ISO8601.h>
#include <text.h>
#include <util.h>
#include <i18n.h>
#include <main.h>
// Global context for use by all.
extern Context context;
////////////////////////////////////////////////////////////////////////////////
// Scans all tasks, and for any recurring tasks, determines whether any new
// child tasks need to be generated to fill gaps.
void handleRecurrence ()
{
// Recurrence can be disabled.
// Note: This is currently a workaround for TD-44, TW-1520.
if (! context.config.getBoolean ("recurrence"))
return;
auto tasks = context.tdb2.pending.get_tasks ();
Date now;
// Look at all tasks and find any recurring ones.
for (auto& t : tasks)
{
if (t.getStatus () == Task::recurring)
{
// Generate a list of due dates for this recurring task, regardless of
// the mask.
std::vector <Date> due;
if (!generateDueDates (t, due))
{
// Determine the end date.
t.setStatus (Task::deleted);
context.tdb2.modify (t);
context.footnote (onExpiration (t));
continue;
}
// Get the mask from the parent task.
std::string mask = t.get ("mask");
// Iterate over the due dates, and check each against the mask.
bool changed = false;
unsigned int i = 0;
for (auto& d : due)
{
if (mask.length () <= i)
{
changed = true;
Task rec (t); // Clone the parent.
rec.setStatus (Task::pending); // Change the status.
rec.id = context.tdb2.next_id (); // New ID.
rec.set ("uuid", uuid ()); // New UUID.
rec.set ("parent", t.get ("uuid")); // Remember mom.
rec.setAsNow ("entry"); // New entry date.
char dueDate[16];
sprintf (dueDate, "%u", (unsigned int) d.toEpoch ());
rec.set ("due", dueDate); // Store generated due date.
if (t.has ("wait"))
{
Date old_wait (t.get_date ("wait"));
Date old_due (t.get_date ("due"));
Date due (d);
sprintf (dueDate, "%u", (unsigned int) (due + (old_wait - old_due)).toEpoch ());
rec.set ("wait", dueDate);
rec.setStatus (Task::waiting);
mask += 'W';
}
else
{
mask += '-';
rec.setStatus (Task::pending);
}
char indexMask[12];
sprintf (indexMask, "%u", (unsigned int) i);
rec.set ("imask", indexMask); // Store index into mask.
rec.remove ("mask"); // Remove the mask of the parent.
// Add the new task to the DB.
context.tdb2.add (rec);
}
++i;
}
// Only modify the parent if necessary.
if (changed)
{
t.set ("mask", mask);
context.tdb2.modify (t);
}
}
// Non-recurring tasks expire too.
else
{
if (t.has ("until") &&
Date (t.get_date ("until")) < now)
{
t.setStatus (Task::deleted);
context.tdb2.modify(t);
context.footnote (onExpiration (t));
}
}
}
}
////////////////////////////////////////////////////////////////////////////////
// Determine a start date (due), an optional end date (until), and an increment
// period (recur). Then generate a set of corresponding dates.
//
// Returns false if the parent recurring task is depleted.
bool generateDueDates (Task& parent, std::vector <Date>& allDue)
{
// Determine due date, recur period and until date.
Date due (parent.get_date ("due"));
if (due == 0)
{
return false;
}
std::string recur = parent.get ("recur");
bool specificEnd = false;
Date until;
if (parent.get ("until") != "")
{
until = Date (parent.get ("until"));
specificEnd = true;
}
int recurrence_limit = context.config.getInteger ("recurrence.limit");
int recurrence_counter = 0;
Date now;
for (Date i = due; ; i = getNextRecurrence (i, recur))
{
allDue.push_back (i);
if (specificEnd && i > until)
{
// If i > until, it means there are no more tasks to generate, and if the
// parent mask contains all + or X, then there never will be another task
// to generate, and this parent task may be safely reaped.
std::string mask = parent.get ("mask");
if (mask.length () == allDue.size () &&
mask.find ('-') == std::string::npos)
return false;
return true;
}
if (i > now)
++recurrence_counter;
if (recurrence_counter >= recurrence_limit)
return true;
}
return true;
}
////////////////////////////////////////////////////////////////////////////////
Date getNextRecurrence (Date& current, std::string& period)
{
int m = current.month ();
int d = current.day ();
int y = current.year ();
// Some periods are difficult, because they can be vague.
if (period == "monthly" ||
period == "P1M")
{
if (++m > 12)
{
m -= 12;
++y;
}
while (! Date::valid (m, d, y))
--d;
return Date (m, d, y);
}
else if (period == "weekdays")
{
int dow = current.dayOfWeek ();
int days;
if (dow == 5) days = 3;
else if (dow == 6) days = 2;
else days = 1;
return current + (days * 86400);
}
else if (Lexer::isDigit (period[0]) &&
period[period.length () - 1] == 'm')
{
int increment = strtol (period.substr (0, period.length () - 1).c_str (), NULL, 10);
m += increment;
while (m > 12)
{
m -= 12;
++y;
}
while (! Date::valid (m, d, y))
--d;
return Date (m, d, y);
}
else if (period[0] == 'P' &&
Lexer::isAllDigits (period.substr (1, period.length () - 2)) &&
period[period.length () - 1] == 'M')
{
int increment = strtol (period.substr (0, period.length () - 1).c_str (), NULL, 10);
m += increment;
while (m > 12)
{
m -= 12;
++y;
}
while (! Date::valid (m, d, y))
--d;
return Date (m, d, y);
}
else if (period == "quarterly" ||
period == "P3M")
{
m += 3;
if (m > 12)
{
m -= 12;
++y;
}
while (! Date::valid (m, d, y))
--d;
return Date (m, d, y);
}
else if (Lexer::isDigit (period[0]) && period[period.length () - 1] == 'q')
{
int increment = strtol (period.substr (0, period.length () - 1).c_str (), NULL, 10);
m += 3 * increment;
while (m > 12)
{
m -= 12;
++y;
}
while (! Date::valid (m, d, y))
--d;
return Date (m, d, y);
}
else if (period == "semiannual" ||
period == "P6M")
{
m += 6;
if (m > 12)
{
m -= 12;
++y;
}
while (! Date::valid (m, d, y))
--d;
return Date (m, d, y);
}
else if (period == "bimonthly" ||
period == "P2M")
{
m += 2;
if (m > 12)
{
m -= 12;
++y;
}
while (! Date::valid (m, d, y))
--d;
return Date (m, d, y);
}
else if (period == "biannual" ||
period == "biyearly" ||
period == "P2Y")
{
y += 2;
return Date (m, d, y);
}
else if (period == "annual" ||
period == "yearly" ||
period == "P1Y")
{
y += 1;
// If the due data just happens to be 2/29 in a leap year, then simply
// incrementing y is going to create an invalid date.
if (m == 2 && d == 29)
d = 28;
return Date (m, d, y);
}
// Add the period to current, and we're done.
int secs = 0;
std::string::size_type idx = 0;
ISO8601p p;
if (! p.parse (period, idx))
throw std::string (format (STRING_TASK_VALID_RECUR, period));
secs = (time_t) p;
return current + secs;
}
////////////////////////////////////////////////////////////////////////////////
// When the status of a recurring child task changes, the parent task must
// update it's mask.
void updateRecurrenceMask (Task& task)
{
std::string uuid = task.get ("parent");
Task parent;
if (uuid != "" &&
context.tdb2.get (uuid, parent))
{
unsigned int index = strtol (task.get ("imask").c_str (), NULL, 10);
std::string mask = parent.get ("mask");
if (mask.length () > index)
{
mask[index] = (task.getStatus () == Task::pending) ? '-'
: (task.getStatus () == Task::completed) ? '+'
: (task.getStatus () == Task::deleted) ? 'X'
: (task.getStatus () == Task::waiting) ? 'W'
: '?';
}
else
{
std::string mask;
for (unsigned int i = 0; i < index; ++i)
mask += "?";
mask += (task.getStatus () == Task::pending) ? '-'
: (task.getStatus () == Task::completed) ? '+'
: (task.getStatus () == Task::deleted) ? 'X'
: (task.getStatus () == Task::waiting) ? 'W'
: '?';
}
parent.set ("mask", mask);
context.tdb2.modify (parent);
}
}
////////////////////////////////////////////////////////////////////////////////
// Returns a Boolean indicator as to whether a nag message was generated, so
// that commands can control the number of nag messages displayed (ie one is
// enough).
//
// Otherwise generates a nag message, if one is defined, if there are tasks of
// higher urgency.
bool nag (Task& task)
{
// Special tag overrides nagging.
if (task.hasTag ("nonag"))
return false;
std::string nagMessage = context.config.get ("nag");
if (nagMessage != "")
{
// Scan all pending, non-recurring tasks.
auto pending = context.tdb2.pending.get_tasks ();
for (auto& t : pending)
{
if ((t.getStatus () == Task::pending ||
t.getStatus () == Task::waiting) &&
t.urgency () > task.urgency ())
{
context.footnote (nagMessage);
return true;
}
}
}
return false;
}
////////////////////////////////////////////////////////////////////////////////
<|endoftext|> |
<commit_before>#include "Utility.h"
#include <vector>
#include <random>
#include <chrono>
#include <fstream>
#include <algorithm>
std::vector<std::string> String::split(const std::string& s, const std::string& delim, size_t count)
{
std::vector<std::string> result;
size_t start_index = 0;
size_t end_index = 0;
size_t split_count = 0;
while(end_index < s.size() && split_count < count)
{
end_index = (delim.empty() ?
s.find_first_of(" \t\n", start_index) :
s.find(delim, start_index));
result.push_back(s.substr(start_index, end_index-start_index));
if(end_index == std::string::npos)
{
start_index = std::string::npos;
}
else
{
start_index = end_index + (delim.empty() ? 1 : delim.size());
}
++split_count;
}
if(start_index < s.size())
{
result.push_back(s.substr(start_index));
}
if(delim.empty())
{
auto it = result.begin();
while(it != result.end())
{
if((*it).empty())
{
it = result.erase(it);
}
else
{
(*it) = String::trim_outer_whitespace(*it);
++it;
}
}
}
return result;
}
bool String::starts_with(const std::string& s, const std::string& beginning)
{
if(beginning.size() > s.size())
{
return false;
}
for(size_t i = 0; i < beginning.size(); ++i)
{
if(beginning[i] != s[i])
{
return false;
}
}
return true;
}
bool String::starts_with(const std::string& s, char beginning)
{
return s[0] == beginning;
}
std::string String::trim_outer_whitespace(const std::string& str)
{
if (str.empty())
{
return str;
}
size_t start = 0;
while(start < str.size() && isspace(str[start]))
{
++start;
}
size_t end = std::max(str.size() - 1, start);
while(end > start && isspace(str[end]))
{
--end;
}
return str.substr(start, end - start + 1);
}
std::string String::strip_comments(const std::string& str, char comment)
{
return trim_outer_whitespace(str.substr(0, str.find(comment)));
}
std::string String::strip_block_comment(const std::string& str, char start, char end)
{
auto start_comment_index = str.find(start);
auto end_comment_index = str.find(end);
if(start_comment_index == std::string::npos || end_comment_index == std::string::npos)
{
return String::trim_outer_whitespace(str);
}
auto first_part = trim_outer_whitespace(str.substr(0, start_comment_index));
auto last_part = trim_outer_whitespace(str.substr(end_comment_index + 1));
return strip_block_comment(first_part + " " + last_part, start, end);
}
int Random::random_integer(int min, int max)
{
static std::mt19937_64
generator(std::chrono::system_clock::now().time_since_epoch().count());
return std::uniform_int_distribution<int>(min, max)(generator);
}
double Random::random_normal(double standard_deviation)
{
static std::mt19937_64
generator(std::chrono::system_clock::now().time_since_epoch().count());
return std::normal_distribution<double>(0, standard_deviation)(generator);
}
double Random::random_real(double min, double max)
{
static std::mt19937_64
generator(std::chrono::system_clock::now().time_since_epoch().count());
return std::uniform_real_distribution<double>(min, max)(generator);
}
bool Random::coin_flip()
{
return success_probability(0.5);
}
bool Random::success_probability(double probability)
{
return random_real(0, 1) < probability;
}
// Mean moves left in game given that a number of moves have been made already.
double Math::average_moves_left(double mean_moves, size_t moves_so_far)
{
double A = 0;
double A_prev = -1;
double B = 0;
double B_prev = -1;
// Calculate $$\textrm{moves left}=\sum_{n=n_0}^\infty \frac{nP(n)}{P(n)}$$
// Here, P(n) is the Poisson distribution
for(size_t N = moves_so_far + 1; A != A_prev && B != B_prev; ++N)
{
A_prev = A;
B_prev = B;
auto p = poisson_probability(mean_moves, N);
A += p;
B += N*p;
}
return B/A - moves_so_far;
}
double Math::poisson_probability(double mean, size_t value)
{
auto p = std::exp(-mean);
for(size_t i = 1; i <= value; ++i)
{
p *= (mean/i);
}
return p;
}
Configuration_File::Configuration_File(const std::string& file_name)
{
std::ifstream ifs(file_name);
std::string line;
while(getline(ifs, line))
{
line = String::strip_comments(line, '#');
if(line.empty())
{
continue;
}
if( ! String::contains(line, '='))
{
throw std::runtime_error("Configuration file lines must be of form \"Name = Value\"\n" + line);
}
auto line_split = String::split(line, "=", 1);
parameters[String::trim_outer_whitespace(line_split[0])] = line_split[1];
}
}
std::string Configuration_File::get_text(const std::string& parameter) const
{
try
{
return String::trim_outer_whitespace(parameters.at(parameter));
}
catch(const std::out_of_range&)
{
return "";
}
}
double Configuration_File::get_number(const std::string& parameter) const
{
try
{
return std::stod(get_text(parameter));
}
catch(const std::invalid_argument&)
{
return 0.0;
}
}
std::ofstream Scoped_Stopwatch::out_file;
std::mutex Scoped_Stopwatch::write_lock;
Scoped_Stopwatch::Scoped_Stopwatch(const std::string& name) :
place_name(name),
start_time(std::chrono::steady_clock::now()),
stopped(false)
{
}
Scoped_Stopwatch::~Scoped_Stopwatch()
{
stop();
}
void Scoped_Stopwatch::stop()
{
auto end_time = std::chrono::steady_clock::now();
if(stopped)
{
return;
}
std::lock_guard<std::mutex> write_lock_guard(write_lock);
if( ! out_file)
{
out_file.open("timings.txt");
}
out_file << place_name << "|"
<< std::chrono::duration_cast<std::chrono::duration<double>>
(end_time - start_time).count()
<< '\n';
stopped = true;
}
void Scoped_Stopwatch::add_info(const std::string& info)
{
place_name += info;
}
<commit_msg>Open file for stopwatch on program start<commit_after>#include "Utility.h"
#include <vector>
#include <random>
#include <chrono>
#include <fstream>
#include <algorithm>
std::vector<std::string> String::split(const std::string& s, const std::string& delim, size_t count)
{
std::vector<std::string> result;
size_t start_index = 0;
size_t end_index = 0;
size_t split_count = 0;
while(end_index < s.size() && split_count < count)
{
end_index = (delim.empty() ?
s.find_first_of(" \t\n", start_index) :
s.find(delim, start_index));
result.push_back(s.substr(start_index, end_index-start_index));
if(end_index == std::string::npos)
{
start_index = std::string::npos;
}
else
{
start_index = end_index + (delim.empty() ? 1 : delim.size());
}
++split_count;
}
if(start_index < s.size())
{
result.push_back(s.substr(start_index));
}
if(delim.empty())
{
auto it = result.begin();
while(it != result.end())
{
if((*it).empty())
{
it = result.erase(it);
}
else
{
(*it) = String::trim_outer_whitespace(*it);
++it;
}
}
}
return result;
}
bool String::starts_with(const std::string& s, const std::string& beginning)
{
if(beginning.size() > s.size())
{
return false;
}
for(size_t i = 0; i < beginning.size(); ++i)
{
if(beginning[i] != s[i])
{
return false;
}
}
return true;
}
bool String::starts_with(const std::string& s, char beginning)
{
return s[0] == beginning;
}
std::string String::trim_outer_whitespace(const std::string& str)
{
if (str.empty())
{
return str;
}
size_t start = 0;
while(start < str.size() && isspace(str[start]))
{
++start;
}
size_t end = std::max(str.size() - 1, start);
while(end > start && isspace(str[end]))
{
--end;
}
return str.substr(start, end - start + 1);
}
std::string String::strip_comments(const std::string& str, char comment)
{
return trim_outer_whitespace(str.substr(0, str.find(comment)));
}
std::string String::strip_block_comment(const std::string& str, char start, char end)
{
auto start_comment_index = str.find(start);
auto end_comment_index = str.find(end);
if(start_comment_index == std::string::npos || end_comment_index == std::string::npos)
{
return String::trim_outer_whitespace(str);
}
auto first_part = trim_outer_whitespace(str.substr(0, start_comment_index));
auto last_part = trim_outer_whitespace(str.substr(end_comment_index + 1));
return strip_block_comment(first_part + " " + last_part, start, end);
}
int Random::random_integer(int min, int max)
{
static std::mt19937_64
generator(std::chrono::system_clock::now().time_since_epoch().count());
return std::uniform_int_distribution<int>(min, max)(generator);
}
double Random::random_normal(double standard_deviation)
{
static std::mt19937_64
generator(std::chrono::system_clock::now().time_since_epoch().count());
return std::normal_distribution<double>(0, standard_deviation)(generator);
}
double Random::random_real(double min, double max)
{
static std::mt19937_64
generator(std::chrono::system_clock::now().time_since_epoch().count());
return std::uniform_real_distribution<double>(min, max)(generator);
}
bool Random::coin_flip()
{
return success_probability(0.5);
}
bool Random::success_probability(double probability)
{
return random_real(0, 1) < probability;
}
// Mean moves left in game given that a number of moves have been made already.
double Math::average_moves_left(double mean_moves, size_t moves_so_far)
{
double A = 0;
double A_prev = -1;
double B = 0;
double B_prev = -1;
// Calculate $$\textrm{moves left}=\sum_{n=n_0}^\infty \frac{nP(n)}{P(n)}$$
// Here, P(n) is the Poisson distribution
for(size_t N = moves_so_far + 1; A != A_prev && B != B_prev; ++N)
{
A_prev = A;
B_prev = B;
auto p = poisson_probability(mean_moves, N);
A += p;
B += N*p;
}
return B/A - moves_so_far;
}
double Math::poisson_probability(double mean, size_t value)
{
auto p = std::exp(-mean);
for(size_t i = 1; i <= value; ++i)
{
p *= (mean/i);
}
return p;
}
Configuration_File::Configuration_File(const std::string& file_name)
{
std::ifstream ifs(file_name);
std::string line;
while(getline(ifs, line))
{
line = String::strip_comments(line, '#');
if(line.empty())
{
continue;
}
if( ! String::contains(line, '='))
{
throw std::runtime_error("Configuration file lines must be of form \"Name = Value\"\n" + line);
}
auto line_split = String::split(line, "=", 1);
parameters[String::trim_outer_whitespace(line_split[0])] = line_split[1];
}
}
std::string Configuration_File::get_text(const std::string& parameter) const
{
try
{
return String::trim_outer_whitespace(parameters.at(parameter));
}
catch(const std::out_of_range&)
{
return "";
}
}
double Configuration_File::get_number(const std::string& parameter) const
{
try
{
return std::stod(get_text(parameter));
}
catch(const std::invalid_argument&)
{
return 0.0;
}
}
std::ofstream Scoped_Stopwatch::out_file("timings.txt");
std::mutex Scoped_Stopwatch::write_lock;
Scoped_Stopwatch::Scoped_Stopwatch(const std::string& name) :
place_name(name),
start_time(std::chrono::steady_clock::now()),
stopped(false)
{
}
Scoped_Stopwatch::~Scoped_Stopwatch()
{
stop();
}
void Scoped_Stopwatch::stop()
{
auto end_time = std::chrono::steady_clock::now();
if(stopped)
{
return;
}
std::lock_guard<std::mutex> write_lock_guard(write_lock);
out_file << place_name << "|"
<< std::chrono::duration_cast<std::chrono::duration<double>>
(end_time - start_time).count()
<< '\n';
stopped = true;
}
void Scoped_Stopwatch::add_info(const std::string& info)
{
place_name += info;
}
<|endoftext|> |
<commit_before>/*
@ Kingsley Chen
*/
#include "kbase\strings\string_format.h"
#include <cctype>
#include "kbase\scope_guard.h"
namespace {
using kbase::StringFormatSpecifierError;
using kbase::internal::FmtStr;
using kbase::internal::Placeholder;
using kbase::internal::PlaceholderList;
using kbase::internal::IsDigit;
using kbase::internal::StrToUL;
using kbase::internal::EnsureFormatSpecifier;
enum class FormatStringParseState {
IN_TEXT,
IN_FORMAT
};
const char kEscapeBegin = '{';
const char kEscapeEnd = '}';
const char kSpecifierDelimeter = ':';
const char kPlaceholderChar = '@';
template<typename CharT>
inline unsigned long ExtractPlaceholderIndex(const CharT* first_digit, CharT** last_digit)
{
auto index = StrToUL(first_digit, last_digit);
--*last_digit;
return index;
}
template<typename CharT>
typename FmtStr<CharT>::String AnalyzeFormatStringT(const CharT* fmt,
PlaceholderList<CharT>* placeholders)
{
const size_t kInitialCapacity = 32;
typename FmtStr<CharT>::String analyzed_fmt;
analyzed_fmt.reserve(kInitialCapacity);
placeholders->clear();
Placeholder<CharT> placeholder;
auto state = FormatStringParseState::IN_TEXT;
for (auto ptr = fmt; *ptr != '\0'; ++ptr) {
if (*ptr == kEscapeBegin) {
// `{` is an invalid token for format-state.
EnsureFormatSpecifier(state != FormatStringParseState::IN_FORMAT);
if (*(ptr + 1) == kEscapeBegin) {
// Use `{{` to represent literal `{`.
analyzed_fmt += kEscapeBegin;
++ptr;
} else if (IsDigit(*(ptr + 1))) {
CharT* last_digit;
placeholder.index = ExtractPlaceholderIndex(ptr + 1, &last_digit);
ptr = last_digit;
EnsureFormatSpecifier(*(ptr + 1) == kEscapeEnd ||
*(ptr + 1) == kSpecifierDelimeter);
if (*(ptr + 1) == kSpecifierDelimeter) {
++ptr;
}
// Get into format-state.
state = FormatStringParseState::IN_FORMAT;
} else {
throw StringFormatSpecifierError("Format string is not valid");
}
} else if (*ptr == kEscapeEnd) {
if (state == FormatStringParseState::IN_TEXT) {
EnsureFormatSpecifier(*(ptr + 1) == kEscapeEnd);
analyzed_fmt += kEscapeEnd;
++ptr;
} else {
placeholder.pos = analyzed_fmt.length();
analyzed_fmt += '@';
placeholders->push_back(placeholder);
// Now we turn back to text-state.
state = FormatStringParseState::IN_TEXT;
}
} else {
if (state == FormatStringParseState::IN_TEXT) {
analyzed_fmt += *ptr;
} else {
placeholder.format_specifier += *ptr;
}
}
}
EnsureFormatSpecifier(state == FormatStringParseState::IN_TEXT);
std::sort(std::begin(*placeholders), std::end(*placeholders),
[](const Placeholder<CharT>& lhs, const Placeholder<CharT>& rhs) {
return lhs.index < rhs.index;
});
return analyzed_fmt;
}
} // namespace
namespace kbase {
namespace internal {
std::string AnalyzeFormatString(const char* fmt, PlaceholderList<char>* placeholders)
{
return AnalyzeFormatStringT(fmt, placeholders);
}
std::wstring AnalyzeFormatString(const wchar_t* fmt,
PlaceholderList<wchar_t>* placeholders)
{
return AnalyzeFormatStringT(fmt, placeholders);
}
} // namespace internal
inline int vsnprintfT(char* buf, size_t buf_size, size_t count_to_write,
const char* fmt, va_list args)
{
return vsnprintf_s(buf, buf_size, count_to_write, fmt, args);
}
inline int vsnprintfT(wchar_t* buf, size_t buf_size, size_t count_to_write,
const wchar_t* fmt, va_list args)
{
return _vsnwprintf_s(buf, buf_size, count_to_write, fmt, args);
}
template<typename strT>
void StringAppendPrintfT(strT* str, const typename strT::value_type* fmt, va_list ap)
{
typedef typename strT::value_type charT;
const int kDefaultCharCount = 1024;
charT buf[kDefaultCharCount];
int ret = vsnprintfT(buf, kDefaultCharCount, kDefaultCharCount - 1, fmt, ap);
if (ret >= 0) {
str->append(buf, ret);
return;
}
// data is truncated.
// adjust the buffer size until it fits
const int kMaxAllowedCharCount = (1 << 25);
int tentative_char_count = kDefaultCharCount;
while (true) {
tentative_char_count <<= 1;
if (tentative_char_count > kMaxAllowedCharCount) {
throw StringPrintfDataLengthError("memory needed exceeds the threshold");
}
std::vector<charT> dynamic_buf(tentative_char_count);
// vsnprintf-like functions on Windows don't change the |ap|
// while their counterparts on Linux do.
// if you use VS2013 or higher, or compilers that support C99
// you alternatively can use |va_copy| to make a copy of |ap|
// during each iteration.
int ret = vsnprintfT(&dynamic_buf[0], tentative_char_count,
tentative_char_count - 1, fmt, ap);
if (ret >= 0) {
str->append(&dynamic_buf[0], ret);
return;
}
}
}
void StringAppendPrintf(std::string* str, const char* fmt, ...)
{
va_list args;
va_start(args, fmt);
ON_SCOPE_EXIT([&] { va_end(args); });
StringAppendPrintfT(str, fmt, args);
}
void StringAppendPrintf(std::wstring* str, const wchar_t* fmt, ...)
{
va_list args;
va_start(args, fmt);
ON_SCOPE_EXIT([&] { va_end(args); });
StringAppendPrintfT(str, fmt, args);
}
std::string StringPrintf(const char* fmt, ...)
{
va_list args;
va_start(args, fmt);
ON_SCOPE_EXIT([&] { va_end(args); });
std::string str;
StringAppendPrintfT(&str, fmt, args);
return str;
}
std::wstring StringPrintf(const wchar_t* fmt, ...)
{
va_list args;
va_start(args, fmt);
ON_SCOPE_EXIT([&] { va_end(args); });
std::wstring str;
StringAppendPrintfT(&str, fmt, args);
return str;
}
const std::string& StringPrintf(std::string* str, const char* fmt, ...)
{
va_list args;
va_start(args, fmt);
ON_SCOPE_EXIT([&] { va_end(args); });
str->clear();
StringAppendPrintfT(str, fmt, args);
return *str;
}
const std::wstring& StringPrintf(std::wstring* str, const wchar_t* fmt, ...)
{
va_list args;
va_start(args, fmt);
ON_SCOPE_EXIT([&] { va_end(args); });
str->clear();
StringAppendPrintfT(str, fmt, args);
return *str;
}
} // namespace kbase<commit_msg>string_format: [bugfix] forget to clear temp format-specifier content for the previous placeholder before adding the next one.<commit_after>/*
@ Kingsley Chen
*/
#include "kbase\strings\string_format.h"
#include <cctype>
#include <cstdarg>
#include "kbase\scope_guard.h"
namespace {
using kbase::StringFormatSpecifierError;
using kbase::internal::FmtStr;
using kbase::internal::Placeholder;
using kbase::internal::PlaceholderList;
using kbase::internal::IsDigit;
using kbase::internal::StrToUL;
using kbase::internal::EnsureFormatSpecifier;
enum class FormatStringParseState {
IN_TEXT,
IN_FORMAT
};
const char kEscapeBegin = '{';
const char kEscapeEnd = '}';
const char kSpecifierDelimeter = ':';
const char kPlaceholderChar = '@';
template<typename CharT>
inline unsigned long ExtractPlaceholderIndex(const CharT* first_digit, CharT** last_digit)
{
auto index = StrToUL(first_digit, last_digit);
--*last_digit;
return index;
}
template<typename CharT>
typename FmtStr<CharT>::String AnalyzeFormatStringT(const CharT* fmt,
PlaceholderList<CharT>* placeholders)
{
const size_t kInitialCapacity = 32;
typename FmtStr<CharT>::String analyzed_fmt;
analyzed_fmt.reserve(kInitialCapacity);
placeholders->clear();
Placeholder<CharT> placeholder;
auto state = FormatStringParseState::IN_TEXT;
for (auto ptr = fmt; *ptr != '\0'; ++ptr) {
if (*ptr == kEscapeBegin) {
// `{` is an invalid token for format-state.
EnsureFormatSpecifier(state != FormatStringParseState::IN_FORMAT);
if (*(ptr + 1) == kEscapeBegin) {
// Use `{{` to represent literal `{`.
analyzed_fmt += kEscapeBegin;
++ptr;
} else if (IsDigit(*(ptr + 1))) {
CharT* last_digit;
placeholder.index = ExtractPlaceholderIndex(ptr + 1, &last_digit);
ptr = last_digit;
EnsureFormatSpecifier(*(ptr + 1) == kEscapeEnd ||
*(ptr + 1) == kSpecifierDelimeter);
if (*(ptr + 1) == kSpecifierDelimeter) {
++ptr;
}
// Get into format-state.
state = FormatStringParseState::IN_FORMAT;
} else {
throw StringFormatSpecifierError("Format string is not valid");
}
} else if (*ptr == kEscapeEnd) {
if (state == FormatStringParseState::IN_TEXT) {
EnsureFormatSpecifier(*(ptr + 1) == kEscapeEnd);
analyzed_fmt += kEscapeEnd;
++ptr;
} else {
placeholder.pos = analyzed_fmt.length();
analyzed_fmt += '@';
placeholders->push_back(placeholder);
placeholder.format_specifier.clear();
// Now we turn back to text-state.
state = FormatStringParseState::IN_TEXT;
}
} else {
if (state == FormatStringParseState::IN_TEXT) {
analyzed_fmt += *ptr;
} else {
placeholder.format_specifier += *ptr;
}
}
}
EnsureFormatSpecifier(state == FormatStringParseState::IN_TEXT);
std::sort(std::begin(*placeholders), std::end(*placeholders),
[](const Placeholder<CharT>& lhs, const Placeholder<CharT>& rhs) {
return lhs.index < rhs.index;
});
return analyzed_fmt;
}
} // namespace
namespace kbase {
namespace internal {
std::string AnalyzeFormatString(const char* fmt, PlaceholderList<char>* placeholders)
{
return AnalyzeFormatStringT(fmt, placeholders);
}
std::wstring AnalyzeFormatString(const wchar_t* fmt,
PlaceholderList<wchar_t>* placeholders)
{
return AnalyzeFormatStringT(fmt, placeholders);
}
} // namespace internal
inline int vsnprintfT(char* buf, size_t buf_size, size_t count_to_write,
const char* fmt, va_list args)
{
return vsnprintf_s(buf, buf_size, count_to_write, fmt, args);
}
inline int vsnprintfT(wchar_t* buf, size_t buf_size, size_t count_to_write,
const wchar_t* fmt, va_list args)
{
return _vsnwprintf_s(buf, buf_size, count_to_write, fmt, args);
}
template<typename strT>
void StringAppendPrintfT(strT* str, const typename strT::value_type* fmt, va_list ap)
{
typedef typename strT::value_type charT;
const int kDefaultCharCount = 1024;
charT buf[kDefaultCharCount];
int ret = vsnprintfT(buf, kDefaultCharCount, kDefaultCharCount - 1, fmt, ap);
if (ret >= 0) {
str->append(buf, ret);
return;
}
// data is truncated.
// adjust the buffer size until it fits
const int kMaxAllowedCharCount = (1 << 25);
int tentative_char_count = kDefaultCharCount;
while (true) {
tentative_char_count <<= 1;
if (tentative_char_count > kMaxAllowedCharCount) {
throw StringPrintfDataLengthError("memory needed exceeds the threshold");
}
std::vector<charT> dynamic_buf(tentative_char_count);
// vsnprintf-like functions on Windows don't change the |ap|
// while their counterparts on Linux do.
// if you use VS2013 or higher, or compilers that support C99
// you alternatively can use |va_copy| to make a copy of |ap|
// during each iteration.
int ret = vsnprintfT(&dynamic_buf[0], tentative_char_count,
tentative_char_count - 1, fmt, ap);
if (ret >= 0) {
str->append(&dynamic_buf[0], ret);
return;
}
}
}
void StringAppendPrintf(std::string* str, const char* fmt, ...)
{
va_list args;
va_start(args, fmt);
ON_SCOPE_EXIT([&] { va_end(args); });
StringAppendPrintfT(str, fmt, args);
}
void StringAppendPrintf(std::wstring* str, const wchar_t* fmt, ...)
{
va_list args;
va_start(args, fmt);
ON_SCOPE_EXIT([&] { va_end(args); });
StringAppendPrintfT(str, fmt, args);
}
std::string StringPrintf(const char* fmt, ...)
{
va_list args;
va_start(args, fmt);
ON_SCOPE_EXIT([&] { va_end(args); });
std::string str;
StringAppendPrintfT(&str, fmt, args);
return str;
}
std::wstring StringPrintf(const wchar_t* fmt, ...)
{
va_list args;
va_start(args, fmt);
ON_SCOPE_EXIT([&] { va_end(args); });
std::wstring str;
StringAppendPrintfT(&str, fmt, args);
return str;
}
const std::string& StringPrintf(std::string* str, const char* fmt, ...)
{
va_list args;
va_start(args, fmt);
ON_SCOPE_EXIT([&] { va_end(args); });
str->clear();
StringAppendPrintfT(str, fmt, args);
return *str;
}
const std::wstring& StringPrintf(std::wstring* str, const wchar_t* fmt, ...)
{
va_list args;
va_start(args, fmt);
ON_SCOPE_EXIT([&] { va_end(args); });
str->clear();
StringAppendPrintfT(str, fmt, args);
return *str;
}
} // namespace kbase<|endoftext|> |
<commit_before>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/service/net/service_url_request_context.h"
#include "chrome/service/service_process.h"
#include "net/base/cookie_monster.h"
#include "net/base/cookie_policy.h"
#include "net/base/host_resolver.h"
#include "net/base/ssl_config_service_defaults.h"
#include "net/ftp/ftp_network_layer.h"
#include "net/http/http_auth_handler_factory.h"
#include "net/http/http_cache.h"
#include "net/http/http_network_layer.h"
#include "net/proxy/proxy_service.h"
ServiceURLRequestContextGetter::ServiceURLRequestContextGetter()
: io_message_loop_proxy_(
g_service_process->io_thread()->message_loop_proxy()) {
}
ServiceURLRequestContext::ServiceURLRequestContext() {
host_resolver_ = net::CreateSystemHostResolver(NULL);
DCHECK(g_service_process);
// TODO(sanjeevr): Change CreateSystemProxyConfigService to accept a
// MessageLoopProxy* instead of MessageLoop*.
// Also this needs to be created on the UI thread on Linux. Fix this.
net::ProxyConfigService * proxy_config_service =
net::ProxyService::CreateSystemProxyConfigService(
g_service_process->io_thread()->message_loop(),
g_service_process->file_thread()->message_loop());
proxy_service_ = net::ProxyService::Create(proxy_config_service, false, this,
NULL, NULL, NULL);
ftp_transaction_factory_ = new net::FtpNetworkLayer(host_resolver_);
ssl_config_service_ = new net::SSLConfigServiceDefaults;
http_auth_handler_factory_ = net::HttpAuthHandlerFactory::CreateDefault();
http_transaction_factory_ = new net::HttpCache(
net::HttpNetworkLayer::CreateFactory(NULL, host_resolver_,
proxy_service_,
ssl_config_service_,
http_auth_handler_factory_),
disk_cache::CreateInMemoryCacheBackend(0));
// In-memory cookie store.
cookie_store_ = new net::CookieMonster(NULL, NULL);
accept_language_ = "en-us,fr";
accept_charset_ = "iso-8859-1,*,utf-8";
}
ServiceURLRequestContext::~ServiceURLRequestContext() {
delete ftp_transaction_factory_;
delete http_transaction_factory_;
delete http_auth_handler_factory_;
}
<commit_msg>Fixed build break caused by using the new BackendFactory method of constructing an in-memory cache. BUG=None TEST=Buildbots should pass.<commit_after>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/service/net/service_url_request_context.h"
#include "chrome/service/service_process.h"
#include "net/base/cookie_monster.h"
#include "net/base/cookie_policy.h"
#include "net/base/host_resolver.h"
#include "net/base/ssl_config_service_defaults.h"
#include "net/ftp/ftp_network_layer.h"
#include "net/http/http_auth_handler_factory.h"
#include "net/http/http_cache.h"
#include "net/http/http_network_layer.h"
#include "net/proxy/proxy_service.h"
ServiceURLRequestContextGetter::ServiceURLRequestContextGetter()
: io_message_loop_proxy_(
g_service_process->io_thread()->message_loop_proxy()) {
}
ServiceURLRequestContext::ServiceURLRequestContext() {
host_resolver_ = net::CreateSystemHostResolver(NULL);
DCHECK(g_service_process);
// TODO(sanjeevr): Change CreateSystemProxyConfigService to accept a
// MessageLoopProxy* instead of MessageLoop*.
// Also this needs to be created on the UI thread on Linux. Fix this.
net::ProxyConfigService * proxy_config_service =
net::ProxyService::CreateSystemProxyConfigService(
g_service_process->io_thread()->message_loop(),
g_service_process->file_thread()->message_loop());
proxy_service_ = net::ProxyService::Create(proxy_config_service, false, this,
NULL, NULL, NULL);
ftp_transaction_factory_ = new net::FtpNetworkLayer(host_resolver_);
ssl_config_service_ = new net::SSLConfigServiceDefaults;
http_auth_handler_factory_ = net::HttpAuthHandlerFactory::CreateDefault();
http_transaction_factory_ = new net::HttpCache(
net::HttpNetworkLayer::CreateFactory(NULL, host_resolver_,
proxy_service_,
ssl_config_service_,
http_auth_handler_factory_),
net::HttpCache::DefaultBackend::InMemory(0));
// In-memory cookie store.
cookie_store_ = new net::CookieMonster(NULL, NULL);
accept_language_ = "en-us,fr";
accept_charset_ = "iso-8859-1,*,utf-8";
}
ServiceURLRequestContext::~ServiceURLRequestContext() {
delete ftp_transaction_factory_;
delete http_transaction_factory_;
delete http_auth_handler_factory_;
}
<|endoftext|> |
<commit_before>/*
* Copyright (c) 2016, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
*/
#include <chrono>
#include <gtest/gtest.h>
#include <folly/Baton.h>
#include <folly/futures/InlineExecutor.h>
#include <wangle/concurrent/CPUThreadPoolExecutor.h>
#include <wangle/concurrent/SerialExecutor.h>
using namespace std::chrono;
using wangle::SerialExecutor;
namespace {
void burnMs(uint64_t ms) {
/* sleep override */ std::this_thread::sleep_for(milliseconds(ms));
}
} // namespace
void SimpleTest(std::shared_ptr<folly::Executor> const& parent) {
SerialExecutor executor(parent);
std::vector<int> values;
std::vector<int> expected;
for (int i = 0; i < 20; ++i) {
executor.add([i, &values] {
// make this extra vulnerable to concurrent execution
values.push_back(0);
burnMs(10);
values.back() = i;
});
expected.push_back(i);
}
// wait until last task has executed
folly::Baton<> finished_baton;
executor.add([&finished_baton] { finished_baton.post(); });
finished_baton.wait();
EXPECT_EQ(expected, values);
}
TEST(SerialExecutor, Simple) {
SimpleTest(std::make_shared<wangle::CPUThreadPoolExecutor>(4));
}
TEST(SerialExecutor, SimpleInline) {
SimpleTest(std::make_shared<folly::InlineExecutor>());
}
// The Afterlife test only works with an asynchronous executor (not the
// InlineExecutor), because we want execution of tasks to happen after we
// destroy the SerialExecutor
TEST(SerialExecutor, Afterlife) {
auto cpu_executor = std::make_shared<wangle::CPUThreadPoolExecutor>(4);
auto executor = std::make_unique<SerialExecutor>(cpu_executor);
// block executor until we call start_baton.post()
folly::Baton<> start_baton;
executor->add([&start_baton] { start_baton.wait(); });
std::vector<int> values;
std::vector<int> expected;
for (int i = 0; i < 20; ++i) {
executor->add([i, &values] {
// make this extra vulnerable to concurrent execution
values.push_back(0);
burnMs(10);
values.back() = i;
});
expected.push_back(i);
}
folly::Baton<> finished_baton;
executor->add([&finished_baton] { finished_baton.post(); });
// destroy SerialExecutor
executor.reset();
// now kick off the tasks
start_baton.post();
// wait until last task has executed
finished_baton.wait();
EXPECT_EQ(expected, values);
}
void RecursiveAddTest(std::shared_ptr<folly::Executor> const& parent) {
SerialExecutor executor(parent);
folly::Baton<> finished_baton;
std::vector<int> values;
std::vector<int> expected = {{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}};
int i = 0;
std::function<void()> lambda = [&] {
if (i < 10) {
// make this extra vulnerable to concurrent execution
values.push_back(0);
burnMs(10);
values.back() = i;
executor.add(lambda);
} else if (i < 12) {
// Below we will post this lambda three times to the executor. When
// executed, the lambda will re-post itself during the first ten
// executions. Afterwards we do nothing twice (this else-branch), and
// then on the 13th execution signal that we are finished.
} else {
finished_baton.post();
}
++i;
};
executor.add(lambda);
executor.add(lambda);
executor.add(lambda);
// wait until last task has executed
finished_baton.wait();
EXPECT_EQ(expected, values);
}
TEST(SerialExecutor, RecursiveAdd) {
RecursiveAddTest(std::make_shared<wangle::CPUThreadPoolExecutor>(4));
}
TEST(SerialExecutor, RecursiveAddInline) {
RecursiveAddTest(std::make_shared<folly::InlineExecutor>());
}
TEST(SerialExecutor, ExecutionThrows) {
SerialExecutor executor(std::make_shared<folly::InlineExecutor>());
// an empty folly::Func will throw std::bad_function_call when invoked,
// but SerialExecutor should catch that exception
executor.add(folly::Func{});
}
<commit_msg>don't use std::make_unique, not supported on all platforms<commit_after>/*
* Copyright (c) 2016, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
*/
#include <chrono>
#include <gtest/gtest.h>
#include <folly/Baton.h>
#include <folly/futures/InlineExecutor.h>
#include <wangle/concurrent/CPUThreadPoolExecutor.h>
#include <wangle/concurrent/SerialExecutor.h>
using namespace std::chrono;
using wangle::SerialExecutor;
namespace {
void burnMs(uint64_t ms) {
/* sleep override */ std::this_thread::sleep_for(milliseconds(ms));
}
} // namespace
void SimpleTest(std::shared_ptr<folly::Executor> const& parent) {
SerialExecutor executor(parent);
std::vector<int> values;
std::vector<int> expected;
for (int i = 0; i < 20; ++i) {
executor.add([i, &values] {
// make this extra vulnerable to concurrent execution
values.push_back(0);
burnMs(10);
values.back() = i;
});
expected.push_back(i);
}
// wait until last task has executed
folly::Baton<> finished_baton;
executor.add([&finished_baton] { finished_baton.post(); });
finished_baton.wait();
EXPECT_EQ(expected, values);
}
TEST(SerialExecutor, Simple) {
SimpleTest(std::make_shared<wangle::CPUThreadPoolExecutor>(4));
}
TEST(SerialExecutor, SimpleInline) {
SimpleTest(std::make_shared<folly::InlineExecutor>());
}
// The Afterlife test only works with an asynchronous executor (not the
// InlineExecutor), because we want execution of tasks to happen after we
// destroy the SerialExecutor
TEST(SerialExecutor, Afterlife) {
auto cpu_executor = std::make_shared<wangle::CPUThreadPoolExecutor>(4);
auto executor = folly::make_unique<SerialExecutor>(cpu_executor);
// block executor until we call start_baton.post()
folly::Baton<> start_baton;
executor->add([&start_baton] { start_baton.wait(); });
std::vector<int> values;
std::vector<int> expected;
for (int i = 0; i < 20; ++i) {
executor->add([i, &values] {
// make this extra vulnerable to concurrent execution
values.push_back(0);
burnMs(10);
values.back() = i;
});
expected.push_back(i);
}
folly::Baton<> finished_baton;
executor->add([&finished_baton] { finished_baton.post(); });
// destroy SerialExecutor
executor.reset();
// now kick off the tasks
start_baton.post();
// wait until last task has executed
finished_baton.wait();
EXPECT_EQ(expected, values);
}
void RecursiveAddTest(std::shared_ptr<folly::Executor> const& parent) {
SerialExecutor executor(parent);
folly::Baton<> finished_baton;
std::vector<int> values;
std::vector<int> expected = {{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}};
int i = 0;
std::function<void()> lambda = [&] {
if (i < 10) {
// make this extra vulnerable to concurrent execution
values.push_back(0);
burnMs(10);
values.back() = i;
executor.add(lambda);
} else if (i < 12) {
// Below we will post this lambda three times to the executor. When
// executed, the lambda will re-post itself during the first ten
// executions. Afterwards we do nothing twice (this else-branch), and
// then on the 13th execution signal that we are finished.
} else {
finished_baton.post();
}
++i;
};
executor.add(lambda);
executor.add(lambda);
executor.add(lambda);
// wait until last task has executed
finished_baton.wait();
EXPECT_EQ(expected, values);
}
TEST(SerialExecutor, RecursiveAdd) {
RecursiveAddTest(std::make_shared<wangle::CPUThreadPoolExecutor>(4));
}
TEST(SerialExecutor, RecursiveAddInline) {
RecursiveAddTest(std::make_shared<folly::InlineExecutor>());
}
TEST(SerialExecutor, ExecutionThrows) {
SerialExecutor executor(std::make_shared<folly::InlineExecutor>());
// an empty folly::Func will throw std::bad_function_call when invoked,
// but SerialExecutor should catch that exception
executor.add(folly::Func{});
}
<|endoftext|> |
<commit_before>// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "ui/aura_shell/activation_controller.h"
#include "base/auto_reset.h"
#include "ui/aura/client/activation_delegate.h"
#include "ui/aura/client/aura_constants.h"
#include "ui/aura/root_window.h"
#include "ui/aura/window.h"
#include "ui/aura/window_delegate.h"
#include "ui/aura_shell/shell.h"
#include "ui/aura_shell/shell_window_ids.h"
#include "ui/aura_shell/window_util.h"
namespace aura_shell {
namespace internal {
namespace {
aura::Window* GetContainer(int id) {
return Shell::GetInstance()->GetContainer(id);
}
// Returns true if children of |window| can be activated.
bool SupportsChildActivation(aura::Window* window) {
return window->id() == kShellWindowId_DefaultContainer ||
window->id() == kShellWindowId_AlwaysOnTopContainer ||
window->id() == kShellWindowId_ModalContainer ||
window->id() == kShellWindowId_LockModalContainer;
}
// Returns true if |window| can be activated or deactivated.
// A window manager typically defines some notion of "top level window" that
// supports activation/deactivation.
bool CanActivateWindow(aura::Window* window) {
return window &&
window->IsVisible() &&
(!aura::ActivationDelegate::GetActivationDelegate(window) ||
aura::ActivationDelegate::GetActivationDelegate(window)->
ShouldActivate(NULL)) &&
SupportsChildActivation(window->parent());
}
} // namespace
////////////////////////////////////////////////////////////////////////////////
// ActivationController, public:
ActivationController::ActivationController()
: updating_activation_(false),
default_container_for_test_(NULL) {
aura::ActivationClient::SetActivationClient(this);
aura::RootWindow::GetInstance()->AddRootWindowObserver(this);
}
ActivationController::~ActivationController() {
aura::RootWindow::GetInstance()->RemoveRootWindowObserver(this);
}
// static
aura::Window* ActivationController::GetActivatableWindow(aura::Window* window) {
aura::Window* parent = window->parent();
aura::Window* child = window;
while (parent) {
if (SupportsChildActivation(parent))
return child;
// If |child| isn't activatable, but has transient parent, trace
// that path instead.
if (child->transient_parent())
return GetActivatableWindow(child->transient_parent());
parent = parent->parent();
child = child->parent();
}
return NULL;
}
////////////////////////////////////////////////////////////////////////////////
// StackingController, aura::ActivationClient implementation:
void ActivationController::ActivateWindow(aura::Window* window) {
// Prevent recursion when called from focus.
if (updating_activation_)
return;
AutoReset<bool> in_activate_window(&updating_activation_, true);
if (!window)
return;
// Nothing may actually have changed.
aura::Window* old_active = GetActiveWindow();
if (old_active == window)
return;
// The stacking client may impose rules on what window configurations can be
// activated or deactivated.
if (!CanActivateWindow(window))
return;
if (!window->Contains(window->GetFocusManager()->GetFocusedWindow()))
window->GetFocusManager()->SetFocusedWindow(window);
aura::RootWindow::GetInstance()->SetProperty(aura::kRootWindowActiveWindow,
window);
// Invoke OnLostActive after we've changed the active window. That way if the
// delegate queries for active state it doesn't think the window is still
// active.
if (old_active && aura::ActivationDelegate::GetActivationDelegate(old_active))
aura::ActivationDelegate::GetActivationDelegate(old_active)->OnLostActive();
if (window) {
window->parent()->StackChildAtTop(window);
if (aura::ActivationDelegate::GetActivationDelegate(window))
aura::ActivationDelegate::GetActivationDelegate(window)->OnActivated();
}
}
void ActivationController::DeactivateWindow(aura::Window* window) {
if (window)
ActivateNextWindow(window);
}
aura::Window* ActivationController::GetActiveWindow() {
return reinterpret_cast<aura::Window*>(
aura::RootWindow::GetInstance()->GetProperty(
aura::kRootWindowActiveWindow));
}
bool ActivationController::CanFocusWindow(aura::Window* window) const {
return CanActivateWindow(GetActivatableWindow(window));
}
////////////////////////////////////////////////////////////////////////////////
// ActivationController, aura::WindowObserver implementation:
void ActivationController::OnWindowVisibilityChanged(aura::Window* window,
bool visible) {
if (!visible)
ActivateNextWindow(window);
}
void ActivationController::OnWindowDestroyed(aura::Window* window) {
if (IsActiveWindow(window)) {
// Clear the property before activating something else, since
// ActivateWindow() will attempt to notify the window stored in this value
// otherwise.
aura::RootWindow::GetInstance()->SetProperty(aura::kRootWindowActiveWindow,
NULL);
ActivateWindow(GetTopmostWindowToActivate(window));
}
window->RemoveObserver(this);
}
////////////////////////////////////////////////////////////////////////////////
// ActivationController, aura::RootWindowObserver implementation:
void ActivationController::OnWindowInitialized(aura::Window* window) {
window->AddObserver(this);
}
void ActivationController::OnWindowFocused(aura::Window* window) {
ActivateWindow(GetActivatableWindow(window));
}
////////////////////////////////////////////////////////////////////////////////
// ActivationController, private:
void ActivationController::ActivateNextWindow(aura::Window* window) {
if (IsActiveWindow(window))
ActivateWindow(GetTopmostWindowToActivate(window));
}
aura::Window* ActivationController::GetTopmostWindowToActivate(
aura::Window* ignore) const {
const aura::Window* container =
default_container_for_test_ ? default_container_for_test_ :
GetContainer(kShellWindowId_DefaultContainer);
for (aura::Window::Windows::const_reverse_iterator i =
container->children().rbegin();
i != container->children().rend();
++i) {
if (*i != ignore && CanActivateWindow(*i))
return *i;
}
return NULL;
}
} // namespace internal
} // namespace aura_shell
<commit_msg>[Aura] Mark LockScreen container as supporting activation.<commit_after>// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "ui/aura_shell/activation_controller.h"
#include "base/auto_reset.h"
#include "ui/aura/client/activation_delegate.h"
#include "ui/aura/client/aura_constants.h"
#include "ui/aura/root_window.h"
#include "ui/aura/window.h"
#include "ui/aura/window_delegate.h"
#include "ui/aura_shell/shell.h"
#include "ui/aura_shell/shell_window_ids.h"
#include "ui/aura_shell/window_util.h"
namespace aura_shell {
namespace internal {
namespace {
aura::Window* GetContainer(int id) {
return Shell::GetInstance()->GetContainer(id);
}
// Returns true if children of |window| can be activated.
bool SupportsChildActivation(aura::Window* window) {
return window->id() == kShellWindowId_DefaultContainer ||
window->id() == kShellWindowId_AlwaysOnTopContainer ||
window->id() == kShellWindowId_ModalContainer ||
window->id() == kShellWindowId_LockScreenContainer ||
window->id() == kShellWindowId_LockModalContainer;
}
// Returns true if |window| can be activated or deactivated.
// A window manager typically defines some notion of "top level window" that
// supports activation/deactivation.
bool CanActivateWindow(aura::Window* window) {
return window &&
window->IsVisible() &&
(!aura::ActivationDelegate::GetActivationDelegate(window) ||
aura::ActivationDelegate::GetActivationDelegate(window)->
ShouldActivate(NULL)) &&
SupportsChildActivation(window->parent());
}
} // namespace
////////////////////////////////////////////////////////////////////////////////
// ActivationController, public:
ActivationController::ActivationController()
: updating_activation_(false),
default_container_for_test_(NULL) {
aura::ActivationClient::SetActivationClient(this);
aura::RootWindow::GetInstance()->AddRootWindowObserver(this);
}
ActivationController::~ActivationController() {
aura::RootWindow::GetInstance()->RemoveRootWindowObserver(this);
}
// static
aura::Window* ActivationController::GetActivatableWindow(aura::Window* window) {
aura::Window* parent = window->parent();
aura::Window* child = window;
while (parent) {
if (SupportsChildActivation(parent))
return child;
// If |child| isn't activatable, but has transient parent, trace
// that path instead.
if (child->transient_parent())
return GetActivatableWindow(child->transient_parent());
parent = parent->parent();
child = child->parent();
}
return NULL;
}
////////////////////////////////////////////////////////////////////////////////
// StackingController, aura::ActivationClient implementation:
void ActivationController::ActivateWindow(aura::Window* window) {
// Prevent recursion when called from focus.
if (updating_activation_)
return;
AutoReset<bool> in_activate_window(&updating_activation_, true);
if (!window)
return;
// Nothing may actually have changed.
aura::Window* old_active = GetActiveWindow();
if (old_active == window)
return;
// The stacking client may impose rules on what window configurations can be
// activated or deactivated.
if (!CanActivateWindow(window))
return;
if (!window->Contains(window->GetFocusManager()->GetFocusedWindow()))
window->GetFocusManager()->SetFocusedWindow(window);
aura::RootWindow::GetInstance()->SetProperty(aura::kRootWindowActiveWindow,
window);
// Invoke OnLostActive after we've changed the active window. That way if the
// delegate queries for active state it doesn't think the window is still
// active.
if (old_active && aura::ActivationDelegate::GetActivationDelegate(old_active))
aura::ActivationDelegate::GetActivationDelegate(old_active)->OnLostActive();
if (window) {
window->parent()->StackChildAtTop(window);
if (aura::ActivationDelegate::GetActivationDelegate(window))
aura::ActivationDelegate::GetActivationDelegate(window)->OnActivated();
}
}
void ActivationController::DeactivateWindow(aura::Window* window) {
if (window)
ActivateNextWindow(window);
}
aura::Window* ActivationController::GetActiveWindow() {
return reinterpret_cast<aura::Window*>(
aura::RootWindow::GetInstance()->GetProperty(
aura::kRootWindowActiveWindow));
}
bool ActivationController::CanFocusWindow(aura::Window* window) const {
return CanActivateWindow(GetActivatableWindow(window));
}
////////////////////////////////////////////////////////////////////////////////
// ActivationController, aura::WindowObserver implementation:
void ActivationController::OnWindowVisibilityChanged(aura::Window* window,
bool visible) {
if (!visible)
ActivateNextWindow(window);
}
void ActivationController::OnWindowDestroyed(aura::Window* window) {
if (IsActiveWindow(window)) {
// Clear the property before activating something else, since
// ActivateWindow() will attempt to notify the window stored in this value
// otherwise.
aura::RootWindow::GetInstance()->SetProperty(aura::kRootWindowActiveWindow,
NULL);
ActivateWindow(GetTopmostWindowToActivate(window));
}
window->RemoveObserver(this);
}
////////////////////////////////////////////////////////////////////////////////
// ActivationController, aura::RootWindowObserver implementation:
void ActivationController::OnWindowInitialized(aura::Window* window) {
window->AddObserver(this);
}
void ActivationController::OnWindowFocused(aura::Window* window) {
ActivateWindow(GetActivatableWindow(window));
}
////////////////////////////////////////////////////////////////////////////////
// ActivationController, private:
void ActivationController::ActivateNextWindow(aura::Window* window) {
if (IsActiveWindow(window))
ActivateWindow(GetTopmostWindowToActivate(window));
}
aura::Window* ActivationController::GetTopmostWindowToActivate(
aura::Window* ignore) const {
const aura::Window* container =
default_container_for_test_ ? default_container_for_test_ :
GetContainer(kShellWindowId_DefaultContainer);
for (aura::Window::Windows::const_reverse_iterator i =
container->children().rbegin();
i != container->children().rend();
++i) {
if (*i != ignore && CanActivateWindow(*i))
return *i;
}
return NULL;
}
} // namespace internal
} // namespace aura_shell
<|endoftext|> |
<commit_before>//------------------------------------------------------------------------------
// CLING - the C++ LLVM-based InterpreterG :)
// version: $Id$
// author: Axel Naumann <axel@cern.ch>
//------------------------------------------------------------------------------
#include "cling/MetaProcessor/MetaProcessor.h"
#include "InputValidator.h"
#include "cling/Interpreter/Interpreter.h"
#include "clang/Basic/FileManager.h"
#include "clang/Basic/TargetInfo.h"
#include "clang/Frontend/CompilerInstance.h"
#include "clang/Lex/Preprocessor.h"
#include "llvm/Support/Path.h"
using namespace clang;
namespace cling {
namespace tok {
enum TokenKind {
commandstart,
ident,
l_paren,
r_paren,
anystring,
comma,
booltrue,
boolfalse,
eof,
unknown
};
}
class Token {
private:
tok::TokenKind kind;
const char* bufStart;
const char* bufEnd;
void startToken() {
bufStart = 0;
bufEnd = 0;
kind = tok::unknown;
}
public:
tok::TokenKind getKind() const { return kind; }
size_t getLength() const { return bufEnd - bufStart; }
const char* getBufStart() const { return bufStart; }
friend class CommandLexer;
};
class CommandLexer {
private:
const char* bufferStart;
const char* bufferEnd;
const char* curPos;
const InvocationOptions& m_Opts;
public:
CommandLexer(const char* bufStart, const char* bufEnd,
const InvocationOptions& Opts)
: bufferStart(bufStart), bufferEnd(bufEnd), curPos(bufStart), m_Opts(Opts)
{ }
void LexBlankSpace() {
// TODO: React on EOF.
while (*curPos == ' ' || *curPos == '\t')
++curPos;
}
bool LexCommandSymbol(Token& Result) {
Result.startToken();
LexBlankSpace();
Result.bufStart = curPos;
for (size_t i = 0; i < m_Opts.MetaString.size(); ++i, ++curPos)
if (*curPos != m_Opts.MetaString[i]) {
Result.bufEnd = Result.bufStart;
return false;
}
Result.bufEnd = curPos;
return true;
}
bool LexIdent(Token& Result) {
Result.startToken();
Result.bufStart = curPos;
unsigned char C = *curPos;
while ((C >= 'A' && C <= 'Z') || (C >= 'a' && C <= 'z'))
C = *++curPos;
Result.bufEnd = curPos;
if (Result.getLength() > 0) {
Result.kind = tok::ident;
return true;
}
return false;
}
bool LexAnyString(Token& Result) {
Result.startToken();
LexBlankSpace();
Result.bufStart = curPos;
unsigned char C = *curPos;
while (C != ' ' && C != '\n' && C != '\t' &&
C != '\0' && C != '(' && C != ')')
C = *++curPos;
Result.bufEnd = curPos;
if (Result.getLength() > 0) {
Result.kind = tok::anystring;
return true;
}
return false;
}
bool LexSpecialSymbol(Token& Result) {
Result.startToken();
LexBlankSpace();
Result.bufStart = curPos;
if (*curPos == '(') {
Result.kind = tok::l_paren;
++curPos;
}
else if (*curPos == ')') {
Result.kind = tok::r_paren;
++curPos;
}
else if (*curPos == ',') {
Result.kind = tok::comma;
++curPos;
}
Result.bufEnd = curPos;
return Result.kind != tok::unknown;
}
bool LexBool(Token& Result) {
Result.startToken();
LexBlankSpace();
Result.bufStart = curPos;
if (*curPos == '0') {
Result.kind = tok::boolfalse;
++curPos;
}
else if (*curPos == '1') {
Result.kind = tok::booltrue;
++curPos;
}
Result.bufEnd = curPos;
return Result.kind != tok::unknown;
}
};
MetaProcessor::MetaProcessor(Interpreter& interp) : m_Interp(interp) {
m_InputValidator.reset(new InputValidator());
}
MetaProcessor::~MetaProcessor() {}
int MetaProcessor::process(const char* input_text,
StoredValueRef* result /*=0*/) {
if (!input_text) { // null pointer, nothing to do.
return 0;
}
if (!input_text[0]) { // empty string, nothing to do.
return m_InputValidator->getExpectedIndent();
}
std::string input_line(input_text);
if (input_line == "\n") { // just a blank line, nothing to do.
return 0;
}
// Check for and handle meta commands.
if (ProcessMeta(input_line, result)) {
return 0;
}
// Check if the current statement is now complete. If not, return to
// prompt for more.
if (m_InputValidator->validate(input_line, m_Interp.getCI()->getLangOpts())
== InputValidator::kIncomplete) {
return m_InputValidator->getExpectedIndent();
}
// We have a complete statement, compile and execute it.
std::string input = m_InputValidator->getInput();
m_InputValidator->reset();
if (m_Options.RawInput)
m_Interp.declare(input);
else
m_Interp.process(input, result);
return 0;
}
MetaProcessorOpts& MetaProcessor::getMetaProcessorOpts() {
// Take interpreter's state
m_Options.PrintingAST = m_Interp.isPrintingAST();
return m_Options;
}
// Command syntax: meta_command := <command_symbol><command>[arg_list]
// command_symbol := '.' | '//.'
// command := ident
// arg_list := any_string[(extra_arg_list)] [' ' arg_list]
// extra_arg_list := any_string [, extra_arg_list]
//
bool MetaProcessor::ProcessMeta(const std::string& input_line,
StoredValueRef* result){
llvm::MemoryBuffer* MB = llvm::MemoryBuffer::getMemBuffer(input_line);
Token Tok;
CommandLexer CmdLexer(MB->getBufferStart(), MB->getBufferEnd(),
m_Interp.getOptions());
if (!CmdLexer.LexCommandSymbol(Tok)) {
// No error because it may be line containing code
return false;
}
if (!CmdLexer.LexIdent(Tok)) {
llvm::errs() << "Command name token expected. Try .help\n";
return false;
}
llvm::StringRef Command (Tok.getBufStart(), Tok.getLength());
// Should be used for faster comparison if the command is only one char long.
unsigned char CmdStartChar = *Tok.getBufStart();
// .q Exits the process.
if (CmdStartChar == 'q') {
m_Options.Quitting = true;
return true;
}
else if (CmdStartChar == 'L') {
if (!CmdLexer.LexAnyString(Tok)) {
llvm::errs() << "Filename expected.\n";
return false;
}
//TODO: Check if the file exists and is readable.
if (!m_Interp.loadFile(llvm::StringRef(Tok.getBufStart(), Tok.getLength())))
llvm::errs() << "Load file failed.\n";
return true;
}
else if (CmdStartChar == 'x' || CmdStartChar == 'X') {
if (!CmdLexer.LexAnyString(Tok)) {
llvm::errs() << "Filename expected.\n";
return false;
}
llvm::sys::Path file(llvm::StringRef(Tok.getBufStart(), Tok.getLength()));
llvm::StringRef args;
// TODO: Check whether the file exists using the compilers header search.
// if (!file.canRead()) {
// llvm::errs() << "File doesn't exist or not readable.\n";
// return false;
// }
CmdLexer.LexSpecialSymbol(Tok);
if (Tok.getKind() == tok::l_paren) {
// Good enough for now.
if (!CmdLexer.LexAnyString(Tok)) {
llvm::errs() << "Argument list expected.\n";
return false;
}
args = llvm::StringRef(Tok.getBufStart(), Tok.getLength());
if (!CmdLexer.LexSpecialSymbol(Tok) && Tok.getKind() == tok::r_paren) {
llvm::errs() << "Closing parenthesis expected.\n";
return false;
}
}
if (!executeFile(file.str(), args, result))
llvm::errs() << "Execute file failed.\n";
return true;
}
else if (CmdStartChar == 'U') {
// if (!CmdLexer.LexAnyString(Tok)) {
// llvm::errs() << "Filename expected.\n";
// return false;
// }
// llvm::sys::Path file(llvm::StringRef(Tok.bufStart, Tok.getLength()));
// TODO: Check whether the file exists using the compilers header search.
// if (!file.canRead()) {
// llvm::errs() << "File doesn't exist or not readable.\n";
// return false;
// } else
// if (file.isDynamicLibrary()) {
// llvm::errs() << "cannot unload shared libraries yet!.\n";
// return false;
// }
// TODO: Later comes more fine-grained unloading. For now just:
m_Interp.unload();
return true;
}
else if (CmdStartChar == '@') {
m_InputValidator->reset();
return true;
}
else if (CmdStartChar == 'I') {
if (CmdLexer.LexAnyString(Tok)) {
llvm::sys::Path path(llvm::StringRef(Tok.getBufStart(), Tok.getLength()));
// TODO: Check whether the file exists using the compilers header search.
// if (!path.canRead()) {
// llvm::errs() << "Path doesn't exist or not readable.\n";
// return false;
// }
m_Interp.AddIncludePath(path.str());
}
else {
m_Interp.DumpIncludePath();
}
return true;
}
else if (Command.equals("printAST")) {
if (!CmdLexer.LexBool(Tok)) {
bool flag = !m_Interp.isPrintingAST();
m_Interp.enablePrintAST(flag);
llvm::outs() << (flag ? "P" : "Not p") << "rinting AST\n";
}
else {
if (Tok.getKind() == tok::boolfalse)
m_Interp.enablePrintAST(false);
else if (Tok.getKind() == tok::booltrue)
m_Interp.enablePrintAST(true);
else {
llvm::errs() << "Boolean value expected.\n";
return false;
}
}
//m_Options.PrintingAST = m_Interp.isPrintingAST(); ????
return true;
}
else if (Command.equals("rawInput")) {
if (!CmdLexer.LexBool(Tok)) {
m_Options.RawInput = !m_Options.RawInput;
llvm::outs() << (m_Options.RawInput ? "U" :"Not u") << "sing raw input\n";
}
else {
if (Tok.getKind() == tok::boolfalse)
m_Options.RawInput = false;
else if (Tok.getKind() == tok::booltrue)
m_Options.RawInput = true;
else {
llvm::errs() << "Boolean value expected.\n";
return false;
}
}
return true;
}
else if (Command.equals("dynamicExtensions")) {
if (!CmdLexer.LexBool(Tok)) {
bool flag = !m_Interp.isDynamicLookupEnabled();
m_Interp.enableDynamicLookup(flag);
llvm::outs() << (flag ? "U" : "Not u") << "sing dynamic extensions\n";
}
else {
if (Tok.getKind() == tok::boolfalse)
m_Interp.enableDynamicLookup(false);
else if (Tok.getKind() == tok::booltrue)
m_Interp.enableDynamicLookup(true);
else {
llvm::errs() << "Boolean value expected.\n";
return false;
}
}
return true;
}
else if (Command.equals("help")) {
PrintCommandHelp();
return true;
}
else if (Command.equals("file")) {
PrintFileStats();
return true;
}
return false;
}
void MetaProcessor::PrintCommandHelp() {
std::string& metaString = m_Interp.getOptions().MetaString;
llvm::outs() << "Cling meta commands usage\n";
llvm::outs() << "Syntax: .Command [arg0 arg1 ... argN]\n";
llvm::outs() << "\n";
llvm::outs() << metaString << "q\t\t\t\t- Exit the program\n";
llvm::outs() << metaString << "L <filename>\t\t\t - Load file or library\n";
llvm::outs() << metaString << "(x|X) <filename>[args]\t\t- Same as .L and runs a ";
llvm::outs() << "function with signature ";
llvm::outs() << "\t\t\t\tret_type filename(args)\n";
llvm::outs() << metaString << "I [path]\t\t\t- Shows the include path. If a path is ";
llvm::outs() << "given - \n\t\t\t\tadds the path to the include paths\n";
llvm::outs() << metaString << "@ \t\t\t\t- Cancels and ignores the multiline input\n";
llvm::outs() << metaString << "rawInput [0|1]\t\t\t- Toggle wrapping and printing ";
llvm::outs() << "the execution\n\t\t\t\tresults of the input\n";
llvm::outs() << metaString << "dynamicExtensions [0|1]\t- Toggles the use of the ";
llvm::outs() << "dynamic scopes and the \t\t\t\tlate binding\n";
llvm::outs() << metaString << "printAST [0|1]\t\t\t- Toggles the printing of input's ";
llvm::outs() << "corresponding \t\t\t\tAST nodes\n";
llvm::outs() << metaString << "help\t\t\t\t- Shows this information\n";
}
void MetaProcessor::PrintFileStats() {
const SourceManager& SM = m_Interp.getCI()->getSourceManager();
SM.getFileManager().PrintStats();
llvm::outs() << "\n***\n\n";
for (SourceManager::fileinfo_iterator I = SM.fileinfo_begin(),
E = SM.fileinfo_end(); I != E; ++I) {
llvm::outs() << (*I).first->getName();
llvm::outs() << "\n";
}
}
// Run a file: .x file[(args)]
bool MetaProcessor::executeFile(llvm::StringRef file, llvm::StringRef args,
StoredValueRef* result) {
// Look for start of parameters:
typedef std::pair<llvm::StringRef,llvm::StringRef> StringRefPair;
// StringRefPair pairFileArgs = llvm::StringRef(fileWithArgs).split('(');
// if (pairFileArgs.second.empty()) {
// pairFileArgs.second = ")";
// }
StringRefPair pairPathFile = file.rsplit('/');
if (pairPathFile.second.empty()) {
pairPathFile.second = pairPathFile.first;
}
StringRefPair pairFuncExt = pairPathFile.second.rsplit('.');
Interpreter::CompilationResult interpRes = Interpreter::kSuccess;
if (m_Interp.loadFile(file)) {
std::string expression = pairFuncExt.first.str() + "(" + args.str() + ")";
interpRes = m_Interp.evaluate(expression, result);
}
return (interpRes != Interpreter::kFailure);
}
} // end namespace cling
<commit_msg>Fix memory leak (coverity #47844)<commit_after>//------------------------------------------------------------------------------
// CLING - the C++ LLVM-based InterpreterG :)
// version: $Id$
// author: Axel Naumann <axel@cern.ch>
//------------------------------------------------------------------------------
#include "cling/MetaProcessor/MetaProcessor.h"
#include "InputValidator.h"
#include "cling/Interpreter/Interpreter.h"
#include "clang/Basic/FileManager.h"
#include "clang/Basic/TargetInfo.h"
#include "clang/Frontend/CompilerInstance.h"
#include "clang/Lex/Preprocessor.h"
#include "llvm/Support/Path.h"
using namespace clang;
namespace cling {
namespace tok {
enum TokenKind {
commandstart,
ident,
l_paren,
r_paren,
anystring,
comma,
booltrue,
boolfalse,
eof,
unknown
};
}
class Token {
private:
tok::TokenKind kind;
const char* bufStart;
const char* bufEnd;
void startToken() {
bufStart = 0;
bufEnd = 0;
kind = tok::unknown;
}
public:
tok::TokenKind getKind() const { return kind; }
size_t getLength() const { return bufEnd - bufStart; }
const char* getBufStart() const { return bufStart; }
friend class CommandLexer;
};
class CommandLexer {
private:
const char* bufferStart;
const char* bufferEnd;
const char* curPos;
const InvocationOptions& m_Opts;
public:
CommandLexer(const char* bufStart, const char* bufEnd,
const InvocationOptions& Opts)
: bufferStart(bufStart), bufferEnd(bufEnd), curPos(bufStart), m_Opts(Opts)
{ }
void LexBlankSpace() {
// TODO: React on EOF.
while (*curPos == ' ' || *curPos == '\t')
++curPos;
}
bool LexCommandSymbol(Token& Result) {
Result.startToken();
LexBlankSpace();
Result.bufStart = curPos;
for (size_t i = 0; i < m_Opts.MetaString.size(); ++i, ++curPos)
if (*curPos != m_Opts.MetaString[i]) {
Result.bufEnd = Result.bufStart;
return false;
}
Result.bufEnd = curPos;
return true;
}
bool LexIdent(Token& Result) {
Result.startToken();
Result.bufStart = curPos;
unsigned char C = *curPos;
while ((C >= 'A' && C <= 'Z') || (C >= 'a' && C <= 'z'))
C = *++curPos;
Result.bufEnd = curPos;
if (Result.getLength() > 0) {
Result.kind = tok::ident;
return true;
}
return false;
}
bool LexAnyString(Token& Result) {
Result.startToken();
LexBlankSpace();
Result.bufStart = curPos;
unsigned char C = *curPos;
while (C != ' ' && C != '\n' && C != '\t' &&
C != '\0' && C != '(' && C != ')')
C = *++curPos;
Result.bufEnd = curPos;
if (Result.getLength() > 0) {
Result.kind = tok::anystring;
return true;
}
return false;
}
bool LexSpecialSymbol(Token& Result) {
Result.startToken();
LexBlankSpace();
Result.bufStart = curPos;
if (*curPos == '(') {
Result.kind = tok::l_paren;
++curPos;
}
else if (*curPos == ')') {
Result.kind = tok::r_paren;
++curPos;
}
else if (*curPos == ',') {
Result.kind = tok::comma;
++curPos;
}
Result.bufEnd = curPos;
return Result.kind != tok::unknown;
}
bool LexBool(Token& Result) {
Result.startToken();
LexBlankSpace();
Result.bufStart = curPos;
if (*curPos == '0') {
Result.kind = tok::boolfalse;
++curPos;
}
else if (*curPos == '1') {
Result.kind = tok::booltrue;
++curPos;
}
Result.bufEnd = curPos;
return Result.kind != tok::unknown;
}
};
MetaProcessor::MetaProcessor(Interpreter& interp) : m_Interp(interp) {
m_InputValidator.reset(new InputValidator());
}
MetaProcessor::~MetaProcessor() {}
int MetaProcessor::process(const char* input_text,
StoredValueRef* result /*=0*/) {
if (!input_text) { // null pointer, nothing to do.
return 0;
}
if (!input_text[0]) { // empty string, nothing to do.
return m_InputValidator->getExpectedIndent();
}
std::string input_line(input_text);
if (input_line == "\n") { // just a blank line, nothing to do.
return 0;
}
// Check for and handle meta commands.
if (ProcessMeta(input_line, result)) {
return 0;
}
// Check if the current statement is now complete. If not, return to
// prompt for more.
if (m_InputValidator->validate(input_line, m_Interp.getCI()->getLangOpts())
== InputValidator::kIncomplete) {
return m_InputValidator->getExpectedIndent();
}
// We have a complete statement, compile and execute it.
std::string input = m_InputValidator->getInput();
m_InputValidator->reset();
if (m_Options.RawInput)
m_Interp.declare(input);
else
m_Interp.process(input, result);
return 0;
}
MetaProcessorOpts& MetaProcessor::getMetaProcessorOpts() {
// Take interpreter's state
m_Options.PrintingAST = m_Interp.isPrintingAST();
return m_Options;
}
// Command syntax: meta_command := <command_symbol><command>[arg_list]
// command_symbol := '.' | '//.'
// command := ident
// arg_list := any_string[(extra_arg_list)] [' ' arg_list]
// extra_arg_list := any_string [, extra_arg_list]
//
bool MetaProcessor::ProcessMeta(const std::string& input_line,
StoredValueRef* result){
llvm::OwningPtr<llvm::MemoryBuffer> MB;
MB.reset(llvm::MemoryBuffer::getMemBuffer(input_line));
Token Tok;
CommandLexer CmdLexer(MB->getBufferStart(), MB->getBufferEnd(),
m_Interp.getOptions());
if (!CmdLexer.LexCommandSymbol(Tok)) {
// No error because it may be line containing code
return false;
}
if (!CmdLexer.LexIdent(Tok)) {
llvm::errs() << "Command name token expected. Try .help\n";
return false;
}
llvm::StringRef Command (Tok.getBufStart(), Tok.getLength());
// Should be used for faster comparison if the command is only one char long.
unsigned char CmdStartChar = *Tok.getBufStart();
// .q Exits the process.
if (CmdStartChar == 'q') {
m_Options.Quitting = true;
return true;
}
else if (CmdStartChar == 'L') {
if (!CmdLexer.LexAnyString(Tok)) {
llvm::errs() << "Filename expected.\n";
return false;
}
//TODO: Check if the file exists and is readable.
if (!m_Interp.loadFile(llvm::StringRef(Tok.getBufStart(), Tok.getLength())))
llvm::errs() << "Load file failed.\n";
return true;
}
else if (CmdStartChar == 'x' || CmdStartChar == 'X') {
if (!CmdLexer.LexAnyString(Tok)) {
llvm::errs() << "Filename expected.\n";
return false;
}
llvm::sys::Path file(llvm::StringRef(Tok.getBufStart(), Tok.getLength()));
llvm::StringRef args;
// TODO: Check whether the file exists using the compilers header search.
// if (!file.canRead()) {
// llvm::errs() << "File doesn't exist or not readable.\n";
// return false;
// }
CmdLexer.LexSpecialSymbol(Tok);
if (Tok.getKind() == tok::l_paren) {
// Good enough for now.
if (!CmdLexer.LexAnyString(Tok)) {
llvm::errs() << "Argument list expected.\n";
return false;
}
args = llvm::StringRef(Tok.getBufStart(), Tok.getLength());
if (!CmdLexer.LexSpecialSymbol(Tok) && Tok.getKind() == tok::r_paren) {
llvm::errs() << "Closing parenthesis expected.\n";
return false;
}
}
if (!executeFile(file.str(), args, result))
llvm::errs() << "Execute file failed.\n";
return true;
}
else if (CmdStartChar == 'U') {
// if (!CmdLexer.LexAnyString(Tok)) {
// llvm::errs() << "Filename expected.\n";
// return false;
// }
// llvm::sys::Path file(llvm::StringRef(Tok.bufStart, Tok.getLength()));
// TODO: Check whether the file exists using the compilers header search.
// if (!file.canRead()) {
// llvm::errs() << "File doesn't exist or not readable.\n";
// return false;
// } else
// if (file.isDynamicLibrary()) {
// llvm::errs() << "cannot unload shared libraries yet!.\n";
// return false;
// }
// TODO: Later comes more fine-grained unloading. For now just:
m_Interp.unload();
return true;
}
else if (CmdStartChar == '@') {
m_InputValidator->reset();
return true;
}
else if (CmdStartChar == 'I') {
if (CmdLexer.LexAnyString(Tok)) {
llvm::sys::Path path(llvm::StringRef(Tok.getBufStart(), Tok.getLength()));
// TODO: Check whether the file exists using the compilers header search.
// if (!path.canRead()) {
// llvm::errs() << "Path doesn't exist or not readable.\n";
// return false;
// }
m_Interp.AddIncludePath(path.str());
}
else {
m_Interp.DumpIncludePath();
}
return true;
}
else if (Command.equals("printAST")) {
if (!CmdLexer.LexBool(Tok)) {
bool flag = !m_Interp.isPrintingAST();
m_Interp.enablePrintAST(flag);
llvm::outs() << (flag ? "P" : "Not p") << "rinting AST\n";
}
else {
if (Tok.getKind() == tok::boolfalse)
m_Interp.enablePrintAST(false);
else if (Tok.getKind() == tok::booltrue)
m_Interp.enablePrintAST(true);
else {
llvm::errs() << "Boolean value expected.\n";
return false;
}
}
//m_Options.PrintingAST = m_Interp.isPrintingAST(); ????
return true;
}
else if (Command.equals("rawInput")) {
if (!CmdLexer.LexBool(Tok)) {
m_Options.RawInput = !m_Options.RawInput;
llvm::outs() << (m_Options.RawInput ? "U" :"Not u") << "sing raw input\n";
}
else {
if (Tok.getKind() == tok::boolfalse)
m_Options.RawInput = false;
else if (Tok.getKind() == tok::booltrue)
m_Options.RawInput = true;
else {
llvm::errs() << "Boolean value expected.\n";
return false;
}
}
return true;
}
else if (Command.equals("dynamicExtensions")) {
if (!CmdLexer.LexBool(Tok)) {
bool flag = !m_Interp.isDynamicLookupEnabled();
m_Interp.enableDynamicLookup(flag);
llvm::outs() << (flag ? "U" : "Not u") << "sing dynamic extensions\n";
}
else {
if (Tok.getKind() == tok::boolfalse)
m_Interp.enableDynamicLookup(false);
else if (Tok.getKind() == tok::booltrue)
m_Interp.enableDynamicLookup(true);
else {
llvm::errs() << "Boolean value expected.\n";
return false;
}
}
return true;
}
else if (Command.equals("help")) {
PrintCommandHelp();
return true;
}
else if (Command.equals("file")) {
PrintFileStats();
return true;
}
return false;
}
void MetaProcessor::PrintCommandHelp() {
std::string& metaString = m_Interp.getOptions().MetaString;
llvm::outs() << "Cling meta commands usage\n";
llvm::outs() << "Syntax: .Command [arg0 arg1 ... argN]\n";
llvm::outs() << "\n";
llvm::outs() << metaString << "q\t\t\t\t- Exit the program\n";
llvm::outs() << metaString << "L <filename>\t\t\t - Load file or library\n";
llvm::outs() << metaString << "(x|X) <filename>[args]\t\t- Same as .L and runs a ";
llvm::outs() << "function with signature ";
llvm::outs() << "\t\t\t\tret_type filename(args)\n";
llvm::outs() << metaString << "I [path]\t\t\t- Shows the include path. If a path is ";
llvm::outs() << "given - \n\t\t\t\tadds the path to the include paths\n";
llvm::outs() << metaString << "@ \t\t\t\t- Cancels and ignores the multiline input\n";
llvm::outs() << metaString << "rawInput [0|1]\t\t\t- Toggle wrapping and printing ";
llvm::outs() << "the execution\n\t\t\t\tresults of the input\n";
llvm::outs() << metaString << "dynamicExtensions [0|1]\t- Toggles the use of the ";
llvm::outs() << "dynamic scopes and the \t\t\t\tlate binding\n";
llvm::outs() << metaString << "printAST [0|1]\t\t\t- Toggles the printing of input's ";
llvm::outs() << "corresponding \t\t\t\tAST nodes\n";
llvm::outs() << metaString << "help\t\t\t\t- Shows this information\n";
}
void MetaProcessor::PrintFileStats() {
const SourceManager& SM = m_Interp.getCI()->getSourceManager();
SM.getFileManager().PrintStats();
llvm::outs() << "\n***\n\n";
for (SourceManager::fileinfo_iterator I = SM.fileinfo_begin(),
E = SM.fileinfo_end(); I != E; ++I) {
llvm::outs() << (*I).first->getName();
llvm::outs() << "\n";
}
}
// Run a file: .x file[(args)]
bool MetaProcessor::executeFile(llvm::StringRef file, llvm::StringRef args,
StoredValueRef* result) {
// Look for start of parameters:
typedef std::pair<llvm::StringRef,llvm::StringRef> StringRefPair;
// StringRefPair pairFileArgs = llvm::StringRef(fileWithArgs).split('(');
// if (pairFileArgs.second.empty()) {
// pairFileArgs.second = ")";
// }
StringRefPair pairPathFile = file.rsplit('/');
if (pairPathFile.second.empty()) {
pairPathFile.second = pairPathFile.first;
}
StringRefPair pairFuncExt = pairPathFile.second.rsplit('.');
Interpreter::CompilationResult interpRes = Interpreter::kSuccess;
if (m_Interp.loadFile(file)) {
std::string expression = pairFuncExt.first.str() + "(" + args.str() + ")";
interpRes = m_Interp.evaluate(expression, result);
}
return (interpRes != Interpreter::kFailure);
}
} // end namespace cling
<|endoftext|> |
<commit_before>//------------------------------------------------------------------------------
// CLING - the C++ LLVM-based InterpreterG :)
// version: $Id$
// author: Axel Naumann <axel@cern.ch>
//------------------------------------------------------------------------------
#include "cling/UserInterface/UserInterface.h"
#include "cling/Interpreter/RuntimeExceptions.h"
#include "cling/Interpreter/StoredValueRef.h"
#include "cling/MetaProcessor/MetaProcessor.h"
#include "textinput/TextInput.h"
#include "textinput/StreamReader.h"
#include "textinput/TerminalDisplay.h"
#include "llvm/Support/raw_ostream.h"
#include "llvm/Support/PathV1.h"
#include "llvm/Config/config.h"
// Fragment copied from LLVM's raw_ostream.cpp
#if defined(HAVE_UNISTD_H)
# include <unistd.h>
#endif
#if defined(_MSC_VER)
#ifndef STDIN_FILENO
# define STDIN_FILENO 0
#endif
#ifndef STDOUT_FILENO
# define STDOUT_FILENO 1
#endif
#ifndef STDERR_FILENO
# define STDERR_FILENO 2
#endif
#endif
namespace cling {
UserInterface::UserInterface(Interpreter& interp) {
// We need stream that doesn't close its file descriptor, thus we are not
// using llvm::outs. Keeping file descriptor open we will be able to use
// the results in pipes (Savannah #99234).
static llvm::raw_fd_ostream m_MPOuts (STDOUT_FILENO, /*ShouldClose*/false);
m_MetaProcessor.reset(new MetaProcessor(interp, m_MPOuts));
}
UserInterface::~UserInterface() {}
void UserInterface::runInteractively(bool nologo /* = false */) {
if (!nologo) {
PrintLogo();
}
// History file is $HOME/.cling_history
static const char* histfile = ".cling_history";
llvm::sys::Path histfilePath = llvm::sys::Path::GetUserHomeDirectory();
histfilePath.appendComponent(histfile);
using namespace textinput;
StreamReader* R = StreamReader::Create();
TerminalDisplay* D = TerminalDisplay::Create();
TextInput TI(*R, *D, histfilePath.c_str());
TI.SetPrompt("[cling]$ ");
std::string line;
while (true) {
try {
m_MetaProcessor->getOuts().flush();
TextInput::EReadResult RR = TI.ReadInput();
TI.TakeInput(line);
if (RR == TextInput::kRREOF) {
break;
}
cling::Interpreter::CompilationResult compRes;
int indent
= m_MetaProcessor->process(line.c_str(), compRes, 0/*result*/);
// Quit requested
if (indent < 0)
break;
std::string Prompt = "[cling]";
if (m_MetaProcessor->getInterpreter().isRawInputEnabled())
Prompt.append("! ");
else
Prompt.append("$ ");
if (indent > 0)
// Continuation requested.
Prompt.append('?' + std::string(indent * 3, ' '));
TI.SetPrompt(Prompt.c_str());
}
catch(runtime::NullDerefException& e) {
llvm::errs() << "Exception was thrown at runtime. Recovering...\n";
e.what();
}
catch(runtime::InterpreterException& e) {
// The diagnostic goes here:
e.what();
}
catch(...) {
llvm::errs() << "Exception occurred. Recovering...\n";
}
}
}
void UserInterface::PrintLogo() {
llvm::raw_ostream& outs = m_MetaProcessor->getOuts();
outs << "\n";
outs << "****************** CLING ******************" << "\n";
outs << "* Type C++ code and press enter to run it *" << "\n";
outs << "* Type .q to exit *" << "\n";
outs << "*******************************************" << "\n";
}
} // end namespace cling
<commit_msg>Handle better the exceptions.<commit_after>//------------------------------------------------------------------------------
// CLING - the C++ LLVM-based InterpreterG :)
// version: $Id$
// author: Axel Naumann <axel@cern.ch>
//------------------------------------------------------------------------------
#include "cling/UserInterface/UserInterface.h"
#include "cling/Interpreter/RuntimeExceptions.h"
#include "cling/Interpreter/StoredValueRef.h"
#include "cling/MetaProcessor/MetaProcessor.h"
#include "textinput/TextInput.h"
#include "textinput/StreamReader.h"
#include "textinput/TerminalDisplay.h"
#include "llvm/Support/raw_ostream.h"
#include "llvm/Support/PathV1.h"
#include "llvm/Config/config.h"
// Fragment copied from LLVM's raw_ostream.cpp
#if defined(HAVE_UNISTD_H)
# include <unistd.h>
#endif
#if defined(_MSC_VER)
#ifndef STDIN_FILENO
# define STDIN_FILENO 0
#endif
#ifndef STDOUT_FILENO
# define STDOUT_FILENO 1
#endif
#ifndef STDERR_FILENO
# define STDERR_FILENO 2
#endif
#endif
namespace cling {
UserInterface::UserInterface(Interpreter& interp) {
// We need stream that doesn't close its file descriptor, thus we are not
// using llvm::outs. Keeping file descriptor open we will be able to use
// the results in pipes (Savannah #99234).
static llvm::raw_fd_ostream m_MPOuts (STDOUT_FILENO, /*ShouldClose*/false);
m_MetaProcessor.reset(new MetaProcessor(interp, m_MPOuts));
}
UserInterface::~UserInterface() {}
void UserInterface::runInteractively(bool nologo /* = false */) {
if (!nologo) {
PrintLogo();
}
// History file is $HOME/.cling_history
static const char* histfile = ".cling_history";
llvm::sys::Path histfilePath = llvm::sys::Path::GetUserHomeDirectory();
histfilePath.appendComponent(histfile);
using namespace textinput;
StreamReader* R = StreamReader::Create();
TerminalDisplay* D = TerminalDisplay::Create();
TextInput TI(*R, *D, histfilePath.c_str());
TI.SetPrompt("[cling]$ ");
std::string line;
while (true) {
try {
m_MetaProcessor->getOuts().flush();
TextInput::EReadResult RR = TI.ReadInput();
TI.TakeInput(line);
if (RR == TextInput::kRREOF) {
break;
}
cling::Interpreter::CompilationResult compRes;
int indent
= m_MetaProcessor->process(line.c_str(), compRes, 0/*result*/);
// Quit requested
if (indent < 0)
break;
std::string Prompt = "[cling]";
if (m_MetaProcessor->getInterpreter().isRawInputEnabled())
Prompt.append("! ");
else
Prompt.append("$ ");
if (indent > 0)
// Continuation requested.
Prompt.append('?' + std::string(indent * 3, ' '));
TI.SetPrompt(Prompt.c_str());
}
catch(runtime::NullDerefException& e) {
e.diagnose();
}
catch(runtime::InterpreterException& e) {
llvm::errs() << e.what();
}
catch(...) {
llvm::errs() << "Exception occurred. Recovering...\n";
}
}
}
void UserInterface::PrintLogo() {
llvm::raw_ostream& outs = m_MetaProcessor->getOuts();
outs << "\n";
outs << "****************** CLING ******************" << "\n";
outs << "* Type C++ code and press enter to run it *" << "\n";
outs << "* Type .q to exit *" << "\n";
outs << "*******************************************" << "\n";
}
} // end namespace cling
<|endoftext|> |
<commit_before>//------------------------------------------------------------------------------
// CLING - the C++ LLVM-based InterpreterG :)
// version: $Id$
// author: Axel Naumann <axel@cern.ch>
//------------------------------------------------------------------------------
#include "cling/UserInterface/UserInterface.h"
#include "cling/MetaProcessor/MetaProcessor.h"
#include "textinput/TextInput.h"
#include "textinput/StreamReader.h"
#include "textinput/TerminalDisplay.h"
#include "llvm/Support/raw_ostream.h"
#include "llvm/Support/PathV1.h"
namespace cling {
UserInterface::UserInterface(Interpreter& interp) {
// We need stream that doesn't close its file descriptor, thus we are not
// using llvm::outs. Keeping file descriptor open we will be able to use
// the results in pipes (Savannah #99234).
static llvm::raw_fd_ostream m_MPOuts (STDOUT_FILENO, /*ShouldClose*/false);
m_MetaProcessor.reset(new MetaProcessor(interp, m_MPOuts));
}
UserInterface::~UserInterface() {}
void UserInterface::runInteractively(bool nologo /* = false */) {
if (!nologo) {
PrintLogo();
}
// History file is $HOME/.cling_history
static const char* histfile = ".cling_history";
llvm::sys::Path histfilePath = llvm::sys::Path::GetUserHomeDirectory();
histfilePath.appendComponent(histfile);
using namespace textinput;
StreamReader* R = StreamReader::Create();
TerminalDisplay* D = TerminalDisplay::Create();
TextInput TI(*R, *D, histfilePath.c_str());
TI.SetPrompt("[cling]$ ");
std::string line;
while (true) {
m_MetaProcessor->getOuts().flush();
TextInput::EReadResult RR = TI.ReadInput();
TI.TakeInput(line);
if (RR == TextInput::kRREOF) {
break;
}
int indent = m_MetaProcessor->process(line.c_str());
// Quit requested
if (indent < 0)
break;
std::string Prompt = "[cling]";
if (m_MetaProcessor->getInterpreter().isRawInputEnabled())
Prompt.append("! ");
else
Prompt.append("$ ");
if (indent > 0)
// Continuation requested.
Prompt.append('?' + std::string(indent * 3, ' '));
TI.SetPrompt(Prompt.c_str());
}
}
void UserInterface::PrintLogo() {
llvm::raw_ostream& outs = m_MetaProcessor->getOuts();
outs << "\n";
outs << "****************** CLING ******************" << "\n";
outs << "* Type C++ code and press enter to run it *" << "\n";
outs << "* Type .q to exit *" << "\n";
outs << "*******************************************" << "\n";
}
} // end namespace cling
<commit_msg>Try to Windows for cling standalone.<commit_after>//------------------------------------------------------------------------------
// CLING - the C++ LLVM-based InterpreterG :)
// version: $Id$
// author: Axel Naumann <axel@cern.ch>
//------------------------------------------------------------------------------
#include "cling/UserInterface/UserInterface.h"
#include "cling/MetaProcessor/MetaProcessor.h"
#include "textinput/TextInput.h"
#include "textinput/StreamReader.h"
#include "textinput/TerminalDisplay.h"
#include "llvm/Support/raw_ostream.h"
#include "llvm/Support/PathV1.h"
#include <unistd.h>
namespace cling {
UserInterface::UserInterface(Interpreter& interp) {
// We need stream that doesn't close its file descriptor, thus we are not
// using llvm::outs. Keeping file descriptor open we will be able to use
// the results in pipes (Savannah #99234).
static llvm::raw_fd_ostream m_MPOuts (STDOUT_FILENO, /*ShouldClose*/false);
m_MetaProcessor.reset(new MetaProcessor(interp, m_MPOuts));
}
UserInterface::~UserInterface() {}
void UserInterface::runInteractively(bool nologo /* = false */) {
if (!nologo) {
PrintLogo();
}
// History file is $HOME/.cling_history
static const char* histfile = ".cling_history";
llvm::sys::Path histfilePath = llvm::sys::Path::GetUserHomeDirectory();
histfilePath.appendComponent(histfile);
using namespace textinput;
StreamReader* R = StreamReader::Create();
TerminalDisplay* D = TerminalDisplay::Create();
TextInput TI(*R, *D, histfilePath.c_str());
TI.SetPrompt("[cling]$ ");
std::string line;
while (true) {
m_MetaProcessor->getOuts().flush();
TextInput::EReadResult RR = TI.ReadInput();
TI.TakeInput(line);
if (RR == TextInput::kRREOF) {
break;
}
int indent = m_MetaProcessor->process(line.c_str());
// Quit requested
if (indent < 0)
break;
std::string Prompt = "[cling]";
if (m_MetaProcessor->getInterpreter().isRawInputEnabled())
Prompt.append("! ");
else
Prompt.append("$ ");
if (indent > 0)
// Continuation requested.
Prompt.append('?' + std::string(indent * 3, ' '));
TI.SetPrompt(Prompt.c_str());
}
}
void UserInterface::PrintLogo() {
llvm::raw_ostream& outs = m_MetaProcessor->getOuts();
outs << "\n";
outs << "****************** CLING ******************" << "\n";
outs << "* Type C++ code and press enter to run it *" << "\n";
outs << "* Type .q to exit *" << "\n";
outs << "*******************************************" << "\n";
}
} // end namespace cling
<|endoftext|> |
<commit_before>#include <iostream>
#include <iomanip>
#define WIN32_LEAN_AND_MEAN
#include <Windows.h>
#include <ShlObj.h>
#include "Osiris.hpp"
#include "Modules/OsirisModule.hpp"
#include "Modules/OsirisModules.hpp"
#include <Utils/Utils.hpp>
#include <Ausar/Ausar.hpp>
#include <vector>
#include <iterator>
Osiris::Osiris()
{
wchar_t UserPath[MAX_PATH] = { 0 };
SHGetSpecialFolderPathW(nullptr, UserPath, CSIDL_PROFILE, false);
std::wstring LogPath(UserPath);
LogPath += L"\\AppData\\Local\\Packages\\Microsoft.Halo5Forge_8wekyb3d8bbwe\\LocalState\\Log.txt";
Util::Log::Instance()->SetFile(LogPath);
LOG << "Osiris" << "---- ";
LOG << '[' << __DATE__ << " : " << __TIME__ << ']' << std::endl;
LOG << "\t-https://github.com/Wunkolo/Osiris\n";
LOG << std::wstring(80, '-') << std::endl;
LOG << std::hex << std::uppercase << std::setfill(L'0')
<< "Process Base: 0x" << Util::Process::Base() << std::endl;
LOG << "Osiris Thread ID: 0x" << Util::Thread::GetCurrentThreadId() << std::endl;
LOG << "Osiris Base: 0x" << Util::Process::GetModuleBase("Osiris.dll") << std::endl;
// Push Commands
PushModule<GlobalInfo>("globals");
}
Osiris::~Osiris()
{
}
void Osiris::Tick(const std::chrono::high_resolution_clock::duration &DeltaTime)
{
for( std::pair<std::string, std::shared_ptr<OsirisModule>> Command : Commands )
{
if( Command.second )
{
Command.second->Tick(DeltaTime);
}
}
}<commit_msg>Log now uses TempState rather than LocalState<commit_after>#include <iostream>
#include <iomanip>
#define WIN32_LEAN_AND_MEAN
#include <Windows.h>
#include <ShlObj.h>
#include "Osiris.hpp"
#include "Modules/OsirisModule.hpp"
#include "Modules/OsirisModules.hpp"
#include <Utils/Utils.hpp>
#include <Ausar/Ausar.hpp>
#include <vector>
#include <iterator>
Osiris::Osiris()
{
wchar_t UserPath[MAX_PATH] = { 0 };
SHGetSpecialFolderPathW(nullptr, UserPath, CSIDL_PROFILE, false);
std::wstring LogPath(UserPath);
LogPath += L"\\AppData\\Local\\Packages\\Microsoft.Halo5Forge_8wekyb3d8bbwe\\TempState\\Log.txt";
Util::Log::Instance()->SetFile(LogPath);
LOG << "Osiris" << "---- ";
LOG << '[' << __DATE__ << " : " << __TIME__ << ']' << std::endl;
LOG << "\t-https://github.com/Wunkolo/Osiris\n";
LOG << std::wstring(80, '-') << std::endl;
LOG << std::hex << std::uppercase << std::setfill(L'0')
<< "Process Base: 0x" << Util::Process::Base() << std::endl;
LOG << "Osiris Thread ID: 0x" << Util::Thread::GetCurrentThreadId() << std::endl;
LOG << "Osiris Base: 0x" << Util::Process::GetModuleBase("Osiris.dll") << std::endl;
// Push Commands
PushModule<GlobalInfo>("globals");
}
Osiris::~Osiris()
{
}
void Osiris::Tick(const std::chrono::high_resolution_clock::duration &DeltaTime)
{
for( std::pair<std::string, std::shared_ptr<OsirisModule>> Command : Commands )
{
if( Command.second )
{
Command.second->Tick(DeltaTime);
}
}
}<|endoftext|> |
<commit_before>
#include "Globals.h" // NOTE: MSVC stupidness requires this to be the same across all modules
#include "Authenticator.h"
#include "OSSupport/BlockingTCPLink.h"
#include "Root.h"
#include "Server.h"
#include "inifile/iniFile.h"
#include "json/json.h"
#include "polarssl/config.h"
#include "polarssl/net.h"
#include "polarssl/ssl.h"
#include "polarssl/entropy.h"
#include "polarssl/ctr_drbg.h"
#include "polarssl/error.h"
#include "polarssl/certs.h"
#include <sstream>
#include <iomanip>
#define DEFAULT_AUTH_SERVER "sessionserver.mojang.com"
#define DEFAULT_AUTH_ADDRESS "/session/minecraft/hasJoined?username=%USERNAME%&serverId=%SERVERID%"
#define MAX_REDIRECTS 10
cAuthenticator::cAuthenticator(void) :
super("cAuthenticator"),
m_Server(DEFAULT_AUTH_SERVER),
m_Address(DEFAULT_AUTH_ADDRESS),
m_ShouldAuthenticate(true)
{
}
cAuthenticator::~cAuthenticator()
{
Stop();
}
void cAuthenticator::ReadINI(cIniFile & IniFile)
{
m_Server = IniFile.GetValueSet("Authentication", "Server", DEFAULT_AUTH_SERVER);
m_Address = IniFile.GetValueSet("Authentication", "Address", DEFAULT_AUTH_ADDRESS);
m_ShouldAuthenticate = IniFile.GetValueSetB("Authentication", "Authenticate", true);
}
void cAuthenticator::Authenticate(int a_ClientID, const AString & a_UserName, const AString & a_ServerHash)
{
if (!m_ShouldAuthenticate)
{
cRoot::Get()->AuthenticateUser(a_ClientID, a_UserName, Printf("%d", a_ClientID));
return;
}
cCSLock LOCK(m_CS);
m_Queue.push_back(cUser(a_ClientID, a_UserName, a_ServerHash));
m_QueueNonempty.Set();
}
void cAuthenticator::Start(cIniFile & IniFile)
{
ReadINI(IniFile);
m_ShouldTerminate = false;
super::Start();
}
void cAuthenticator::Stop(void)
{
m_ShouldTerminate = true;
m_QueueNonempty.Set();
Wait();
}
void cAuthenticator::Execute(void)
{
for (;;)
{
cCSLock Lock(m_CS);
while (!m_ShouldTerminate && (m_Queue.size() == 0))
{
cCSUnlock Unlock(Lock);
m_QueueNonempty.Wait();
}
if (m_ShouldTerminate)
{
return;
}
ASSERT(!m_Queue.empty());
int ClientID = m_Queue.front().m_ClientID;
AString UserName = m_Queue.front().m_Name;
AString ServerID = m_Queue.front().m_ServerID;
m_Queue.pop_front();
Lock.Unlock();
AString NewUserName = UserName;
AString UUID;
if (AuthWithYggdrasil(NewUserName, ServerID, UUID))
{
LOGINFO("User %s authenticated with UUID '%s'", NewUserName.c_str(), UUID.c_str());
cRoot::Get()->AuthenticateUser(ClientID, NewUserName, UUID);
}
else
{
cRoot::Get()->KickUser(ClientID, "Failed to authenticate account!");
}
} // for (-ever)
}
bool cAuthenticator::AuthWithYggdrasil(AString & a_UserName, const AString & a_ServerId, AString & a_UUID)
{
AString REQUEST;
int ret, len, server_fd = -1;
unsigned char buf[1024];
const char *pers = "cAuthenticator";
entropy_context entropy;
ctr_drbg_context ctr_drbg;
ssl_context ssl;
x509_crt cacert;
/* Initialize the RNG and the session data */
memset(&ssl, 0, sizeof(ssl_context));
x509_crt_init(&cacert);
entropy_init(&entropy);
if ((ret = ctr_drbg_init(&ctr_drbg, entropy_func, &entropy, (const unsigned char *)pers, strlen(pers))) != 0)
{
LOGERROR("cAuthenticator: ctr_drbg_init returned %d", ret);
return false;
}
/* Initialize certificates */
#if defined(POLARSSL_CERTS_C)
ret = x509_crt_parse(&cacert, (const unsigned char *)test_ca_list, strlen(test_ca_list));
#else
ret = 1;
LOGWARNING("cAuthenticator: POLARSSL_CERTS_C is not defined.");
#endif
if (ret < 0)
{
LOGERROR("cAuthenticator: x509_crt_parse returned -0x%x", -ret);
return false;
}
/* Connect */
if ((ret = net_connect(&server_fd, m_Server.c_str(), 443)) != 0)
{
LOGERROR("cAuthenticator: Can't connect to %s: %d", m_Server.c_str(), ret);
return false;
}
/* Setup */
if ((ret = ssl_init(&ssl)) != 0)
{
LOGERROR("cAuthenticator: ssl_init returned %d", ret);
return false;
}
ssl_set_endpoint(&ssl, SSL_IS_CLIENT);
ssl_set_authmode(&ssl, SSL_VERIFY_OPTIONAL);
ssl_set_ca_chain(&ssl, &cacert, NULL, "PolarSSL Server 1");
ssl_set_rng(&ssl, ctr_drbg_random, &ctr_drbg);
ssl_set_bio(&ssl, net_recv, &server_fd, net_send, &server_fd);
/* Handshake */
while ((ret = ssl_handshake(&ssl)) != 0)
{
if (ret != POLARSSL_ERR_NET_WANT_READ && ret != POLARSSL_ERR_NET_WANT_WRITE)
{
LOGERROR("cAuthenticator: ssl_handshake returned -0x%x", -ret);
return false;
}
}
/* Write the GET request */
AString ActualAddress = m_Address;
ReplaceString(ActualAddress, "%USERNAME%", a_UserName);
ReplaceString(ActualAddress, "%SERVERID%", a_ServerId);
REQUEST += "GET " + ActualAddress + " HTTP/1.1\r\n";
REQUEST += "Host: " + m_Server + "\r\n";
REQUEST += "User-Agent: MCServer\r\n";
REQUEST += "Connection: close\r\n";
REQUEST += "\r\n";
len = sprintf_s((char *)buf, sizeof(buf), REQUEST.c_str());
while ((ret = ssl_write(&ssl, buf, len)) <= 0)
{
if (ret != POLARSSL_ERR_NET_WANT_READ && ret != POLARSSL_ERR_NET_WANT_WRITE)
{
LOGERROR("cAuthenticator: ssl_write returned %d", ret);
return false;
}
}
/* Read the HTTP response */
std::string Builder;
for (;;)
{
len = sizeof(buf)-1;
memset(buf, 0, sizeof(buf));
ret = ssl_read(&ssl, buf, len);
if (ret > 0)
{
buf[ret] = '\0';
}
if (ret == POLARSSL_ERR_NET_WANT_READ || ret == POLARSSL_ERR_NET_WANT_WRITE)
continue;
if (ret == POLARSSL_ERR_SSL_PEER_CLOSE_NOTIFY)
break;
if (ret < 0)
{
LOGERROR("cAuthenticator: ssl_read returned %d", ret);
break;
}
if (ret == 0)
{
LOGERROR("cAuthenticator: EOF");
break;
}
std::string str;
str.append(reinterpret_cast<const char*>(buf));
Builder += str;
}
ssl_close_notify(&ssl);
x509_crt_free(&cacert);
net_close(server_fd);
ssl_free(&ssl);
entropy_free(&entropy);
memset(&ssl, 0, sizeof(ssl));
std::string prefix("HTTP/1.1 200 OK");
if (Builder.compare(0, prefix.size(), prefix))
return false;
std::stringstream ResponseBuilder;
bool NewLine = false;
bool IsNewLine = false;
for (std::string::const_iterator i = Builder.begin(); i <= Builder.end(); ++i)
{
if (NewLine)
{
ResponseBuilder << *i;
}
else if (!NewLine && *i == '\n')
{
if (IsNewLine)
{
NewLine = true;
}
else
{
IsNewLine = true;
}
}
else if (*i != '\r')
{
IsNewLine = false;
}
}
AString RESPONSE = ResponseBuilder.str();
if (RESPONSE.empty())
return false;
Json::Value root;
Json::Reader reader;
if (!reader.parse(RESPONSE, root, false))
{
LOGWARNING("cAuthenticator: Cannot parse Received Data to json!");
return false;
}
a_UserName = root.get("name", "Unknown").asString();
a_UUID = root.get("id", "").asString();
return true;
}
<commit_msg>Code Update<commit_after>
#include "Globals.h" // NOTE: MSVC stupidness requires this to be the same across all modules
#include "Authenticator.h"
#include "OSSupport/BlockingTCPLink.h"
#include "Root.h"
#include "Server.h"
#include "inifile/iniFile.h"
#include "json/json.h"
#include "polarssl/config.h"
#include "polarssl/net.h"
#include "polarssl/ssl.h"
#include "polarssl/entropy.h"
#include "polarssl/ctr_drbg.h"
#include "polarssl/error.h"
#include "polarssl/certs.h"
#include <sstream>
#include <iomanip>
#define DEFAULT_AUTH_SERVER "sessionserver.mojang.com"
#define DEFAULT_AUTH_ADDRESS "/session/minecraft/hasJoined?username=%USERNAME%&serverId=%SERVERID%"
cAuthenticator::cAuthenticator(void) :
super("cAuthenticator"),
m_Server(DEFAULT_AUTH_SERVER),
m_Address(DEFAULT_AUTH_ADDRESS),
m_ShouldAuthenticate(true)
{
}
cAuthenticator::~cAuthenticator()
{
Stop();
}
void cAuthenticator::ReadINI(cIniFile & IniFile)
{
m_Server = IniFile.GetValueSet("Authentication", "Server", DEFAULT_AUTH_SERVER);
m_Address = IniFile.GetValueSet("Authentication", "Address", DEFAULT_AUTH_ADDRESS);
m_ShouldAuthenticate = IniFile.GetValueSetB("Authentication", "Authenticate", true);
}
void cAuthenticator::Authenticate(int a_ClientID, const AString & a_UserName, const AString & a_ServerHash)
{
if (!m_ShouldAuthenticate)
{
cRoot::Get()->AuthenticateUser(a_ClientID, a_UserName, Printf("%d", a_ClientID));
return;
}
cCSLock LOCK(m_CS);
m_Queue.push_back(cUser(a_ClientID, a_UserName, a_ServerHash));
m_QueueNonempty.Set();
}
void cAuthenticator::Start(cIniFile & IniFile)
{
ReadINI(IniFile);
m_ShouldTerminate = false;
super::Start();
}
void cAuthenticator::Stop(void)
{
m_ShouldTerminate = true;
m_QueueNonempty.Set();
Wait();
}
void cAuthenticator::Execute(void)
{
for (;;)
{
cCSLock Lock(m_CS);
while (!m_ShouldTerminate && (m_Queue.size() == 0))
{
cCSUnlock Unlock(Lock);
m_QueueNonempty.Wait();
}
if (m_ShouldTerminate)
{
return;
}
ASSERT(!m_Queue.empty());
int ClientID = m_Queue.front().m_ClientID;
AString UserName = m_Queue.front().m_Name;
AString ServerID = m_Queue.front().m_ServerID;
m_Queue.pop_front();
Lock.Unlock();
AString NewUserName = UserName;
AString UUID;
if (AuthWithYggdrasil(NewUserName, ServerID, UUID))
{
LOGINFO("User %s authenticated with UUID '%s'", NewUserName.c_str(), UUID.c_str());
cRoot::Get()->AuthenticateUser(ClientID, NewUserName, UUID);
}
else
{
cRoot::Get()->KickUser(ClientID, "Failed to authenticate account!");
}
} // for (-ever)
}
bool cAuthenticator::AuthWithYggdrasil(AString & a_UserName, const AString & a_ServerId, AString & a_UUID)
{
AString REQUEST;
int ret, server_fd = -1;
size_t len = -1;
unsigned char * buf;
const char *pers = "cAuthenticator";
entropy_context entropy;
ctr_drbg_context ctr_drbg;
ssl_context ssl;
x509_crt cacert;
/* Initialize the RNG and the session data */
memset(&ssl, 0, sizeof(ssl_context));
x509_crt_init(&cacert);
entropy_init(&entropy);
if ((ret = ctr_drbg_init(&ctr_drbg, entropy_func, &entropy, (const unsigned char *)pers, strlen(pers))) != 0)
{
LOGERROR("cAuthenticator: ctr_drbg_init returned %d", ret);
return false;
}
/* Initialize certificates */
#if defined(POLARSSL_CERTS_C)
ret = x509_crt_parse(&cacert, (const unsigned char *)test_ca_list, strlen(test_ca_list));
#else
ret = 1;
LOGWARNING("cAuthenticator: POLARSSL_CERTS_C is not defined.");
#endif
if (ret < 0)
{
LOGERROR("cAuthenticator: x509_crt_parse returned -0x%x", -ret);
return false;
}
/* Connect */
if ((ret = net_connect(&server_fd, m_Server.c_str(), 443)) != 0)
{
LOGERROR("cAuthenticator: Can't connect to %s: %d", m_Server.c_str(), ret);
return false;
}
/* Setup */
if ((ret = ssl_init(&ssl)) != 0)
{
LOGERROR("cAuthenticator: ssl_init returned %d", ret);
return false;
}
ssl_set_endpoint(&ssl, SSL_IS_CLIENT);
ssl_set_authmode(&ssl, SSL_VERIFY_OPTIONAL);
ssl_set_ca_chain(&ssl, &cacert, NULL, "PolarSSL Server 1");
ssl_set_rng(&ssl, ctr_drbg_random, &ctr_drbg);
ssl_set_bio(&ssl, net_recv, &server_fd, net_send, &server_fd);
/* Handshake */
while ((ret = ssl_handshake(&ssl)) != 0)
{
if (ret != POLARSSL_ERR_NET_WANT_READ && ret != POLARSSL_ERR_NET_WANT_WRITE)
{
LOGERROR("cAuthenticator: ssl_handshake returned -0x%x", -ret);
return false;
}
}
/* Write the GET request */
AString ActualAddress = m_Address;
ReplaceString(ActualAddress, "%USERNAME%", a_UserName);
ReplaceString(ActualAddress, "%SERVERID%", a_ServerId);
REQUEST += "GET " + ActualAddress + " HTTP/1.1\r\n";
REQUEST += "Host: " + m_Server + "\r\n";
REQUEST += "User-Agent: MCServer\r\n";
REQUEST += "Connection: close\r\n";
REQUEST += "\r\n";
len = REQUEST.size();
buf = (unsigned char *)REQUEST.c_str();
while ((ret = ssl_write(&ssl, buf, len)) <= 0)
{
if (ret != POLARSSL_ERR_NET_WANT_READ && ret != POLARSSL_ERR_NET_WANT_WRITE)
{
LOGERROR("cAuthenticator: ssl_write returned %d", ret);
return false;
}
}
/* Read the HTTP response */
std::string Builder;
for (;;)
{
len = sizeof(buf)-1;
memset(buf, 0, sizeof(buf));
ret = ssl_read(&ssl, buf, len);
if (ret > 0)
{
buf[ret] = '\0';
}
if (ret == POLARSSL_ERR_NET_WANT_READ || ret == POLARSSL_ERR_NET_WANT_WRITE)
continue;
if (ret == POLARSSL_ERR_SSL_PEER_CLOSE_NOTIFY)
break;
if (ret < 0)
{
LOGERROR("cAuthenticator: ssl_read returned %d", ret);
break;
}
if (ret == 0)
{
LOGERROR("cAuthenticator: EOF");
break;
}
std::string str;
str.append(reinterpret_cast<const char*>(buf));
Builder += str;
}
ssl_close_notify(&ssl);
x509_crt_free(&cacert);
net_close(server_fd);
ssl_free(&ssl);
entropy_free(&entropy);
memset(&ssl, 0, sizeof(ssl));
std::string prefix("HTTP/1.1 200 OK");
if (Builder.compare(0, prefix.size(), prefix))
return false;
std::stringstream ResponseBuilder;
bool NewLine = false;
bool IsNewLine = false;
for (std::string::const_iterator i = Builder.begin(); i <= Builder.end(); ++i)
{
if (NewLine)
{
ResponseBuilder << *i;
}
else if (!NewLine && *i == '\n')
{
if (IsNewLine)
{
NewLine = true;
}
else
{
IsNewLine = true;
}
}
else if (*i != '\r')
{
IsNewLine = false;
}
}
AString RESPONSE = ResponseBuilder.str();
if (RESPONSE.empty())
return false;
Json::Value root;
Json::Reader reader;
if (!reader.parse(RESPONSE, root, false))
{
LOGWARNING("cAuthenticator: Cannot parse Received Data to json!");
return false;
}
a_UserName = root.get("name", "Unknown").asString();
a_UUID = root.get("id", "").asString();
return true;
}
<|endoftext|> |
<commit_before>// -*- mode:C++; tab-width:4; c-basic-offset:4; indent-tabs-mode:nil -*-
#include "RdYarpRobotManager.hpp"
namespace rd{
bool RdYarpRobotManager::moveForward(int velocity) {
double velocities[] = {2000,1000};
vel->velocityMove(velocities);
return true;
}
bool RdYarpRobotManager::moveBackwards(int velocity) {
double velocities[] = {1000,2000};
vel->velocityMove(velocities);
return true;
}
bool RdYarpRobotManager::turnLeft(int velocity) {
double velocities[] = {1000,1000};
vel->velocityMove(velocities);
return true;
}
bool RdYarpRobotManager::turnRight(int velocity) {
double velocities[] = {2000,2000};
vel->velocityMove(velocities);
return true;
}
bool RdYarpRobotManager::stopMovement() {
vel->stop();
return true;
}
bool RdYarpRobotManager::tiltUp(int velocity) {
return true;
}
bool RdYarpRobotManager::tiltDown(int velocity) {
return true;
}
bool RdYarpRobotManager::panLeft(int velocity) {
return true;
}
bool RdYarpRobotManager::panRight(int velocity) {
return true;
}
bool RdYarpRobotManager::connect() {
std::ostringstream local_s;
local_s << "/";
local_s << playerId;
local_s << "/robot";
std::ostringstream remote_s;
remote_s << "/";
remote_s << playerId;
remote_s << "/rd1";
yarp::os::Property robotOptions;
robotOptions.put("device","remote_controlboard");
robotOptions.put("local", local_s.str().c_str() );
robotOptions.put("remote", remote_s.str().c_str() );
robotDevice.open(robotOptions);
if( ! robotDevice.isValid() ) {
RD_ERROR("Could not connect to remote robot.\n");
return false;
}
if(! robotDevice.view(vel) )
{
RD_ERROR("Could not aquire robot motor velocity interface.\n");
return false;
}
RD_SUCCESS("Acquired robot motor velocity interface.\n");
return true;
}
bool RdYarpRobotManager::disconnect() {
robotDevice.close();
return true;
}
bool RdYarpRobotManager::test() {
return true;
}
bool RdYarpRobotManager::ping() {
return true;
}
void RdYarpRobotManager::onDestroy(){
return;
}
} //rd
<commit_msg>Check if device is valid before attempting to view interfaces: success message if true.<commit_after>// -*- mode:C++; tab-width:4; c-basic-offset:4; indent-tabs-mode:nil -*-
#include "RdYarpRobotManager.hpp"
namespace rd{
bool RdYarpRobotManager::moveForward(int velocity) {
double velocities[] = {2000,1000};
vel->velocityMove(velocities);
return true;
}
bool RdYarpRobotManager::moveBackwards(int velocity) {
double velocities[] = {1000,2000};
vel->velocityMove(velocities);
return true;
}
bool RdYarpRobotManager::turnLeft(int velocity) {
double velocities[] = {1000,1000};
vel->velocityMove(velocities);
return true;
}
bool RdYarpRobotManager::turnRight(int velocity) {
double velocities[] = {2000,2000};
vel->velocityMove(velocities);
return true;
}
bool RdYarpRobotManager::stopMovement() {
vel->stop();
return true;
}
bool RdYarpRobotManager::tiltUp(int velocity) {
return true;
}
bool RdYarpRobotManager::tiltDown(int velocity) {
return true;
}
bool RdYarpRobotManager::panLeft(int velocity) {
return true;
}
bool RdYarpRobotManager::panRight(int velocity) {
return true;
}
bool RdYarpRobotManager::connect() {
std::ostringstream local_s;
local_s << "/";
local_s << playerId;
local_s << "/robot";
std::ostringstream remote_s;
remote_s << "/";
remote_s << playerId;
remote_s << "/rd1";
yarp::os::Property robotOptions;
robotOptions.put("device","remote_controlboard");
robotOptions.put("local", local_s.str().c_str() );
robotOptions.put("remote", remote_s.str().c_str() );
robotDevice.open(robotOptions);
if( ! robotDevice.isValid() ) {
RD_ERROR("Could not connect to remote robot.\n");
return false;
}
RD_SUCCESS("Connected to remote robot.\n");
if(! robotDevice.view(vel) )
{
RD_ERROR("Could not aquire robot motor velocity interface.\n");
return false;
}
RD_SUCCESS("Acquired robot motor velocity interface.\n");
return true;
}
bool RdYarpRobotManager::disconnect() {
robotDevice.close();
return true;
}
bool RdYarpRobotManager::test() {
return true;
}
bool RdYarpRobotManager::ping() {
return true;
}
void RdYarpRobotManager::onDestroy(){
return;
}
} //rd
<|endoftext|> |
<commit_before>// Copyright (c) 2012 Intel Corp
// Copyright (c) 2012 The Chromium Authors
//
// 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 co
// pies 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 al
// l copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IM
// PLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNES
// S FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS
// OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WH
// ETHER 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 "content/nw/src/renderer/shell_content_renderer_client.h"
#include "base/command_line.h"
#include "base/files/file_path.h"
#include "base/file_util.h"
#include "base/logging.h"
#include "base/string16.h"
#include "base/strings/string_number_conversions.h"
#include "base/utf_string_conversions.h"
#include "components/autofill/renderer/page_click_tracker.h"
#include "content/nw/src/api/dispatcher.h"
#include "content/nw/src/api/api_messages.h"
#include "content/nw/src/api/window_bindings.h"
#include "content/nw/src/common/shell_switches.h"
#include "content/nw/src/nw_package.h"
#include "content/nw/src/nw_version.h"
#include "components/autofill/renderer/autofill_agent.h"
#include "components/autofill/renderer/password_autofill_agent.h"
#include "content/nw/src/renderer/nw_render_view_observer.h"
#include "content/nw/src/renderer/prerenderer/prerenderer_client.h"
#include "content/nw/src/renderer/printing/print_web_view_helper.h"
#include "content/nw/src/renderer/shell_render_process_observer.h"
#include "content/public/common/content_switches.h"
#include "content/public/renderer/render_view.h"
#include "content/renderer/render_view_impl.h"
#include "net/proxy/proxy_bypass_rules.h"
#include "third_party/node/src/node.h"
#include "third_party/node/src/req_wrap.h"
#include "third_party/WebKit/Source/WebKit/chromium/public/WebDocument.h"
#include "third_party/WebKit/Source/WebKit/chromium/public/WebFrame.h"
#include "third_party/WebKit/Source/WebKit/chromium/public/WebSecurityOrigin.h"
#include "third_party/WebKit/Source/WebKit/chromium/public/WebSecurityPolicy.h"
#include "third_party/WebKit/Source/WebKit/chromium/public/WebView.h"
//#include "third_party/WebKit/Source/WebKit/chromium/public/platform/WebString.h"
#include "webkit/dom_storage/dom_storage_map.h"
using content::RenderView;
using content::RenderViewImpl;
using autofill::AutofillAgent;
using autofill::PasswordAutofillAgent;
using net::ProxyBypassRules;
using WebKit::WebFrame;
using WebKit::WebView;
using WebKit::WebString;
using WebKit::WebSecurityPolicy;
namespace content {
namespace {
RenderView* GetCurrentRenderView() {
WebFrame* frame = WebFrame::frameForCurrentContext();
DCHECK(frame);
if (!frame)
return NULL;
WebView* view = frame->view();
if (!view)
return NULL; // can happen during closing.
RenderView* render_view = RenderView::FromWebView(view);
DCHECK(render_view);
return render_view;
}
} // namespace
ShellContentRendererClient::ShellContentRendererClient() {
}
ShellContentRendererClient::~ShellContentRendererClient() {
}
void ShellContentRendererClient::RenderThreadStarted() {
// Change working directory.
CommandLine* command_line = CommandLine::ForCurrentProcess();
if (command_line->HasSwitch(switches::kWorkingDirectory)) {
file_util::SetCurrentDirectory(
command_line->GetSwitchValuePath(switches::kWorkingDirectory));
}
int argc = 1;
char* argv[] = { const_cast<char*>("node"), NULL, NULL };
std::string node_main;
// Check if there is a 'node-main'.
if (command_line->HasSwitch(switches::kNodeMain)) {
argc++;
node_main = command_line->GetSwitchValueASCII(switches::kNodeMain);
argv[1] = const_cast<char*>(node_main.c_str());
}
// Initialize uv.
node::SetupUv(argc, argv);
std::string snapshot_path;
if (command_line->HasSwitch(switches::kSnapshot)) {
snapshot_path = command_line->GetSwitchValuePath(switches::kSnapshot).AsUTF8Unsafe();
}
if (command_line->HasSwitch(switches::kDomStorageQuota)) {
std::string quota_str = command_line->GetSwitchValueASCII(switches::kDomStorageQuota);
int quota = 0;
if (base::StringToInt(quota_str, "a) && quota > 0)
dom_storage::DomStorageMap::SetQuotaOverride(quota * 1024 * 1024);
}
// Initialize node after render thread is started.
if (!snapshot_path.empty()) {
v8::V8::Initialize(snapshot_path.c_str());
}else
v8::V8::Initialize();
v8::HandleScope scope;
// Install window bindings into node. The Window API is implemented in node's
// context, so when a Shell changes to a new location and destroy previous
// window context, our Window API can still work.
window_bindings_.reset(new api::WindowBindings());
v8::RegisterExtension(window_bindings_.get());
const char* names[] = { "window_bindings.js" };
v8::ExtensionConfiguration extension_configuration(1, names);
node::g_context = v8::Context::New(&extension_configuration);
node::g_context->SetSecurityToken(v8::String::NewSymbol("nw-token", 8));
node::g_context->Enter();
// Setup node.js.
node::SetupContext(argc, argv, node::g_context->Global());
// Start observers.
shell_observer_.reset(new ShellRenderProcessObserver());
WebString file_scheme(ASCIIToUTF16("file"));
// file: resources should be allowed to receive CORS requests.
WebSecurityPolicy::registerURLSchemeAsCORSEnabled(file_scheme);
}
void ShellContentRendererClient::RenderViewCreated(RenderView* render_view) {
new api::Dispatcher(render_view);
new nw::NwRenderViewObserver(render_view);
new prerender::PrerendererClient(render_view);
#if defined(ENABLE_PRINTING)
new printing::PrintWebViewHelper(render_view);
#endif
// PageClickTracker* page_click_tracker = new PageClickTracker(render_view);
PasswordAutofillAgent* password_autofill_agent =
new PasswordAutofillAgent(render_view);
new AutofillAgent(render_view, password_autofill_agent);
//page_click_tracker->AddListener(autofill_agent);
}
void ShellContentRendererClient::DidCreateScriptContext(
WebKit::WebFrame* frame,
v8::Handle<v8::Context> context,
int extension_group,
int world_id) {
GURL url(frame->document().url());
VLOG(1) << "DidCreateScriptContext: " << url;
InstallNodeSymbols(frame, context, url);
}
bool ShellContentRendererClient::goodForNode(WebKit::WebFrame* frame)
{
RenderViewImpl* rv = RenderViewImpl::FromWebView(frame->view());
GURL url(frame->document().url());
ProxyBypassRules rules;
rules.ParseFromString(rv->renderer_preferences_.nw_remote_page_rules);
bool force_on = rules.Matches(url);
bool is_nw_protocol = url.SchemeIs("nw") || !url.is_valid();
bool use_node =
CommandLine::ForCurrentProcess()->HasSwitch(switches::kNodejs) &&
!frame->isNwDisabledChildFrame() &&
(force_on || url.SchemeIsFile() || is_nw_protocol);
return use_node;
}
bool ShellContentRendererClient::WillSetSecurityToken(
WebKit::WebFrame* frame,
v8::Handle<v8::Context> context) {
GURL url(frame->document().url());
VLOG(1) << "WillSetSecurityToken: " << url;
if (goodForNode(frame)) {
// Override context's security token
context->SetSecurityToken(node::g_context->GetSecurityToken());
frame->document().securityOrigin().grantUniversalAccess();
return true;
}
// window.open frame was enabled for Node earlier
if (frame->isNodeJS()) {
frame->setNodeJS(false);
UninstallNodeSymbols(frame, context);
}
return false;
}
void ShellContentRendererClient::InstallNodeSymbols(
WebKit::WebFrame* frame,
v8::Handle<v8::Context> context,
const GURL& url) {
v8::HandleScope handle_scope;
static bool installed_once = false;
v8::Local<v8::Object> nodeGlobal = node::g_context->Global();
v8::Local<v8::Object> v8Global = context->Global();
// Use WebKit's console globally
nodeGlobal->Set(v8::String::New("console"),
v8Global->Get(v8::String::New("console")));
// Do we integrate node?
bool use_node = goodForNode(frame);
// Test if protocol is 'nw:'
// test for 'about:blank' is also here becuase window.open would
// open 'about:blank' first // FIXME
bool is_nw_protocol = url.SchemeIs("nw") || !url.is_valid();
if (use_node || is_nw_protocol) {
frame->setNodeJS(true);
v8::Local<v8::Array> symbols = v8::Array::New(4);
symbols->Set(0, v8::String::New("global"));
symbols->Set(1, v8::String::New("process"));
symbols->Set(2, v8::String::New("Buffer"));
symbols->Set(3, v8::String::New("root"));
for (unsigned i = 0; i < symbols->Length(); ++i) {
v8::Local<v8::Value> key = symbols->Get(i);
v8Global->Set(key, nodeGlobal->Get(key));
}
if (!installed_once) {
installed_once = true;
// The following listener on process should not be added each
// time when a document is created, or it will leave the
// reference to the closure created by the call back and leak
// memory (see #203)
nodeGlobal->Set(v8::String::New("window"), v8Global);
// Listen uncaughtException with ReportException.
v8::Local<v8::Function> cb = v8::FunctionTemplate::New(ReportException)->
GetFunction();
v8::Local<v8::Value> argv[] = { v8::String::New("uncaughtException"), cb };
node::MakeCallback(node::process, "on", 2, argv);
}
}
if (use_node) {
v8::Local<v8::Script> script = v8::Script::New(v8::String::New(
// Make node's relative modules work
"if (!process.mainModule.filename) {"
#if defined(OS_WIN)
"process.mainModule.filename = decodeURIComponent(window.location.pathname.substr(1));"
#else
"process.mainModule.filename = decodeURIComponent(window.location.pathname);"
#endif
"process.mainModule.paths = global.require('module')._nodeModulePaths(process.cwd());"
"process.mainModule.loaded = true;"
"}"
));
script->Run();
}
if (use_node || is_nw_protocol) {
v8::Local<v8::Script> script = v8::Script::New(v8::String::New(
// Overload require
"window.require = function(name) {"
" if (name == 'nw.gui')"
" return nwDispatcher.requireNwGui();"
" return global.require(name);"
"};"
// Save node-webkit version
"process.versions['node-webkit'] = '" NW_VERSION_STRING "';"
));
script->Run();
}
}
// static
v8::Handle<v8::Value> ShellContentRendererClient::ReportException(
const v8::Arguments& args) {
v8::HandleScope handle_scope;
// Do nothing if user is listening to uncaughtException.
v8::Local<v8::Value> listeners_v =
node::process->Get(v8::String::New("listeners"));
v8::Local<v8::Function> listeners =
v8::Local<v8::Function>::Cast(listeners_v);
v8::Local<v8::Value> argv[1] = { v8::String::New("uncaughtException") };
v8::Local<v8::Value> ret = listeners->Call(node::process, 1, argv);
v8::Local<v8::Array> listener_array = v8::Local<v8::Array>::Cast(ret);
uint32_t length = listener_array->Length();
if (length > 1)
return v8::Undefined();
// Print stacktrace.
v8::Local<v8::String> stack_symbol = v8::String::New("stack");
std::string error;
v8::Local<v8::Object> exception = args[0]->ToObject();
if (exception->Has(stack_symbol))
error = *v8::String::Utf8Value(exception->Get(stack_symbol));
else
error = *v8::String::Utf8Value(exception);
RenderView* render_view = GetCurrentRenderView();
if (!render_view)
return v8::Undefined();
render_view->Send(new ShellViewHostMsg_UncaughtException(
render_view->GetRoutingID(),
error));
return v8::Undefined();
}
void ShellContentRendererClient::UninstallNodeSymbols(
WebKit::WebFrame* frame,
v8::Handle<v8::Context> context) {
v8::HandleScope handle_scope;
v8::Local<v8::Object> v8Global = context->Global();
v8::Local<v8::Array> symbols = v8::Array::New(5);
symbols->Set(0, v8::String::New("global"));
symbols->Set(1, v8::String::New("process"));
symbols->Set(2, v8::String::New("Buffer"));
symbols->Set(3, v8::String::New("root"));
symbols->Set(4, v8::String::New("require"));
for (unsigned i = 0; i < symbols->Length(); ++i) {
v8::Local<v8::String> key = symbols->Get(i)->ToString();
if(v8Global->Has(key))
v8Global->Delete(key);
}
}
} // namespace content
<commit_msg>Setting context data for debugger in Node context<commit_after>// Copyright (c) 2012 Intel Corp
// Copyright (c) 2012 The Chromium Authors
//
// 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 co
// pies 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 al
// l copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IM
// PLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNES
// S FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS
// OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WH
// ETHER 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 "content/nw/src/renderer/shell_content_renderer_client.h"
#include "base/command_line.h"
#include "base/files/file_path.h"
#include "base/file_util.h"
#include "base/logging.h"
#include "base/string16.h"
#include "base/strings/string_number_conversions.h"
#include "base/utf_string_conversions.h"
#include "components/autofill/renderer/page_click_tracker.h"
#include "content/nw/src/api/dispatcher.h"
#include "content/nw/src/api/api_messages.h"
#include "content/nw/src/api/window_bindings.h"
#include "content/nw/src/common/shell_switches.h"
#include "content/nw/src/nw_package.h"
#include "content/nw/src/nw_version.h"
#include "components/autofill/renderer/autofill_agent.h"
#include "components/autofill/renderer/password_autofill_agent.h"
#include "content/nw/src/renderer/nw_render_view_observer.h"
#include "content/nw/src/renderer/prerenderer/prerenderer_client.h"
#include "content/nw/src/renderer/printing/print_web_view_helper.h"
#include "content/nw/src/renderer/shell_render_process_observer.h"
#include "content/public/common/content_switches.h"
#include "content/public/renderer/render_view.h"
#include "content/renderer/render_view_impl.h"
#include "net/proxy/proxy_bypass_rules.h"
#include "third_party/node/src/node.h"
#include "third_party/node/src/req_wrap.h"
#include "third_party/WebKit/Source/WebKit/chromium/public/WebDocument.h"
#include "third_party/WebKit/Source/WebKit/chromium/public/WebFrame.h"
#include "third_party/WebKit/Source/WebKit/chromium/public/WebSecurityOrigin.h"
#include "third_party/WebKit/Source/WebKit/chromium/public/WebSecurityPolicy.h"
#include "third_party/WebKit/Source/WebKit/chromium/public/WebView.h"
//#include "third_party/WebKit/Source/WebKit/chromium/public/platform/WebString.h"
#include "webkit/dom_storage/dom_storage_map.h"
using content::RenderView;
using content::RenderViewImpl;
using autofill::AutofillAgent;
using autofill::PasswordAutofillAgent;
using net::ProxyBypassRules;
using WebKit::WebFrame;
using WebKit::WebView;
using WebKit::WebString;
using WebKit::WebSecurityPolicy;
namespace content {
namespace {
RenderView* GetCurrentRenderView() {
WebFrame* frame = WebFrame::frameForCurrentContext();
DCHECK(frame);
if (!frame)
return NULL;
WebView* view = frame->view();
if (!view)
return NULL; // can happen during closing.
RenderView* render_view = RenderView::FromWebView(view);
DCHECK(render_view);
return render_view;
}
} // namespace
ShellContentRendererClient::ShellContentRendererClient() {
}
ShellContentRendererClient::~ShellContentRendererClient() {
}
void ShellContentRendererClient::RenderThreadStarted() {
// Change working directory.
CommandLine* command_line = CommandLine::ForCurrentProcess();
if (command_line->HasSwitch(switches::kWorkingDirectory)) {
file_util::SetCurrentDirectory(
command_line->GetSwitchValuePath(switches::kWorkingDirectory));
}
int argc = 1;
char* argv[] = { const_cast<char*>("node"), NULL, NULL };
std::string node_main;
// Check if there is a 'node-main'.
if (command_line->HasSwitch(switches::kNodeMain)) {
argc++;
node_main = command_line->GetSwitchValueASCII(switches::kNodeMain);
argv[1] = const_cast<char*>(node_main.c_str());
}
// Initialize uv.
node::SetupUv(argc, argv);
std::string snapshot_path;
if (command_line->HasSwitch(switches::kSnapshot)) {
snapshot_path = command_line->GetSwitchValuePath(switches::kSnapshot).AsUTF8Unsafe();
}
if (command_line->HasSwitch(switches::kDomStorageQuota)) {
std::string quota_str = command_line->GetSwitchValueASCII(switches::kDomStorageQuota);
int quota = 0;
if (base::StringToInt(quota_str, "a) && quota > 0)
dom_storage::DomStorageMap::SetQuotaOverride(quota * 1024 * 1024);
}
// Initialize node after render thread is started.
if (!snapshot_path.empty()) {
v8::V8::Initialize(snapshot_path.c_str());
}else
v8::V8::Initialize();
v8::HandleScope scope;
// Install window bindings into node. The Window API is implemented in node's
// context, so when a Shell changes to a new location and destroy previous
// window context, our Window API can still work.
window_bindings_.reset(new api::WindowBindings());
v8::RegisterExtension(window_bindings_.get());
const char* names[] = { "window_bindings.js" };
v8::ExtensionConfiguration extension_configuration(1, names);
node::g_context = v8::Context::New(&extension_configuration);
node::g_context->SetSecurityToken(v8::String::NewSymbol("nw-token", 8));
node::g_context->Enter();
node::g_context->SetEmbedderData(0, v8::String::NewSymbol("node"));
// Setup node.js.
node::SetupContext(argc, argv, node::g_context->Global());
// Start observers.
shell_observer_.reset(new ShellRenderProcessObserver());
WebString file_scheme(ASCIIToUTF16("file"));
// file: resources should be allowed to receive CORS requests.
WebSecurityPolicy::registerURLSchemeAsCORSEnabled(file_scheme);
}
void ShellContentRendererClient::RenderViewCreated(RenderView* render_view) {
new api::Dispatcher(render_view);
new nw::NwRenderViewObserver(render_view);
new prerender::PrerendererClient(render_view);
#if defined(ENABLE_PRINTING)
new printing::PrintWebViewHelper(render_view);
#endif
// PageClickTracker* page_click_tracker = new PageClickTracker(render_view);
PasswordAutofillAgent* password_autofill_agent =
new PasswordAutofillAgent(render_view);
new AutofillAgent(render_view, password_autofill_agent);
//page_click_tracker->AddListener(autofill_agent);
}
void ShellContentRendererClient::DidCreateScriptContext(
WebKit::WebFrame* frame,
v8::Handle<v8::Context> context,
int extension_group,
int world_id) {
GURL url(frame->document().url());
VLOG(1) << "DidCreateScriptContext: " << url;
InstallNodeSymbols(frame, context, url);
}
bool ShellContentRendererClient::goodForNode(WebKit::WebFrame* frame)
{
RenderViewImpl* rv = RenderViewImpl::FromWebView(frame->view());
GURL url(frame->document().url());
ProxyBypassRules rules;
rules.ParseFromString(rv->renderer_preferences_.nw_remote_page_rules);
bool force_on = rules.Matches(url);
bool is_nw_protocol = url.SchemeIs("nw") || !url.is_valid();
bool use_node =
CommandLine::ForCurrentProcess()->HasSwitch(switches::kNodejs) &&
!frame->isNwDisabledChildFrame() &&
(force_on || url.SchemeIsFile() || is_nw_protocol);
return use_node;
}
bool ShellContentRendererClient::WillSetSecurityToken(
WebKit::WebFrame* frame,
v8::Handle<v8::Context> context) {
GURL url(frame->document().url());
VLOG(1) << "WillSetSecurityToken: " << url;
if (goodForNode(frame)) {
// Override context's security token
context->SetSecurityToken(node::g_context->GetSecurityToken());
frame->document().securityOrigin().grantUniversalAccess();
return true;
}
// window.open frame was enabled for Node earlier
if (frame->isNodeJS()) {
frame->setNodeJS(false);
UninstallNodeSymbols(frame, context);
}
return false;
}
void ShellContentRendererClient::InstallNodeSymbols(
WebKit::WebFrame* frame,
v8::Handle<v8::Context> context,
const GURL& url) {
v8::HandleScope handle_scope;
static bool installed_once = false;
v8::Local<v8::Object> nodeGlobal = node::g_context->Global();
v8::Local<v8::Object> v8Global = context->Global();
// Use WebKit's console globally
nodeGlobal->Set(v8::String::New("console"),
v8Global->Get(v8::String::New("console")));
// Do we integrate node?
bool use_node = goodForNode(frame);
// Test if protocol is 'nw:'
// test for 'about:blank' is also here becuase window.open would
// open 'about:blank' first // FIXME
bool is_nw_protocol = url.SchemeIs("nw") || !url.is_valid();
if (use_node || is_nw_protocol) {
frame->setNodeJS(true);
v8::Local<v8::Array> symbols = v8::Array::New(4);
symbols->Set(0, v8::String::New("global"));
symbols->Set(1, v8::String::New("process"));
symbols->Set(2, v8::String::New("Buffer"));
symbols->Set(3, v8::String::New("root"));
for (unsigned i = 0; i < symbols->Length(); ++i) {
v8::Local<v8::Value> key = symbols->Get(i);
v8Global->Set(key, nodeGlobal->Get(key));
}
if (!installed_once) {
installed_once = true;
// The following listener on process should not be added each
// time when a document is created, or it will leave the
// reference to the closure created by the call back and leak
// memory (see #203)
nodeGlobal->Set(v8::String::New("window"), v8Global);
// Listen uncaughtException with ReportException.
v8::Local<v8::Function> cb = v8::FunctionTemplate::New(ReportException)->
GetFunction();
v8::Local<v8::Value> argv[] = { v8::String::New("uncaughtException"), cb };
node::MakeCallback(node::process, "on", 2, argv);
}
}
if (use_node) {
v8::Local<v8::Script> script = v8::Script::New(v8::String::New(
// Make node's relative modules work
"if (!process.mainModule.filename) {"
#if defined(OS_WIN)
"process.mainModule.filename = decodeURIComponent(window.location.pathname.substr(1));"
#else
"process.mainModule.filename = decodeURIComponent(window.location.pathname);"
#endif
"process.mainModule.paths = global.require('module')._nodeModulePaths(process.cwd());"
"process.mainModule.loaded = true;"
"}"
));
script->Run();
}
if (use_node || is_nw_protocol) {
v8::Local<v8::Script> script = v8::Script::New(v8::String::New(
// Overload require
"window.require = function(name) {"
" if (name == 'nw.gui')"
" return nwDispatcher.requireNwGui();"
" return global.require(name);"
"};"
// Save node-webkit version
"process.versions['node-webkit'] = '" NW_VERSION_STRING "';"
));
script->Run();
}
}
// static
v8::Handle<v8::Value> ShellContentRendererClient::ReportException(
const v8::Arguments& args) {
v8::HandleScope handle_scope;
// Do nothing if user is listening to uncaughtException.
v8::Local<v8::Value> listeners_v =
node::process->Get(v8::String::New("listeners"));
v8::Local<v8::Function> listeners =
v8::Local<v8::Function>::Cast(listeners_v);
v8::Local<v8::Value> argv[1] = { v8::String::New("uncaughtException") };
v8::Local<v8::Value> ret = listeners->Call(node::process, 1, argv);
v8::Local<v8::Array> listener_array = v8::Local<v8::Array>::Cast(ret);
uint32_t length = listener_array->Length();
if (length > 1)
return v8::Undefined();
// Print stacktrace.
v8::Local<v8::String> stack_symbol = v8::String::New("stack");
std::string error;
v8::Local<v8::Object> exception = args[0]->ToObject();
if (exception->Has(stack_symbol))
error = *v8::String::Utf8Value(exception->Get(stack_symbol));
else
error = *v8::String::Utf8Value(exception);
RenderView* render_view = GetCurrentRenderView();
if (!render_view)
return v8::Undefined();
render_view->Send(new ShellViewHostMsg_UncaughtException(
render_view->GetRoutingID(),
error));
return v8::Undefined();
}
void ShellContentRendererClient::UninstallNodeSymbols(
WebKit::WebFrame* frame,
v8::Handle<v8::Context> context) {
v8::HandleScope handle_scope;
v8::Local<v8::Object> v8Global = context->Global();
v8::Local<v8::Array> symbols = v8::Array::New(5);
symbols->Set(0, v8::String::New("global"));
symbols->Set(1, v8::String::New("process"));
symbols->Set(2, v8::String::New("Buffer"));
symbols->Set(3, v8::String::New("root"));
symbols->Set(4, v8::String::New("require"));
for (unsigned i = 0; i < symbols->Length(); ++i) {
v8::Local<v8::String> key = symbols->Get(i)->ToString();
if(v8Global->Has(key))
v8Global->Delete(key);
}
}
} // namespace content
<|endoftext|> |
<commit_before>/*************************************************************************
*
* $RCSfile: DataSeriesHelper.cxx,v $
*
* $Revision: 1.1 $
*
* last change: $Author: bm $ $Date: 2004-01-26 09:01:12 $
*
* 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: 2003 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#include "DataSeriesHelper.hxx"
#ifndef _COM_SUN_STAR_BEANS_XPROPERTYSET_HPP_
#include <com/sun/star/beans/XPropertySet.hpp>
#endif
#include <functional>
#include <algorithm>
using namespace ::com::sun::star;
using ::com::sun::star::uno::Reference;
using ::com::sun::star::uno::Sequence;
using ::rtl::OUString;
// ----------------------------------------
namespace
{
class lcl_MatchesRole : public ::std::unary_function< bool, Reference< chart2::XDataSequence > >
{
public:
lcl_MatchesRole( const OUString & aRole ) :
m_aRole( aRole )
{}
bool operator () ( const Reference< chart2::XDataSequence > & xSeq )
{
Reference< beans::XPropertySet > xProp( xSeq, uno::UNO_QUERY );
OUString aRole;
return ( xProp.is() &&
(xProp->getPropertyValue(
OUString( RTL_CONSTASCII_USTRINGPARAM( "Role" )) ) >>= aRole ) &&
m_aRole.equals( aRole ));
}
private:
OUString m_aRole;
};
} // anonymous namespace
// ----------------------------------------
namespace chart
{
namespace DataSeriesHelper
{
Reference< chart2::XDataSequence >
getDataSequenceByRole(
const Reference< chart2::XDataSource > & xSource, OUString aRole )
{
Reference< chart2::XDataSequence > aNoResult;
if( ! xSource.is())
return aNoResult;
Sequence< Reference< chart2::XDataSequence > > aSeq( xSource->getDataSequences());
const Reference< chart2::XDataSequence > * pBegin = aSeq.getConstArray();
const Reference< chart2::XDataSequence > * pEnd = pBegin + aSeq.getLength();
const Reference< chart2::XDataSequence > * pMatch =
::std::find_if( pBegin, pEnd, lcl_MatchesRole( aRole ));
if( pMatch != pEnd )
return *pMatch;
return aNoResult;
}
} // namespace DataSeriesHelper
} // namespace chart
<commit_msg>INTEGRATION: CWS ooo19126 (1.1.110); FILE MERGED 2005/09/05 18:43:29 rt 1.1.110.1: #i54170# Change license header: remove SISSL<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: DataSeriesHelper.cxx,v $
*
* $Revision: 1.2 $
*
* last change: $Author: rt $ $Date: 2005-09-08 01:27:54 $
*
* 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
*
************************************************************************/
#include "DataSeriesHelper.hxx"
#ifndef _COM_SUN_STAR_BEANS_XPROPERTYSET_HPP_
#include <com/sun/star/beans/XPropertySet.hpp>
#endif
#include <functional>
#include <algorithm>
using namespace ::com::sun::star;
using ::com::sun::star::uno::Reference;
using ::com::sun::star::uno::Sequence;
using ::rtl::OUString;
// ----------------------------------------
namespace
{
class lcl_MatchesRole : public ::std::unary_function< bool, Reference< chart2::XDataSequence > >
{
public:
lcl_MatchesRole( const OUString & aRole ) :
m_aRole( aRole )
{}
bool operator () ( const Reference< chart2::XDataSequence > & xSeq )
{
Reference< beans::XPropertySet > xProp( xSeq, uno::UNO_QUERY );
OUString aRole;
return ( xProp.is() &&
(xProp->getPropertyValue(
OUString( RTL_CONSTASCII_USTRINGPARAM( "Role" )) ) >>= aRole ) &&
m_aRole.equals( aRole ));
}
private:
OUString m_aRole;
};
} // anonymous namespace
// ----------------------------------------
namespace chart
{
namespace DataSeriesHelper
{
Reference< chart2::XDataSequence >
getDataSequenceByRole(
const Reference< chart2::XDataSource > & xSource, OUString aRole )
{
Reference< chart2::XDataSequence > aNoResult;
if( ! xSource.is())
return aNoResult;
Sequence< Reference< chart2::XDataSequence > > aSeq( xSource->getDataSequences());
const Reference< chart2::XDataSequence > * pBegin = aSeq.getConstArray();
const Reference< chart2::XDataSequence > * pEnd = pBegin + aSeq.getLength();
const Reference< chart2::XDataSequence > * pMatch =
::std::find_if( pBegin, pEnd, lcl_MatchesRole( aRole ));
if( pMatch != pEnd )
return *pMatch;
return aNoResult;
}
} // namespace DataSeriesHelper
} // namespace chart
<|endoftext|> |
<commit_before>#include "math-lib.h"
double ml_add(double n1, double n2) {return n1/2+n2;}<commit_msg>Corrected a small bug in ml_add. Fixes #2<commit_after>#include "math-lib.h"
double ml_add(double n1, double n2) {return n1+n2;}
<|endoftext|> |
<commit_before>#ifndef __CPREL_CPREL_GRELATION_HH__
#define __CPREL_CPREL_GRELATION_HH__
#include <boost/shared_ptr.hpp>
#include <cprel/tuple.hh>
namespace MPG { namespace CPRel {
/**
* \defgroup GRelation Ground relations
*
* Ground relations are the basic construct of the relation domain. The term
* ground is used to differenciate this relation from a relation represented by
* a decission variable. This module offers the capability to define and operate
* on this kind of relations.
*/
class BadRelation : public Gecode::Exception {
public:
BadRelation(const char* l)
: Exception(l,"Bad relation description") {}
};
namespace VarImpl {
class RelationImpl;
}
class GRelationIter;
/**
* \brief Class representing a ground relation
* \ingroup GRelation
*/
class GRelation {
private:
friend class GRelationIter;
typedef boost::shared_ptr<VarImpl::RelationImpl> Impl;
/// Relation storage
Impl pimpl_;
/// Avoid default construction
GRelation(void);
/// Constructor taking an implementation
explicit GRelation(Impl impl);
public:
/// \name Constructors, destructors and assignement
//@{
/// Constructor for an empty relation of arity \a a
explicit GRelation(int a);
/// Copy constructor
GRelation(const GRelation& r);
/// Assignment
GRelation& operator=(GRelation& right);
/// Destructor
~GRelation(void);
//@}
/// \name Modification operations
//@{
/**
* \brief Adds tuple \a t to the relation
*
* The returned value indicates if the relation changed due to the operation.
*/
bool add(const Tuple& t);
/**
* \brief Union of relations: \f$ this = this \cup r \f$.
*
* The returned boolean indicates of \c this relation changed
* because the operation.
*/
bool unionAssign(const GRelation& r);
/**
* \brief Difference of relations: \f$ this = this \setminus r \f$.
*
* The returned boolean indicates of \c this relation changed
* because the operation.
*/
bool differenceAssign(const GRelation& r);
//@}
/// \name Relation operations
//@{
/// Computes \f$ this \setminus r \f$
GRelation difference(const GRelation& r) const;
//@}
/// \name Test operations
//@{
/// Tests \f$ this \subseteq r \f$
bool subsetEq(const GRelation& r) const;
/// Tests \f$ this \supset r \f$
bool superset(const GRelation& r) const;
/// Tests \f$ this \cap r = \emptyset \f$
bool disjoint(const GRelation& r) const;
/// Tests whether this represents the same relation as \a r
bool eq(const GRelation& r) const;
//@}
/// \name Information
//@{
/// Returns the arity of the relation
int arity(void) const;
/// Returns the cardinality of the relation
double cardinality(void) const;
//@}
};
/**
* \brief Creates a relation with the elements contained in \a dom.
* \ingroup GRelation
*/
GRelation create(const std::vector<Tuple>& dom);
/**
* \brief Outputs relation \a r to \a os
* \ingroup GRelation
*/
std::ostream& operator<< (std::ostream& os, const GRelation& r);
namespace VarImpl {
class RelationImplIter;
}
/**
* \brief Iterator on the tuples of a ground relation
* \ingroup GRelation
*/
class GRelationIter {
private:
typedef boost::shared_ptr<VarImpl::RelationImplIter> Impl;
/// Relation storage
Impl pimpl_;
/**
* \brief Stores the current tuple
*
* This temporal storage is needed because the iterator provided by the
* implementation is not at least forward iterator.
*/
Tuple current_;
/// Indicates if there is a current element to be read
bool valid_;
/// Avoid default construction
GRelationIter(void);
public:
/// Constructs an iterator on relation \a r
GRelationIter(const GRelation& r);
/// Copy constructor
GRelationIter(const GRelationIter& it);
/// Destructor
~GRelationIter(void);
/// Tests whether the iterator is still valid
bool operator()(void) const;
/// Returns the current value under iteration
Tuple val(void) const;
/// Advances the iterator
void operator++(void);
};
}}
#endif
<commit_msg>removed exception code<commit_after>#ifndef __CPREL_CPREL_GRELATION_HH__
#define __CPREL_CPREL_GRELATION_HH__
#include <boost/shared_ptr.hpp>
#include <cprel/tuple.hh>
namespace MPG { namespace CPRel {
/**
* \defgroup GRelation Ground relations
*
* Ground relations are the basic construct of the relation domain. The term
* ground is used to differenciate this relation from a relation represented by
* a decission variable. This module offers the capability to define and operate
* on this kind of relations.
*/
namespace VarImpl {
class RelationImpl;
}
class GRelationIter;
/**
* \brief Class representing a ground relation
* \ingroup GRelation
*/
class GRelation {
private:
friend class GRelationIter;
typedef boost::shared_ptr<VarImpl::RelationImpl> Impl;
/// Relation storage
Impl pimpl_;
/// Avoid default construction
GRelation(void);
/// Constructor taking an implementation
explicit GRelation(Impl impl);
public:
/// \name Constructors, destructors and assignement
//@{
/// Constructor for an empty relation of arity \a a
explicit GRelation(int a);
/// Copy constructor
GRelation(const GRelation& r);
/// Assignment
GRelation& operator=(GRelation& right);
/// Destructor
~GRelation(void);
//@}
/// \name Modification operations
//@{
/**
* \brief Adds tuple \a t to the relation
*
* The returned value indicates if the relation changed due to the operation.
*/
bool add(const Tuple& t);
/**
* \brief Union of relations: \f$ this = this \cup r \f$.
*
* The returned boolean indicates of \c this relation changed
* because the operation.
*/
bool unionAssign(const GRelation& r);
/**
* \brief Difference of relations: \f$ this = this \setminus r \f$.
*
* The returned boolean indicates of \c this relation changed
* because the operation.
*/
bool differenceAssign(const GRelation& r);
//@}
/// \name Relation operations
//@{
/// Computes \f$ this \setminus r \f$
GRelation difference(const GRelation& r) const;
//@}
/// \name Test operations
//@{
/// Tests \f$ this \subseteq r \f$
bool subsetEq(const GRelation& r) const;
/// Tests \f$ this \supset r \f$
bool superset(const GRelation& r) const;
/// Tests \f$ this \cap r = \emptyset \f$
bool disjoint(const GRelation& r) const;
/// Tests whether this represents the same relation as \a r
bool eq(const GRelation& r) const;
//@}
/// \name Information
//@{
/// Returns the arity of the relation
int arity(void) const;
/// Returns the cardinality of the relation
double cardinality(void) const;
//@}
};
/**
* \brief Creates a relation with the elements contained in \a dom.
* \ingroup GRelation
*/
GRelation create(const std::vector<Tuple>& dom);
/**
* \brief Outputs relation \a r to \a os
* \ingroup GRelation
*/
std::ostream& operator<< (std::ostream& os, const GRelation& r);
namespace VarImpl {
class RelationImplIter;
}
/**
* \brief Iterator on the tuples of a ground relation
* \ingroup GRelation
*/
class GRelationIter {
private:
typedef boost::shared_ptr<VarImpl::RelationImplIter> Impl;
/// Relation storage
Impl pimpl_;
/**
* \brief Stores the current tuple
*
* This temporal storage is needed because the iterator provided by the
* implementation is not at least forward iterator.
*/
Tuple current_;
/// Indicates if there is a current element to be read
bool valid_;
/// Avoid default construction
GRelationIter(void);
public:
/// Constructs an iterator on relation \a r
GRelationIter(const GRelation& r);
/// Copy constructor
GRelationIter(const GRelationIter& it);
/// Destructor
~GRelationIter(void);
/// Tests whether the iterator is still valid
bool operator()(void) const;
/// Returns the current value under iteration
Tuple val(void) const;
/// Advances the iterator
void operator++(void);
};
}}
#endif
<|endoftext|> |
<commit_before>
#include "scene.h"
Scene::Scene(const ros::NodeHandle& node)
: Ped::Tscene(), nh_(node)
{
// useful for keeping track of agents in the cleaning process
tree = new Ped::Ttree(this, 0, 0, 0, 1000, 1000);
}
Scene::Scene( double left, double up, double width, double height, const ros::NodeHandle& node )
: Ped::Tscene(left, up, width, height), nh_(node)
{
// useful for keeping track of agents in the cleaning process
tree = new Ped::Ttree(this, 0, 0, 0, 1000, 1000);
}
bool Scene::srvMoveAgentHandler(pedsim_srvs::SetAgentState::Request& req, pedsim_srvs::SetAgentState::Response& res)
{
pedsim_msgs::AgentState state = req.state;
ROS_INFO("Rceived (%f) (%f)", state.position.x, state.position.y);
double vx = state.velocity.x;
double vy = state.velocity.y;
if (robot_->getid() == state.id) {
robot_->setvx( vx );
robot_->setvy( vy );
robot_->setVmax( sqrt( vx * vx + vy * vy ) );
}
res.finished = true;
return true;
}
void Scene::cleanupItems() {
cleanup();
}
void Scene::clear() {
all_agents_.clear();
foreach(Waypoint* waypoint, waypoints)
delete waypoint;
waypoints.clear();
foreach(Obstacle* obs, obstacles)
delete obs;
obstacles.clear();
}
void Scene::runSimulation() {
/// setup the agents and the robot
all_agents_ = getAllAgents();
for (vector<Ped::Tagent*>::const_iterator iter = all_agents_.begin(); iter != all_agents_.end(); ++iter)
{
Ped::Tagent *a = (*iter);
if (a->gettype() == 2)
robot_ = a;
}
ros::Rate r( 1 / CONFIG.simh );
while (ros::ok())
{
moveAllAgents();
publishAgentStatus();
publishAgentVisuals();
publishObstacles();
// helps to make things faster
cleanupItems();
ros::spinOnce();
r.sleep();
}
}
bool Scene::initialize()
{
// start the time steps
timestep = 0;
/// setup the list of all agents and the robot agent
all_agents_.clear();
// setup publishers
pub_all_agents_ = nh_.advertise<pedsim_msgs::AllAgentsState>("AllAgentsStatus", 0);
pub_agent_visuals_ = nh_.advertise<visualization_msgs::Marker>( "agents_markers", 0 );
pub_obstacles_ = nh_.advertise<nav_msgs::GridCells>( "static_obstacles", 0 );
// services hooks
srv_move_agent_ = nh_.advertiseService("SetAgentState", &Scene::srvMoveAgentHandler, this);
// load parameters
std::string scene_file_param;
nh_.getParam("/simulator/scene_file", scene_file_param);
double cell_size;
nh_.getParam("/simulator/cell_size", cell_size);
CONFIG.width = cell_size;
CONFIG.height = cell_size;
// load scenario file
QString scenefile = QString::fromStdString(scene_file_param);
if (!readFromFile(scenefile)) {
ROS_WARN("Could not load the scene file, check paths");
return false;
}
return true;
}
void Scene::moveAllAgents()
{
timestep++;
// move the agents by social force
Ped::Tscene::moveAgents(CONFIG.simh);
}
void Scene::publishAgentStatus()
{
pedsim_msgs::AllAgentsState all_status;
for (vector<Ped::Tagent*>::const_iterator iter = all_agents_.begin(); iter != all_agents_.end(); ++iter) {
Ped::Tagent *a = (*iter);
pedsim_msgs::AgentState state;
state.id = a->getid();
state.position.x = a->getx();
state.position.y = a->gety();
state.position.z = a->getz();
state.velocity.x = a->getvx();
state.velocity.y = a->getvy();
state.velocity.z = a->getvz();
all_status.agent_states.push_back(state);
}
pub_all_agents_.publish(all_status);
}
void Scene::publishAgentVisuals()
{
for (vector<Ped::Tagent*>::const_iterator iter = all_agents_.begin(); iter != all_agents_.end(); ++iter)
{
Ped::Tagent *a = (*iter);
visualization_msgs::Marker marker;
marker.header.frame_id = "world";
marker.header.stamp = ros::Time();
marker.ns = "pedsim";
marker.id = a->getid();
if (a->gettype() == robot_->gettype())
{
// marker.type = visualization_msgs::Marker::CUBE;
marker.type = visualization_msgs::Marker::MESH_RESOURCE;
marker.mesh_resource = "package://simulator/images/darylbot.dae";
marker.color.a = 1.0;
marker.color.r = 1.0;
marker.color.g = 1.0;
marker.color.b = 1.0;
marker.scale.x = 0.5;
marker.scale.y = 0.5;
marker.scale.z = 0.5;
}
else
{
marker.type = visualization_msgs::Marker::CYLINDER;
marker.color.a = 1.0;
marker.color.r = 0.0;
marker.color.g = 1.0;
marker.color.b = 0.0;
marker.scale.x = 0.2;
marker.scale.y = 0.2;
marker.scale.z = 1;
}
marker.action = 0; // add or modify
marker.pose.position.x = a->getx();
marker.pose.position.y = a->gety();
marker.pose.position.z = 0;
marker.pose.orientation.x = 0.0;
marker.pose.orientation.y = 0.0;
marker.pose.orientation.z = 0.0;
marker.pose.orientation.w = 1.0;
pub_agent_visuals_.publish( marker );
}
}
void Scene::publishObstacles()
{
// ROS_INFO("publishing (%d) obstacles", (int)obstacle_cells_.size());
nav_msgs::GridCells obstacles;
obstacles.header.frame_id = "world";
obstacles.cell_width = CONFIG.width;
obstacles.cell_height = CONFIG.height;
BOOST_FOREACH(TLoc loc, obstacle_cells_)
{
geometry_msgs::Point p;
p.x = loc.x;
p.y = loc.y;
p.z = 0.0;
obstacles.cells.push_back(p);
}
pub_obstacles_.publish(obstacles);
}
std::set<const Ped::Tagent*> Scene::getNeighbors(double x, double y, double maxDist)
{
std::set<const Ped::Tagent*> potentialNeighbours = Ped::Tscene::getNeighbors(x, y, maxDist);
// filter according to euclidean distance
std::set<const Ped::Tagent*>::const_iterator agentIter = potentialNeighbours.begin();
while(agentIter != potentialNeighbours.end())
{
double aX = (*agentIter)->getx();
double aY = (*agentIter)->gety();
double distance = sqrt((x-aX)*(x-aX) + (y-aY)*(y-aY));
// remove distant neighbors
if(distance > maxDist) {
potentialNeighbours.erase(agentIter++);
} else {
++agentIter;
}
}
return potentialNeighbours;
}
bool Scene::readFromFile(const QString& filename) {
// ROS_INFO("Loading scenario file '%s'.", filename.toStdString);
// open file
QFile file(filename);
if(!file.open(QIODevice::ReadOnly | QIODevice::Text)) {
// ERROR_LOG("Couldn't open scenario file!");
return false;
}
// read input
while(!file.atEnd()) {
QByteArray line = file.readLine();
processData(line);
}
// report success
return true;
}
/// Called for each line in the file
void Scene::processData(QByteArray& data)
{
// TODO - switch to tinyxml for reading in the scene files
xmlReader.addData(data);
obstacle_cells_.clear();
while(!xmlReader.atEnd()) {
xmlReader.readNext();
if(xmlReader.isStartElement()) {
if((xmlReader.name() == "scenario") || (xmlReader.name() == "welcome")) {
// nothing to do
}
else if(xmlReader.name() == "obstacle") {
double x1 = xmlReader.attributes().value("x1").toString().toDouble();
double y1 = xmlReader.attributes().value("y1").toString().toDouble();
double x2 = xmlReader.attributes().value("x2").toString().toDouble();
double y2 = xmlReader.attributes().value("y2").toString().toDouble();
Obstacle* obs = new Obstacle(x1, y1, x2, y2);
this->addObstacle(obs);
// fill the obstacle cells
drawObstacles(x1, y1, x2, y2);
}
else if(xmlReader.name() == "waypoint") {
// TODO - add an explicit waypoint type
QString id = xmlReader.attributes().value("id").toString();
double x = xmlReader.attributes().value("x").toString().toDouble();
double y = xmlReader.attributes().value("y").toString().toDouble();
double r = xmlReader.attributes().value("r").toString().toDouble();
Waypoint* w = new Waypoint(id, x, y, r);
if (boost::starts_with(id, "start")) {
w->setType(Ped::Twaypoint::TYPE_BIRTH);
ROS_INFO("adding a birth waypoint");
}
if (boost::starts_with(id, "stop")) {
w->setType(Ped::Twaypoint::TYPE_DEATH);
ROS_INFO("adding a death waypoint");
}
this->waypoints[id] = w;
}
else if(xmlReader.name() == "agent") {
double x = xmlReader.attributes().value("x").toString().toDouble();
double y = xmlReader.attributes().value("y").toString().toDouble();
int n = xmlReader.attributes().value("n").toString().toDouble();
double dx = xmlReader.attributes().value("dx").toString().toDouble();
double dy = xmlReader.attributes().value("dy").toString().toDouble();
double type = xmlReader.attributes().value("type").toString().toInt();
for (int i=0; i<n; i++) {
Agent* a = new Agent();
double randomizedX = x;
double randomizedY = y;
// handle dx=0 or dy=0 cases
if(dx != 0)
randomizedX += rand()/(double)RAND_MAX * dx - dx/2;
if(dy != 0)
randomizedY += rand()/(double)RAND_MAX * dy - dy/2;
a->setPosition(randomizedX, randomizedY);
a->setType(type);
this->addAgent(a);
currentAgents.append(a);
}
}
else if(xmlReader.name() == "addwaypoint") {
QString id = xmlReader.attributes().value("id").toString();
// add waypoints to current agents, not just those of the current <agent> element
foreach(Agent* a, currentAgents)
a->addWaypoint(this->waypoints[id]);
}
else {
// inform the user about invalid elements
// ROS_WARN("Unknown element: %s", xmlReader.name().toString());
}
}
else if(xmlReader.isEndElement()) {
if (xmlReader.name() == "agent") {
currentAgents.clear();
}
}
}
}
void Scene::drawObstacles(float x1, float y1, float x2, float y2)
{
// Modified Bresenham's line algorithm (addding a buffer around obstacles)
const bool steep = (fabs(y2 - y1) > fabs(x2 - x1));
if(steep)
{
std::swap(x1, y1);
std::swap(x2, y2);
}
if(x1 > x2)
{
std::swap(x1, x2);
std::swap(y1, y2);
}
const float dx = x2 - x1;
const float dy = fabs(y2 - y1);
float error = dx / 8.0f;
const int ystep = (y1 < y2) ? 1 : -1;
int y = (int)y1;
const int maxX = (int)x2;
for(int x=(int)x1; x<maxX; x++)
{
if(steep)
{
obstacle_cells_.push_back(TLoc(y,x));
obstacle_cells_.push_back(TLoc(y+CONFIG.height,x+CONFIG.width));
obstacle_cells_.push_back(TLoc(y-CONFIG.height,x-CONFIG.width));
}
else
{
obstacle_cells_.push_back(TLoc(y,x));
obstacle_cells_.push_back(TLoc(x,y));
obstacle_cells_.push_back(TLoc(x+CONFIG.width,y+CONFIG.height));
obstacle_cells_.push_back(TLoc(x-CONFIG.width,y-CONFIG.height));
}
error -= dy;
if(error < 0)
{
y += ystep;
error += dx;
}
}
}
int main(int argc, char** argv)
{
// initialize resources
ros::init(argc, argv, "simulator");
ROS_INFO("node initialized");
ros::NodeHandle node;
// TOOD - read scene params automatically from launch file
Scene sim_scene(0, 0, 50, 50, node);
if (sim_scene.initialize())
{
ROS_INFO("loaded parameters, starting simulation...");
sim_scene.runSimulation();
}
else
return EXIT_FAILURE;
return EXIT_SUCCESS;
}
<commit_msg>reverting previous message header changes to fix momo bug<commit_after>
#include "scene.h"
Scene::Scene(const ros::NodeHandle& node)
: Ped::Tscene(), nh_(node)
{
// useful for keeping track of agents in the cleaning process
tree = new Ped::Ttree(this, 0, 0, 0, 1000, 1000);
}
Scene::Scene( double left, double up, double width, double height, const ros::NodeHandle& node )
: Ped::Tscene(left, up, width, height), nh_(node)
{
// useful for keeping track of agents in the cleaning process
tree = new Ped::Ttree(this, 0, 0, 0, 1000, 1000);
}
bool Scene::srvMoveAgentHandler(pedsim_srvs::SetAgentState::Request& req, pedsim_srvs::SetAgentState::Response& res)
{
pedsim_msgs::AgentState state = req.state;
ROS_INFO("Rceived (%f) (%f)", state.position.x, state.position.y);
double vx = state.velocity.x;
double vy = state.velocity.y;
if (robot_->getid() == state.id) {
robot_->setvx( vx );
robot_->setvy( vy );
robot_->setVmax( sqrt( vx * vx + vy * vy ) );
}
res.finished = true;
return true;
}
void Scene::cleanupItems() {
cleanup();
}
void Scene::clear() {
all_agents_.clear();
foreach(Waypoint* waypoint, waypoints)
delete waypoint;
waypoints.clear();
foreach(Obstacle* obs, obstacles)
delete obs;
obstacles.clear();
}
void Scene::runSimulation() {
/// setup the agents and the robot
all_agents_ = getAllAgents();
for (vector<Ped::Tagent*>::const_iterator iter = all_agents_.begin(); iter != all_agents_.end(); ++iter)
{
Ped::Tagent *a = (*iter);
if (a->gettype() == 2)
robot_ = a;
}
ros::Rate r( 1 / CONFIG.simh );
while (ros::ok())
{
moveAllAgents();
publishAgentStatus();
publishAgentVisuals();
publishObstacles();
// helps to make things faster
cleanupItems();
ros::spinOnce();
r.sleep();
}
}
bool Scene::initialize()
{
// start the time steps
timestep = 0;
/// setup the list of all agents and the robot agent
all_agents_.clear();
// setup publishers
pub_all_agents_ = nh_.advertise<pedsim_msgs::AllAgentsState>("AllAgentsStatus", 0);
pub_agent_visuals_ = nh_.advertise<visualization_msgs::Marker>( "agents_markers", 0 );
pub_obstacles_ = nh_.advertise<nav_msgs::GridCells>( "static_obstacles", 0 );
// services hooks
srv_move_agent_ = nh_.advertiseService("SetAgentState", &Scene::srvMoveAgentHandler, this);
// load parameters
std::string scene_file_param;
nh_.getParam("/simulator/scene_file", scene_file_param);
double cell_size;
nh_.getParam("/simulator/cell_size", cell_size);
CONFIG.width = cell_size;
CONFIG.height = cell_size;
// load scenario file
QString scenefile = QString::fromStdString(scene_file_param);
if (!readFromFile(scenefile)) {
ROS_WARN("Could not load the scene file, check paths");
return false;
}
return true;
}
void Scene::moveAllAgents()
{
timestep++;
// move the agents by social force
Ped::Tscene::moveAgents(CONFIG.simh);
}
void Scene::publishAgentStatus()
{
pedsim_msgs::AllAgentsState all_status;
std_msgs::Header all_header;
all_header.stamp = ros::Time::now();
all_status.header = all_header;
for (vector<Ped::Tagent*>::const_iterator iter = all_agents_.begin(); iter != all_agents_.end(); ++iter) {
Ped::Tagent *a = (*iter);
pedsim_msgs::AgentState state;
std_msgs::Header agent_header;
agent_header.stamp = ros::Time::now();
state.header = agent_header;
state.id = a->getid();
state.position.x = a->getx();
state.position.y = a->gety();
state.position.z = a->getz();
state.velocity.x = a->getvx();
state.velocity.y = a->getvy();
state.velocity.z = a->getvz();
all_status.agent_states.push_back(state);
}
pub_all_agents_.publish(all_status);
}
void Scene::publishAgentVisuals()
{
for (vector<Ped::Tagent*>::const_iterator iter = all_agents_.begin(); iter != all_agents_.end(); ++iter)
{
Ped::Tagent *a = (*iter);
visualization_msgs::Marker marker;
marker.header.frame_id = "world";
marker.header.stamp = ros::Time();
marker.ns = "pedsim";
marker.id = a->getid();
if (a->gettype() == robot_->gettype())
{
// marker.type = visualization_msgs::Marker::CUBE;
marker.type = visualization_msgs::Marker::MESH_RESOURCE;
marker.mesh_resource = "package://simulator/images/darylbot.dae";
marker.color.a = 1.0;
marker.color.r = 1.0;
marker.color.g = 1.0;
marker.color.b = 1.0;
marker.scale.x = 0.5;
marker.scale.y = 0.5;
marker.scale.z = 0.5;
}
else
{
marker.type = visualization_msgs::Marker::CYLINDER;
marker.color.a = 1.0;
marker.color.r = 0.0;
marker.color.g = 1.0;
marker.color.b = 0.0;
marker.scale.x = 0.2;
marker.scale.y = 0.2;
marker.scale.z = 1;
}
marker.action = 0; // add or modify
marker.pose.position.x = a->getx();
marker.pose.position.y = a->gety();
marker.pose.position.z = 0;
marker.pose.orientation.x = 0.0;
marker.pose.orientation.y = 0.0;
marker.pose.orientation.z = 0.0;
marker.pose.orientation.w = 1.0;
pub_agent_visuals_.publish( marker );
}
}
void Scene::publishObstacles()
{
// ROS_INFO("publishing (%d) obstacles", (int)obstacle_cells_.size());
nav_msgs::GridCells obstacles;
obstacles.header.frame_id = "world";
obstacles.cell_width = CONFIG.width;
obstacles.cell_height = CONFIG.height;
BOOST_FOREACH(TLoc loc, obstacle_cells_)
{
geometry_msgs::Point p;
p.x = loc.x;
p.y = loc.y;
p.z = 0.0;
obstacles.cells.push_back(p);
}
pub_obstacles_.publish(obstacles);
}
std::set<const Ped::Tagent*> Scene::getNeighbors(double x, double y, double maxDist)
{
std::set<const Ped::Tagent*> potentialNeighbours = Ped::Tscene::getNeighbors(x, y, maxDist);
// filter according to euclidean distance
std::set<const Ped::Tagent*>::const_iterator agentIter = potentialNeighbours.begin();
while(agentIter != potentialNeighbours.end())
{
double aX = (*agentIter)->getx();
double aY = (*agentIter)->gety();
double distance = sqrt((x-aX)*(x-aX) + (y-aY)*(y-aY));
// remove distant neighbors
if(distance > maxDist) {
potentialNeighbours.erase(agentIter++);
} else {
++agentIter;
}
}
return potentialNeighbours;
}
bool Scene::readFromFile(const QString& filename) {
// ROS_INFO("Loading scenario file '%s'.", filename.toStdString);
// open file
QFile file(filename);
if(!file.open(QIODevice::ReadOnly | QIODevice::Text)) {
// ERROR_LOG("Couldn't open scenario file!");
return false;
}
// read input
while(!file.atEnd()) {
QByteArray line = file.readLine();
processData(line);
}
// report success
return true;
}
/// Called for each line in the file
void Scene::processData(QByteArray& data)
{
// TODO - switch to tinyxml for reading in the scene files
xmlReader.addData(data);
obstacle_cells_.clear();
while(!xmlReader.atEnd()) {
xmlReader.readNext();
if(xmlReader.isStartElement()) {
if((xmlReader.name() == "scenario") || (xmlReader.name() == "welcome")) {
// nothing to do
}
else if(xmlReader.name() == "obstacle") {
double x1 = xmlReader.attributes().value("x1").toString().toDouble();
double y1 = xmlReader.attributes().value("y1").toString().toDouble();
double x2 = xmlReader.attributes().value("x2").toString().toDouble();
double y2 = xmlReader.attributes().value("y2").toString().toDouble();
Obstacle* obs = new Obstacle(x1, y1, x2, y2);
this->addObstacle(obs);
// fill the obstacle cells
drawObstacles(x1, y1, x2, y2);
}
else if(xmlReader.name() == "waypoint") {
// TODO - add an explicit waypoint type
QString id = xmlReader.attributes().value("id").toString();
double x = xmlReader.attributes().value("x").toString().toDouble();
double y = xmlReader.attributes().value("y").toString().toDouble();
double r = xmlReader.attributes().value("r").toString().toDouble();
Waypoint* w = new Waypoint(id, x, y, r);
if (boost::starts_with(id, "start")) {
w->setType(Ped::Twaypoint::TYPE_BIRTH);
ROS_INFO("adding a birth waypoint");
}
if (boost::starts_with(id, "stop")) {
w->setType(Ped::Twaypoint::TYPE_DEATH);
ROS_INFO("adding a death waypoint");
}
this->waypoints[id] = w;
}
else if(xmlReader.name() == "agent") {
double x = xmlReader.attributes().value("x").toString().toDouble();
double y = xmlReader.attributes().value("y").toString().toDouble();
int n = xmlReader.attributes().value("n").toString().toDouble();
double dx = xmlReader.attributes().value("dx").toString().toDouble();
double dy = xmlReader.attributes().value("dy").toString().toDouble();
double type = xmlReader.attributes().value("type").toString().toInt();
for (int i=0; i<n; i++) {
Agent* a = new Agent();
double randomizedX = x;
double randomizedY = y;
// handle dx=0 or dy=0 cases
if(dx != 0)
randomizedX += rand()/(double)RAND_MAX * dx - dx/2;
if(dy != 0)
randomizedY += rand()/(double)RAND_MAX * dy - dy/2;
a->setPosition(randomizedX, randomizedY);
a->setType(type);
this->addAgent(a);
currentAgents.append(a);
}
}
else if(xmlReader.name() == "addwaypoint") {
QString id = xmlReader.attributes().value("id").toString();
// add waypoints to current agents, not just those of the current <agent> element
foreach(Agent* a, currentAgents)
a->addWaypoint(this->waypoints[id]);
}
else {
// inform the user about invalid elements
// ROS_WARN("Unknown element: %s", xmlReader.name().toString());
}
}
else if(xmlReader.isEndElement()) {
if (xmlReader.name() == "agent") {
currentAgents.clear();
}
}
}
}
void Scene::drawObstacles(float x1, float y1, float x2, float y2)
{
// Modified Bresenham's line algorithm (addding a buffer around obstacles)
const bool steep = (fabs(y2 - y1) > fabs(x2 - x1));
if(steep)
{
std::swap(x1, y1);
std::swap(x2, y2);
}
if(x1 > x2)
{
std::swap(x1, x2);
std::swap(y1, y2);
}
const float dx = x2 - x1;
const float dy = fabs(y2 - y1);
float error = dx / 8.0f;
const int ystep = (y1 < y2) ? 1 : -1;
int y = (int)y1;
const int maxX = (int)x2;
for(int x=(int)x1; x<maxX; x++)
{
if(steep)
{
obstacle_cells_.push_back(TLoc(y,x));
obstacle_cells_.push_back(TLoc(y+CONFIG.height,x+CONFIG.width));
obstacle_cells_.push_back(TLoc(y-CONFIG.height,x-CONFIG.width));
}
else
{
obstacle_cells_.push_back(TLoc(y,x));
obstacle_cells_.push_back(TLoc(x+CONFIG.width,y+CONFIG.height));
obstacle_cells_.push_back(TLoc(x-CONFIG.width,y-CONFIG.height));
}
error -= dy;
if(error < 0)
{
y += ystep;
error += dx;
}
}
}
int main(int argc, char** argv)
{
// initialize resources
ros::init(argc, argv, "simulator");
ROS_INFO("node initialized");
ros::NodeHandle node;
// TOOD - read scene params automatically from launch file
Scene sim_scene(0, 0, 50, 50, node);
if (sim_scene.initialize())
{
ROS_INFO("loaded parameters, starting simulation...");
sim_scene.runSimulation();
}
else
return EXIT_FAILURE;
return EXIT_SUCCESS;
}
<|endoftext|> |
<commit_before>/** \file DbConnection.cc
* \brief Implementation of the DbConnection class.
* \author Dr. Johannes Ruscheinski (johannes.ruscheinski@uni-tuebingen.de)
*
* \copyright 2015 Universitätsbibliothek Tübingen. All rights reserved.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "DbConnection.h"
#include <stdexcept>
#include <cstdlib>
#include "RegexMatcher.h"
#include "StringUtil.h"
#include "UrlUtil.h"
#include "util.h"
DbConnection::DbConnection(const std::string &mysql_url) {
static const RegexMatcher * const mysql_url_matcher(
RegexMatcher::RegexMatcherFactory("mysql://([^:]+):([^@]+)@([^:/]+)(\\d+:)?/(.+)"));
std::string err_msg;
if (not mysql_url_matcher->matched(mysql_url, &err_msg))
throw std::runtime_error("\"" + mysql_url + "\" does not look like an expected MySQL URL! (" + err_msg + ")");
const std::string user(UrlUtil::UrlDecode((*mysql_url_matcher)[1]));
const std::string passwd((*mysql_url_matcher)[2]);
const std::string host(UrlUtil::UrlDecode((*mysql_url_matcher)[3]));
const std::string db_name(UrlUtil::UrlDecode((*mysql_url_matcher)[5]));
const std::string port_plus_colon((*mysql_url_matcher)[4]);
unsigned port;
if (port_plus_colon.empty())
port = MYSQL_PORT;
else
port = StringUtil::ToUnsigned(port_plus_colon.substr(0, port_plus_colon.length() - 1));
init(db_name, user, passwd, host, port);
}
DbConnection::~DbConnection() {
if (initialised_)
::mysql_close(&mysql_);
}
void DbConnection::queryOrDie(const std::string &query_statement) {
if (not query(query_statement))
Error("in DbConnection::queryOrDie: \"" + query_statement + "\" failed: " + getLastErrorMessage());
}
DbResultSet DbConnection::getLastResultSet() {
MYSQL_RES * const result_set(::mysql_store_result(&mysql_));
if (result_set == nullptr)
throw std::runtime_error("in DbConnection::getLastResultSet: mysql_store_result() failed! ("
+ getLastErrorMessage() + ")");
return DbResultSet(result_set);
}
std::string DbConnection::escapeString(const std::string &unescaped_string) {
char * const buffer(reinterpret_cast<char * const>(std::malloc(unescaped_string.size() * 2 + 1)));
const size_t escaped_length(::mysql_real_escape_string(&mysql_, buffer, unescaped_string.data(),
unescaped_string.size()));
const std::string escaped_string(buffer, escaped_length);
std::free(buffer);
return escaped_string;
}
void DbConnection::init(const std::string &database_name, const std::string &user, const std::string &passwd,
const std::string &host, const unsigned port)
{
initialised_ = false;
if (::mysql_init(&mysql_) == nullptr)
throw std::runtime_error("in DbConnection::init: mysql_init() failed!");
if (::mysql_real_connect(&mysql_, host.c_str(), user.c_str(), passwd.c_str(), database_name.c_str(), port,
/* unix_socket = */nullptr, /* client_flag = */CLIENT_MULTI_STATEMENTS) == nullptr)
throw std::runtime_error("in DbConnection::init: mysql_real_connect() failed! (" + getLastErrorMessage() + ")");
initialised_ = true;
}
<commit_msg>By defaultw e read and write UTF-8.<commit_after>/** \file DbConnection.cc
* \brief Implementation of the DbConnection class.
* \author Dr. Johannes Ruscheinski (johannes.ruscheinski@uni-tuebingen.de)
*
* \copyright 2015 Universitätsbibliothek Tübingen. All rights reserved.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "DbConnection.h"
#include <stdexcept>
#include <cstdlib>
#include "RegexMatcher.h"
#include "StringUtil.h"
#include "UrlUtil.h"
#include "util.h"
DbConnection::DbConnection(const std::string &mysql_url) {
static const RegexMatcher * const mysql_url_matcher(
RegexMatcher::RegexMatcherFactory("mysql://([^:]+):([^@]+)@([^:/]+)(\\d+:)?/(.+)"));
std::string err_msg;
if (not mysql_url_matcher->matched(mysql_url, &err_msg))
throw std::runtime_error("\"" + mysql_url + "\" does not look like an expected MySQL URL! (" + err_msg + ")");
const std::string user(UrlUtil::UrlDecode((*mysql_url_matcher)[1]));
const std::string passwd((*mysql_url_matcher)[2]);
const std::string host(UrlUtil::UrlDecode((*mysql_url_matcher)[3]));
const std::string db_name(UrlUtil::UrlDecode((*mysql_url_matcher)[5]));
const std::string port_plus_colon((*mysql_url_matcher)[4]);
unsigned port;
if (port_plus_colon.empty())
port = MYSQL_PORT;
else
port = StringUtil::ToUnsigned(port_plus_colon.substr(0, port_plus_colon.length() - 1));
init(db_name, user, passwd, host, port);
}
DbConnection::~DbConnection() {
if (initialised_)
::mysql_close(&mysql_);
}
void DbConnection::queryOrDie(const std::string &query_statement) {
if (not query(query_statement))
Error("in DbConnection::queryOrDie: \"" + query_statement + "\" failed: " + getLastErrorMessage());
}
DbResultSet DbConnection::getLastResultSet() {
MYSQL_RES * const result_set(::mysql_store_result(&mysql_));
if (result_set == nullptr)
throw std::runtime_error("in DbConnection::getLastResultSet: mysql_store_result() failed! ("
+ getLastErrorMessage() + ")");
return DbResultSet(result_set);
}
std::string DbConnection::escapeString(const std::string &unescaped_string) {
char * const buffer(reinterpret_cast<char * const>(std::malloc(unescaped_string.size() * 2 + 1)));
const size_t escaped_length(::mysql_real_escape_string(&mysql_, buffer, unescaped_string.data(),
unescaped_string.size()));
const std::string escaped_string(buffer, escaped_length);
std::free(buffer);
return escaped_string;
}
void DbConnection::init(const std::string &database_name, const std::string &user, const std::string &passwd,
const std::string &host, const unsigned port)
{
initialised_ = false;
if (::mysql_init(&mysql_) == nullptr)
throw std::runtime_error("in DbConnection::init: mysql_init() failed!");
if (::mysql_real_connect(&mysql_, host.c_str(), user.c_str(), passwd.c_str(), database_name.c_str(), port,
/* unix_socket = */nullptr, /* client_flag = */CLIENT_MULTI_STATEMENTS) == nullptr)
throw std::runtime_error("in DbConnection::init: mysql_real_connect() failed! (" + getLastErrorMessage()
+ ")");
if (::mysql_set_character_set(&mysql_, "utf8") != 0)
throw std::runtime_error("in DbConnection::init: mysql_set_character_set() failed! (" + getLastErrorMessage()
+ ")");
initialised_ = true;
}
<|endoftext|> |
<commit_before>/* -------------------------------------------------------------------------- *
* OpenSim: PSimTool.cpp *
* -------------------------------------------------------------------------- *
* The OpenSim API is a toolkit for musculoskeletal modeling and simulation. *
* See http://opensim.stanford.edu and the NOTICE file for more information. *
* OpenSim is developed at Stanford University and supported by the US *
* National Institutes of Health (U54 GM072970, R24 HD065690) and by DARPA *
* through the Warrior Web program. *
* *
* Copyright (c) 2005-2014 Stanford University and the Authors *
* Author(s): Chris Dembia *
* *
* 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 "PSimTool.h"
#include "PSimDynamicOptimizationSolver.h"
#include "StatesCollector.h"
#include "StateTrajectory.h"
#include <OpenSim/Simulation/Manager/Manager.h>
namespace OpenSim {
PSimTool::PSimTool()
{
constructProperties();
}
PSimTool::PSimTool(const std::string& fileName)
: Object(fileName, false)
{
constructProperties();
updateFromXMLDocument();
if (!get_base_model_file().empty()) {
m_model.reset(new Model(getAbsolutePathname(get_base_model_file())));
}
}
void PSimTool::constructProperties() {
constructProperty_base_model_file("");
constructProperty_solver(PSimDynamicOptimizationSolver());
constructProperty_results_dir("");
constructProperty_initial_time(0);
constructProperty_final_time(1);
constructProperty_visualize(false);
constructProperty_parameters();
constructProperty_goals();
PSimParameterValueSet initial_guess;
constructProperty_initial_guess(initial_guess);
}
unsigned int PSimTool::numOptimizerParameters() const
{
unsigned int sum = 0;
for (unsigned int itp = 0; itp < getProperty_parameters().size(); ++itp) {
const PSimParameter & param = get_parameters(itp);
if (param.get_apply() && param.get_optimize()) {
sum += get_parameters(itp).numScalarParameters();
}
}
return sum;
}
void PSimTool::applyParametersToModel(const PSimParameterValueSet& paramValues,
Model& model) const
{
// Indexes through tool parameters.
for (unsigned int itp = 0; itp < getProperty_parameters().size(); ++itp) {
const PSimParameter & param = get_parameters(itp);
// If we should pay attention to this parameter.
if (param.get_apply()) {
// If the parameter is to be optimized.
if (param.get_optimize()) {
const double value = paramValues.get(param.getName()).get_value();
param.applyToModel(value, model);
}
else {
// Use the default value of the parameter.
// TODO if we decide not to create a new copy of the model,
// we don't need to do this after the first call.
param.applyToModel(param.get_default_value(), model);
}
}
}
}
void PSimTool::applyParametersToInitState(
const PSimParameterValueSet& paramValues,
const Model& model, SimTK::State& initState) const
{
// Indexes through tool parameters.
for (unsigned int itp = 0; itp < getProperty_parameters().size(); ++itp) {
const PSimParameter & param = get_parameters(itp);
// If we should pay attention to this parameter.
if (param.get_apply()) {
// If the parameter is to be optimized.
if (param.get_optimize()) {
const double value = paramValues.get(param.getName()).get_value();
param.applyToInitialState(value, model, initState);
}
else {
// Use the default value of the parameter.
// TODO if we decide not to create a new copy of the model,
// we don't need to do this after the first call.
param.applyToInitialState(param.get_default_value(), model,
initState);
}
}
}
}
void PSimTool::applyParametersToStateCache(
const PSimParameterValueSet& paramValues,
const Model& model, const SimTK::State& s) const
{
// TODO this could be costly?
// Indexes through tool parameters.
for (unsigned int itp = 0; itp < getProperty_parameters().size(); ++itp) {
const PSimParameter & param = get_parameters(itp);
// If we should pay attention to this parameter.
if (param.get_apply()) {
// If the parameter is to be optimized.
if (param.get_optimize()) {
const double value = paramValues.get(param.getName()).get_value();
param.applyToStateCache(value, model, s);
}
else {
// Use the default value of the parameter.
// TODO if we decide not to create a new copy of the model,
// we don't need to do this after the first call.
param.applyToStateCache(param.get_default_value(), model, s);
}
}
}
}
void PSimTool::initialOptimizerParameterValuesAndLimits(
SimTK::Vector& initOptParams,
SimTK::Vector& lowerLimits,
SimTK::Vector& upperLimits) const
{
initOptParams.resize(numOptimizerParameters());
lowerLimits.resize(numOptimizerParameters());
upperLimits.resize(numOptimizerParameters());
// Indexes through optimizer parameters.
unsigned int iop = 0;
// Indexes through tool parameters.
for (unsigned int itp = 0; itp < getProperty_parameters().size(); ++itp) {
const PSimParameter& param = get_parameters(itp);
// If the parameter is to be optimized.
if (param.get_apply() && param.get_optimize()) {
// Ignore values in initial_guess for parameters that are not
// set to be optimized.
double unnormalized;
// The user supplied an initial guess.
if (get_initial_guess().contains(param.getName())) {
const PSimParameterValue& pval =
get_initial_guess().get(param.getName());
unnormalized = pval.get_value();
}
else {
unnormalized = param.get_default_value();
}
// Normalize the parameter, place it in the initial opt. params.
initOptParams[iop] = param.normalized(unnormalized);
// Normalize the lower and upper limits.
lowerLimits[iop] = param.normalized(param.get_lower_limit());
upperLimits[iop] = param.normalized(param.get_upper_limit());
iop++;
}
}
}
PSimParameterValueSet PSimTool::solve() const
{
checkForUnusedInitialGuesses();
// TODO print the updated model?
// TODO print the objective values (at each iteration?)
return get_solver().solve(*this);
}
double PSimTool::simulate(const PSimParameterValueSet& pvalset) const
{
// Initialize model and apply model parameters.
// ============================================
// Create a copy of the base model.
Model model(getBaseModel());
if (get_visualize()) model.setUseVisualizer(true);
applyParametersToModel(pvalset, model);
// Add PSimGoal's to Model as ModelComponents. Do this after applying the
// parameters, as the goals may depend on the effect of parameters.
const auto goals = addGoalsToModel(model);
// Mechanism to record the trajectory of successful states.
// --------------------------------------------------------
StatesCollector* statesCollector = new StatesCollector();
statesCollector->setName("statesCollector");
model.addAnalysis(statesCollector);
// Generate an initial state. Must also be done after applying to model.
SimTK::State& state = model.initSystem();
// Now that the model is finalized for this sim., modify initial state.
// ====================================================================
applyParametersToInitState(pvalset, model, state);
// Simulate.
// =========
SimTK::RungeKuttaMersonIntegrator integrator(model.getSystem());
OpenSim::Manager manager(model, integrator);
manager.setWriteToStorage(false);
manager.setInitialTime(get_initial_time());
manager.setFinalTime(get_final_time());
manager.integrate(state);
// Compute objective function value with the goals.
// ================================================
const StateTrajectory& states = statesCollector->getStateTrajectory();
return evaluateGoals(goals, pvalset, states);
}
PSimParameterValueSet PSimTool::createParameterValueSet(
const SimTK::Vector &optParamValues) const
{
// TODO will have to change if the solver adds its own parameters.
PSimParameterValueSet pvalset;
// Indexes through optimizer parameters.
unsigned int iop = 0;
// Indexes through tool parameters.
for (unsigned int itp = 0; itp < getProperty_parameters().size(); ++itp) {
const PSimParameter& param = get_parameters(itp);
// If the parameter was optimized.
if (param.get_apply() && param.get_optimize()) {
PSimParameterValue* pval = new PSimParameterValue();
pval->setName(param.getName());
// TODO get subvector.
pval->set_value(param.unnormalized(optParamValues[iop]));
pvalset.adoptAndAppend(pval);
// TODO increase index by #scalar parameters.
iop++;
}
}
return pvalset;
}
void PSimTool::checkForUnusedInitialGuesses() const {
for (unsigned int ig = 0; ig < get_initial_guess().getSize(); ++ig) {
const PSimParameterValue& initialGuess = get_initial_guess().get(ig);
bool unused = true;
for (unsigned int itp = 0; itp < getProperty_parameters().size(); ++itp)
{
const PSimParameter& param = get_parameters(itp);
if (initialGuess.getName() == param.getName()) {
unused = false;
break;
}
}
if (unused) {
// TODO make this into a warning. TODO test this.
throw OpenSim::Exception("Initial guess '" + initialGuess.getName()
+ "' does not match any parameter.");
}
}
}
std::vector<const PSimGoal*> PSimTool::addGoalsToModel(Model& model) const
{
std::vector<const PSimGoal*> goals;
for (unsigned int ig = 0; ig < getProperty_goals().size(); ++ig) {
const PSimGoal& goal = get_goals(ig);
if (goal.get_enabled()) {
PSimGoal* clone = goal.clone();
// The model now owns this clone.
model.addModelComponent(clone);
// Append to the return vector.
goals.push_back(clone);
}
}
return goals;
}
SimTK::Real PSimTool::evaluateGoals(
const std::vector<const PSimGoal*>& objectives,
const PSimParameterValueSet& pvalset,
const StateTrajectory& states)
{
SimTK::Real f = 0;
for (auto obj : objectives) {
if (obj->get_enabled()) {
// TODO move enabled check to PSimGoal.
f += obj->get_weight() * obj->evaluate(pvalset, states);
}
}
return f;
}
} // namespace OpenSim
<commit_msg>Improve initial guess check exc.<commit_after>/* -------------------------------------------------------------------------- *
* OpenSim: PSimTool.cpp *
* -------------------------------------------------------------------------- *
* The OpenSim API is a toolkit for musculoskeletal modeling and simulation. *
* See http://opensim.stanford.edu and the NOTICE file for more information. *
* OpenSim is developed at Stanford University and supported by the US *
* National Institutes of Health (U54 GM072970, R24 HD065690) and by DARPA *
* through the Warrior Web program. *
* *
* Copyright (c) 2005-2014 Stanford University and the Authors *
* Author(s): Chris Dembia *
* *
* 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 "PSimTool.h"
#include "PSimDynamicOptimizationSolver.h"
#include "StatesCollector.h"
#include "StateTrajectory.h"
#include <OpenSim/Simulation/Manager/Manager.h>
namespace OpenSim {
PSimTool::PSimTool()
{
constructProperties();
}
PSimTool::PSimTool(const std::string& fileName)
: Object(fileName, false)
{
constructProperties();
updateFromXMLDocument();
if (!get_base_model_file().empty()) {
m_model.reset(new Model(getAbsolutePathname(get_base_model_file())));
}
}
void PSimTool::constructProperties() {
constructProperty_base_model_file("");
constructProperty_solver(PSimDynamicOptimizationSolver());
constructProperty_results_dir("");
constructProperty_initial_time(0);
constructProperty_final_time(1);
constructProperty_visualize(false);
constructProperty_parameters();
constructProperty_goals();
PSimParameterValueSet initial_guess;
constructProperty_initial_guess(initial_guess);
}
unsigned int PSimTool::numOptimizerParameters() const
{
unsigned int sum = 0;
for (unsigned int itp = 0; itp < getProperty_parameters().size(); ++itp) {
const PSimParameter & param = get_parameters(itp);
if (param.get_apply() && param.get_optimize()) {
sum += get_parameters(itp).numScalarParameters();
}
}
return sum;
}
void PSimTool::applyParametersToModel(const PSimParameterValueSet& paramValues,
Model& model) const
{
// Indexes through tool parameters.
for (unsigned int itp = 0; itp < getProperty_parameters().size(); ++itp) {
const PSimParameter & param = get_parameters(itp);
// If we should pay attention to this parameter.
if (param.get_apply()) {
// If the parameter is to be optimized.
if (param.get_optimize()) {
const double value = paramValues.get(param.getName()).get_value();
param.applyToModel(value, model);
}
else {
// Use the default value of the parameter.
// TODO if we decide not to create a new copy of the model,
// we don't need to do this after the first call.
param.applyToModel(param.get_default_value(), model);
}
}
}
}
void PSimTool::applyParametersToInitState(
const PSimParameterValueSet& paramValues,
const Model& model, SimTK::State& initState) const
{
// Indexes through tool parameters.
for (unsigned int itp = 0; itp < getProperty_parameters().size(); ++itp) {
const PSimParameter & param = get_parameters(itp);
// If we should pay attention to this parameter.
if (param.get_apply()) {
// If the parameter is to be optimized.
if (param.get_optimize()) {
const double value = paramValues.get(param.getName()).get_value();
param.applyToInitialState(value, model, initState);
}
else {
// Use the default value of the parameter.
// TODO if we decide not to create a new copy of the model,
// we don't need to do this after the first call.
param.applyToInitialState(param.get_default_value(), model,
initState);
}
}
}
}
void PSimTool::applyParametersToStateCache(
const PSimParameterValueSet& paramValues,
const Model& model, const SimTK::State& s) const
{
// TODO this could be costly?
// Indexes through tool parameters.
for (unsigned int itp = 0; itp < getProperty_parameters().size(); ++itp) {
const PSimParameter & param = get_parameters(itp);
// If we should pay attention to this parameter.
if (param.get_apply()) {
// If the parameter is to be optimized.
if (param.get_optimize()) {
const double value = paramValues.get(param.getName()).get_value();
param.applyToStateCache(value, model, s);
}
else {
// Use the default value of the parameter.
// TODO if we decide not to create a new copy of the model,
// we don't need to do this after the first call.
param.applyToStateCache(param.get_default_value(), model, s);
}
}
}
}
void PSimTool::initialOptimizerParameterValuesAndLimits(
SimTK::Vector& initOptParams,
SimTK::Vector& lowerLimits,
SimTK::Vector& upperLimits) const
{
initOptParams.resize(numOptimizerParameters());
lowerLimits.resize(numOptimizerParameters());
upperLimits.resize(numOptimizerParameters());
// Indexes through optimizer parameters.
unsigned int iop = 0;
// Indexes through tool parameters.
for (unsigned int itp = 0; itp < getProperty_parameters().size(); ++itp) {
const PSimParameter& param = get_parameters(itp);
// If the parameter is to be optimized.
if (param.get_apply() && param.get_optimize()) {
// Ignore values in initial_guess for parameters that are not
// set to be optimized.
double unnormalized;
// The user supplied an initial guess.
if (get_initial_guess().contains(param.getName())) {
const PSimParameterValue& pval =
get_initial_guess().get(param.getName());
unnormalized = pval.get_value();
}
else {
unnormalized = param.get_default_value();
}
// Normalize the parameter, place it in the initial opt. params.
initOptParams[iop] = param.normalized(unnormalized);
// Normalize the lower and upper limits.
lowerLimits[iop] = param.normalized(param.get_lower_limit());
upperLimits[iop] = param.normalized(param.get_upper_limit());
iop++;
}
}
}
PSimParameterValueSet PSimTool::solve() const
{
checkForUnusedInitialGuesses();
// TODO print the updated model?
// TODO print the objective values (at each iteration?)
return get_solver().solve(*this);
}
double PSimTool::simulate(const PSimParameterValueSet& pvalset) const
{
// Initialize model and apply model parameters.
// ============================================
// Create a copy of the base model.
Model model(getBaseModel());
if (get_visualize()) model.setUseVisualizer(true);
applyParametersToModel(pvalset, model);
// Add PSimGoal's to Model as ModelComponents. Do this after applying the
// parameters, as the goals may depend on the effect of parameters.
const auto goals = addGoalsToModel(model);
// Mechanism to record the trajectory of successful states.
// --------------------------------------------------------
StatesCollector* statesCollector = new StatesCollector();
statesCollector->setName("statesCollector");
model.addAnalysis(statesCollector);
// Generate an initial state. Must also be done after applying to model.
SimTK::State& state = model.initSystem();
// Now that the model is finalized for this sim., modify initial state.
// ====================================================================
applyParametersToInitState(pvalset, model, state);
// Simulate.
// =========
SimTK::RungeKuttaMersonIntegrator integrator(model.getSystem());
OpenSim::Manager manager(model, integrator);
manager.setWriteToStorage(false);
manager.setInitialTime(get_initial_time());
manager.setFinalTime(get_final_time());
manager.integrate(state);
// Compute objective function value with the goals.
// ================================================
const StateTrajectory& states = statesCollector->getStateTrajectory();
return evaluateGoals(goals, pvalset, states);
}
PSimParameterValueSet PSimTool::createParameterValueSet(
const SimTK::Vector &optParamValues) const
{
// TODO will have to change if the solver adds its own parameters.
PSimParameterValueSet pvalset;
// Indexes through optimizer parameters.
unsigned int iop = 0;
// Indexes through tool parameters.
for (unsigned int itp = 0; itp < getProperty_parameters().size(); ++itp) {
const PSimParameter& param = get_parameters(itp);
// If the parameter was optimized.
if (param.get_apply() && param.get_optimize()) {
PSimParameterValue* pval = new PSimParameterValue();
pval->setName(param.getName());
// TODO get subvector.
pval->set_value(param.unnormalized(optParamValues[iop]));
pvalset.adoptAndAppend(pval);
// TODO increase index by #scalar parameters.
iop++;
}
}
return pvalset;
}
void PSimTool::checkForUnusedInitialGuesses() const {
for (unsigned int ig = 0; ig < get_initial_guess().getSize(); ++ig) {
const PSimParameterValue& initialGuess = get_initial_guess().get(ig);
bool unused = true;
for (unsigned int itp = 0; itp < getProperty_parameters().size(); ++itp)
{
const PSimParameter& param = get_parameters(itp);
if (initialGuess.getName() == param.getName()) {
unused = false;
break;
}
}
if (unused) {
// TODO make this into a warning. TODO test this.
throw OpenSim::Exception("Initial guess '" + initialGuess.getName()
+ "' does not match any parameter.", __FILE__, __LINE__);
}
}
}
std::vector<const PSimGoal*> PSimTool::addGoalsToModel(Model& model) const
{
std::vector<const PSimGoal*> goals;
for (unsigned int ig = 0; ig < getProperty_goals().size(); ++ig) {
const PSimGoal& goal = get_goals(ig);
if (goal.get_enabled()) {
PSimGoal* clone = goal.clone();
// The model now owns this clone.
model.addModelComponent(clone);
// Append to the return vector.
goals.push_back(clone);
}
}
return goals;
}
SimTK::Real PSimTool::evaluateGoals(
const std::vector<const PSimGoal*>& objectives,
const PSimParameterValueSet& pvalset,
const StateTrajectory& states)
{
SimTK::Real f = 0;
for (auto obj : objectives) {
if (obj->get_enabled()) {
// TODO move enabled check to PSimGoal.
f += obj->get_weight() * obj->evaluate(pvalset, states);
}
}
return f;
}
} // namespace OpenSim
<|endoftext|> |
<commit_before>#ifndef __STAN__META__TRAITS_HPP__
#define __STAN__META__TRAITS_HPP__
#include <vector>
#include <boost/type_traits.hpp>
#include <boost/math/tools/promotion.hpp>
#include <stan/math/matrix.hpp>
namespace stan {
/**
* Metaprogramming struct to detect whether a given type is constant
* in the mathematical sense (not the C++ <code>const</code>
* sense). If the parameter type is constant, <code>value</code>
* will be equal to <code>true</code>.
*
* The baseline implementation in this abstract base class is to
* classify a type <code>T</code> as constant if it can be converted
* (i.e., assigned) to a <code>double</code>. This baseline should
* be overridden for any type that should be treated as a variable.
*
* @tparam T Type being tested.
*/
template <typename T>
struct is_constant {
/**
* A boolean constant with equal to <code>true</code> if the
* type parameter <code>T</code> is a mathematical constant.
*/
enum { value = boost::is_convertible<T,double>::value };
};
/**
* Metaprogram to determine if a type has a base scalar
* type that can be assigned to type double.
*/
template <typename T>
struct is_constant_struct {
enum { value = is_constant<T>::value };
};
template <typename T>
struct is_constant_struct<std::vector<T> > {
enum { value = is_constant_struct<T>::value };
};
template <typename T, int R, int C>
struct is_constant_struct<Eigen::Matrix<T,R,C> > {
enum { value = is_constant_struct<T>::value };
};
// FIXME: use boost::type_traits::remove_all_extents to extend to array/ptr types
template <typename T>
struct is_vector {
enum { value = 0 };
typedef T type;
};
template <typename T>
struct is_vector<const T> {
enum { value = is_vector<T>::value };
typedef T type;
};
template <typename T>
struct is_vector<std::vector<T> > {
enum { value = 1 };
typedef T type;
};
template <typename T>
struct is_vector<Eigen::Matrix<T,Eigen::Dynamic,1> > {
enum { value = 1 };
typedef T type;
};
template <typename T>
struct is_vector<Eigen::Matrix<T,1,Eigen::Dynamic> > {
enum { value = 1 };
typedef T type;
};
namespace {
template <bool is_vec, typename T>
struct scalar_type_helper {
typedef T type;
};
template <typename T>
struct scalar_type_helper<true, T> {
typedef typename scalar_type_helper<is_vector<typename T::value_type>::value, typename T::value_type>::type type;
};
}
/**
* Metaprogram structure to determine the base scalar type
* of a template argument.
*
* <p>This base class should be specialized for structured types.
*
* @tparam T Type of object.
*/
template <typename T>
struct scalar_type {
typedef typename scalar_type_helper<is_vector<T>::value, T>::type type;
};
// length() should only be applied to primitive or std vector or Eigen vector
template <typename T>
size_t length(const T& x) {
return 1U;
}
template <typename T>
size_t length(const std::vector<T>& x) {
return x.size();
}
template <typename T>
size_t length(const Eigen::Matrix<T,Eigen::Dynamic,1>& v) {
return v.size();
}
template <typename T>
size_t length(const Eigen::Matrix<T,1,Eigen::Dynamic>& rv) {
return rv.size();
}
template<typename T, bool is_vec>
struct size_of_helper {
static size_t size_of(const T& x) {
return 1U;
}
};
template<typename T>
struct size_of_helper<T, true> {
static size_t size_of(const T& x) {
return x.size();
}
};
template <typename T>
size_t size_of(const T& x) {
return size_of_helper<T, is_vector<T>::value>::size_of(x);
}
template <typename T1, typename T2>
size_t max_size(const T1& x1, const T2& x2) {
size_t result = length(x1);
result = result > length(x2) ? result : length(x2);
return result;
}
template <typename T1, typename T2, typename T3>
size_t max_size(const T1& x1, const T2& x2, const T3& x3) {
size_t result = length(x1);
result = result > length(x2) ? result : length(x2);
result = result > length(x3) ? result : length(x3);
return result;
}
template <typename T1, typename T2, typename T3, typename T4>
size_t max_size(const T1& x1, const T2& x2, const T3& x3, const T4& x4) {
size_t result = length(x1);
result = result > length(x2) ? result : length(x2);
result = result > length(x3) ? result : length(x3);
result = result > length(x4) ? result : length(x4);
return result;
}
// ****************** additions for new VV *************************
template <typename T>
struct scalar_type<Eigen::Matrix<T,Eigen::Dynamic,Eigen::Dynamic> > {
typedef typename scalar_type<T>::type type;
};
template <typename T>
struct scalar_type<T*> {
typedef typename scalar_type<T>::type type;
};
// handles scalar, eigen vec, eigen row vec, std vec
template <typename T>
struct is_vector_like {
enum { value = stan::is_vector<T>::value };
};
template <typename T>
struct is_vector_like<T*> {
enum { value = true };
};
// handles const
template <typename T>
struct is_vector_like<const T> {
enum { value = stan::is_vector_like<T>::value };
};
// handles eigen matrix
template <typename T>
struct is_vector_like<Eigen::Matrix<T,Eigen::Dynamic,Eigen::Dynamic> > {
enum { value = true };
};
template <typename T,
bool is_array = stan::is_vector_like<T>::value>
class VectorView {
public:
typedef typename scalar_type<T>::type scalar_t;
VectorView(scalar_t& c) : x_(&c) { }
VectorView(std::vector<scalar_t>& v) : x_(&v[0]) { }
template <int R, int C>
VectorView(Eigen::Matrix<scalar_t,R,C>& m) : x_(&m(0)) { }
VectorView(scalar_t* x) : x_(x) { }
scalar_t& operator[](int i) {
if (is_array) return x_[i];
else return x_[0];
}
private:
scalar_t* x_;
};
template <typename T, bool is_array>
class VectorView<const T, is_array> {
public:
typedef typename scalar_type<T>::type scalar_t;
VectorView(const scalar_t& c) : x_(&c) { }
VectorView(const scalar_t* x) : x_(x) { }
VectorView(const std::vector<scalar_t>& v) : x_(&v[0]) { }
template <int R, int C>
VectorView(const Eigen::Matrix<scalar_t,R,C>& m) : x_(&m(0)) { }
const scalar_t operator[](int i) const {
if (is_array) return x_[i];
else return x_[0];
}
private:
const scalar_t* x_;
};
// simplify to hold value in common case where it's more efficient
template <>
class VectorView<const double, false> {
public:
VectorView(double x) : x_(x) { }
double operator[](int /* i */) const {
return x_;
}
private:
const double x_;
};
template<bool used, bool is_vec>
class DoubleVectorView {
public:
DoubleVectorView(size_t /* n */) { }
double& operator[](size_t /* i */) {
throw std::runtime_error("used is false. this should never be called");
}
};
template<typename T>
class DoubleVectorView<true, false> {
private:
double x_;
public:
DoubleVectorView(size_t /* n */) : x_(0.0) { }
double& operator[](size_t /* i */) {
return x_;
}
};
template<typename T>
class DoubleVectorView<true, true> {
private:
std::vector<double> x_;
public:
DoubleVectorView(size_t n) : x_(n) { }
double& operator[](size_t i) {
return x_[i];
}
};
/**
* Metaprogram to calculate the base scalar return type resulting
* from promoting all the scalar types of the template parameters.
*/
template <typename T1,
typename T2 = double,
typename T3 = double,
typename T4 = double,
typename T5 = double,
typename T6 = double>
struct return_type {
typedef typename
boost::math::tools::promote_args<typename scalar_type<T1>::type,
typename scalar_type<T2>::type,
typename scalar_type<T3>::type,
typename scalar_type<T4>::type,
typename scalar_type<T5>::type,
typename scalar_type<T6>::type>::type
type;
};
}
#endif
<commit_msg>refactored traits by removing second template parameter<commit_after>#ifndef __STAN__META__TRAITS_HPP__
#define __STAN__META__TRAITS_HPP__
#include <vector>
#include <boost/type_traits.hpp>
#include <boost/math/tools/promotion.hpp>
#include <stan/math/matrix.hpp>
namespace stan {
/**
* Metaprogramming struct to detect whether a given type is constant
* in the mathematical sense (not the C++ <code>const</code>
* sense). If the parameter type is constant, <code>value</code>
* will be equal to <code>true</code>.
*
* The baseline implementation in this abstract base class is to
* classify a type <code>T</code> as constant if it can be converted
* (i.e., assigned) to a <code>double</code>. This baseline should
* be overridden for any type that should be treated as a variable.
*
* @tparam T Type being tested.
*/
template <typename T>
struct is_constant {
/**
* A boolean constant with equal to <code>true</code> if the
* type parameter <code>T</code> is a mathematical constant.
*/
enum { value = boost::is_convertible<T,double>::value };
};
/**
* Metaprogram to determine if a type has a base scalar
* type that can be assigned to type double.
*/
template <typename T>
struct is_constant_struct {
enum { value = is_constant<T>::value };
};
template <typename T>
struct is_constant_struct<std::vector<T> > {
enum { value = is_constant_struct<T>::value };
};
template <typename T, int R, int C>
struct is_constant_struct<Eigen::Matrix<T,R,C> > {
enum { value = is_constant_struct<T>::value };
};
// FIXME: use boost::type_traits::remove_all_extents to extend to array/ptr types
template <typename T>
struct is_vector {
enum { value = 0 };
typedef T type;
};
template <typename T>
struct is_vector<const T> {
enum { value = is_vector<T>::value };
typedef T type;
};
template <typename T>
struct is_vector<std::vector<T> > {
enum { value = 1 };
typedef T type;
};
template <typename T>
struct is_vector<Eigen::Matrix<T,Eigen::Dynamic,1> > {
enum { value = 1 };
typedef T type;
};
template <typename T>
struct is_vector<Eigen::Matrix<T,1,Eigen::Dynamic> > {
enum { value = 1 };
typedef T type;
};
namespace {
template <bool is_vec, typename T>
struct scalar_type_helper {
typedef T type;
};
template <typename T>
struct scalar_type_helper<true, T> {
typedef typename scalar_type_helper<is_vector<typename T::value_type>::value, typename T::value_type>::type type;
};
}
/**
* Metaprogram structure to determine the base scalar type
* of a template argument.
*
* <p>This base class should be specialized for structured types.
*
* @tparam T Type of object.
*/
template <typename T>
struct scalar_type {
typedef typename scalar_type_helper<is_vector<T>::value, T>::type type;
};
// length() should only be applied to primitive or std vector or Eigen vector
template <typename T>
size_t length(const T& x) {
return 1U;
}
template <typename T>
size_t length(const std::vector<T>& x) {
return x.size();
}
template <typename T>
size_t length(const Eigen::Matrix<T,Eigen::Dynamic,1>& v) {
return v.size();
}
template <typename T>
size_t length(const Eigen::Matrix<T,1,Eigen::Dynamic>& rv) {
return rv.size();
}
template<typename T, bool is_vec>
struct size_of_helper {
static size_t size_of(const T& x) {
return 1U;
}
};
template<typename T>
struct size_of_helper<T, true> {
static size_t size_of(const T& x) {
return x.size();
}
};
template <typename T>
size_t size_of(const T& x) {
return size_of_helper<T, is_vector<T>::value>::size_of(x);
}
template <typename T1, typename T2>
size_t max_size(const T1& x1, const T2& x2) {
size_t result = length(x1);
result = result > length(x2) ? result : length(x2);
return result;
}
template <typename T1, typename T2, typename T3>
size_t max_size(const T1& x1, const T2& x2, const T3& x3) {
size_t result = length(x1);
result = result > length(x2) ? result : length(x2);
result = result > length(x3) ? result : length(x3);
return result;
}
template <typename T1, typename T2, typename T3, typename T4>
size_t max_size(const T1& x1, const T2& x2, const T3& x3, const T4& x4) {
size_t result = length(x1);
result = result > length(x2) ? result : length(x2);
result = result > length(x3) ? result : length(x3);
result = result > length(x4) ? result : length(x4);
return result;
}
// ****************** additions for new VV *************************
template <typename T>
struct scalar_type<Eigen::Matrix<T,Eigen::Dynamic,Eigen::Dynamic> > {
typedef typename scalar_type<T>::type type;
};
template <typename T>
struct scalar_type<T*> {
typedef typename scalar_type<T>::type type;
};
// handles scalar, eigen vec, eigen row vec, std vec
template <typename T>
struct is_vector_like {
enum { value = stan::is_vector<T>::value };
};
template <typename T>
struct is_vector_like<T*> {
enum { value = true };
};
// handles const
template <typename T>
struct is_vector_like<const T> {
enum { value = stan::is_vector_like<T>::value };
};
// handles eigen matrix
template <typename T>
struct is_vector_like<Eigen::Matrix<T,Eigen::Dynamic,Eigen::Dynamic> > {
enum { value = true };
};
template <typename T,
bool is_array = stan::is_vector_like<T>::value>
class VectorView {
public:
typedef typename scalar_type<T>::type scalar_t;
VectorView(scalar_t& c) : x_(&c) { }
VectorView(std::vector<scalar_t>& v) : x_(&v[0]) { }
template <int R, int C>
VectorView(Eigen::Matrix<scalar_t,R,C>& m) : x_(&m(0)) { }
VectorView(scalar_t* x) : x_(x) { }
scalar_t& operator[](int i) {
if (is_array) return x_[i];
else return x_[0];
}
private:
scalar_t* x_;
};
template <typename T, bool is_array>
class VectorView<const T, is_array> {
public:
typedef typename scalar_type<T>::type scalar_t;
VectorView(const scalar_t& c) : x_(&c) { }
VectorView(const scalar_t* x) : x_(x) { }
VectorView(const std::vector<scalar_t>& v) : x_(&v[0]) { }
template <int R, int C>
VectorView(const Eigen::Matrix<scalar_t,R,C>& m) : x_(&m(0)) { }
const scalar_t operator[](int i) const {
if (is_array) return x_[i];
else return x_[0];
}
private:
const scalar_t* x_;
};
// simplify to hold value in common case where it's more efficient
template <>
class VectorView<const double, false> {
public:
VectorView(double x) : x_(x) { }
double operator[](int /* i */) const {
return x_;
}
private:
const double x_;
};
template<bool used, bool is_vec>
class DoubleVectorView {
public:
DoubleVectorView(size_t /* n */) { }
double& operator[](size_t /* i */) {
throw std::runtime_error("used is false. this should never be called");
}
};
template<>
class DoubleVectorView<true, false> {
private:
double x_;
public:
DoubleVectorView(size_t /* n */) : x_(0.0) { }
double& operator[](size_t /* i */) {
return x_;
}
};
template<>
class DoubleVectorView<true, true> {
private:
std::vector<double> x_;
public:
DoubleVectorView(size_t n) : x_(n) { }
double& operator[](size_t i) {
return x_[i];
}
};
/**
* Metaprogram to calculate the base scalar return type resulting
* from promoting all the scalar types of the template parameters.
*/
template <typename T1,
typename T2 = double,
typename T3 = double,
typename T4 = double,
typename T5 = double,
typename T6 = double>
struct return_type {
typedef typename
boost::math::tools::promote_args<typename scalar_type<T1>::type,
typename scalar_type<T2>::type,
typename scalar_type<T3>::type,
typename scalar_type<T4>::type,
typename scalar_type<T5>::type,
typename scalar_type<T6>::type>::type
type;
};
}
#endif
<|endoftext|> |
<commit_before>/*************************************************************************
*
* $RCSfile: res.cxx,v $
*
* $Revision: 1.3 $
*
* last change: $Author: hr $ $Date: 2004-02-04 14:32:55 $
*
* 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 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
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#if OSL_DEBUG_LEVEL == 0
# ifndef NDEBUG
# define NDEBUG
# endif
#endif
#include <assert.h>
#include <interface.hxx>
#include <cstdio>
#include <hash_map>
#include <string>
using namespace std;
static hash_map< string, string >* pStringResources = NULL;
static string getResFileName( const char* progname )
{
string aRet = progname;
size_t pos = aRet.rfind( '/' );
// FIXME: search PATH if necessary
assert( pos != string::npos );
aRet.erase( pos );
aRet.append( "/resource/crash_dump.res" );
return aRet;
}
static void filterString( string& rString )
{
static const char* pProductName = getenv( "PRODUCTNAME" );
static int nProductLen = pProductName ? strlen( pProductName ) : 0;
static const char* pProductVersion = getenv( "PRODUCTVERSION" );
static int nVersionLen = pProductVersion ? strlen( pProductVersion ) : 0;
// fill in eventually escaped characters
string::size_type pos = 0;
while( (pos = rString.find( '\\' ) ) != string::npos )
{
char cRep = 0;
switch( rString[pos+1] )
{
case 't': cRep = '\t';break;
case 'n': cRep = '\n';break;
case 'r': cRep = '\r';break;
case 'f': cRep = '\f';break;
default: cRep = rString[pos+1];
}
if( cRep )
rString.replace( pos, 2, &cRep, 1 );
}
while( (pos = rString.find( '~' ) ) != string::npos )
{
// replace mnemonic marker
rString.replace( pos, 1, "_", 1 );
}
while( (pos = rString.find( "%PRODUCTNAME%" ) ) != string::npos )
{
rString.replace( pos, 13, pProductName ? pProductName : "OpenOffice" );
}
while( (pos = rString.find( "%PRODUCTVERSION%" ) ) != string::npos )
{
rString.replace( pos, 16, pProductVersion ? pProductVersion : "" );
}
// remove whitespace at end
pos = rString.find_last_not_of( "\r\n\t\f " );
if( pos != string::npos )
rString.erase( pos+1 );
}
void StringResource::init( int argc, char** argv )
{
pStringResources = new hash_map< string, string >();
string aResFile = getResFileName( argv[0] );
FILE* fp = fopen( aResFile.c_str(), "r" );
if( fp )
{
char buf[4096];
string aKey;
string aValue;
while( ! feof( fp ) )
{
if( ! fgets( buf, sizeof(buf), fp ) )
break;
char* pEq = strchr( buf, '=' );
if( ! pEq || *(pEq+1) == 0 ) // invalid line
continue;
aKey = string(buf, pEq-buf);
aValue = pEq+1;
while( (aValue.empty() || aValue[ aValue.size()-1 ] != '\n') && ! feof( fp ) )
{
if( fgets( buf, sizeof( buf ), fp ) )
aValue.append( buf );
}
filterString( aValue );
(*pStringResources)[aKey] = aValue;
}
fclose( fp );
}
}
const char* StringResource::get( const char* pKey )
{
hash_map< string, string >::const_iterator it = pStringResources->find( pKey );
return (it == pStringResources->end()) ? "" : it->second.c_str();
}
<commit_msg>INTEGRATION: CWS ooo19126 (1.3.106); FILE MERGED 2005/09/05 14:09:23 rt 1.3.106.1: #i54170# Change license header: remove SISSL<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: res.cxx,v $
*
* $Revision: 1.4 $
*
* last change: $Author: rt $ $Date: 2005-09-08 09:42:57 $
*
* 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
*
************************************************************************/
#if OSL_DEBUG_LEVEL == 0
# ifndef NDEBUG
# define NDEBUG
# endif
#endif
#include <assert.h>
#include <interface.hxx>
#include <cstdio>
#include <hash_map>
#include <string>
using namespace std;
static hash_map< string, string >* pStringResources = NULL;
static string getResFileName( const char* progname )
{
string aRet = progname;
size_t pos = aRet.rfind( '/' );
// FIXME: search PATH if necessary
assert( pos != string::npos );
aRet.erase( pos );
aRet.append( "/resource/crash_dump.res" );
return aRet;
}
static void filterString( string& rString )
{
static const char* pProductName = getenv( "PRODUCTNAME" );
static int nProductLen = pProductName ? strlen( pProductName ) : 0;
static const char* pProductVersion = getenv( "PRODUCTVERSION" );
static int nVersionLen = pProductVersion ? strlen( pProductVersion ) : 0;
// fill in eventually escaped characters
string::size_type pos = 0;
while( (pos = rString.find( '\\' ) ) != string::npos )
{
char cRep = 0;
switch( rString[pos+1] )
{
case 't': cRep = '\t';break;
case 'n': cRep = '\n';break;
case 'r': cRep = '\r';break;
case 'f': cRep = '\f';break;
default: cRep = rString[pos+1];
}
if( cRep )
rString.replace( pos, 2, &cRep, 1 );
}
while( (pos = rString.find( '~' ) ) != string::npos )
{
// replace mnemonic marker
rString.replace( pos, 1, "_", 1 );
}
while( (pos = rString.find( "%PRODUCTNAME%" ) ) != string::npos )
{
rString.replace( pos, 13, pProductName ? pProductName : "OpenOffice" );
}
while( (pos = rString.find( "%PRODUCTVERSION%" ) ) != string::npos )
{
rString.replace( pos, 16, pProductVersion ? pProductVersion : "" );
}
// remove whitespace at end
pos = rString.find_last_not_of( "\r\n\t\f " );
if( pos != string::npos )
rString.erase( pos+1 );
}
void StringResource::init( int argc, char** argv )
{
pStringResources = new hash_map< string, string >();
string aResFile = getResFileName( argv[0] );
FILE* fp = fopen( aResFile.c_str(), "r" );
if( fp )
{
char buf[4096];
string aKey;
string aValue;
while( ! feof( fp ) )
{
if( ! fgets( buf, sizeof(buf), fp ) )
break;
char* pEq = strchr( buf, '=' );
if( ! pEq || *(pEq+1) == 0 ) // invalid line
continue;
aKey = string(buf, pEq-buf);
aValue = pEq+1;
while( (aValue.empty() || aValue[ aValue.size()-1 ] != '\n') && ! feof( fp ) )
{
if( fgets( buf, sizeof( buf ), fp ) )
aValue.append( buf );
}
filterString( aValue );
(*pStringResources)[aKey] = aValue;
}
fclose( fp );
}
}
const char* StringResource::get( const char* pKey )
{
hash_map< string, string >::const_iterator it = pStringResources->find( pKey );
return (it == pStringResources->end()) ? "" : it->second.c_str();
}
<|endoftext|> |
<commit_before>//example skeleton code
//modified from http://learnopengl.com/
#include "GL/glew.h" // include GL Extension Wrangler
#include "GLFW/glfw3.h" // include GLFW helper library
#include <stdio.h>
#include <iostream>
#include <string>
#include <fstream>
#include "glm/glm.hpp"
#include "glm/gtc/matrix_transform.hpp"
#include "glm/gtc/type_ptr.hpp"
#include "objloader.hpp" //include the object loader
using namespace std;
// Window dimensions
const GLuint WIDTH = 800, HEIGHT = 600;
glm::vec3 camera_position;
glm::vec3 triangle_scale;
glm::mat4 projection_matrix;
// Constant vectors
const glm::vec3 center(0.0f, 0.0f, 0.0f);
const glm::vec3 up(0.0f, 1.0f, 0.0f);
const glm::vec3 eye(2.0f, 2.0f, 3.0f);
// rotation globals
static GLfloat view_rotx = 20.f, view_roty = 30.f, view_rotz = 0.f;
// Is called whenever a key is pressed/released via GLFW
void key_callback(GLFWwindow* window, int key, int scancode, int action, int mode)
{
std::cout << key << std::endl;
if (action != GLFW_PRESS) return;
switch (key) {
case GLFW_KEY_Z:
if (mode & GLFW_MOD_SHIFT)
view_rotz -= 5.0;
else
view_rotz += 5.0;
break;
case GLFW_KEY_ESCAPE:
glfwSetWindowShouldClose(window, GLFW_TRUE);
break;
case GLFW_KEY_UP:
view_rotx += 5.0;
break;
case GLFW_KEY_DOWN:
view_rotx -= 5.0;
break;
case GLFW_KEY_LEFT:
view_roty += 5.0;
break;
case GLFW_KEY_RIGHT:
view_roty -= 5.0;
break;
default:
return;
};
}
// The MAIN function, from here we start the application and run the game loop
int main()
{
std::cout << "Starting GLFW context, OpenGL 3.3" << std::endl;
// Init GLFW
glfwInit();
// Set all the required options for GLFW
glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);
glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
// Create a GLFWwindow object that we can use for GLFW's functions
GLFWwindow* window = glfwCreateWindow(WIDTH, HEIGHT, "Pacman by Christopher McArthur", nullptr, nullptr);
if (window == nullptr)
{
std::cout << "Failed to create GLFW window" << std::endl;
glfwTerminate();
return -1;
}
glfwMakeContextCurrent(window);
// Set the required callback functions
glfwSetKeyCallback(window, key_callback);
// Set this to true so GLEW knows to use a modern approach to retrieving function pointers and extensions
glewExperimental = GL_TRUE;
// Initialize GLEW to setup the OpenGL Function pointers
if (glewInit() != GLEW_OK)
{
std::cout << "Failed to initialize GLEW" << std::endl;
return -1;
}
// Define the viewport dimensions
int width, height;
glfwGetFramebufferSize(window, &width, &height);
glViewport(0, 0, width, height);
projection_matrix = glm::perspective(45.0f, (GLfloat)width / (GLfloat)height, 0.0f, 100.0f);
// Build and compile our shader program
// Vertex shader
// Read the Vertex Shader code from the file
string vertex_shader_path = "vertex.shader";
string VertexShaderCode;
std::ifstream VertexShaderStream(vertex_shader_path, ios::in);
if (VertexShaderStream.is_open()) {
string Line = "";
while (getline(VertexShaderStream, Line))
VertexShaderCode += "\n" + Line;
VertexShaderStream.close();
}
else {
printf("Impossible to open %s. Are you in the right directory ?\n", vertex_shader_path.c_str());
getchar();
exit(-1);
}
// Read the Fragment Shader code from the file
string fragment_shader_path = "fragment.shader";
std::string FragmentShaderCode;
std::ifstream FragmentShaderStream(fragment_shader_path, std::ios::in);
if (FragmentShaderStream.is_open()) {
std::string Line = "";
while (getline(FragmentShaderStream, Line))
FragmentShaderCode += "\n" + Line;
FragmentShaderStream.close();
}
else {
printf("Impossible to open %s. Are you in the right directory?\n", fragment_shader_path.c_str());
getchar();
exit(-1);
}
GLuint vertexShader = glCreateShader(GL_VERTEX_SHADER);
char const * VertexSourcePointer = VertexShaderCode.c_str();
glShaderSource(vertexShader, 1, &VertexSourcePointer, NULL);
glCompileShader(vertexShader);
// Check for compile time errors
GLint success;
GLchar infoLog[512];
glGetShaderiv(vertexShader, GL_COMPILE_STATUS, &success);
if (!success)
{
glGetShaderInfoLog(vertexShader, 512, NULL, infoLog);
std::cout << "ERROR::SHADER::VERTEX::COMPILATION_FAILED\n" << infoLog << std::endl;
}
// Fragment shader
GLuint fragmentShader = glCreateShader(GL_FRAGMENT_SHADER);
char const * FragmentSourcePointer = FragmentShaderCode.c_str();
glShaderSource(fragmentShader, 1, &FragmentSourcePointer, NULL);
glCompileShader(fragmentShader);
// Check for compile time errors
glGetShaderiv(fragmentShader, GL_COMPILE_STATUS, &success);
if (!success)
{
glGetShaderInfoLog(fragmentShader, 512, NULL, infoLog);
std::cout << "ERROR::SHADER::FRAGMENT::COMPILATION_FAILED\n" << infoLog << std::endl;
}
// Link shaders
GLuint shaderProgram = glCreateProgram();
glAttachShader(shaderProgram, vertexShader);
glAttachShader(shaderProgram, fragmentShader);
glLinkProgram(shaderProgram);
// Check for linking errors
glGetProgramiv(shaderProgram, GL_LINK_STATUS, &success);
if (!success) {
glGetProgramInfoLog(shaderProgram, 512, NULL, infoLog);
std::cout << "ERROR::SHADER::PROGRAM::LINKING_FAILED\n" << infoLog << std::endl;
}
glDeleteShader(vertexShader); //free up memory
glDeleteShader(fragmentShader);
glUseProgram(shaderProgram);
std::vector<glm::vec3> vertices_cube;
std::vector<glm::vec3> normals_cube;
std::vector<glm::vec2> UVs_cube;
loadOBJ("cube.obj", vertices_cube, normals_cube, UVs_cube); //read the vertices_cube from the cube.obj file
GLuint VAO_cube;
glGenVertexArrays(1, &VAO_cube);
// Bind the Vertex Array Object first, then bind and set vertex buffer(s) and attribute pointer(s).
GLuint vertices_VBO, normals_VBO;
glGenBuffers(1, &vertices_VBO);
glGenBuffers(1, &normals_VBO);
// Bind the Vertex Array Object first, then bind and set vertex buffer(s) and attribute pointer(s).
glBindVertexArray(VAO_cube);
glBindBuffer(GL_ARRAY_BUFFER, vertices_VBO);
glBufferData(GL_ARRAY_BUFFER, vertices_cube.size() * sizeof(glm::vec3), &vertices_cube.front(), GL_STATIC_DRAW);
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 3 * sizeof(GLfloat), (GLvoid*)0);
glEnableVertexAttribArray(0);
glBindBuffer(GL_ARRAY_BUFFER, normals_VBO);
glBufferData(GL_ARRAY_BUFFER, normals_cube.size() * sizeof(glm::vec3), &normals_cube.front(), GL_STATIC_DRAW);
glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 3 * sizeof(GLfloat), (GLvoid*)0);
glEnableVertexAttribArray(1);
glBindBuffer(GL_ARRAY_BUFFER, 0);
glBindVertexArray(0); // Unbind VAO_cube (it's always a good thing to unbind any buffer/array to prevent strange bugs)
// ----------------------------------------------------------------------------------------------------------------------------------------------
// cmc-edit : This will be a test for drawing a the axises
std::vector<glm::vec3> vertices_axis = { { -0.5f, 0.0f, 0.0f }, { 2.5f, 0.0f, 0.0f }, // cmc-edit : this is the start-end points for the x axis
{ 0.0f, -0.5f, 0.0f }, { 0.0f, 2.5f, 0.0f }, // cmc-edit : this is the start-end points for the y axis
{ 0.0f, 0.0f, -0.5f }, { 0.0f, 0.0f, 2.5f } }; // cmc-edit : this is the start-end points for the z axis
std::vector<glm::vec3> colors_axis = { { 1.0f, 1.0f, 1.0f }, { 1.0f, 0.0f, 0.0f }, // cmc-edit : white to red
{ 1.0f, 1.0f, 1.0f }, { 0.0f, 1.0f, 0.0f }, // cmc-edit : white to blue
{ 1.0f, 1.0f, 1.0f }, { 0.0f, 0.0f, 1.0f } }; // cmc-edit : white to green
GLuint VAO_axis, VBO_axis, VBO_colors; // cmc-edit : basic memory buffers
glGenVertexArrays(1, &VAO_axis); // cmc-edit : get mem_buf https://www.khronos.org/registry/OpenGL-Refpages/gl4/html/glGenVertexArrays.xhtml should always be one for this usage
glBindVertexArray(VAO_axis); // cmc-edit : now we start to work with our mem_buf
glGenBuffers(1, &VBO_axis); // cmc-edit : associate buffer within index 0 (matches vertex.shader)
glBindBuffer(GL_ARRAY_BUFFER, VBO_axis); // cmc-edit : bind array buffer for use
glBufferData(GL_ARRAY_BUFFER, vertices_axis.size() * sizeof(glm::vec3), &vertices_axis.front(), GL_STATIC_DRAW); // cmc-edit : load the vec of verticies
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 3 * sizeof(GLfloat), (GLvoid*)0); // cmc-edit : bind vertices at index 0
glEnableVertexAttribArray(0); // cmc-edit : close verticies at 0
glGenBuffers(1, &VBO_colors); // cmc-edit : associate buffer within index 1 (matches vertex.shader)
glBindBuffer(GL_ARRAY_BUFFER, VBO_colors);// cmc-edit : bind array buffer for use
glBufferData(GL_ARRAY_BUFFER, colors_axis.size() * sizeof(glm::vec3), &colors_axis.front(), GL_STATIC_DRAW); // cmc-edit : load the vec of verticies
glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 3 * sizeof(GLfloat), (GLvoid*)0); // cmc-edit : bind vertices at index 1
glEnableVertexAttribArray(1); // cmc-edit : close verticies at 1
glBindBuffer(GL_ARRAY_BUFFER, 0); // cmc-edit : close buffer
glBindVertexArray(0); // cmc-edit : Unbind VAO_xaxis (it's always a good thing to unbind any buffer/array to prevent strange bugs)
// ----------------------------------------------------------------------------------------------------------------------------------------------
triangle_scale = glm::vec3(0.5f); // cmc-edit : this scales the view
GLuint projectionLoc = glGetUniformLocation(shaderProgram, "projection_matrix");
GLuint viewMatrixLoc = glGetUniformLocation(shaderProgram, "view_matrix");
GLuint transformLoc = glGetUniformLocation(shaderProgram, "model_matrix");
// Game loop
while (!glfwWindowShouldClose(window))
{
// Check if any events have been activiated (key pressed, mouse moved etc.) and call corresponding response functions
glfwPollEvents();
// Render
// Clear the colorbuffer
glClearColor(0.2f, 0.3f, 0.3f, 1.0f);
glClear(GL_COLOR_BUFFER_BIT);
glm::mat4 view_matrix;
view_matrix = glm::lookAt(eye, center, up);
glm::mat4 model_matrix;
model_matrix = glm::scale(model_matrix, triangle_scale);
glUniformMatrix4fv(transformLoc, 1, GL_FALSE, glm::value_ptr(model_matrix));
glUniformMatrix4fv(viewMatrixLoc, 1, GL_FALSE, glm::value_ptr(view_matrix));
glUniformMatrix4fv(projectionLoc, 1, GL_FALSE, glm::value_ptr(projection_matrix));
//glBindVertexArray(VAO_cube);
//glDrawArrays(GL_TRIANGLES, 0, (GLsizei)vertices_cube.size());
//glBindVertexArray(0);
// ----------------------------------------------------------------------------------------------------------------------------------------------
glBindVertexArray(VAO_axis); // cmc-edit : lets displays the axis
glDrawArrays(GL_LINES, 0, (GLsizei)vertices_axis.size()); // cmc-edit : lets displays the axis
glBindVertexArray(0); // cmc-edit : lets displays the axis
// ----------------------------------------------------------------------------------------------------------------------------------------------
// Swap the screen buffers
glfwSwapBuffers(window);
}
// Terminate GLFW, clearing any resources allocated by GLFW.
glfwTerminate();
return 0;
}
<commit_msg>tried color defined by floats<commit_after>//example skeleton code
//modified from http://learnopengl.com/
#include "GL/glew.h" // include GL Extension Wrangler
#include "GLFW/glfw3.h" // include GLFW helper library
#include <stdio.h>
#include <iostream>
#include <string>
#include <fstream>
#include "glm/glm.hpp"
#include "glm/gtc/matrix_transform.hpp"
#include "glm/gtc/type_ptr.hpp"
#include "objloader.hpp" //include the object loader
using namespace std;
// Window dimensions
const GLuint WIDTH = 800, HEIGHT = 600;
glm::vec3 camera_position;
glm::vec3 triangle_scale;
glm::mat4 projection_matrix;
// Constant vectors
const glm::vec3 center(0.0f, 0.0f, 0.0f);
const glm::vec3 up(0.0f, 1.0f, 0.0f);
const glm::vec3 eye(2.0f, 2.0f, 3.0f);
// rotation globals
static GLfloat view_rotx = 20.f, view_roty = 30.f, view_rotz = 0.f;
// Is called whenever a key is pressed/released via GLFW
void key_callback(GLFWwindow* window, int key, int scancode, int action, int mode)
{
std::cout << key << std::endl;
if (action != GLFW_PRESS) return;
switch (key) {
case GLFW_KEY_Z:
if (mode & GLFW_MOD_SHIFT)
view_rotz -= 5.0;
else
view_rotz += 5.0;
break;
case GLFW_KEY_ESCAPE:
glfwSetWindowShouldClose(window, GLFW_TRUE);
break;
case GLFW_KEY_UP:
view_rotx += 5.0;
break;
case GLFW_KEY_DOWN:
view_rotx -= 5.0;
break;
case GLFW_KEY_LEFT:
view_roty += 5.0;
break;
case GLFW_KEY_RIGHT:
view_roty -= 5.0;
break;
default:
return;
};
}
// The MAIN function, from here we start the application and run the game loop
int main()
{
std::cout << "Starting GLFW context, OpenGL 3.3" << std::endl;
// Init GLFW
glfwInit();
// Set all the required options for GLFW
glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);
glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
// Create a GLFWwindow object that we can use for GLFW's functions
GLFWwindow* window = glfwCreateWindow(WIDTH, HEIGHT, "Pacman by Christopher McArthur", nullptr, nullptr);
if (window == nullptr)
{
std::cout << "Failed to create GLFW window" << std::endl;
glfwTerminate();
return -1;
}
glfwMakeContextCurrent(window);
// Set the required callback functions
glfwSetKeyCallback(window, key_callback);
// Set this to true so GLEW knows to use a modern approach to retrieving function pointers and extensions
glewExperimental = GL_TRUE;
// Initialize GLEW to setup the OpenGL Function pointers
if (glewInit() != GLEW_OK)
{
std::cout << "Failed to initialize GLEW" << std::endl;
return -1;
}
// Define the viewport dimensions
int width, height;
glfwGetFramebufferSize(window, &width, &height);
glViewport(0, 0, width, height);
projection_matrix = glm::perspective(45.0f, (GLfloat)width / (GLfloat)height, 0.0f, 100.0f);
// Build and compile our shader program
// Vertex shader
// Read the Vertex Shader code from the file
string vertex_shader_path = "vertex.shader";
string VertexShaderCode;
std::ifstream VertexShaderStream(vertex_shader_path, ios::in);
if (VertexShaderStream.is_open()) {
string Line = "";
while (getline(VertexShaderStream, Line))
VertexShaderCode += "\n" + Line;
VertexShaderStream.close();
}
else {
printf("Impossible to open %s. Are you in the right directory ?\n", vertex_shader_path.c_str());
getchar();
exit(-1);
}
// Read the Fragment Shader code from the file
string fragment_shader_path = "fragment.shader";
std::string FragmentShaderCode;
std::ifstream FragmentShaderStream(fragment_shader_path, std::ios::in);
if (FragmentShaderStream.is_open()) {
std::string Line = "";
while (getline(FragmentShaderStream, Line))
FragmentShaderCode += "\n" + Line;
FragmentShaderStream.close();
}
else {
printf("Impossible to open %s. Are you in the right directory?\n", fragment_shader_path.c_str());
getchar();
exit(-1);
}
GLuint vertexShader = glCreateShader(GL_VERTEX_SHADER);
char const * VertexSourcePointer = VertexShaderCode.c_str();
glShaderSource(vertexShader, 1, &VertexSourcePointer, NULL);
glCompileShader(vertexShader);
// Check for compile time errors
GLint success;
GLchar infoLog[512];
glGetShaderiv(vertexShader, GL_COMPILE_STATUS, &success);
if (!success)
{
glGetShaderInfoLog(vertexShader, 512, NULL, infoLog);
std::cout << "ERROR::SHADER::VERTEX::COMPILATION_FAILED\n" << infoLog << std::endl;
}
// Fragment shader
GLuint fragmentShader = glCreateShader(GL_FRAGMENT_SHADER);
char const * FragmentSourcePointer = FragmentShaderCode.c_str();
glShaderSource(fragmentShader, 1, &FragmentSourcePointer, NULL);
glCompileShader(fragmentShader);
// Check for compile time errors
glGetShaderiv(fragmentShader, GL_COMPILE_STATUS, &success);
if (!success)
{
glGetShaderInfoLog(fragmentShader, 512, NULL, infoLog);
std::cout << "ERROR::SHADER::FRAGMENT::COMPILATION_FAILED\n" << infoLog << std::endl;
}
// Link shaders
GLuint shaderProgram = glCreateProgram();
glAttachShader(shaderProgram, vertexShader);
glAttachShader(shaderProgram, fragmentShader);
glLinkProgram(shaderProgram);
// Check for linking errors
glGetProgramiv(shaderProgram, GL_LINK_STATUS, &success);
if (!success) {
glGetProgramInfoLog(shaderProgram, 512, NULL, infoLog);
std::cout << "ERROR::SHADER::PROGRAM::LINKING_FAILED\n" << infoLog << std::endl;
}
glDeleteShader(vertexShader); //free up memory
glDeleteShader(fragmentShader);
glUseProgram(shaderProgram);
std::vector<glm::vec3> vertices_cube;
std::vector<glm::vec3> normals_cube;
std::vector<glm::vec2> UVs_cube;
loadOBJ("cube.obj", vertices_cube, normals_cube, UVs_cube); //read the vertices_cube from the cube.obj file
GLuint VAO_cube;
glGenVertexArrays(1, &VAO_cube);
// Bind the Vertex Array Object first, then bind and set vertex buffer(s) and attribute pointer(s).
GLuint vertices_VBO, normals_VBO;
glGenBuffers(1, &vertices_VBO);
glGenBuffers(1, &normals_VBO);
// Bind the Vertex Array Object first, then bind and set vertex buffer(s) and attribute pointer(s).
glBindVertexArray(VAO_cube);
glBindBuffer(GL_ARRAY_BUFFER, vertices_VBO);
glBufferData(GL_ARRAY_BUFFER, vertices_cube.size() * sizeof(glm::vec3), &vertices_cube.front(), GL_STATIC_DRAW);
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 3 * sizeof(GLfloat), (GLvoid*)0);
glEnableVertexAttribArray(0);
glBindBuffer(GL_ARRAY_BUFFER, normals_VBO);
glBufferData(GL_ARRAY_BUFFER, normals_cube.size() * sizeof(glm::vec3), &normals_cube.front(), GL_STATIC_DRAW);
glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 3 * sizeof(GLfloat), (GLvoid*)0);
glEnableVertexAttribArray(1);
glBindBuffer(GL_ARRAY_BUFFER, 0);
glBindVertexArray(0); // Unbind VAO_cube (it's always a good thing to unbind any buffer/array to prevent strange bugs)
// ----------------------------------------------------------------------------------------------------------------------------------------------
// cmc-edit : This will be a test for drawing a the axises
std::vector<glm::vec3> vertices_axis = { { -0.5f, 0.0f, 0.0f }, { 2.5f, 0.0f, 0.0f }, // cmc-edit : this is the start-end points for the x axis
{ 0.0f, -0.5f, 0.0f }, { 0.0f, 2.5f, 0.0f }, // cmc-edit : this is the start-end points for the y axis
{ 0.0f, 0.0f, -0.5f }, { 0.0f, 0.0f, 2.5f } }; // cmc-edit : this is the start-end points for the z axis
//std::vector<glm::vec3> colors_axis = { { 1.0f, 1.0f, 1.0f }, { 1.0f, 0.0f, 0.0f }, // cmc-edit : white to red
// { 1.0f, 1.0f, 1.0f }, { 0.0f, 1.0f, 0.0f }, // cmc-edit : white to blue
// { 1.0f, 1.0f, 1.0f }, { 0.0f, 0.0f, 1.0f } }; // cmc-edit : white to green
float axis_colors[] = { 1.0f, 1.0f, 1.0f, 1.0f, 0.0f, 0.0f,
1.0f, 1.0f, 1.0f, 0.0f, 1.0f, 0.0f,
1.0f, 1.0f, 1.0f, 0.0f, 0.0f, 1.0f };
GLuint VAO_axis, VBO_axis, VBO_colors; // cmc-edit : basic memory buffers
glGenVertexArrays(1, &VAO_axis); // cmc-edit : get mem_buf https://www.khronos.org/registry/OpenGL-Refpages/gl4/html/glGenVertexArrays.xhtml should always be one for this usage
glBindVertexArray(VAO_axis); // cmc-edit : now we start to work with our mem_buf
glGenBuffers(1, &VBO_axis); // cmc-edit : associate buffer within index 0 (matches vertex.shader)
glBindBuffer(GL_ARRAY_BUFFER, VBO_axis); // cmc-edit : bind array buffer for use
glBufferData(GL_ARRAY_BUFFER, vertices_axis.size() * sizeof(glm::vec3), &vertices_axis.front(), GL_STATIC_DRAW); // cmc-edit : load the vec of verticies
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 3 * sizeof(GLfloat), (GLvoid*)0); // cmc-edit : bind vertices at index 0
glEnableVertexAttribArray(0); // cmc-edit : close verticies at 0
glGenBuffers(1, &VBO_colors); // cmc-edit : associate buffer within index 1 (matches vertex.shader)
glBindBuffer(GL_ARRAY_BUFFER, VBO_colors);// cmc-edit : bind array buffer for use
//glBufferData(GL_ARRAY_BUFFER, colors_axis.size() * sizeof(glm::vec3), &colors_axis.front(), GL_STATIC_DRAW); // cmc-edit : load the vec of verticies
//glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 3 * sizeof(GLfloat), (GLvoid*)0); // cmc-edit : bind vertices at index 1
glBufferData(GL_ARRAY_BUFFER, sizeof(axis_colors), axis_colors, GL_STATIC_DRAW);
glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 3 * sizeof(float), (void*)0);
glEnableVertexAttribArray(1); // cmc-edit : close verticies at 1
glBindBuffer(GL_ARRAY_BUFFER, 0); // cmc-edit : close buffer
glBindVertexArray(0); // cmc-edit : Unbind VAO_xaxis (it's always a good thing to unbind any buffer/array to prevent strange bugs)
// ----------------------------------------------------------------------------------------------------------------------------------------------
triangle_scale = glm::vec3(0.5f); // cmc-edit : this scales the view
GLuint projectionLoc = glGetUniformLocation(shaderProgram, "projection_matrix");
GLuint viewMatrixLoc = glGetUniformLocation(shaderProgram, "view_matrix");
GLuint transformLoc = glGetUniformLocation(shaderProgram, "model_matrix");
// Game loop
while (!glfwWindowShouldClose(window))
{
// Check if any events have been activiated (key pressed, mouse moved etc.) and call corresponding response functions
glfwPollEvents();
// Render
// Clear the colorbuffer
glClearColor(0.2f, 0.3f, 0.3f, 1.0f);
glClear(GL_COLOR_BUFFER_BIT);
glm::mat4 view_matrix;
view_matrix = glm::lookAt(eye, center, up);
glm::mat4 model_matrix;
model_matrix = glm::scale(model_matrix, triangle_scale);
glUniformMatrix4fv(transformLoc, 1, GL_FALSE, glm::value_ptr(model_matrix));
glUniformMatrix4fv(viewMatrixLoc, 1, GL_FALSE, glm::value_ptr(view_matrix));
glUniformMatrix4fv(projectionLoc, 1, GL_FALSE, glm::value_ptr(projection_matrix));
//glBindVertexArray(VAO_cube);
//glDrawArrays(GL_TRIANGLES, 0, (GLsizei)vertices_cube.size());
//glBindVertexArray(0);
// ----------------------------------------------------------------------------------------------------------------------------------------------
glBindVertexArray(VAO_axis); // cmc-edit : lets displays the axis
glDrawArrays(GL_LINES, 0, (GLsizei)vertices_axis.size()); // cmc-edit : lets displays the axis
glBindVertexArray(0); // cmc-edit : lets displays the axis
// ----------------------------------------------------------------------------------------------------------------------------------------------
// Swap the screen buffers
glfwSwapBuffers(window);
}
// Terminate GLFW, clearing any resources allocated by GLFW.
glfwTerminate();
return 0;
}
<|endoftext|> |
<commit_before>#ifndef __STAN__META__TRAITS_HPP__
#define __STAN__META__TRAITS_HPP__
#include <vector>
#include <boost/type_traits.hpp>
namespace stan {
/**
* Metaprogramming struct to detect whether a given type is constant
* in the mathematical sense (not the C++ <code>const</code>
* sense). If the parameter type is constant, <code>value</code>
* will be equal to <code>true</code>.
*
* The baseline implementation in this abstract base class is to
* classify a type <code>T</code> as constant if it can be converted
* (i.e., assigned) to a <code>double</code>. This baseline should
* be overridden for any type that should be treated as a variable.
*
* @tparam T Type being tested.
*/
template <typename T>
struct is_constant {
/**
* A boolean constant with equal to <code>true</code> if the
* type parameter <code>T</code> is a mathematical constant.
*/
enum { value = boost::is_convertible<T,double>::value };
};
// FIXME: use boost::type_traits::remove_all_extents to extend to array/ptr types
/**
* Metaprogram structure to determine the base scalar type
* of a template argument.
*
* <p>This base class should be specialized for structured types.
*
* @tparam T Type of object.
*/
template <typename T>
struct scalar_type {
/**
* Base scalar type for object.
*/
typedef T type;
};
/**
* Metaprogram specialization extracting the base type of
* a standard vector recursively.
*
* @tparam Scalar type of vector.
*/
template <typename T>
struct scalar_type<std::vector<T> > {
typedef typename scalar_type<T>::type type;
};
template <typename T>
struct is_vector {
enum { value = 0 };
typedef T type;
};
template <typename T>
struct is_vector <std::vector<T> > {
enum { value = 1 };
typedef T type;
};
template <typename T>
struct is_vector <const std::vector<T> > {
enum { value = 1 };
typedef T type;
};
template <typename T>
size_t length(const T& x) {
if (is_vector<T>::value)
return ((std::vector<typename is_vector<T>::type>*)&x)->size();
else
return 1;
}
template <typename T1, typename T2, typename T3>
size_t max_size(const T1& x1, const T2& x2, const T3& x3) {
size_t result = length(x1);
result = result > length(x2) ? result : length(x2);
result = result > length(x3) ? result : length(x3);
assert((length(x1) == 1) || (length(x1) == result));
assert((length(x2) == 1) || (length(x2) == result));
assert((length(x3) == 1) || (length(x3) == result));
return result;
}
// AmbiguousVector is the simple VectorView for writing doubles into
template <typename T, bool is_vec = 0>
class AmbiguousVector {
private:
T x_;
public:
AmbiguousVector(size_t /*n*/) : x_(0) { }
T& operator[](int /*i*/) { return x_; }
size_t size() { return 1; }
};
template <typename T>
class AmbiguousVector<T, 1> {
private:
std::vector<T> x_;
public:
AmbiguousVector(size_t n) : x_(n, 0) { }
T& operator[](int i) { return x_[i]; }
size_t size() { return x_.size(); }
};
// two template params for use in partials_vari OperandsAndPartials
template<typename T, bool is_vec = stan::is_vector<T>::value>
class VectorView {
private:
T x_;
public:
VectorView(T x) : x_(x) { }
T& operator[](int /*i*/) { return x_; }
};
template<typename T, bool is_vec>
class VectorView<std::vector<T>, is_vec> {
private:
std::vector<T>* x_;
public:
VectorView(std::vector<T>& x) : x_(&x) { }
T& operator[](int i) {
if (is_vec)
return (*x_)[i];
else
return (*x_)[0];
}
};
template<typename T, bool is_vec>
class VectorView<const std::vector<T>, is_vec> {
private:
const std::vector<T>* x_;
public:
VectorView(const std::vector<T>& x) : x_(&x) { }
const T& operator[](int i) const {
if (is_vec)
return (*x_)[i];
else
return (*x_)[0];
}
};
template<typename T, bool is_vec>
class VectorView<T*, is_vec> {
private:
T* x_;
public:
VectorView(T* x) : x_(x) { }
T& operator[](int i) {
if (is_vec)
return x_[i];
else
return *x_;
}
};
}
#endif
<commit_msg>cleaned up VectorView template params, switches and defaults<commit_after>#ifndef __STAN__META__TRAITS_HPP__
#define __STAN__META__TRAITS_HPP__
#include <vector>
#include <boost/type_traits.hpp>
namespace stan {
/**
* Metaprogramming struct to detect whether a given type is constant
* in the mathematical sense (not the C++ <code>const</code>
* sense). If the parameter type is constant, <code>value</code>
* will be equal to <code>true</code>.
*
* The baseline implementation in this abstract base class is to
* classify a type <code>T</code> as constant if it can be converted
* (i.e., assigned) to a <code>double</code>. This baseline should
* be overridden for any type that should be treated as a variable.
*
* @tparam T Type being tested.
*/
template <typename T>
struct is_constant {
/**
* A boolean constant with equal to <code>true</code> if the
* type parameter <code>T</code> is a mathematical constant.
*/
enum { value = boost::is_convertible<T,double>::value };
};
// FIXME: use boost::type_traits::remove_all_extents to extend to array/ptr types
/**
* Metaprogram structure to determine the base scalar type
* of a template argument.
*
* <p>This base class should be specialized for structured types.
*
* @tparam T Type of object.
*/
template <typename T>
struct scalar_type {
/**
* Base scalar type for object.
*/
typedef T type;
};
/**
* Metaprogram specialization extracting the base type of
* a standard vector recursively.
*
* @tparam Scalar type of vector.
*/
template <typename T>
struct scalar_type<std::vector<T> > {
typedef typename scalar_type<T>::type type;
};
template <typename T>
struct is_vector {
enum { value = 0 };
typedef T type;
};
template <typename T>
struct is_vector <std::vector<T> > {
enum { value = 1 };
typedef T type;
};
template <typename T>
struct is_vector <const std::vector<T> > {
enum { value = 1 };
typedef T type;
};
template <typename T>
size_t length(const T& x) {
if (is_vector<T>::value)
return ((std::vector<typename is_vector<T>::type>*)&x)->size();
else
return 1;
}
template <typename T1, typename T2, typename T3>
size_t max_size(const T1& x1, const T2& x2, const T3& x3) {
size_t result = length(x1);
result = result > length(x2) ? result : length(x2);
result = result > length(x3) ? result : length(x3);
assert((length(x1) == 1) || (length(x1) == result));
assert((length(x2) == 1) || (length(x2) == result));
assert((length(x3) == 1) || (length(x3) == result));
return result;
}
// AmbiguousVector is the simple VectorView for writing doubles into
template <typename T, bool is_vec = 0>
class AmbiguousVector {
private:
T x_;
public:
AmbiguousVector(size_t /*n*/) : x_(0) { }
T& operator[](int /*i*/) { return x_; }
size_t size() { return 1; }
};
template <typename T>
class AmbiguousVector<T, 1> {
private:
std::vector<T> x_;
public:
AmbiguousVector(size_t n) : x_(n, 0) { }
T& operator[](int i) { return x_[i]; }
size_t size() { return x_.size(); }
};
// two template params for use in partials_vari OperandsAndPartials
template<typename T, bool is_vec = stan::is_vector<T>::value>
class VectorView {
private:
T x_;
public:
VectorView(T x) : x_(x) { }
T& operator[](int /*i*/) {
return x_;
}
};
template<typename T>
class VectorView<std::vector<T>, true> {
private:
std::vector<T>& x_;
public:
VectorView(std::vector<T>& x) : x_(x) { }
T& operator[](int i) {
return x_[i];
}
};
template<typename T>
class VectorView<const std::vector<T>, true> {
private:
const std::vector<T>& x_;
public:
VectorView(const std::vector<T>& x) : x_(x) { }
const T& operator[](int i) const {
return x_[i];
}
};
template<typename T, bool is_vec>
class VectorView<T*, is_vec> {
private:
T* x_;
public:
VectorView(T* x) : x_(x) { }
T& operator[](int i) {
if (is_vec)
return x_[i];
else
return *x_;
}
};
}
#endif
<|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: inetdef.hxx,v $
*
* $Revision: 1.2 $
*
* last change: $Author: rt $ $Date: 2005-09-08 09:42: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 _TOOLS_INETDEF_HXX
#include <tools/inetdef.hxx>
#endif
<commit_msg>INTEGRATION: CWS changefileheader (1.2.774); FILE MERGED 2008/04/01 15:44:21 thb 1.2.774.2: #i85898# Stripping all external header guards 2008/03/31 13:00:52 rt 1.2.774.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: inetdef.hxx,v $
* $Revision: 1.3 $
*
* 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.
*
************************************************************************/
#include <tools/inetdef.hxx>
<|endoftext|> |
<commit_before>/*-------------------------------------------------
参考プログラム
read_csv.cpp : https://gist.github.com/yoneken/5765597#file-read_csv-cpp
-------------------------------------------------- */
#include <ros/ros.h>
#include <ros/package.h>
#include <tf/transform_listener.h>
#include <move_base_msgs/MoveBaseAction.h>
#include <actionlib/client/simple_action_client.h>
#include <geometry_msgs/Pose.h>
#include <jsk_recognition_msgs/BoundingBox.h>
#include <jsk_recognition_msgs/BoundingBoxArray.h>
#include <iostream>
#include <string>
#include <sstream>
#include <fstream>
#include <boost/tokenizer.hpp>
#include <boost/shared_array.hpp>
#include <ros/package.h>
typedef actionlib::SimpleActionClient<move_base_msgs::MoveBaseAction> MoveBaseClient;
typedef boost::tokenizer<boost::char_separator<char> > tokenizer;
namespace RobotBehaviors
{
enum State
{
WAYPOINT_NAV,
DETECT_TARGET_NAV,
REACHED_GOAL,
INIT_NAV,
};
}
class WayPoint
{
public:
WayPoint();
WayPoint(move_base_msgs::MoveBaseGoal goal, int area_type, double reach_threshold)
: goal_(goal), area_type_(area_type), reach_threshold_(reach_threshold_)
{
}
~WayPoint(){}
bool isSearchArea()
{
if (area_type_ == 1) {
return true;
}else{
return false;
}
}
move_base_msgs::MoveBaseGoal goal_;
int area_type_;
double reach_threshold_;
};
class WaypointNavigator
{
public:
WaypointNavigator() : ac_("move_base", true), rate_(100)
{
target_waypoint_index_ = 0;
robot_behavior_state_ = RobotBehaviors::INIT_NAV;
std::string filename;
ros::NodeHandle n("~");
n.param<std::string>("waypointsfile", filename,
ros::package::getPath("waypoint_navigator")
+ "/waypoints/garden_waypoints.csv");
n.param("dist_thres_to_target_object", dist_thres_to_target_object_, 1.5);
ROS_INFO("[Waypoints file name] : %s", filename.c_str());
ROS_INFO("Reading Waypoints.");
readWaypoint(filename.c_str());
ROS_INFO("Waiting for action server to start.");
ac_.waitForServer();
}
void sendNewGoal(geometry_msgs::Pose pose)
{
move_base_msgs::MoveBaseGoal goal;
goal.target_pose.pose = pose;
goal.target_pose.header.frame_id = "map";
goal.target_pose.header.stamp = ros::Time::now();
ac_.sendGoal(goal);
now_goal_ = goal.target_pose.pose;
}
void cancelGoal(){
ROS_INFO("cancelGoal() is called !!");
ac_.cancelGoal();
}
int readWaypoint(std::string filename)
{
const int rows_num = 9; // x, y, z, Qx,Qy,Qz,Qw, area_type, reach_threshold
boost::char_separator<char> sep("," ,"", boost::keep_empty_tokens);
std::ifstream ifs(filename.c_str());
std::string line;
while(ifs.good()){
getline(ifs, line);
if(line.empty()){ break; }
tokenizer tokens(line, sep);
std::vector<double> data;
tokenizer::iterator it = tokens.begin();
for(; it != tokens.end() ; ++it){
std::stringstream ss;
double d;
ss << *it;
ss >> d;
data.push_back(d);
}
if(data.size() != rows_num){
ROS_ERROR("Row size is mismatch!!");
return -1;
}else{
move_base_msgs::MoveBaseGoal waypoint;
waypoint.target_pose.pose.position.x = data[0];
waypoint.target_pose.pose.position.y = data[1];
waypoint.target_pose.pose.position.z = data[2];
waypoint.target_pose.pose.orientation.x = data[3];
waypoint.target_pose.pose.orientation.y = data[4];
waypoint.target_pose.pose.orientation.z = data[5];
waypoint.target_pose.pose.orientation.w = data[6];
waypoints_.push_back(WayPoint(waypoint, (int)data[7], data[8]));
}
}
return 0;
}
void detectTargetObjectCallback(const jsk_recognition_msgs::BoundingBoxArray::ConstPtr &target_objects_ptr)
{
target_objects_ = *target_objects_ptr;
}
WayPoint getNextWaypoint()
{
WayPoint next_waypoint = waypoints_[target_waypoint_index_];
target_waypoint_index_++;
return next_waypoint;
}
bool isFinalGoal()
{
if (target_waypoint_index_ == (int)waypoints_.size()) {
return true;
}else{
return false;
}
}
bool isAlreadyApproachedToTargetObject(jsk_recognition_msgs::BoundingBox target_object)
{
for (int i = 0; i < approached_target_objects_.boxes.size(); ++i) {
double dist = calculateDistance(target_object.pose,
approached_target_objects_.boxes[i].pose);
if (dist < 3.0) { // しきい値はパラメータサーバで設定できるようにする
return true;
}
}
return false;
}
double calculateDistance(geometry_msgs::Pose a,geometry_msgs::Pose b)
{
sqrt(pow((a.position.x - b.position.x), 2.0) +
pow((a.position.y - b.position.y), 2.0));
}
// 探索対象へのアプローチの場合
void setNextGoal(jsk_recognition_msgs::BoundingBox target_object,
double threshold)
{
reach_threshold_ = threshold;
// 探索対象へのアプローチの場合はアプローチ時のロボットの姿勢を計算する必要がある
// まだ出来てない。
approached_target_objects_.boxes.push_back(target_object);//探索済みに追加
this->sendNewGoal(target_object.pose);
}
// 通常のwaypointの場合
void setNextGoal(WayPoint waypoint)
{
reach_threshold_ = waypoint.reach_threshold_;
this->sendNewGoal(waypoint.goal_.target_pose.pose);
}
double getReachThreshold()
{
return reach_threshold_;
}
geometry_msgs::Pose getRobotCurrentPosition()
{
// tfを使ってロボットの現在位置を取得する
tf::StampedTransform transform;
geometry_msgs::Pose pose;
try {
listener_.lookupTransform("/map", "/base_link", ros::Time(0), transform);
} catch (tf::TransformException ex) {
ROS_ERROR("%s", ex.what());
}
pose.position.x = transform.getOrigin().x();
pose.position.y = transform.getOrigin().y();
return pose;
}
geometry_msgs::Pose getNowGoalPosition()
{
return now_goal_;
}
void run()
{
robot_behavior_state_ = RobotBehaviors::INIT_NAV;
while(ros::ok()){
WayPoint next_waypoint = this->getNextWaypoint();
if (next_waypoint.isSearchArea()) { // 次のwaypointが探索エリアがどうか判定
if(target_objects_.boxes.size() > 0){ // 探索対象が見つかっているか
for (int i = 0; i < target_objects_.boxes.size(); ++i) {
if (! this->isAlreadyApproachedToTargetObject(target_objects_.boxes[i])) { // 探索対象にまだアプローチしていなかったら
this->setNextGoal(target_objects_.boxes[i], dist_thres_to_target_object_); // 探索対象を次のゴールに設定
robot_behavior_state_ = RobotBehaviors::DETECT_TARGET_NAV;
break;
}
}
}else // 探索エリアだが探索対象がいない
{
this->setNextGoal(next_waypoint);
robot_behavior_state_ = RobotBehaviors::WAYPOINT_NAV;
}
}else // 探索エリアではない
{
this->setNextGoal(next_waypoint);
robot_behavior_state_ = RobotBehaviors::WAYPOINT_NAV;
}
while(1)
{
geometry_msgs::Pose robot_current_position = this->getRobotCurrentPosition(); // 現在のロボットの座標
geometry_msgs::Pose now_goal_position = this->getNowGoalPosition(); // 現在目指している座標
double distance_to_goal = this->calculateDistance(robot_current_position,
now_goal_position);
// ここでスタック判定してもいいかもしれない。
// 一定時間進んでない、もしくは一定回数後も移動距離が変化していないなら
// ゴールをキャンセルして次のwaypointに進むとか?
if(distance_to_goal < this->getReachThreshold()) // 目標座標までの距離がしきい値になれば
{
robot_behavior_state_ = RobotBehaviors::REACHED_GOAL;
break;
}
rate_.sleep();
ros::spinOnce();
}
if (robot_behavior_state_ == RobotBehaviors::REACHED_GOAL) { //waypointか探索対象に到達してて
if (this->isFinalGoal()) { // そのwaypointが最後だったら
this->cancelGoal(); // ゴールをキャンセルして終了
return;
}
}
rate_.sleep();
ros::spinOnce();
}// while(ros::ok())
}
private:
MoveBaseClient ac_;
RobotBehaviors::State robot_behavior_state_;
ros::Rate rate_;
std::vector<WayPoint> waypoints_;
ros::NodeHandle nh_;
tf::TransformListener listener_;
int target_waypoint_index_; // 次に目指すウェイポイントのインデックス
jsk_recognition_msgs::BoundingBoxArray target_objects_; //探索対象
jsk_recognition_msgs::BoundingBoxArray approached_target_objects_; //アプローチ済みの探索対象
double dist_thres_to_target_object_; // 探索対象にどれだけ近づいたらゴールとするか
double reach_threshold_; // 今セットされてるゴール(waypointもしくは探索対象)へのしきい値
geometry_msgs::Pose now_goal_; // 現在目指しているゴールの座標
};
int main(int argc, char** argv){
ros::init(argc, argv, "waypoint_navigator");
WaypointNavigator waypoint_navigator;
waypoint_navigator.run();
return 0;
}
<commit_msg>some fix<commit_after>/*-------------------------------------------------
参考プログラム
read_csv.cpp : https://gist.github.com/yoneken/5765597#file-read_csv-cpp
-------------------------------------------------- */
#include <ros/ros.h>
#include <ros/package.h>
#include <tf/transform_listener.h>
#include <move_base_msgs/MoveBaseAction.h>
#include <actionlib/client/simple_action_client.h>
#include <geometry_msgs/Pose.h>
#include <jsk_recognition_msgs/BoundingBox.h>
#include <jsk_recognition_msgs/BoundingBoxArray.h>
#include <iostream>
#include <string>
#include <sstream>
#include <fstream>
#include <boost/tokenizer.hpp>
#include <boost/shared_array.hpp>
#include <ros/package.h>
typedef actionlib::SimpleActionClient<move_base_msgs::MoveBaseAction> MoveBaseClient;
typedef boost::tokenizer<boost::char_separator<char> > tokenizer;
namespace RobotBehaviors
{
enum State
{
WAYPOINT_NAV,
DETECT_TARGET_NAV,
REACHED_GOAL,
INIT_NAV,
};
}
class WayPoint
{
public:
WayPoint();
WayPoint(move_base_msgs::MoveBaseGoal goal, int area_type, double reach_threshold)
: goal_(goal), area_type_(area_type), reach_threshold_(reach_threshold)
{
}
~WayPoint(){}
bool isSearchArea()
{
if (area_type_ == 1) {
return true;
}else{
return false;
}
}
move_base_msgs::MoveBaseGoal goal_;
int area_type_;
double reach_threshold_;
};
class WaypointNavigator
{
public:
WaypointNavigator() : ac_("move_base", true), rate_(100)
{
target_waypoint_index_ = 0;
robot_behavior_state_ = RobotBehaviors::INIT_NAV;
std::string filename;
ros::NodeHandle n("~");
n.param<std::string>("waypointsfile", filename,
ros::package::getPath("waypoint_navigator")
+ "/waypoints/garden_waypoints.csv");
n.param("dist_thres_to_target_object", dist_thres_to_target_object_, 1.5);
ROS_INFO("[Waypoints file name] : %s", filename.c_str());
ROS_INFO("Reading Waypoints.");
readWaypoint(filename.c_str());
ROS_INFO("Waiting for action server to start.");
ac_.waitForServer();
}
void sendNewGoal(geometry_msgs::Pose pose)
{
move_base_msgs::MoveBaseGoal goal;
goal.target_pose.pose = pose;
goal.target_pose.header.frame_id = "map";
goal.target_pose.header.stamp = ros::Time::now();
ac_.sendGoal(goal);
now_goal_ = goal.target_pose.pose;
}
void cancelGoal(){
ROS_INFO("cancelGoal() is called !!");
ac_.cancelGoal();
}
int readWaypoint(std::string filename)
{
const int rows_num = 9; // x, y, z, Qx,Qy,Qz,Qw, area_type, reach_threshold
boost::char_separator<char> sep("," ,"", boost::keep_empty_tokens);
std::ifstream ifs(filename.c_str());
std::string line;
while(ifs.good()){
getline(ifs, line);
if(line.empty()){ break; }
tokenizer tokens(line, sep);
std::vector<double> data;
tokenizer::iterator it = tokens.begin();
for(; it != tokens.end() ; ++it){
std::stringstream ss;
double d;
ss << *it;
ss >> d;
data.push_back(d);
}
if(data.size() != rows_num){
ROS_ERROR("Row size is mismatch!!");
return -1;
}else{
move_base_msgs::MoveBaseGoal waypoint;
waypoint.target_pose.pose.position.x = data[0];
waypoint.target_pose.pose.position.y = data[1];
waypoint.target_pose.pose.position.z = data[2];
waypoint.target_pose.pose.orientation.x = data[3];
waypoint.target_pose.pose.orientation.y = data[4];
waypoint.target_pose.pose.orientation.z = data[5];
waypoint.target_pose.pose.orientation.w = data[6];
waypoints_.push_back(WayPoint(waypoint, (int)data[7], data[8]/2.0));
}
}
return 0;
}
void detectTargetObjectCallback(const jsk_recognition_msgs::BoundingBoxArray::ConstPtr &target_objects_ptr)
{
target_objects_ = *target_objects_ptr;
}
WayPoint getNextWaypoint()
{
WayPoint next_waypoint = waypoints_[target_waypoint_index_];
target_waypoint_index_++;
return next_waypoint;
}
bool isFinalGoal()
{
if ((target_waypoint_index_-1) == ((int)waypoints_.size())) {
return true;
}else{
return false;
}
}
bool isAlreadyApproachedToTargetObject(jsk_recognition_msgs::BoundingBox target_object)
{
for (int i = 0; i < approached_target_objects_.boxes.size(); ++i) {
double dist = calculateDistance(target_object.pose,
approached_target_objects_.boxes[i].pose);
if (dist < 3.0) { // しきい値はパラメータサーバで設定できるようにする
return true;
}
}
return false;
}
double calculateDistance(geometry_msgs::Pose a,geometry_msgs::Pose b)
{
sqrt(pow((a.position.x - b.position.x), 2.0) +
pow((a.position.y - b.position.y), 2.0));
}
// 探索対象へのアプローチの場合
void setNextGoal(jsk_recognition_msgs::BoundingBox target_object,
double threshold)
{
reach_threshold_ = threshold;
// 探索対象へのアプローチの場合はアプローチ時のロボットの姿勢を計算する必要がある
// まだ出来てない。
approached_target_objects_.boxes.push_back(target_object);//探索済みに追加
this->sendNewGoal(target_object.pose);
}
// 通常のwaypointの場合
void setNextGoal(WayPoint waypoint)
{
reach_threshold_ = waypoint.reach_threshold_;
this->sendNewGoal(waypoint.goal_.target_pose.pose);
}
double getReachThreshold()
{
return reach_threshold_;
}
geometry_msgs::Pose getRobotCurrentPosition()
{
// tfを使ってロボットの現在位置を取得する
tf::StampedTransform transform;
geometry_msgs::Pose pose;
try {
listener_.lookupTransform("/map", "/base_link", ros::Time(0), transform);
} catch (tf::TransformException ex) {
ROS_ERROR("%s", ex.what());
}
pose.position.x = transform.getOrigin().x();
pose.position.y = transform.getOrigin().y();
return pose;
}
geometry_msgs::Pose getNowGoalPosition()
{
return now_goal_;
}
void run()
{
robot_behavior_state_ = RobotBehaviors::INIT_NAV;
while(ros::ok()){
WayPoint next_waypoint = this->getNextWaypoint();
ROS_INFO("Next WayPoint is got");
if (next_waypoint.isSearchArea()) { // 次のwaypointが探索エリアがどうか判定
if(target_objects_.boxes.size() > 0){ // 探索対象が見つかっているか
for (int i = 0; i < target_objects_.boxes.size(); ++i) {
if (! this->isAlreadyApproachedToTargetObject(target_objects_.boxes[i])) { // 探索対象にまだアプローチしていなかったら
this->setNextGoal(target_objects_.boxes[i], dist_thres_to_target_object_); // 探索対象を次のゴールに設定
robot_behavior_state_ = RobotBehaviors::DETECT_TARGET_NAV;
break;
}
}
}else // 探索エリアだが探索対象がいない
{
ROS_INFO("Searching area but there are not target objects.");
this->setNextGoal(next_waypoint);
robot_behavior_state_ = RobotBehaviors::WAYPOINT_NAV;
}
}else // 探索エリアではない
{
ROS_INFO("Go next_waypoint.");
this->setNextGoal(next_waypoint);
robot_behavior_state_ = RobotBehaviors::WAYPOINT_NAV;
}
while(ros::ok())
{
geometry_msgs::Pose robot_current_position = this->getRobotCurrentPosition(); // 現在のロボットの座標
geometry_msgs::Pose now_goal_position = this->getNowGoalPosition(); // 現在目指している座標
double distance_to_goal = this->calculateDistance(robot_current_position,
now_goal_position);
// ROS_INFO_STREAM("dist : " << distance_to_goal);
// ROS_INFO_STREAM("thres: " << this->getReachThreshold());
// ここでスタック判定してもいいかもしれない。
// 一定時間進んでない、もしくは一定回数後も移動距離が変化していないなら
// ゴールをキャンセルして次のwaypointに進むとか?
if(distance_to_goal < this->getReachThreshold()) // 目標座標までの距離がしきい値になれば
{
robot_behavior_state_ = RobotBehaviors::REACHED_GOAL;
break;
}
rate_.sleep();
ros::spinOnce();
}
if (robot_behavior_state_ == RobotBehaviors::REACHED_GOAL) { //waypointか探索対象に到達してて
ROS_INFO("REACHED_GOAL");
if (this->isFinalGoal()) { // そのwaypointが最後だったら
this->cancelGoal(); // ゴールをキャンセルして終了
return;
}
}
rate_.sleep();
ros::spinOnce();
}// while(ros::ok())
}
private:
MoveBaseClient ac_;
RobotBehaviors::State robot_behavior_state_;
ros::Rate rate_;
std::vector<WayPoint> waypoints_;
ros::NodeHandle nh_;
tf::TransformListener listener_;
int target_waypoint_index_; // 次に目指すウェイポイントのインデックス
jsk_recognition_msgs::BoundingBoxArray target_objects_; //探索対象
jsk_recognition_msgs::BoundingBoxArray approached_target_objects_; //アプローチ済みの探索対象
double dist_thres_to_target_object_; // 探索対象にどれだけ近づいたらゴールとするか
double reach_threshold_; // 今セットされてるゴール(waypointもしくは探索対象)へのしきい値
geometry_msgs::Pose now_goal_; // 現在目指しているゴールの座標
};
int main(int argc, char** argv){
ros::init(argc, argv, "waypoint_navigator");
WaypointNavigator waypoint_navigator;
waypoint_navigator.run();
return 0;
}
<|endoftext|> |
<commit_before>/*
* FishersExact.cc
* Apto
*
* Created by David on 2/15/11.
* Copyright 2011 David Michael Bryson. All rights reserved.
* http://programerror.com/software/apto
*
* Redistribution and use in source and binary forms, with or without modification, are permitted provided that the
* following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the
* following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the
* following disclaimer in the documentation and/or other materials provided with the distribution.
* 3. Neither the name of David Michael Bryson, nor the names of contributors may be used to endorse or promote
* products derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY DAVID MICHAEL BRYSON 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 DAVID MICHAEL BRYSON OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
* USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* Authors: David M. Bryson <david@programerror.com>
*
*/
#include "apto/stat/ContingencyTable.h"
#include "apto/stat/Functions.h"
double Apto::Stat::FishersExact(const ContingencyTable& table)
{
}
<commit_msg>Implement a couple of support functions for FishersExact.<commit_after>/*
* FishersExact.cc
* Apto
*
* Created by David on 2/15/11.
* Copyright 2011 David Michael Bryson. All rights reserved.
* http://programerror.com/software/apto
*
* Redistribution and use in source and binary forms, with or without modification, are permitted provided that the
* following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the
* following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the
* following disclaimer in the documentation and/or other materials provided with the distribution.
* 3. Neither the name of David Michael Bryson, nor the names of contributors may be used to endorse or promote
* products derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY DAVID MICHAEL BRYSON 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 DAVID MICHAEL BRYSON OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
* USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* Authors: David M. Bryson <david@programerror.com>
*
*/
#include "apto/stat/ContingencyTable.h"
#include "apto/stat/Functions.h"
#include "apto/core/Array.h"
#include "apto/core/Pair.h"
#include <cmath>
#include <limits>
static struct PastPathLength {
double value;
int observed;
PastPathLength(double in_value) : value(in_value), observed(1) { ; }
};
static struct FExactNode
{
double shortest_path;
double longest_path;
Apto::Array<PastPathLength, Apto::Smart> past_entries;
};
static double cummulativeGamma(double q, double alpha, bool& fault);
static double logGamma(double x, bool& fault);
double Apto::Stat::FishersExact(const ContingencyTable& table)
{
if (table.MarginalTotal() == 0.0) return std::numeric_limits<double>::quiet_NaN(); // All elements are 0
return 0.0;
}
double cummulativeGamma(double q, double alpha, bool& fault)
{
if (q <= 0.0 || alpha <= 0.0) {
fault = true;
return 0.0;
}
double f = exp(alpha * log(q) - logGamma(alpha + 1.0, fault) - q); // no need to test logGamma fail as an error is impossible
if (f == 0.0) {
fault = true;
return 0.0;
}
fault = false;
double c = 1.0;
double ret_val = 1.0;
double a = alpha;
do {
a += 1.0;
c = c * q / a;
ret_val += c;
} while (c / ret_val > (1e-6));
ret_val *= f;
return ret_val;
}
double logGamma(double x, bool& fault)
{
const double a1 = .918938533204673;
const double a2 = 5.95238095238e-4;
const double a3 = 7.93650793651e-4;
const double a4 = .002777777777778;
const double a5 = .083333333333333;
if (x < 0.0) {
fault = true;
return 0.0;
}
fault = false;
double f = 0.0;
if (x < 7.0) {
f = x;
x += 1.0;
while (x < 7.0) {
f *= x;
x += 1.0;
}
f = -log(f);
}
double z = 1 / (x * x);
return f + (x - .5) * log(x) - x + a1 + (((-a2 * z + a3) * z - a4) * z + a5) / x;
}
<|endoftext|> |
<commit_before>/*
* Actuator.cc
*
* Author: Lunatic
*/
#include <cstring>
#include <cstdlib>
#include "actuator.h"
#include "lexer.h"
#include "alarm.h"
namespace Script {
bool Env::contains(const std::string& name) {
return vars.find(name) != vars.end();
}
std::string Env::get(const std::string& name) {
return vars.find(name)->second;
}
void Env::put(const std::string& name, const std::string& value) {
vars[name] = value;
}
//////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////
Actuator::Actuator(Parser& _parser) :
parser(_parser) {
}
Actuator::~Actuator() {
}
void Actuator::load() {
Instruction inst;
while (parser.has_next()) {
parser.next(inst);
if (inst.type == kLabel) {
std::map<std::string, size_t>::iterator it = labels.find(inst.name);
if (it == labels.end())
labels[inst.name] = insts.size();
} else
insts.push_back(inst);
}
}
/*
* 将Token转换为Instruction{type, name, params}
*
void Actuator::load(const std::string& script_code) {
Lexer lexer(script_code);
std::vector<Token> tokens;
while (!lexer.finish()) {
Log::info("新的一行");
Instruction inst;
tokens.clear();
for (;;) {
Token token;
int stat = lexer.next_token(token);
if (stat >= 0)
break;
Log::info(token.to_str());
tokens.push_back(token);
}
if (tokens.empty())
continue;
if (tokens[0].type != kName) {
error("语法错误load", tokens[0].pos);
}
inst.name = tokens[0].token;
inst.pos = tokens[0].pos;
if (tokens.size() == 1) {
inst.type = kInstruction;
} else if (tokens[1].type == kColon) {
inst.type = kLabel;
} else { //处理指令参数
inst.type = kInstruction;
for (size_t i = 1; i < tokens.size(); ++i) {
switch (tokens[i].type) {
case kInt:
case kReal:
case kString:
case kName:
case KCmp:
inst.params.push_back(tokens[i]);
break;
default:
Log::error("%zu", i);
Log::error(tokens[i].to_str());
error("参数不符合要求!", tokens[i].pos);
}
}
}
if (inst.type == kLabel) {
std::map<std::string, size_t>::iterator it = labels.find(inst.name);
if (it == labels.end())
labels[inst.name] = insts.size();
} else
insts.push_back(inst);
}
Log::info("加载完毕!");
}
*/
/*
* 如果是变量 存在则直接取出 否则报错 ?不太妥当
* 其他直接返回
*
*/
std::string get_val_or_var(Env& env, Token& token) {
if (token.type == kName) { //处理变量
if (env.contains(token.token)) {
return env.get(token.token);
} else
error("变量未定义" + token.token, token.pos); //?不太妥当
}
return token.token;
}
bool is_real(const std::string& number) {
return std::string::npos != number.find('.');
}
bool is_int(const std::string& number) {
return !is_real(number);
}
long long str2int(const std::string& val) {
//char *err = NULL;
//long long retval = std::strtoll(val.c_str(), &err, 10);
//if (*err == '\0')
//return retval;
//忽略错误
return std::strtoll(val.c_str(), NULL, 10);
}
long double str2double(const std::string& val) {
//char *err = NULL;
//long double retval = std::strtold(val.c_str(), &err);
//if (*err == '\0')
//return retval;
//else
//
//error!
//return 0.0;
return std::strtold(val.c_str(), NULL);
}
//3.3333
bool is_zero(const std::string& vfloat) {
bool left = true, right = true;
size_t start = 0, pos = vfloat.find('.');
if (pos == std::string::npos)
pos = vfloat.size();
while (start < pos) {
if (vfloat[start++] != '0') {
left = false;
}
}
while (++pos < vfloat.size()) {
if (vfloat[pos] != '0') {
right = false;
}
}
return left && right;
}
std::string eval(const std::string& cmd, const std::string& arg1,
const std::string& arg2, const Position& pos) {
#define EVAL(RES, X, Y, OP) \
do { \
if(is_real(X) || is_real(Y)) { \
RES << (str2double(X) OP str2double(Y)); \
} else { \
RES << (str2int(X) OP str2int(Y)); \
} \
}while(0) \
std::stringstream ss;
if (cmd == "add") { // +
EVAL(ss, arg1, arg2, +);
} else if (cmd == "min") { //-
EVAL(ss, arg1, arg2, -);
} else if (cmd == "mul") { // *
EVAL(ss, arg1, arg2, *);
} else if (cmd == "div") { // /
if (is_zero(arg2)) {
error("除数不能为0!", pos);
}
EVAL(ss, arg1, arg2, /);
}
return ss.str();
#undef EVAL
}
/*
*
* 依次处理指令
* exit
* goto
* set
*
*
*
*/
void Actuator::run(Env& env) {
for (size_t idx = 0; idx < insts.size(); /*++idx*/) {
Instruction& pc = insts[idx]; //模拟PC寄存器
Log::info(pc.to_str());
if (pc.name == "exit") {
if (pc.params.empty())
break;
else
error("exit不能有参数", pc.pos);
} else if (pc.name == "goto") {
if (pc.params.size() == 1 && pc.params[0].type == kName) {
//处理指令跳转
std::map<std::string, size_t>::iterator it = labels.find(
pc.params[0].token);
if (it == labels.end()) {
error("找不到带跳转位置", pc.pos);
} else {
idx = it->second; //更新到下一条指令
continue;
}
} else {
error("goto语句后面必须带有一个跳转Label", pc.pos);
}
} else if (pc.name == "mov") {
if (pc.params.size() == 2 && pc.params[0].type == kName) {
std::string val = get_val_or_var(env, pc.params[1]);
env.put(pc.params[0].token, val);
} else {
error("set语句必须是一个变量和一个对象参数", pc.pos);
}
} else if (pc.name == "add" || pc.name == "min" || pc.name == "mul"
|| pc.name == "div") {
//add a b 1 => a = b + 1
if (pc.params.size() == 3 && pc.params[0].type == kName) {
//把param1和param2求值 把结果放入param0为key结果为value的环境map中
std::string arg1 = get_val_or_var(env, pc.params[1]);
std::string arg2 = get_val_or_var(env, pc.params[2]);
env.put(pc.params[0].token, eval(pc.name, arg1, arg2, pc.params[2].pos));
} else {
error(pc.name + "命令需要一个变量和两个参数", pc.pos);
}
} else if (pc.name == "if") { //if value1 [opcode value2] goto label
bool jmp = false;
if (pc.params.size() == 5 && pc.params[1].type == KCmp) { //if val goto label
std::string left = get_val_or_var(env, pc.params[0]);
std::string right = get_val_or_var(env, pc.params[2]);
if (pc.params[1].token == "==") {
jmp = left == right;
} else if (pc.params[1].token == "!=") {
jmp = left != right;
} else if (pc.params[1].token == "<") {
jmp = str2double(left) < str2double(right);
} else if (pc.params[1].token == ">") {
jmp = str2double(left) > str2double(right);
} else if (pc.params[1].token == "<=") {
jmp = str2double(left) <= str2double(right);
} else if (pc.params[1].token == ">=") {
jmp = str2double(left) < str2double(right);
}
if (jmp && pc.params[3].type == kName
&& pc.params[3].token == "goto"
&& pc.params[4].type == kName) {
//处理指令跳转
std::map<std::string, size_t>::iterator it = labels.find(
pc.params[4].token);
if (it == labels.end()) {
error("找不到带跳转位置", pc.params[4].pos);
} else {
idx = it->second; //更新到下一条指令
continue;
}
} else if (jmp) {
error("goto语句后面必须带有一个跳转Label", pc.params[4].pos);
}
}
} else if (pc.name == "print") {
for (std::vector<Token>::iterator it = pc.params.begin();
it != pc.params.end(); ++it) {
if (it->type == kName) {
if (env.contains(it->token)) {
std::cout << env.get(it->token);
} else
error("变量未定义!", it->pos);
} else
std::cout << it->token;
std::cout << std::endl;
}
} else if (pc.name == "read") {
for (std::vector<Token>::iterator it = pc.params.begin();
it != pc.params.end(); ++it) {
if (it->type != kName) {
error("必须是变量!", it->pos);
}
std::string temp;
std::cin >> temp;
env.put(it->token, temp);
}
}
idx++;
}
}
} /* namespace Script */
<commit_msg>fix bug:处理无法识别的指令<commit_after>/*
* Actuator.cc
*
* Author: Lunatic
*/
#include <cstring>
#include <cstdlib>
#include "actuator.h"
#include "lexer.h"
#include "alarm.h"
namespace Script {
bool Env::contains(const std::string& name) {
return vars.find(name) != vars.end();
}
std::string Env::get(const std::string& name) {
return vars.find(name)->second;
}
void Env::put(const std::string& name, const std::string& value) {
vars[name] = value;
}
//////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////
Actuator::Actuator(Parser& _parser) :
parser(_parser) {
}
Actuator::~Actuator() {
}
void Actuator::load() {
while (parser.has_next()) {
Instruction inst;
parser.next(inst);
if (inst.type == kLabel) {
std::map<std::string, size_t>::iterator it = labels.find(inst.name);
if (it == labels.end())
labels[inst.name] = insts.size();
} else
insts.push_back(inst);
}
}
/*
* 将Token转换为Instruction{type, name, params}
*
void Actuator::load(const std::string& script_code) {
Lexer lexer(script_code);
std::vector<Token> tokens;
while (!lexer.finish()) {
Log::info("新的一行");
Instruction inst;
tokens.clear();
for (;;) {
Token token;
int stat = lexer.next_token(token);
if (stat >= 0)
break;
Log::info(token.to_str());
tokens.push_back(token);
}
if (tokens.empty())
continue;
if (tokens[0].type != kName) {
error("语法错误load", tokens[0].pos);
}
inst.name = tokens[0].token;
inst.pos = tokens[0].pos;
if (tokens.size() == 1) {
inst.type = kInstruction;
} else if (tokens[1].type == kColon) {
inst.type = kLabel;
} else { //处理指令参数
inst.type = kInstruction;
for (size_t i = 1; i < tokens.size(); ++i) {
switch (tokens[i].type) {
case kInt:
case kReal:
case kString:
case kName:
case KCmp:
inst.params.push_back(tokens[i]);
break;
default:
Log::error("%zu", i);
Log::error(tokens[i].to_str());
error("参数不符合要求!", tokens[i].pos);
}
}
}
if (inst.type == kLabel) {
std::map<std::string, size_t>::iterator it = labels.find(inst.name);
if (it == labels.end())
labels[inst.name] = insts.size();
} else
insts.push_back(inst);
}
Log::info("加载完毕!");
}
*/
/*
* 如果是变量 存在则直接取出 否则报错 ?不太妥当
* 其他直接返回
*
*/
std::string get_val_or_var(Env& env, Token& token) {
if (token.type == kName) { //处理变量
if (env.contains(token.token)) {
return env.get(token.token);
} else
error("变量未定义" + token.token, token.pos); //?不太妥当
}
return token.token;
}
bool is_real(const std::string& number) {
return std::string::npos != number.find('.');
}
bool is_int(const std::string& number) {
return !is_real(number);
}
long long str2int(const std::string& val) {
//char *err = NULL;
//long long retval = std::strtoll(val.c_str(), &err, 10);
//if (*err == '\0')
//return retval;
//忽略错误
return std::strtoll(val.c_str(), NULL, 10);
}
long double str2double(const std::string& val) {
//char *err = NULL;
//long double retval = std::strtold(val.c_str(), &err);
//if (*err == '\0')
//return retval;
//else
//
//error!
//return 0.0;
return std::strtold(val.c_str(), NULL);
}
//3.3333
bool is_zero(const std::string& vfloat) {
bool left = true, right = true;
size_t start = 0, pos = vfloat.find('.');
if (pos == std::string::npos)
pos = vfloat.size();
while (start < pos) {
if (vfloat[start++] != '0') {
left = false;
}
}
while (++pos < vfloat.size()) {
if (vfloat[pos] != '0') {
right = false;
}
}
return left && right;
}
std::string eval(const std::string& cmd, const std::string& arg1,
const std::string& arg2, const Position& pos) {
#define EVAL(RES, X, Y, OP) \
do { \
if(is_real(X) || is_real(Y)) { \
RES << (str2double(X) OP str2double(Y)); \
} else { \
RES << (str2int(X) OP str2int(Y)); \
} \
}while(0) \
std::stringstream ss;
if (cmd == "add") { // +
EVAL(ss, arg1, arg2, +);
} else if (cmd == "min") { //-
EVAL(ss, arg1, arg2, -);
} else if (cmd == "mul") { // *
EVAL(ss, arg1, arg2, *);
} else if (cmd == "div") { // /
if (is_zero(arg2)) {
error("除数不能为0!", pos);
}
EVAL(ss, arg1, arg2, /);
}
return ss.str();
#undef EVAL
}
/*
*
* 依次处理指令
* exit
* goto
* set
*
*
*
*/
void Actuator::run(Env& env) {
for (size_t idx = 0; idx < insts.size(); /*++idx*/) {
Instruction& pc = insts[idx]; //模拟PC寄存器
//Log::info(pc.to_str());
if (pc.name == "exit") {
if (pc.params.empty())
break;
else
error("exit不能有参数", pc.pos);
} else if (pc.name == "goto") {
if (pc.params.size() == 1 && pc.params[0].type == kName) {
//处理指令跳转
std::map<std::string, size_t>::iterator it = labels.find(
pc.params[0].token);
if (it == labels.end()) {
error("找不到带跳转位置", pc.pos);
} else {
idx = it->second; //更新到下一条指令
continue;
}
} else {
error("goto语句后面必须带有一个跳转Label", pc.pos);
}
} else if (pc.name == "mov") {
if (pc.params.size() == 2 && pc.params[0].type == kName) {
std::string val = get_val_or_var(env, pc.params[1]);
env.put(pc.params[0].token, val);
} else {
error("set语句必须是一个变量和一个对象参数", pc.pos);
}
} else if (pc.name == "add" || pc.name == "min" || pc.name == "mul"
|| pc.name == "div") {
//add a b 1 => a = b + 1
if (pc.params.size() == 3 && pc.params[0].type == kName) {
//把param1和param2求值 把结果放入param0为key结果为value的环境map中
std::string arg1 = get_val_or_var(env, pc.params[1]);
std::string arg2 = get_val_or_var(env, pc.params[2]);
env.put(pc.params[0].token, eval(pc.name, arg1, arg2, pc.params[2].pos));
} else {
error(pc.name + "命令需要一个变量和两个参数", pc.pos);
}
} else if (pc.name == "if") { //if value1 [opcode value2] goto label
bool jmp = false;
if (pc.params.size() == 5 && pc.params[1].type == KCmp) { //if val goto label
std::string left = get_val_or_var(env, pc.params[0]);
std::string right = get_val_or_var(env, pc.params[2]);
if (pc.params[1].token == "==") {
jmp = left == right;
} else if (pc.params[1].token == "!=") {
jmp = left != right;
} else if (pc.params[1].token == "<") {
jmp = str2double(left) < str2double(right);
} else if (pc.params[1].token == ">") {
jmp = str2double(left) > str2double(right);
} else if (pc.params[1].token == "<=") {
jmp = str2double(left) <= str2double(right);
} else if (pc.params[1].token == ">=") {
jmp = str2double(left) < str2double(right);
}
if (jmp && pc.params[3].type == kName
&& pc.params[3].token == "goto"
&& pc.params[4].type == kName) {
//处理指令跳转
std::map<std::string, size_t>::iterator it = labels.find(
pc.params[4].token);
if (it == labels.end()) {
error("找不到带跳转位置", pc.params[4].pos);
} else {
idx = it->second; //更新到下一条指令
continue;
}
} else if (jmp) {
error("goto语句后面必须带有一个跳转Label", pc.params[4].pos);
}
}
} else if (pc.name == "print") {
for (std::vector<Token>::iterator it = pc.params.begin();
it != pc.params.end(); ++it) {
if (it->type == kName) {
if (env.contains(it->token)) {
std::cout << env.get(it->token);
} else
error("变量未定义!", it->pos);
} else
std::cout << it->token;
std::cout << std::endl;
}
} else if (pc.name == "read") {
for (std::vector<Token>::iterator it = pc.params.begin();
it != pc.params.end(); ++it) {
if (it->type != kName) {
error("必须是变量!", it->pos);
}
std::string temp;
std::cin >> temp;
env.put(it->token, temp);
}
} else {
error("无法识别的指令", pc.pos);
}
idx++;
}
}
} /* namespace Script */
<|endoftext|> |
<commit_before>#include<iostream>
#include<algorithm>
#include<stdio.h>
using namespace std;
void twoSum(int *arr, unsigned int len, int sum){
sort(arr, arr+len);
int begin = 0, end = len-1;
while(begin < end){
long currSum = arr[begin] + arr[end];
if(currSum==sum){
cout << "begin val:" << arr[begin] << " end val:" << arr[end] << endl;
begin++;
end--;
}else{
if(currSum<sum)
begin++;
else
end --;
}
}
}
void threeSum(int *arr, int len){
sort(arr, arr+len);
int second,end,sum;
for(int first=0;first<len-2;first++){
second = first+1;
end=len-1;
while(second<end){
sum=arr[first]+arr[second]+arr[end];
if(sum==0){
cout << "first val:" << arr[first] << " second val:" << arr[second] << " three val:" << arr[end] << endl;
second++;
end--;
while(second<end && arr[second-1]==arr[second]) second++;
while(second<end && arr[end]==arr[end+1]) end--;
}else{
if(sum>0)
end--;
else
second++;
}
}
}
}
void fourSum(int *arr, int len){
sort(arr, arr+len);
int sum;
for(int i=0;i<len-3;i++){
for(int j=i+1;j<len-2;j++){
int k=j+1;
int h=len-1;
while(k<h){
sum=arr[i]+arr[j]+arr[k]+arr[h];
if(sum == 0){
printf("i:%d j:%d k:%d h:%d\n",arr[i],arr[j],arr[k],arr[h]);
k++;
h--;
while(k<h && arr[k-1] == arr[k]) k++;
while(k<h && arr[h] == arr[h+1]) h--;
}else{
if(sum>0)
h--;
else
k++;
}
}
}
}
}
int maxSub(int *arr, int len){
if(len<1) return 0;
int currSum=0,maxSum=arr[0];
for(int i=0;i<len;i++){
currSum=(arr[i]>currSum+arr[i])?arr[i]:currSum+arr[i];
maxSum=(maxSum>currSum)?maxSum:currSum;
}
return maxSum;
}
long long Fibonacci(unsigned int n){
int result[3] = {0, 1, 2};
if (n <= 2) return result[n];
return Fibonacci(n - 1) + Fibonacci(n - 2);
}
//1, 1, 2, 3, 5, 8, 13, 21..
int ClimbStairs(int n){
int dp[3] = { 1, 1 };
if (n < 2) return 1;
for (int i = 2; i <= n; i++){
dp[2] = dp[0] + dp[1];
dp[0] = dp[1];
dp[1] = dp[2];
}
return dp[2];
}
bool isOddNumber(int n){
return (n&0x01)==0x01;
}
void oddEvenSort(int *arr, unsigned int len){
if(arr == NULL || len == 0) return;
int *begin = arr;
int *end = arr+len-1;
while(begin<end){
while(isOddNumber(*begin)) begin++;
while(!isOddNumber(*end)) end--;
if(begin<end){
*begin^=*end;
*end^=*begin;
*begin^=*end;
}
begin++;
end--;
}
}
void dutchFlag(int *arr, int len){
int *begin=arr;
int *cur=arr;
int *end=arr+len-1;
while(cur<=end){
if(*cur==0){
if(*cur!=*begin){
*cur^=*begin;
*begin^=*cur;
*cur^=*begin;
}
cur++;
begin++;
}else if(*cur==1){
cur++;
}else{
if(*cur!=*end){
*cur^=*end;
*end^=*cur;
*cur^=*end;
}
end--;
}
}
}
bool isEqual(int a, int b){
return ((a|b)&b) == a;
}
int main(){
int arr[10] = {-20,-18,-15,17,10,16,8,13,5,7};
// twoSum(arr, 10, 20);
//threeSum(arr, 10);
//fourSum(arr, 10);
//cout << "maxSub:" << maxSub(arr,10) << endl;
//cout << "Fibonacci(5):" << Fibonacci(5) << endl;
//cout << "ClimbStairs(5):" << ClimbStairs(5) << endl;
//oddEvenSort(arr,10);
srand(time(0));
for(int i=0;i<20;i++){
for(int j=0;j<10;j++) arr[j]=rand()%3;
dutchFlag(arr, 10);
for(int i=0;i<10;i++) cout << arr[i] << " ";
cout << endl;
}
//cout << "====:" << isEqual(10,110) << endl;
return 0;
}
<commit_msg>array find one number times<commit_after>#include<iostream>
#include<algorithm>
#include<stdio.h>
using namespace std;
void twoSum(int *arr, unsigned int len, int sum){
sort(arr, arr+len);
int begin = 0, end = len-1;
while(begin < end){
long currSum = arr[begin] + arr[end];
if(currSum==sum){
cout << "begin val:" << arr[begin] << " end val:" << arr[end] << endl;
begin++;
end--;
}else{
if(currSum<sum)
begin++;
else
end --;
}
}
}
void threeSum(int *arr, int len){
sort(arr, arr+len);
int second,end,sum;
for(int first=0;first<len-2;first++){
second = first+1;
end=len-1;
while(second<end){
sum=arr[first]+arr[second]+arr[end];
if(sum==0){
cout << "first val:" << arr[first] << " second val:" << arr[second] << " three val:" << arr[end] << endl;
second++;
end--;
while(second<end && arr[second-1]==arr[second]) second++;
while(second<end && arr[end]==arr[end+1]) end--;
}else{
if(sum>0)
end--;
else
second++;
}
}
}
}
void fourSum(int *arr, int len){
sort(arr, arr+len);
int sum;
for(int i=0;i<len-3;i++){
for(int j=i+1;j<len-2;j++){
int k=j+1;
int h=len-1;
while(k<h){
sum=arr[i]+arr[j]+arr[k]+arr[h];
if(sum == 0){
printf("i:%d j:%d k:%d h:%d\n",arr[i],arr[j],arr[k],arr[h]);
k++;
h--;
while(k<h && arr[k-1] == arr[k]) k++;
while(k<h && arr[h] == arr[h+1]) h--;
}else{
if(sum>0)
h--;
else
k++;
}
}
}
}
}
int maxSub(int *arr, int len){
if(len<1) return 0;
int currSum=0,maxSum=arr[0];
for(int i=0;i<len;i++){
currSum=(arr[i]>currSum+arr[i])?arr[i]:currSum+arr[i];
maxSum=(maxSum>currSum)?maxSum:currSum;
}
return maxSum;
}
long long Fibonacci(unsigned int n){
int result[3] = {0, 1, 2};
if (n <= 2) return result[n];
return Fibonacci(n - 1) + Fibonacci(n - 2);
}
//1, 1, 2, 3, 5, 8, 13, 21..
int ClimbStairs(int n){
int dp[3] = { 1, 1 };
if (n < 2) return 1;
for (int i = 2; i <= n; i++){
dp[2] = dp[0] + dp[1];
dp[0] = dp[1];
dp[1] = dp[2];
}
return dp[2];
}
bool isOddNumber(int n){
return (n&0x01)==0x01;
}
void oddEvenSort(int *arr, unsigned int len){
if(arr == NULL || len == 0) return;
int *begin = arr;
int *end = arr+len-1;
while(begin<end){
while(isOddNumber(*begin)) begin++;
while(!isOddNumber(*end)) end--;
if(begin<end){
*begin^=*end;
*end^=*begin;
*begin^=*end;
}
begin++;
end--;
}
}
void dutchFlag(int *arr, int len){
int *begin=arr;
int *cur=arr;
int *end=arr+len-1;
while(cur<=end){
if(*cur==0){
if(*cur!=*begin){
*cur^=*begin;
*begin^=*cur;
*cur^=*begin;
}
cur++;
begin++;
}else if(*cur==1){
cur++;
}else{
if(*cur!=*end){
*cur^=*end;
*end^=*cur;
*cur^=*end;
}
end--;
}
}
}
bool isEqual(int a, int b){
return ((a|b)&b) == a;
}
// 查找出现次数超过数组长度一半的数
int findOneNumber(int *arr, int n){
int candidate=arr[0], nTimes=1;
for(int i=1;i<n;i++){
if(candidate!=arr[i]){
if(nTimes>0){
nTimes--;
}else {
candidate=arr[i];
nTimes=1;
}
}else{
nTimes++;
}
}
return candidate;
}
int main(){
int arr[10] = {-20,-18,-15,17,10,16,8,13,5,7};
// twoSum(arr, 10, 20);
//threeSum(arr, 10);
//fourSum(arr, 10);
//cout << "maxSub:" << maxSub(arr,10) << endl;
//cout << "Fibonacci(5):" << Fibonacci(5) << endl;
//cout << "ClimbStairs(5):" << ClimbStairs(5) << endl;
//oddEvenSort(arr,10);
srand(time(0));
for(int i=0;i<20;i++){
for(int j=0;j<10;j++) arr[j]=rand()%3;
dutchFlag(arr, 10);
for(int i=0;i<10;i++) cout << arr[i] << " ";
cout << endl;
}
//cout << "====:" << isEqual(10,110) << endl;
return 0;
}
<|endoftext|> |
<commit_before>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// Note that the single accessor, Module::Get(), is not actually implemented
// in this file. This is an intentional hook that allows users of ppapi's
// C++ wrapper objects to provide difference semantics for how the singleton
// object is accessed.
//
// In general, users of ppapi will also link in ppp_entrypoints.cc, which
// provides a simple default implementation of Module::Get().
//
// A notable exception where the default ppp_entrypoints will not work is
// when implementing "internal plugins" that are statically linked into the
// browser. In this case, the process may actually have multiple Modules
// loaded at once making a traditional "singleton" unworkable. To get around
// this, the users of ppapi need to get creative about how to properly
// implement the Module::Get() so that ppapi's C++ wrappers can find the
// right Module object. One example solution is to use thread local storage
// to change the Module* returned based on which thread is invoking the
// function. Leaving Module::Get() unimplemented provides a hook for
// implementing such behavior.
#include "ppapi/cpp/module.h"
#include <string.h>
#include "ppapi/c/pp_instance.h"
#include "ppapi/c/pp_var.h"
#include "ppapi/c/ppp_instance.h"
#include "ppapi/c/ppp_printing.h"
#include "ppapi/c/ppp_scrollbar.h"
#include "ppapi/c/ppp_widget.h"
#include "ppapi/cpp/instance.h"
#include "ppapi/cpp/resource.h"
#include "ppapi/cpp/scrollbar.h"
#include "ppapi/cpp/url_loader.h"
#include "ppapi/cpp/var.h"
#include "ppapi/cpp/widget.h"
namespace pp {
// PPP_Instance implementation -------------------------------------------------
bool Instance_New(PP_Instance instance) {
Module* module_singleton = Module::Get();
if (!module_singleton)
return false;
Instance* obj = module_singleton->CreateInstance(instance);
if (obj) {
module_singleton->current_instances_[instance] = obj;
return true;
}
return false;
}
void Instance_Delete(PP_Instance instance) {
Module* module_singleton = Module::Get();
if (!module_singleton)
return;
Module::InstanceMap::iterator found =
module_singleton->current_instances_.find(instance);
if (found == module_singleton->current_instances_.end())
return;
// Remove it from the map before deleting to try to catch reentrancy.
Instance* obj = found->second;
module_singleton->current_instances_.erase(found);
delete obj;
}
bool Instance_Initialize(PP_Instance pp_instance,
uint32_t argc,
const char* argn[],
const char* argv[]) {
Module* module_singleton = Module::Get();
if (!module_singleton)
return false;
Instance* instance = module_singleton->InstanceForPPInstance(pp_instance);
if (!instance)
return false;
return instance->Init(argc, argn, argv);
}
bool Instance_HandleDocumentLoad(PP_Instance pp_instance,
PP_Resource pp_url_loader) {
Module* module_singleton = Module::Get();
if (!module_singleton)
return false;
Instance* instance = module_singleton->InstanceForPPInstance(pp_instance);
if (!instance)
return false;
return instance->HandleDocumentLoad(URLLoader(pp_url_loader));
}
bool Instance_HandleEvent(PP_Instance pp_instance,
const PP_Event* event) {
Module* module_singleton = Module::Get();
if (!module_singleton)
return false;
Instance* instance = module_singleton->InstanceForPPInstance(pp_instance);
if (!instance)
return false;
return instance->HandleEvent(*event);
}
PP_Var Instance_GetInstanceObject(PP_Instance pp_instance) {
Module* module_singleton = Module::Get();
if (!module_singleton)
return Var().Detach();
Instance* instance = module_singleton->InstanceForPPInstance(pp_instance);
if (!instance)
return Var().Detach();
return instance->GetInstanceObject().Detach();
}
void Instance_ViewChanged(PP_Instance pp_instance,
const PP_Rect* position,
const PP_Rect* clip) {
Module* module_singleton = Module::Get();
if (!module_singleton)
return;
Instance* instance = module_singleton->InstanceForPPInstance(pp_instance);
if (!instance)
return;
instance->ViewChanged(*position, *clip);
}
static PPP_Instance instance_interface = {
&Instance_New,
&Instance_Delete,
&Instance_Initialize,
&Instance_HandleDocumentLoad,
&Instance_HandleEvent,
&Instance_GetInstanceObject,
&Instance_ViewChanged,
};
// PPP_Printing implementation -------------------------------------------------
const PP_PrintOutputFormat* Printing_QuerySupportedFormats(
uint32_t* format_count) {
Module* module_singleton = Module::Get();
if (!module_singleton) {
*format_count = 0;
return NULL;
}
return module_singleton->QuerySupportedPrintOutputFormats(format_count);
}
int32_t Printing_Begin(PP_Instance pp_instance,
const PP_PrintSettings* print_settings) {
Module* module_singleton = Module::Get();
if (!module_singleton)
return 0;
Instance* instance = module_singleton->InstanceForPPInstance(pp_instance);
if (!instance)
return 0;
// See if we support the specified print output format.
uint32_t format_count = 0;
const PP_PrintOutputFormat* formats =
module_singleton->QuerySupportedPrintOutputFormats(&format_count);
if (!formats)
return 0;
for (uint32_t index = 0; index < format_count; index++) {
if (formats[index] == print_settings->format)
return instance->PrintBegin(*print_settings);
}
return 0;
}
PP_Resource Printing_PrintPages(PP_Instance pp_instance,
const PP_PrintPageNumberRange* page_ranges,
uint32_t page_range_count) {
Module* module_singleton = Module::Get();
if (!module_singleton)
return Resource().pp_resource();
Instance* instance = module_singleton->InstanceForPPInstance(pp_instance);
if (!instance)
return Resource().pp_resource();
return instance->PrintPages(page_ranges, page_range_count).pp_resource();
}
void Printing_End(PP_Instance pp_instance) {
Module* module_singleton = Module::Get();
if (!module_singleton)
return;
Instance* instance = module_singleton->InstanceForPPInstance(pp_instance);
if (!instance)
return;
return instance->PrintEnd();
}
static PPP_Printing printing_interface = {
&Printing_QuerySupportedFormats,
&Printing_Begin,
&Printing_PrintPages,
&Printing_End,
};
// PPP_Widget implementation ---------------------------------------------------
void Widget_Invalidate(PP_Instance instance_id,
PP_Resource widget_id,
const PP_Rect* dirty_rect) {
Module* module_singleton = Module::Get();
if (!module_singleton)
return;
Instance* instance = module_singleton->InstanceForPPInstance(instance_id);
if (!instance)
return;
return instance->InvalidateWidget(widget_id, *dirty_rect);
}
static PPP_Widget widget_interface = {
&Widget_Invalidate,
};
// PPP_Scrollbar implementation ------------------------------------------------
void Scrollbar_ValueChanged(PP_Instance instance_id,
PP_Resource scrollbar_id,
uint32_t value) {
Module* module_singleton = Module::Get();
if (!module_singleton)
return;
Instance* instance = module_singleton->InstanceForPPInstance(instance_id);
if (!instance)
return;
return instance->ScrollbarValueChanged(scrollbar_id, value);
}
static PPP_Scrollbar scrollbar_interface = {
&Scrollbar_ValueChanged,
};
// Module ----------------------------------------------------------------------
Module::Module() : pp_module_(NULL), get_browser_interface_(NULL), core_(NULL) {
}
Module::~Module() {
delete core_;
core_ = NULL;
}
const void* Module::GetInstanceInterface(const char* interface_name) {
if (strcmp(interface_name, PPP_INSTANCE_INTERFACE) == 0)
return &instance_interface;
if (strcmp(interface_name, PPP_PRINTING_INTERFACE) == 0)
return &printing_interface;
if (strcmp(interface_name, PPP_WIDGET_INTERFACE) == 0)
return &widget_interface;
if (strcmp(interface_name, PPP_SCROLLBAR_INTERFACE) == 0)
return &scrollbar_interface;
return NULL;
}
const void* Module::GetBrowserInterface(const char* interface_name) {
return get_browser_interface_(interface_name);
}
Instance* Module::InstanceForPPInstance(PP_Instance instance) {
InstanceMap::iterator found = current_instances_.find(instance);
if (found == current_instances_.end())
return NULL;
return found->second;
}
bool Module::InternalInit(PP_Module mod,
PPB_GetInterface get_browser_interface) {
pp_module_ = mod;
get_browser_interface_ = get_browser_interface;
// Get the core interface which we require to run.
const PPB_Core* core = reinterpret_cast<const PPB_Core*>(GetBrowserInterface(
PPB_CORE_INTERFACE));
if (!core)
return false;
core_ = new Core(core);
return Init();
}
} // namespace pp
<commit_msg>Add missing include<commit_after>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// Note that the single accessor, Module::Get(), is not actually implemented
// in this file. This is an intentional hook that allows users of ppapi's
// C++ wrapper objects to provide difference semantics for how the singleton
// object is accessed.
//
// In general, users of ppapi will also link in ppp_entrypoints.cc, which
// provides a simple default implementation of Module::Get().
//
// A notable exception where the default ppp_entrypoints will not work is
// when implementing "internal plugins" that are statically linked into the
// browser. In this case, the process may actually have multiple Modules
// loaded at once making a traditional "singleton" unworkable. To get around
// this, the users of ppapi need to get creative about how to properly
// implement the Module::Get() so that ppapi's C++ wrappers can find the
// right Module object. One example solution is to use thread local storage
// to change the Module* returned based on which thread is invoking the
// function. Leaving Module::Get() unimplemented provides a hook for
// implementing such behavior.
#include "ppapi/cpp/module.h"
#include <string.h>
#include "ppapi/c/pp_instance.h"
#include "ppapi/c/pp_var.h"
#include "ppapi/c/ppp_instance.h"
#include "ppapi/c/ppp_printing.h"
#include "ppapi/c/ppp_scrollbar.h"
#include "ppapi/c/ppp_widget.h"
#include "ppapi/cpp/instance.h"
#include "ppapi/cpp/rect.h"
#include "ppapi/cpp/resource.h"
#include "ppapi/cpp/scrollbar.h"
#include "ppapi/cpp/url_loader.h"
#include "ppapi/cpp/var.h"
#include "ppapi/cpp/widget.h"
namespace pp {
// PPP_Instance implementation -------------------------------------------------
bool Instance_New(PP_Instance instance) {
Module* module_singleton = Module::Get();
if (!module_singleton)
return false;
Instance* obj = module_singleton->CreateInstance(instance);
if (obj) {
module_singleton->current_instances_[instance] = obj;
return true;
}
return false;
}
void Instance_Delete(PP_Instance instance) {
Module* module_singleton = Module::Get();
if (!module_singleton)
return;
Module::InstanceMap::iterator found =
module_singleton->current_instances_.find(instance);
if (found == module_singleton->current_instances_.end())
return;
// Remove it from the map before deleting to try to catch reentrancy.
Instance* obj = found->second;
module_singleton->current_instances_.erase(found);
delete obj;
}
bool Instance_Initialize(PP_Instance pp_instance,
uint32_t argc,
const char* argn[],
const char* argv[]) {
Module* module_singleton = Module::Get();
if (!module_singleton)
return false;
Instance* instance = module_singleton->InstanceForPPInstance(pp_instance);
if (!instance)
return false;
return instance->Init(argc, argn, argv);
}
bool Instance_HandleDocumentLoad(PP_Instance pp_instance,
PP_Resource pp_url_loader) {
Module* module_singleton = Module::Get();
if (!module_singleton)
return false;
Instance* instance = module_singleton->InstanceForPPInstance(pp_instance);
if (!instance)
return false;
return instance->HandleDocumentLoad(URLLoader(pp_url_loader));
}
bool Instance_HandleEvent(PP_Instance pp_instance,
const PP_Event* event) {
Module* module_singleton = Module::Get();
if (!module_singleton)
return false;
Instance* instance = module_singleton->InstanceForPPInstance(pp_instance);
if (!instance)
return false;
return instance->HandleEvent(*event);
}
PP_Var Instance_GetInstanceObject(PP_Instance pp_instance) {
Module* module_singleton = Module::Get();
if (!module_singleton)
return Var().Detach();
Instance* instance = module_singleton->InstanceForPPInstance(pp_instance);
if (!instance)
return Var().Detach();
return instance->GetInstanceObject().Detach();
}
void Instance_ViewChanged(PP_Instance pp_instance,
const PP_Rect* position,
const PP_Rect* clip) {
Module* module_singleton = Module::Get();
if (!module_singleton)
return;
Instance* instance = module_singleton->InstanceForPPInstance(pp_instance);
if (!instance)
return;
instance->ViewChanged(*position, *clip);
}
static PPP_Instance instance_interface = {
&Instance_New,
&Instance_Delete,
&Instance_Initialize,
&Instance_HandleDocumentLoad,
&Instance_HandleEvent,
&Instance_GetInstanceObject,
&Instance_ViewChanged,
};
// PPP_Printing implementation -------------------------------------------------
const PP_PrintOutputFormat* Printing_QuerySupportedFormats(
uint32_t* format_count) {
Module* module_singleton = Module::Get();
if (!module_singleton) {
*format_count = 0;
return NULL;
}
return module_singleton->QuerySupportedPrintOutputFormats(format_count);
}
int32_t Printing_Begin(PP_Instance pp_instance,
const PP_PrintSettings* print_settings) {
Module* module_singleton = Module::Get();
if (!module_singleton)
return 0;
Instance* instance = module_singleton->InstanceForPPInstance(pp_instance);
if (!instance)
return 0;
// See if we support the specified print output format.
uint32_t format_count = 0;
const PP_PrintOutputFormat* formats =
module_singleton->QuerySupportedPrintOutputFormats(&format_count);
if (!formats)
return 0;
for (uint32_t index = 0; index < format_count; index++) {
if (formats[index] == print_settings->format)
return instance->PrintBegin(*print_settings);
}
return 0;
}
PP_Resource Printing_PrintPages(PP_Instance pp_instance,
const PP_PrintPageNumberRange* page_ranges,
uint32_t page_range_count) {
Module* module_singleton = Module::Get();
if (!module_singleton)
return Resource().pp_resource();
Instance* instance = module_singleton->InstanceForPPInstance(pp_instance);
if (!instance)
return Resource().pp_resource();
return instance->PrintPages(page_ranges, page_range_count).pp_resource();
}
void Printing_End(PP_Instance pp_instance) {
Module* module_singleton = Module::Get();
if (!module_singleton)
return;
Instance* instance = module_singleton->InstanceForPPInstance(pp_instance);
if (!instance)
return;
return instance->PrintEnd();
}
static PPP_Printing printing_interface = {
&Printing_QuerySupportedFormats,
&Printing_Begin,
&Printing_PrintPages,
&Printing_End,
};
// PPP_Widget implementation ---------------------------------------------------
void Widget_Invalidate(PP_Instance instance_id,
PP_Resource widget_id,
const PP_Rect* dirty_rect) {
Module* module_singleton = Module::Get();
if (!module_singleton)
return;
Instance* instance = module_singleton->InstanceForPPInstance(instance_id);
if (!instance)
return;
return instance->InvalidateWidget(widget_id, *dirty_rect);
}
static PPP_Widget widget_interface = {
&Widget_Invalidate,
};
// PPP_Scrollbar implementation ------------------------------------------------
void Scrollbar_ValueChanged(PP_Instance instance_id,
PP_Resource scrollbar_id,
uint32_t value) {
Module* module_singleton = Module::Get();
if (!module_singleton)
return;
Instance* instance = module_singleton->InstanceForPPInstance(instance_id);
if (!instance)
return;
return instance->ScrollbarValueChanged(scrollbar_id, value);
}
static PPP_Scrollbar scrollbar_interface = {
&Scrollbar_ValueChanged,
};
// Module ----------------------------------------------------------------------
Module::Module() : pp_module_(NULL), get_browser_interface_(NULL), core_(NULL) {
}
Module::~Module() {
delete core_;
core_ = NULL;
}
const void* Module::GetInstanceInterface(const char* interface_name) {
if (strcmp(interface_name, PPP_INSTANCE_INTERFACE) == 0)
return &instance_interface;
if (strcmp(interface_name, PPP_PRINTING_INTERFACE) == 0)
return &printing_interface;
if (strcmp(interface_name, PPP_WIDGET_INTERFACE) == 0)
return &widget_interface;
if (strcmp(interface_name, PPP_SCROLLBAR_INTERFACE) == 0)
return &scrollbar_interface;
return NULL;
}
const void* Module::GetBrowserInterface(const char* interface_name) {
return get_browser_interface_(interface_name);
}
Instance* Module::InstanceForPPInstance(PP_Instance instance) {
InstanceMap::iterator found = current_instances_.find(instance);
if (found == current_instances_.end())
return NULL;
return found->second;
}
bool Module::InternalInit(PP_Module mod,
PPB_GetInterface get_browser_interface) {
pp_module_ = mod;
get_browser_interface_ = get_browser_interface;
// Get the core interface which we require to run.
const PPB_Core* core = reinterpret_cast<const PPB_Core*>(GetBrowserInterface(
PPB_CORE_INTERFACE));
if (!core)
return false;
core_ = new Core(core);
return Init();
}
} // namespace pp
<|endoftext|> |
<commit_before>/////////////////////////////////////////////////////////////////////////
// $Id$
/////////////////////////////////////////////////////////////////////////
//
// Copyright (c) 2007 Stanislav Shwartsman
// Written by Stanislav Shwartsman [sshwarts at sourceforge net]
//
// 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 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 B 02110-1301 USA
//
/////////////////////////////////////////////////////////////////////////
#define NEED_CPU_REG_SHORTCUTS 1
#include "bochs.h"
#include "cpu.h"
#define LOG_THIS BX_CPU_THIS_PTR
bxPageWriteStampTable pageWriteStampTable;
void flushICaches(void)
{
for (unsigned i=0; i<BX_SMP_PROCESSORS; i++) {
BX_CPU(i)->iCache.flushICacheEntries();
BX_CPU(i)->invalidate_prefetch_q();
#if BX_SUPPORT_TRACE_CACHE
BX_CPU(i)->async_event |= BX_ASYNC_EVENT_STOP_TRACE;
#endif
}
pageWriteStampTable.resetWriteStamps();
}
void purgeICaches(void)
{
flushICaches();
}
#if BX_SUPPORT_TRACE_CACHE
void handleSMC(void)
{
for (unsigned i=0; i<BX_SMP_PROCESSORS; i++)
BX_CPU(i)->async_event |= BX_ASYNC_EVENT_STOP_TRACE;
}
void BX_CPU_C::serveICacheMiss(bxICacheEntry_c *cache_entry, Bit32u eipBiased, bx_phy_address pAddr)
{
BX_CPU_THIS_PTR iCache.alloc_trace(cache_entry);
// Cache miss. We weren't so lucky, but let's be optimistic - try to build
// trace from incoming instruction bytes stream !
cache_entry->pAddr = pAddr;
cache_entry->writeStamp = *(BX_CPU_THIS_PTR currPageWriteStampPtr);
unsigned remainingInPage = BX_CPU_THIS_PTR eipPageWindowSize - eipBiased;
const Bit8u *fetchPtr = BX_CPU_THIS_PTR eipFetchPtr + eipBiased;
unsigned ret;
bxInstruction_c *i = cache_entry->i;
for (unsigned n=0;n<BX_MAX_TRACE_LENGTH;n++)
{
#if BX_SUPPORT_X86_64
if (BX_CPU_THIS_PTR cpu_mode == BX_MODE_LONG_64)
ret = fetchDecode64(fetchPtr, i, remainingInPage);
else
#endif
ret = fetchDecode32(fetchPtr, i, remainingInPage);
if (ret==0) {
// Fetching instruction on segment/page boundary
if (n > 0) {
// The trace is already valid, it has several instructions inside,
// in this case just drop the boundary instruction and stop
// tracing.
break;
}
// First instruction is boundary fetch, leave the trace cache entry
// invalid and do not cache the instruction.
cache_entry->writeStamp = ICacheWriteStampInvalid;
cache_entry->ilen = 1;
boundaryFetch(fetchPtr, remainingInPage, i);
return;
}
// add instruction to the trace
unsigned iLen = i->ilen();
cache_entry->ilen++;
// continue to the next instruction
remainingInPage -= iLen;
if (i->getStopTraceAttr() || remainingInPage == 0) break;
pAddr += iLen;
fetchPtr += iLen;
i++;
// try to find a trace starting from current pAddr and merge
if (mergeTraces(cache_entry, i, pAddr)) break;
}
BX_CPU_THIS_PTR iCache.commit_trace(cache_entry->ilen);
}
bx_bool BX_CPU_C::mergeTraces(bxICacheEntry_c *entry, bxInstruction_c *i, bx_phy_address pAddr)
{
bxICacheEntry_c *e = BX_CPU_THIS_PTR iCache.get_entry(pAddr, BX_CPU_THIS_PTR fetchModeMask);
if ((e->pAddr == pAddr) && (e->writeStamp == entry->writeStamp))
{
// determine max amount of instruction to take from another entry
unsigned max_length = e->ilen;
if (max_length + entry->ilen > BX_MAX_TRACE_LENGTH)
max_length = BX_MAX_TRACE_LENGTH - entry->ilen;
if(max_length == 0) return 0;
memcpy(i, e->i, sizeof(bxInstruction_c)*max_length);
entry->ilen += max_length;
BX_ASSERT(entry->ilen <= BX_MAX_TRACE_LENGTH);
return 1;
}
return 0;
}
#else // BX_SUPPORT_TRACE_CACHE == 0
bx_bool BX_CPU_C::fetchInstruction(bxInstruction_c *iStorage, Bit32u eipBiased)
{
unsigned remainingInPage = BX_CPU_THIS_PTR eipPageWindowSize - eipBiased;
const Bit8u *fetchPtr = BX_CPU_THIS_PTR eipFetchPtr + eipBiased;
unsigned ret;
#if BX_SUPPORT_X86_64
if (BX_CPU_THIS_PTR cpu_mode == BX_MODE_LONG_64)
ret = fetchDecode64(fetchPtr, iStorage, remainingInPage);
else
#endif
ret = fetchDecode32(fetchPtr, iStorage, remainingInPage);
if (ret==0) {
// handle instrumentation callback inside boundaryFetch
boundaryFetch(fetchPtr, remainingInPage, iStorage);
return 0;
}
#if BX_INSTRUMENTATION
BX_INSTR_OPCODE(BX_CPU_ID, fetchPtr, iStorage->ilen(),
BX_CPU_THIS_PTR sregs[BX_SEG_REG_CS].cache.u.segment.d_b, Is64BitMode());
#endif
return 1;
}
void BX_CPU_C::serveICacheMiss(bxICacheEntry_c *cache_entry, Bit32u eipBiased, bx_phy_address pAddr)
{
// The entry will be marked valid if fetchdecode will succeed
cache_entry->writeStamp = ICacheWriteStampInvalid;
if (fetchInstruction(cache_entry->i, eipBiased)) {
cache_entry->pAddr = pAddr;
cache_entry->writeStamp = *(BX_CPU_THIS_PTR currPageWriteStampPtr);
}
}
#endif
<commit_msg>Fix SMC detection optimization<commit_after>/////////////////////////////////////////////////////////////////////////
// $Id$
/////////////////////////////////////////////////////////////////////////
//
// Copyright (c) 2007 Stanislav Shwartsman
// Written by Stanislav Shwartsman [sshwarts at sourceforge net]
//
// 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 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 B 02110-1301 USA
//
/////////////////////////////////////////////////////////////////////////
#define NEED_CPU_REG_SHORTCUTS 1
#include "bochs.h"
#include "cpu.h"
#define LOG_THIS BX_CPU_THIS_PTR
bxPageWriteStampTable pageWriteStampTable;
void flushICaches(void)
{
for (unsigned i=0; i<BX_SMP_PROCESSORS; i++) {
BX_CPU(i)->iCache.flushICacheEntries();
BX_CPU(i)->invalidate_prefetch_q();
#if BX_SUPPORT_TRACE_CACHE
BX_CPU(i)->async_event |= BX_ASYNC_EVENT_STOP_TRACE;
#endif
}
pageWriteStampTable.resetWriteStamps();
}
void purgeICaches(void)
{
flushICaches();
}
#if BX_SUPPORT_TRACE_CACHE
void handleSMC(void)
{
for (unsigned i=0; i<BX_SMP_PROCESSORS; i++)
BX_CPU(i)->async_event |= BX_ASYNC_EVENT_STOP_TRACE;
}
void BX_CPU_C::serveICacheMiss(bxICacheEntry_c *cache_entry, Bit32u eipBiased, bx_phy_address pAddr)
{
BX_CPU_THIS_PTR iCache.alloc_trace(cache_entry);
// Cache miss. We weren't so lucky, but let's be optimistic - try to build
// trace from incoming instruction bytes stream !
cache_entry->pAddr = pAddr;
pageWriteStampTable.markICache(pAddr);
cache_entry->writeStamp = *(BX_CPU_THIS_PTR currPageWriteStampPtr);
unsigned remainingInPage = BX_CPU_THIS_PTR eipPageWindowSize - eipBiased;
const Bit8u *fetchPtr = BX_CPU_THIS_PTR eipFetchPtr + eipBiased;
unsigned ret;
bxInstruction_c *i = cache_entry->i;
for (unsigned n=0;n<BX_MAX_TRACE_LENGTH;n++)
{
#if BX_SUPPORT_X86_64
if (BX_CPU_THIS_PTR cpu_mode == BX_MODE_LONG_64)
ret = fetchDecode64(fetchPtr, i, remainingInPage);
else
#endif
ret = fetchDecode32(fetchPtr, i, remainingInPage);
if (ret==0) {
// Fetching instruction on segment/page boundary
if (n > 0) {
// The trace is already valid, it has several instructions inside,
// in this case just drop the boundary instruction and stop
// tracing.
break;
}
// First instruction is boundary fetch, leave the trace cache entry
// invalid and do not cache the instruction.
cache_entry->writeStamp = ICacheWriteStampInvalid;
cache_entry->ilen = 1;
boundaryFetch(fetchPtr, remainingInPage, i);
return;
}
// add instruction to the trace
unsigned iLen = i->ilen();
cache_entry->ilen++;
// continue to the next instruction
remainingInPage -= iLen;
if (i->getStopTraceAttr() || remainingInPage == 0) break;
pAddr += iLen;
fetchPtr += iLen;
i++;
// try to find a trace starting from current pAddr and merge
if (mergeTraces(cache_entry, i, pAddr)) break;
}
BX_CPU_THIS_PTR iCache.commit_trace(cache_entry->ilen);
}
bx_bool BX_CPU_C::mergeTraces(bxICacheEntry_c *entry, bxInstruction_c *i, bx_phy_address pAddr)
{
bxICacheEntry_c *e = BX_CPU_THIS_PTR iCache.get_entry(pAddr, BX_CPU_THIS_PTR fetchModeMask);
if ((e->pAddr == pAddr) && (e->writeStamp == entry->writeStamp))
{
// determine max amount of instruction to take from another entry
unsigned max_length = e->ilen;
if (max_length + entry->ilen > BX_MAX_TRACE_LENGTH)
max_length = BX_MAX_TRACE_LENGTH - entry->ilen;
if(max_length == 0) return 0;
memcpy(i, e->i, sizeof(bxInstruction_c)*max_length);
entry->ilen += max_length;
BX_ASSERT(entry->ilen <= BX_MAX_TRACE_LENGTH);
return 1;
}
return 0;
}
#else // BX_SUPPORT_TRACE_CACHE == 0
bx_bool BX_CPU_C::fetchInstruction(bxInstruction_c *iStorage, Bit32u eipBiased)
{
unsigned remainingInPage = BX_CPU_THIS_PTR eipPageWindowSize - eipBiased;
const Bit8u *fetchPtr = BX_CPU_THIS_PTR eipFetchPtr + eipBiased;
unsigned ret;
#if BX_SUPPORT_X86_64
if (BX_CPU_THIS_PTR cpu_mode == BX_MODE_LONG_64)
ret = fetchDecode64(fetchPtr, iStorage, remainingInPage);
else
#endif
ret = fetchDecode32(fetchPtr, iStorage, remainingInPage);
if (ret==0) {
// handle instrumentation callback inside boundaryFetch
boundaryFetch(fetchPtr, remainingInPage, iStorage);
return 0;
}
#if BX_INSTRUMENTATION
BX_INSTR_OPCODE(BX_CPU_ID, fetchPtr, iStorage->ilen(),
BX_CPU_THIS_PTR sregs[BX_SEG_REG_CS].cache.u.segment.d_b, Is64BitMode());
#endif
return 1;
}
void BX_CPU_C::serveICacheMiss(bxICacheEntry_c *cache_entry, Bit32u eipBiased, bx_phy_address pAddr)
{
// The entry will be marked valid if fetchdecode will succeed
cache_entry->writeStamp = ICacheWriteStampInvalid;
if (fetchInstruction(cache_entry->i, eipBiased)) {
cache_entry->pAddr = pAddr;
cache_entry->writeStamp = *(BX_CPU_THIS_PTR currPageWriteStampPtr);
}
}
#endif
<|endoftext|> |
<commit_before>/////////////////////////////////////////////////////////////////////////
// $Id: mult64.cc,v 1.34 2009/01/16 18:18:58 sshwarts Exp $
/////////////////////////////////////////////////////////////////////////
//
// Copyright (C) 2001 MandrakeSoft S.A.
//
// MandrakeSoft S.A.
// 43, rue d'Aboukir
// 75002 Paris - France
// http://www.linux-mandrake.com/
// http://www.mandrakesoft.com/
//
// 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 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 B 02110-1301 USA
/////////////////////////////////////////////////////////////////////////
#define NEED_CPU_REG_SHORTCUTS 1
#include "bochs.h"
#include "cpu.h"
#define LOG_THIS BX_CPU_THIS_PTR
#if BX_SUPPORT_X86_64
static unsigned partial_add(Bit32u *sum,Bit32u b)
{
Bit32u t = *sum;
*sum += b;
return (*sum < t);
}
void long_mul(Bit128u *product, Bit64u op1, Bit64u op2)
{
Bit32u op_1[2],op_2[2];
Bit32u result[5];
Bit64u nn;
unsigned c;
int i,j,k;
op_1[0] = (Bit32u)(op1 & 0xffffffff);
op_1[1] = (Bit32u)(op1 >> 32);
op_2[0] = (Bit32u)(op2 & 0xffffffff);
op_2[1] = (Bit32u)(op2 >> 32);
for (i = 0; i < 4; i++) result[i] = 0;
for (i = 0; i < 2; i++) {
for (j = 0; j < 2; j++) {
nn = (Bit64u) op_1[i] * (Bit64u) op_2[j];
k = i + j;
c = partial_add(&result[k++], (Bit32u)(nn & 0xffffffff));
c = partial_add(&result[k++], (Bit32u)(nn >> 32) + c);
while (k < 4 && c != 0) {
c = partial_add(&result[k++], c);
}
}
}
product->lo = result[0] + ((Bit64u) result[1] << 32);
product->hi = result[2] + ((Bit64u) result[3] << 32);
}
void long_neg(Bit128s *n)
{
Bit64u t = n->lo;
n->lo = - (Bit64s)(n->lo);
if (t - 1 > t) --n->hi;
n->hi = ~n->hi;
}
void long_imul(Bit128s *product, Bit64s op1, Bit64s op2)
{
unsigned s1,s2;
if ((s1 = (op1 < 0))) op1 = -op1;
if ((s2 = (op2 < 0))) op2 = -op2;
long_mul((Bit128u*)product,(Bit64u)op1,(Bit64u)op2);
if (s1 ^ s2)
long_neg(product);
}
void long_shl(Bit128u *a)
{
Bit64u c;
c = a->lo >> 63;
a->lo <<= 1;
a->hi <<= 1;
a->hi |= c;
}
void long_shr(Bit128u *a)
{
Bit64u c;
c = a->hi << 63;
a->hi >>= 1;
a->lo >>= 1;
a->lo |= c;
}
unsigned long_sub(Bit128u *a,Bit128u *b)
{
Bit64u t = a->lo;
a->lo -= b->lo;
int c = (a->lo > t);
t = a -> hi;
a->hi -= b->hi + c;
return(a->hi > t);
}
int long_le(Bit128u *a,Bit128u *b)
{
if (a->hi == b->hi) {
return(a->lo <= b->lo);
} else {
return(a->hi <= b->hi);
}
}
void long_div(Bit128u *quotient,Bit64u *remainder,Bit128u *dividend,Bit64u divisor)
{
/*
n := 0;
while (divisor <= dividend) do
inc(n);
divisor := divisor * 2;
end;
quotient := 0;
while n > 0 do
divisor := divisor div 2;
quotient := quotient * 2;
temp := dividend;
dividend := dividend - divisor;
if temp > dividend then
dividend := temp;
else
inc(quotient);
end;
dec(n);
end;
remainder := dividend;
*/
Bit128u d,acc,q,temp;
int n,c;
d.lo = divisor;
d.hi = 0;
acc.lo = dividend->lo;
acc.hi = dividend->hi;
q.lo = 0;
q.hi = 0;
n = 0;
while (long_le(&d,&acc) && n < 128) {
long_shl(&d);
n++;
}
while (n > 0) {
long_shr(&d);
long_shl(&q);
temp.lo = acc.lo;
temp.hi = acc.hi;
c = long_sub(&acc,&d);
if (c) {
acc.lo = temp.lo;
acc.hi = temp.hi;
} else {
q.lo++;
}
n--;
}
*remainder = acc.lo;
quotient->lo = q.lo;
quotient->hi = q.hi;
}
void long_idiv(Bit128s *quotient,Bit64s *remainder,Bit128s *dividend,Bit64s divisor)
{
unsigned s1,s2;
Bit128s temp;
temp = *dividend;
if ((s1 = (temp.hi < 0))) {
long_neg(&temp);
}
if ((s2 = (divisor < 0))) divisor = -divisor;
long_div((Bit128u*)quotient,(Bit64u*)remainder,(Bit128u*)&temp,divisor);
if (s1 ^ s2) {
long_neg(quotient);
}
if (s2) {
*remainder = -*remainder;
}
}
void BX_CPP_AttrRegparmN(1) BX_CPU_C::MUL_RAXEqR(bxInstruction_c *i)
{
Bit128u product_128;
Bit64u op1_64 = RAX;
Bit64u op2_64 = BX_READ_64BIT_REG(i->rm());
// product_128 = ((Bit128u) op1_64) * ((Bit128u) op2_64);
// product_64l = (Bit64u) (product_128 & 0xFFFFFFFFFFFFFFFF);
// product_64h = (Bit64u) (product_128 >> 64);
long_mul(&product_128,op1_64,op2_64);
/* now write product back to destination */
RAX = product_128.lo;
RDX = product_128.hi;
/* set EFLAGS */
SET_FLAGS_OSZAPC_LOGIC_64(product_128.lo);
if(product_128.hi != 0)
{
ASSERT_FLAGS_OxxxxC();
}
}
void BX_CPP_AttrRegparmN(1) BX_CPU_C::IMUL_RAXEqR(bxInstruction_c *i)
{
Bit128s product_128;
Bit64s op1_64 = RAX;
Bit64s op2_64 = BX_READ_64BIT_REG(i->rm());
// product_128 = ((Bit128s) op1_64) * ((Bit128s) op2_64);
// product_64l = (Bit64u) (product_128 & 0xFFFFFFFFFFFFFFFF);
// product_64h = (Bit64u) (product_128 >> 64);
long_imul(&product_128,op1_64,op2_64);
/* now write product back to destination */
RAX = product_128.lo;
RDX = product_128.hi;
/* set eflags:
* IMUL r/m64: condition for clearing CF & OF:
* RDX:RAX = sign-extend of RAX
*/
SET_FLAGS_OSZAPC_LOGIC_64(product_128.lo);
if (((Bit64s)(product_128.lo) >= 0 && product_128.hi == 0) ||
((Bit64s)(product_128.lo) < 0 && product_128.hi == (Bit64s) BX_CONST64(0xffffffffffffffff)))
{
ASSERT_FLAGS_OxxxxC();
}
}
void BX_CPP_AttrRegparmN(1) BX_CPU_C::DIV_RAXEqR(bxInstruction_c *i)
{
Bit64u remainder_64, quotient_64l;
Bit128u op1_128, quotient_128;
Bit64u op2_64 = BX_READ_64BIT_REG(i->rm());
if (op2_64 == 0) {
exception(BX_DE_EXCEPTION, 0, 0);
}
op1_128.lo = RAX;
op1_128.hi = RDX;
// quotient_128 = op1_128 / op2_64;
// remainder_64 = (Bit64u) (op1_128 % op2_64);
// quotient_64l = (Bit64u) (quotient_128 & 0xFFFFFFFFFFFFFFFF);
long_div("ient_128,&remainder_64,&op1_128,op2_64);
quotient_64l = quotient_128.lo;
if (quotient_128.hi != 0)
exception(BX_DE_EXCEPTION, 0, 0);
/* set EFLAGS:
* DIV affects the following flags: O,S,Z,A,P,C are undefined
*/
/* now write quotient back to destination */
RAX = quotient_64l;
RDX = remainder_64;
}
void BX_CPP_AttrRegparmN(1) BX_CPU_C::IDIV_RAXEqR(bxInstruction_c *i)
{
Bit64s remainder_64, quotient_64l;
Bit128s op1_128, quotient_128;
op1_128.lo = RAX;
op1_128.hi = RDX;
/* check MIN_INT case */
if ((op1_128.hi == (Bit64s) BX_CONST64(0x8000000000000000)) && (!op1_128.lo))
exception(BX_DE_EXCEPTION, 0, 0);
Bit64s op2_64 = BX_READ_64BIT_REG(i->rm());
if (op2_64 == 0) {
exception(BX_DE_EXCEPTION, 0, 0);
}
// quotient_128 = op1_128 / op2_64;
// remainder_64 = (Bit64s) (op1_128 % op2_64);
// quotient_64l = (Bit64s) (quotient_128 & 0xFFFFFFFFFFFFFFFF);
long_idiv("ient_128,&remainder_64,&op1_128,op2_64);
quotient_64l = quotient_128.lo;
if ((!(quotient_128.lo & BX_CONST64(0x8000000000000000)) && quotient_128.hi != (Bit64s) 0) ||
(quotient_128.lo & BX_CONST64(0x8000000000000000)) && quotient_128.hi != (Bit64s) BX_CONST64(0xffffffffffffffff))
{
exception(BX_DE_EXCEPTION, 0, 0);
}
/* set EFLAGS:
* IDIV affects the following flags: O,S,Z,A,P,C are undefined
*/
/* now write quotient back to destination */
RAX = quotient_64l;
RDX = remainder_64;
}
void BX_CPP_AttrRegparmN(1) BX_CPU_C::IMUL_GqEqIdR(bxInstruction_c *i)
{
Bit128s product_128;
Bit64s op2_64 = BX_READ_64BIT_REG(i->rm());
Bit64s op3_64 = (Bit32s) i->Id();
long_imul(&product_128,op2_64,op3_64);
/* now write product back to destination */
BX_WRITE_64BIT_REG(i->nnn(), product_128.lo);
SET_FLAGS_OSZAPC_LOGIC_64(product_128.lo);
if (((Bit64s)(product_128.lo) >= 0 && product_128.hi == 0) ||
((Bit64s)(product_128.lo) < 0 && product_128.hi == (Bit64s) BX_CONST64(0xffffffffffffffff)))
{
ASSERT_FLAGS_OxxxxC();
}
}
void BX_CPP_AttrRegparmN(1) BX_CPU_C::IMUL_GqEqR(bxInstruction_c *i)
{
Bit128s product_128;
Bit64s op1_64 = BX_READ_64BIT_REG(i->nnn());
Bit64s op2_64 = BX_READ_64BIT_REG(i->rm());
long_imul(&product_128,op1_64,op2_64);
/* now write product back to destination */
BX_WRITE_64BIT_REG(i->nnn(), product_128.lo);
SET_FLAGS_OSZAPC_LOGIC_64(product_128.lo);
if (((Bit64s)(product_128.lo) >= 0 && product_128.hi == 0) ||
((Bit64s)(product_128.lo) < 0 && product_128.hi == (Bit64s) BX_CONST64(0xffffffffffffffff)))
{
ASSERT_FLAGS_OxxxxC();
}
}
#endif /* if BX_SUPPORT_X86_64 */
<commit_msg>fixed CF/OF flags<commit_after>/////////////////////////////////////////////////////////////////////////
// $Id: mult64.cc,v 1.35 2009/10/24 17:23:19 sshwarts Exp $
/////////////////////////////////////////////////////////////////////////
//
// Copyright (C) 2001 MandrakeSoft S.A.
//
// MandrakeSoft S.A.
// 43, rue d'Aboukir
// 75002 Paris - France
// http://www.linux-mandrake.com/
// http://www.mandrakesoft.com/
//
// 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 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 B 02110-1301 USA
/////////////////////////////////////////////////////////////////////////
#define NEED_CPU_REG_SHORTCUTS 1
#include "bochs.h"
#include "cpu.h"
#define LOG_THIS BX_CPU_THIS_PTR
#if BX_SUPPORT_X86_64
static unsigned partial_add(Bit32u *sum,Bit32u b)
{
Bit32u t = *sum;
*sum += b;
return (*sum < t);
}
void long_mul(Bit128u *product, Bit64u op1, Bit64u op2)
{
Bit32u op_1[2],op_2[2];
Bit32u result[5];
Bit64u nn;
unsigned c;
int i,j,k;
op_1[0] = (Bit32u)(op1 & 0xffffffff);
op_1[1] = (Bit32u)(op1 >> 32);
op_2[0] = (Bit32u)(op2 & 0xffffffff);
op_2[1] = (Bit32u)(op2 >> 32);
for (i = 0; i < 4; i++) result[i] = 0;
for (i = 0; i < 2; i++) {
for (j = 0; j < 2; j++) {
nn = (Bit64u) op_1[i] * (Bit64u) op_2[j];
k = i + j;
c = partial_add(&result[k++], (Bit32u)(nn & 0xffffffff));
c = partial_add(&result[k++], (Bit32u)(nn >> 32) + c);
while (k < 4 && c != 0) {
c = partial_add(&result[k++], c);
}
}
}
product->lo = result[0] + ((Bit64u) result[1] << 32);
product->hi = result[2] + ((Bit64u) result[3] << 32);
}
void long_neg(Bit128s *n)
{
Bit64u t = n->lo;
n->lo = - (Bit64s)(n->lo);
if (t - 1 > t) --n->hi;
n->hi = ~n->hi;
}
void long_imul(Bit128s *product, Bit64s op1, Bit64s op2)
{
unsigned s1,s2;
if ((s1 = (op1 < 0))) op1 = -op1;
if ((s2 = (op2 < 0))) op2 = -op2;
long_mul((Bit128u*)product,(Bit64u)op1,(Bit64u)op2);
if (s1 ^ s2)
long_neg(product);
}
void long_shl(Bit128u *a)
{
Bit64u c;
c = a->lo >> 63;
a->lo <<= 1;
a->hi <<= 1;
a->hi |= c;
}
void long_shr(Bit128u *a)
{
Bit64u c;
c = a->hi << 63;
a->hi >>= 1;
a->lo >>= 1;
a->lo |= c;
}
unsigned long_sub(Bit128u *a,Bit128u *b)
{
Bit64u t = a->lo;
a->lo -= b->lo;
int c = (a->lo > t);
t = a -> hi;
a->hi -= b->hi + c;
return(a->hi > t);
}
int long_le(Bit128u *a,Bit128u *b)
{
if (a->hi == b->hi) {
return(a->lo <= b->lo);
} else {
return(a->hi <= b->hi);
}
}
void long_div(Bit128u *quotient,Bit64u *remainder,Bit128u *dividend,Bit64u divisor)
{
/*
n := 0;
while (divisor <= dividend) do
inc(n);
divisor := divisor * 2;
end;
quotient := 0;
while n > 0 do
divisor := divisor div 2;
quotient := quotient * 2;
temp := dividend;
dividend := dividend - divisor;
if temp > dividend then
dividend := temp;
else
inc(quotient);
end;
dec(n);
end;
remainder := dividend;
*/
Bit128u d,acc,q,temp;
int n,c;
d.lo = divisor;
d.hi = 0;
acc.lo = dividend->lo;
acc.hi = dividend->hi;
q.lo = 0;
q.hi = 0;
n = 0;
while (long_le(&d,&acc) && n < 128) {
long_shl(&d);
n++;
}
while (n > 0) {
long_shr(&d);
long_shl(&q);
temp.lo = acc.lo;
temp.hi = acc.hi;
c = long_sub(&acc,&d);
if (c) {
acc.lo = temp.lo;
acc.hi = temp.hi;
} else {
q.lo++;
}
n--;
}
*remainder = acc.lo;
quotient->lo = q.lo;
quotient->hi = q.hi;
}
void long_idiv(Bit128s *quotient,Bit64s *remainder,Bit128s *dividend,Bit64s divisor)
{
unsigned s1,s2;
Bit128s temp;
temp = *dividend;
if ((s1 = (temp.hi < 0))) {
long_neg(&temp);
}
if ((s2 = (divisor < 0))) divisor = -divisor;
long_div((Bit128u*)quotient,(Bit64u*)remainder,(Bit128u*)&temp,divisor);
if (s1 ^ s2) {
long_neg(quotient);
}
if (s2) {
*remainder = -*remainder;
}
}
void BX_CPP_AttrRegparmN(1) BX_CPU_C::MUL_RAXEqR(bxInstruction_c *i)
{
Bit128u product_128;
Bit64u op1_64 = RAX;
Bit64u op2_64 = BX_READ_64BIT_REG(i->rm());
// product_128 = ((Bit128u) op1_64) * ((Bit128u) op2_64);
// product_64l = (Bit64u) (product_128 & 0xFFFFFFFFFFFFFFFF);
// product_64h = (Bit64u) (product_128 >> 64);
long_mul(&product_128,op1_64,op2_64);
/* now write product back to destination */
RAX = product_128.lo;
RDX = product_128.hi;
/* set EFLAGS */
SET_FLAGS_OSZAPC_LOGIC_64(product_128.lo);
if(product_128.hi != 0)
{
ASSERT_FLAGS_OxxxxC();
}
}
void BX_CPP_AttrRegparmN(1) BX_CPU_C::IMUL_RAXEqR(bxInstruction_c *i)
{
Bit128s product_128;
Bit64s op1_64 = RAX;
Bit64s op2_64 = BX_READ_64BIT_REG(i->rm());
// product_128 = ((Bit128s) op1_64) * ((Bit128s) op2_64);
// product_64l = (Bit64u) (product_128 & 0xFFFFFFFFFFFFFFFF);
// product_64h = (Bit64u) (product_128 >> 64);
long_imul(&product_128,op1_64,op2_64);
/* now write product back to destination */
RAX = product_128.lo;
RDX = product_128.hi;
/* set eflags:
* IMUL r/m64: condition for clearing CF & OF:
* RDX:RAX = sign-extend of RAX
*/
SET_FLAGS_OSZAPC_LOGIC_64(product_128.lo);
if(!(((Bit64s)(product_128.lo) >= 0 && product_128.hi == 0) ||
((Bit64s)(product_128.lo) < 0 && product_128.hi == (Bit64s) BX_CONST64(0xffffffffffffffff))))
{
ASSERT_FLAGS_OxxxxC();
}
}
void BX_CPP_AttrRegparmN(1) BX_CPU_C::DIV_RAXEqR(bxInstruction_c *i)
{
Bit64u remainder_64, quotient_64l;
Bit128u op1_128, quotient_128;
Bit64u op2_64 = BX_READ_64BIT_REG(i->rm());
if (op2_64 == 0) {
exception(BX_DE_EXCEPTION, 0, 0);
}
op1_128.lo = RAX;
op1_128.hi = RDX;
// quotient_128 = op1_128 / op2_64;
// remainder_64 = (Bit64u) (op1_128 % op2_64);
// quotient_64l = (Bit64u) (quotient_128 & 0xFFFFFFFFFFFFFFFF);
long_div("ient_128,&remainder_64,&op1_128,op2_64);
quotient_64l = quotient_128.lo;
if (quotient_128.hi != 0)
exception(BX_DE_EXCEPTION, 0, 0);
/* set EFLAGS:
* DIV affects the following flags: O,S,Z,A,P,C are undefined
*/
/* now write quotient back to destination */
RAX = quotient_64l;
RDX = remainder_64;
}
void BX_CPP_AttrRegparmN(1) BX_CPU_C::IDIV_RAXEqR(bxInstruction_c *i)
{
Bit64s remainder_64, quotient_64l;
Bit128s op1_128, quotient_128;
op1_128.lo = RAX;
op1_128.hi = RDX;
/* check MIN_INT case */
if ((op1_128.hi == (Bit64s) BX_CONST64(0x8000000000000000)) && (!op1_128.lo))
exception(BX_DE_EXCEPTION, 0, 0);
Bit64s op2_64 = BX_READ_64BIT_REG(i->rm());
if (op2_64 == 0) {
exception(BX_DE_EXCEPTION, 0, 0);
}
// quotient_128 = op1_128 / op2_64;
// remainder_64 = (Bit64s) (op1_128 % op2_64);
// quotient_64l = (Bit64s) (quotient_128 & 0xFFFFFFFFFFFFFFFF);
long_idiv("ient_128,&remainder_64,&op1_128,op2_64);
quotient_64l = quotient_128.lo;
if ((!(quotient_128.lo & BX_CONST64(0x8000000000000000)) && quotient_128.hi != (Bit64s) 0) ||
(quotient_128.lo & BX_CONST64(0x8000000000000000)) && quotient_128.hi != (Bit64s) BX_CONST64(0xffffffffffffffff))
{
exception(BX_DE_EXCEPTION, 0, 0);
}
/* set EFLAGS:
* IDIV affects the following flags: O,S,Z,A,P,C are undefined
*/
/* now write quotient back to destination */
RAX = quotient_64l;
RDX = remainder_64;
}
void BX_CPP_AttrRegparmN(1) BX_CPU_C::IMUL_GqEqIdR(bxInstruction_c *i)
{
Bit128s product_128;
Bit64s op2_64 = BX_READ_64BIT_REG(i->rm());
Bit64s op3_64 = (Bit32s) i->Id();
long_imul(&product_128,op2_64,op3_64);
/* now write product back to destination */
BX_WRITE_64BIT_REG(i->nnn(), product_128.lo);
SET_FLAGS_OSZAPC_LOGIC_64(product_128.lo);
if(!(((Bit64s)(product_128.lo) >= 0 && product_128.hi == 0) ||
((Bit64s)(product_128.lo) < 0 && product_128.hi == (Bit64s) BX_CONST64(0xffffffffffffffff))))
{
ASSERT_FLAGS_OxxxxC();
}
}
void BX_CPP_AttrRegparmN(1) BX_CPU_C::IMUL_GqEqR(bxInstruction_c *i)
{
Bit128s product_128;
Bit64s op1_64 = BX_READ_64BIT_REG(i->nnn());
Bit64s op2_64 = BX_READ_64BIT_REG(i->rm());
long_imul(&product_128,op1_64,op2_64);
/* now write product back to destination */
BX_WRITE_64BIT_REG(i->nnn(), product_128.lo);
SET_FLAGS_OSZAPC_LOGIC_64(product_128.lo);
if(!(((Bit64s)(product_128.lo) >= 0 && product_128.hi == 0) ||
((Bit64s)(product_128.lo) < 0 && product_128.hi == (Bit64s) BX_CONST64(0xffffffffffffffff))))
{
ASSERT_FLAGS_OxxxxC();
}
}
#endif /* if BX_SUPPORT_X86_64 */
<|endoftext|> |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.